Files
sign-detector/lib/presentation/camera/camera_screen.dart
T
2026-09-27 19:12:14 +03:00

318 lines
10 KiB
Dart

import 'package:camera/camera.dart';
import 'package:flutter/cupertino.dart';
import '../../core/branding/app_brand.dart';
import '../../theme/tokens.dart';
import '../../ui/ui.dart';
import '../catalog/catalog_page.dart';
import '../theme/sign_style.dart';
import 'recognition_controller.dart';
import 'sign_panel.dart';
class CameraScreen extends StatefulWidget {
const CameraScreen({super.key, required this.controller});
final RecognitionController controller;
@override
State<CameraScreen> createState() => _CameraScreenState();
}
class _CameraScreenState extends State<CameraScreen>
with WidgetsBindingObserver {
RecognitionController get controller => widget.controller;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
controller.addListener(_onChange);
controller.initialize();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
final camera = controller.cameraController;
if (camera == null || !camera.value.isInitialized) {
if (state == AppLifecycleState.resumed) {
controller.openCamera();
}
return;
}
if (state == AppLifecycleState.inactive) {
controller.pause();
} else if (state == AppLifecycleState.resumed) {
controller.openCamera();
}
}
void _onChange() {
if (mounted) {
setState(() {});
}
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
controller.removeListener(_onChange);
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final camera = controller.cameraController;
return ColoredBox(
color: const Color(0xFF101114),
child: Stack(
fit: StackFit.expand,
children: [
if (camera != null && camera.value.isInitialized)
_Preview(controller: controller)
else
_CameraPlaceholder(message: controller.cameraMessage),
const _TopBar(),
Align(
alignment: Alignment.bottomCenter,
child: _BottomSheet(controller: controller),
),
],
),
);
}
}
class _Preview extends StatelessWidget {
const _Preview({required this.controller});
final RecognitionController controller;
@override
Widget build(BuildContext context) {
final camera = controller.cameraController!;
final preview = camera.value.previewSize;
if (preview == null) {
return const SizedBox.shrink();
}
final isPortrait =
MediaQuery.orientationOf(context) == Orientation.portrait;
return ClipRect(
child: FittedBox(
fit: BoxFit.cover,
child: SizedBox(
width: isPortrait ? preview.height : preview.width,
height: isPortrait ? preview.width : preview.height,
child: CameraPreview(
camera,
child: DetectionOverlay(
detections: controller.detections,
onSelect: (detection) => controller.pin(detection.rawLabel),
),
),
),
),
);
}
}
class _CameraPlaceholder extends StatelessWidget {
const _CameraPlaceholder({required this.message});
final String? message;
@override
Widget build(BuildContext context) {
return ColoredBox(
color: const Color(0xFF101114),
child: Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Text(
message ?? 'Открываю камеру…',
textAlign: TextAlign.center,
style: const TextStyle(color: Color(0xFFFFFFFF), fontSize: 16),
),
),
),
);
}
}
class _TopBar extends StatelessWidget {
const _TopBar();
@override
Widget build(BuildContext context) {
return SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
child: Row(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Image.asset(AppBrand.iconAsset, width: 36, height: 36),
),
const SizedBox(width: 10),
const Text(
AppBrand.name,
style: TextStyle(
color: Color(0xFFFFFFFF),
fontSize: 20,
fontWeight: FontWeight.w700,
),
),
const Spacer(),
CupertinoButton(
padding: const EdgeInsets.all(8),
onPressed: () {
Navigator.of(context).push(
CupertinoPageRoute<void>(
builder: (_) => const CatalogPage(),
),
);
},
child: const Icon(
CupertinoIcons.book,
color: Color(0xFFFFFFFF),
),
),
CupertinoButton(
padding: const EdgeInsets.all(8),
onPressed: () => _showHelp(context),
child: const Icon(
CupertinoIcons.slider_horizontal_3,
color: Color(0xFFFFFFFF),
),
),
],
),
),
);
}
void _showHelp(BuildContext context) {
final controller = context
.findAncestorStateOfType<_CameraScreenState>()!
.controller;
showCupertinoModalPopup<void>(
context: context,
builder: (context) {
return ListenableBuilder(
listenable: controller,
builder: (context, _) {
final background = AppColors.of(
context,
AppColors.groupedSurface,
);
return Align(
alignment: Alignment.bottomCenter,
child: Container(
constraints: BoxConstraints(
maxHeight: MediaQuery.sizeOf(context).height * 0.75,
),
decoration: BoxDecoration(
color: background,
borderRadius: const BorderRadius.vertical(
top: Radius.circular(AppRadii.xl),
),
),
child: SafeArea(
top: false,
child: ListView(
shrinkWrap: true,
padding: const EdgeInsets.fromLTRB(20, 16, 20, 24),
children: [
const AppText.headline('Порог уверенности'),
const SizedBox(height: AppSpacing.s2),
AppText.callout(
'${(controller.confidenceThreshold * 100).round()}%. Ниже — больше срабатываний и больше ложных.',
),
CupertinoSlider(
value: controller.confidenceThreshold,
min: 0.25,
max: 0.9,
onChanged: controller.setConfidenceThreshold,
),
const SizedBox(height: AppSpacing.s3),
const AppText.headline('Модель'),
const SizedBox(height: AppSpacing.s2),
const AppText.body(
'Распознавание идёт на телефоне, модель уже лежит в приложении.',
),
const SizedBox(height: AppSpacing.s2),
const AppText.callout(
'Модель собирается скриптом tools/train_signs_model.py на датасете российских знаков. Классы в assets/models/labels.txt идут в том же порядке, что classes.txt этого датасета. Варианты 3.24.1, 3.24.2 и дальше открывают один знак 3.24: цифра скорости на нём, а не номер класса.',
),
const SizedBox(height: AppSpacing.s3),
const AppText.callout(
'Жёлтый фон и знаки на переносных опорах временные. Если временный знак противоречит стационарному, водитель руководствуется временным.',
),
const SizedBox(height: AppSpacing.s3),
const AppText.footnote(datasetAttribution),
],
),
),
),
);
},
);
},
);
}
}
class _BottomSheet extends StatelessWidget {
const _BottomSheet({required this.controller});
final RecognitionController controller;
@override
Widget build(BuildContext context) {
return SafeArea(
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
child: DecoratedBox(
decoration: BoxDecoration(
color: AppColors.of(context, AppColors.groupedSurface),
borderRadius: BorderRadius.circular(AppRadii.xl),
),
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 14, 16, 12),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const AppText.footnote(safetyLine),
const SizedBox(height: AppSpacing.s3),
_body(),
if (controller.inferenceMs != null) ...[
const SizedBox(height: AppSpacing.s1),
AppText.caption('Кадр ${controller.inferenceMs} мс'),
],
],
),
),
),
),
);
}
Widget _body() {
return switch (controller.modelStatus) {
ModelStatus.checking => const AppText.body('Проверяю модель…'),
ModelStatus.missing => const AppText.body(
'Модель не установлена, поэтому знаки в кадре не называются. Справочник работает без неё. Как положить свою модель — кнопка настройки сверху.',
),
ModelStatus.failed => AppText.body(
controller.modelMessage ?? 'Модель не запустилась.',
),
ModelStatus.ready => SignPanel(
detections: controller.detections,
primary: controller.primary,
onSelect: (detection) => controller.pin(detection.rawLabel),
),
};
}
}