import 'dart:io'; import 'dart:isolate'; import 'dart:math'; import 'package:flutter/foundation.dart' show kReleaseMode, Uint8List; import 'package:flutter/material.dart'; import 'package:camera/camera.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'yolo_detector.dart'; import 'preview_screen.dart'; import '../theme/app_theme.dart'; import '../utils/format.dart'; import '../services/app_settings.dart'; import '../widgets/camera_sheet.dart'; import '../widgets/help_sheet.dart'; import '../widgets/ui.dart'; class CameraScreen extends StatefulWidget { const CameraScreen({super.key}); @override State createState() => _CameraScreenState(); } class _CameraScreenState extends State { CameraController? _controller; Future? _initializeControllerFuture; YOLODetector? _yoloDetector; // null until the model has loaded bool _processing = false; // a photo is being analysed // The variable to hold the number of bullets entered by the user (default set to 5) int _numberOfBullets = 5; // Real camera controls (they change the photo itself) double _exposure = 0, _minExposure = 0, _maxExposure = 0; double _zoom = 1, _minZoom = 1, _maxZoom = 1; bool _torch = false; @override void initState() { super.initState(); _loadBulletCount(); _initCamera(); YOLODetector.create().then((detector) { if (mounted) { _yoloDetector = detector; } else { detector.close(); // screen closed while the model was loading } }); } String _t(String key) => AppSettings.instance.t(key); Future _loadBulletCount() async { final prefs = await SharedPreferences.getInstance(); setState(() { // Older versions allowed up to 10 _numberOfBullets = (prefs.getInt('bulletCount') ?? AppSettings.maxBullets) .clamp(AppSettings.minBullets, AppSettings.maxBullets); }); } Future _saveBulletCount(int count) async { final prefs = await SharedPreferences.getInstance(); await prefs.setInt('bulletCount', count); // Save the bullet count } Future _initCamera() async { final cameras = await availableCameras(); final camera = cameras.first; _controller = CameraController( camera, ResolutionPreset.high, enableAudio: false, ); _initializeControllerFuture = _controller!.initialize().then((_) async { // Ranges differ per phone; read them once the camera is ready _minExposure = await _controller!.getMinExposureOffset(); _maxExposure = await _controller!.getMaxExposureOffset(); _minZoom = await _controller!.getMinZoomLevel(); _maxZoom = (await _controller!.getMaxZoomLevel()).clamp(_minZoom, 8.0); }); if (mounted) setState(() {}); } @override void dispose() { _controller?.dispose(); _yoloDetector?.close(); super.dispose(); } Future _takePicture() async { final detector = _yoloDetector; if (_processing || detector == null) return; // busy, or model still loading setState(() => _processing = true); try { await _initializeControllerFuture; final clock = Stopwatch()..start(); final file = await _controller!.takePicture(); final shot = clock.elapsedMilliseconds; // Platform JPEG decoder (off the UI thread); the model input is built in // the background straight from the photo's centre square final bytes = await File(file.path).readAsBytes(); final photo = await decodePhoto(bytes); final decoded = clock.elapsedMilliseconds; // Save the square for the preview while the model runs final squarePath = '${file.path}_square.jpg'; final (_, detections) = await ( saveSquareInBackground(photo, squarePath), detector.detectPhoto(photo), ).wait; debugPrint('⏱ detection: photo $shot ms, decode ${decoded - shot} ms ' '(${photo.channels == 4 ? 'platform' : 'Dart'}), ' 'model + save ${clock.elapsedMilliseconds - decoded} ms, ' 'total ${clock.elapsedMilliseconds} ms'); if (!kReleaseMode) await _compareWithDartDecoder(detector, bytes, detections); if (!mounted) return; // The check screen follows the app theme; the camera is dark again after it AppSettings.instance.releaseDark(); await Navigator.push( context, MaterialPageRoute( builder: (context) => PreviewScreen( imagePath: squarePath, detections: detections, bulletCount: _numberOfBullets, // Pass the bullet count ), ), ); AppSettings.instance.holdDark(); } catch (e) { debugPrint('Error taking picture: $e'); } finally { if (mounted) setState(() => _processing = false); } } // Debug and profile builds only: detect again on the pure-Dart decode of the same photo // and log how far the results are apart (the platform decoder may round a // few pixel values differently). Future _compareWithDartDecoder(YOLODetector detector, Uint8List bytes, List platform) async { final dart = await detector .detectPhoto(await Isolate.run(() => decodePhotoDart(bytes))); String count(List r, int c) => '${r.where((d) => d.classId == c).length}'; var maxShift = 0.0; for (final a in platform) { var nearest = double.infinity; for (final b in dart.where((b) => b.classId == a.classId)) { nearest = min(nearest, sqrt(pow((a.x1 + a.x2 - b.x1 - b.x2) / 2, 2) + pow((a.y1 + a.y2 - b.y1 - b.y2) / 2, 2))); } maxShift = max(maxShift, nearest); } debugPrint('🔍 decoder check: bullets ${count(platform, 0)} vs ${count(dart, 0)}, ' 'rings ${count(platform, 2)} vs ${count(dart, 2)} (platform vs Dart), ' 'largest position difference ${maxShift.isFinite ? maxShift.toStringAsFixed(1) : '–'} px'); } void _showBulletDialog() { showCameraSheet( context, builder: (sheet) => StatefulBuilder( builder: (context, setSheetState) => Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ CameraSheetHeader( title: _t('Select the number of bullets'), subtitle: _t('{a}–{b} shots per target') .replaceAll('{a}', '${AppSettings.minBullets}') .replaceAll('{b}', '${AppSettings.maxBullets}')), SheetStepper( value: _numberOfBullets, min: AppSettings.minBullets, max: AppSettings.maxBullets, onChanged: (n) { _selectBulletCount(n); setSheetState(() {}); }, ), const SizedBox(height: 14), Text(_t('Statistics in the Book only compare targets with the same number of shots.'), style: TextStyle(fontSize: 12, color: Palette.current.muted)), ], ), ), ); } void _showHelpDialog() { showHelpSheet(context, t: _t, clearBarrier: true, items: const [ (Icons.center_focus_strong_outlined, 'Align the target inside the square frame.'), (Icons.photo_camera_outlined, 'Camera button: take a photo. Bullets are detected and you can check and save the result.'), (Icons.grid_view_rounded, 'Number bottom left: shots per target (1–5).'), (Icons.tune_rounded, 'Settings icon: exposure, zoom and flashlight.'), ]); } Future _applyCamera(VoidCallback change, Future Function() camera) async { setState(change); try { await camera(); } catch (_) {} // control not supported on this phone } void _setZoom(double z) => _applyCamera(() => _zoom = z.clamp(_minZoom, _maxZoom), () => _controller!.setZoomLevel(_zoom)); void _toggleTorch() => _applyCamera( () => _torch = !_torch, () => _controller!.setFlashMode(_torch ? FlashMode.torch : FlashMode.off), ); void _showCameraControls() { showCameraSheet( context, builder: (sheet) => StatefulBuilder( builder: (context, setSheetState) { Future apply(VoidCallback change, Future Function() camera) async { await _applyCamera(change, camera); setSheetState(() {}); } return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ CameraSheetHeader( title: _t('Camera settings'), subtitle: _t('Exposure, zoom and flashlight'), trailing: ResetPill( label: _t('Reset'), onTap: () => apply(() { _exposure = 0; _zoom = _minZoom; }, () async { await _controller!.setExposureOffset(0); await _controller!.setZoomLevel(_minZoom); }), ), ), if (_maxExposure > _minExposure) SheetSlider( icon: Icons.light_mode_outlined, label: _t('Exposure'), valueText: '${_exposure >= 0 ? '+' : '−'}${dec(_exposure.abs(), 1)}', value: _exposure, min: _minExposure, max: _maxExposure, onChanged: (v) => apply(() => _exposure = v, () => _controller!.setExposureOffset(v)), ), if (_maxZoom > _minZoom) SheetSlider( icon: Icons.zoom_in_rounded, label: _t('Zoom'), valueText: '${dec(_zoom, 1)}×', value: _zoom, min: _minZoom, max: _maxZoom, onChanged: (v) => apply(() => _zoom = v, () => _controller!.setZoomLevel(v)), ), const SizedBox(height: 8), SheetToggle( icon: Icons.flashlight_on_outlined, label: _t('Flashlight'), active: _torch, onTap: () async { _toggleTorch(); setSheetState(() {}); }, ), ], ); }, ), ); } void _selectBulletCount(int number) { setState(() { _numberOfBullets = number; // Update the selected number }); _saveBulletCount(number); // Save the selected number } @override Widget build(BuildContext context) { final c = Palette.current; final ready = _controller != null && _initializeControllerFuture != null; return Scaffold( backgroundColor: Colors.black, body: Column( children: [ // Header: back, the instruction in a pill, help Padding( padding: EdgeInsets.fromLTRB(12, MediaQuery.paddingOf(context).top + 8, 12, 8), child: Row( children: [ CircleButton(icon: Icons.chevron_left_rounded, iconSize: 26, onTap: () => Navigator.pop(context)), const SizedBox(width: 10), Expanded( child: Container( height: 40, alignment: Alignment.center, padding: const EdgeInsets.symmetric(horizontal: 14), decoration: BoxDecoration(color: c.tile, borderRadius: BorderRadius.circular(20)), child: Text( _t('Align the target inside the square'), maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: c.ink), ), ), ), const SizedBox(width: 10), CircleButton(icon: Icons.info_outline_rounded, onTap: _showHelpDialog), ], ), ), Expanded( child: !ready ? const Center(child: CircularProgressIndicator()) : FutureBuilder( future: _initializeControllerFuture, builder: (context, snapshot) { if (snapshot.connectionState != ConnectionState.done) { return const Center(child: CircularProgressIndicator()); } return LayoutBuilder(builder: (context, box) { // Same square as before: 90 % of the screen width, centred final side = MediaQuery.sizeOf(context).width * 0.9; return Stack( fit: StackFit.expand, children: [ ClipRect( child: FittedBox( fit: BoxFit.cover, child: SizedBox( width: _controller!.value.previewSize!.height, height: _controller!.value.previewSize!.width, child: CameraPreview(_controller!), ), ), ), IgnorePointer(child: CustomPaint(painter: _FramePainter(side: side, color: c.accent))), Positioned( left: 0, right: 0, bottom: 18, child: Center(child: _processing ? _searchingPill(c) : _zoomChips(c)), ), ], ); }); }, ), ), // Bottom bar: shots per target, shutter, flashlight, settings Container( color: c.bg, padding: EdgeInsets.fromLTRB(20, 18, 20, 18 + MediaQuery.paddingOf(context).bottom), child: Row( children: [ Material( color: c.tile, borderRadius: BorderRadius.circular(14), clipBehavior: Clip.antiAlias, child: InkWell( onTap: _showBulletDialog, child: SizedBox( width: 78, height: 56, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text('$_numberOfBullets', style: TextStyle(fontSize: 20, height: 1.1, fontWeight: FontWeight.w800, color: c.ink)), Text(_t('shots'), style: TextStyle(fontSize: 10.5, color: c.muted)), ], ), ), ), ), const Spacer(), _shutter(c), const Spacer(), SquareButton( icon: _torch ? Icons.flashlight_on_rounded : Icons.flashlight_off_outlined, color: _torch ? c.accent : c.ink, tooltip: _t('Flashlight'), onTap: ready ? _toggleTorch : null, ), const SizedBox(width: 10), SquareButton(icon: Icons.tune_rounded, tooltip: _t('Camera settings'), onTap: ready ? _showCameraControls : null), ], ), ), ], ), ); } // White shutter in a ring; while the photo is analysed the ring turns Widget _shutter(Palette c) { return GestureDetector( onTap: _processing ? null : _takePicture, child: SizedBox.square( dimension: 76, child: Stack( alignment: Alignment.center, children: [ if (_processing) SizedBox.square( dimension: 72, child: CircularProgressIndicator(strokeWidth: 4, color: c.ink, backgroundColor: c.tile), ) else Container( decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: c.ink, width: 4)), ), AnimatedContainer( duration: const Duration(milliseconds: 150), width: _processing ? 0 : 58, height: _processing ? 0 : 58, decoration: BoxDecoration(color: c.ink, shape: BoxShape.circle), ), ], ), ), ); } Widget _searchingPill(Palette c) => Container( padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10), decoration: BoxDecoration(color: c.tile, borderRadius: BorderRadius.circular(20)), child: Text(_t('Looking for hits …'), style: TextStyle(fontSize: 13.5, fontWeight: FontWeight.w600, color: c.ink)), ); // 1× 2× 3× quick zoom, the ones this camera can do Widget _zoomChips(Palette c) { final steps = [for (final z in [1.0, 2.0, 3.0]) if (z >= _minZoom && z <= _maxZoom) z]; if (steps.length < 2) return const SizedBox.shrink(); return Container( padding: const EdgeInsets.all(4), decoration: BoxDecoration(color: Colors.black.withValues(alpha: 0.45), borderRadius: BorderRadius.circular(20)), child: Row( mainAxisSize: MainAxisSize.min, children: [ for (final z in steps) GestureDetector( onTap: () => _setZoom(z), child: Container( width: 34, height: 30, alignment: Alignment.center, decoration: BoxDecoration( color: (_zoom - z).abs() < 0.05 ? c.tile : Colors.transparent, shape: BoxShape.circle, ), child: Text('${z.round()}×', style: TextStyle( fontSize: 11.5, fontWeight: FontWeight.w700, color: (_zoom - z).abs() < 0.05 ? c.ink : c.muted)), ), ), ], ), ); } } /// Dims the image outside the centred square and draws accent corners on it. class _FramePainter extends CustomPainter { final double side; final Color color; const _FramePainter({required this.side, required this.color}); @override void paint(Canvas canvas, Size size) { final rect = Rect.fromCenter(center: size.center(Offset.zero), width: side, height: side); canvas.drawPath( Path.combine(PathOperation.difference, Path()..addRect(Offset.zero & size), Path()..addRect(rect)), Paint()..color = Colors.black.withValues(alpha: 0.45), ); final p = Paint() ..color = color ..style = PaintingStyle.stroke ..strokeWidth = 4 ..strokeCap = StrokeCap.round; const l = 34.0; for (final (corner, dx, dy) in [ (rect.topLeft, 1.0, 1.0), (rect.topRight, -1.0, 1.0), (rect.bottomLeft, 1.0, -1.0), (rect.bottomRight, -1.0, -1.0), ]) { canvas.drawPath( Path() ..moveTo(corner.dx, corner.dy + dy * l) ..lineTo(corner.dx, corner.dy) ..lineTo(corner.dx + dx * l, corner.dy), p, ); } } @override bool shouldRepaint(_FramePainter old) => old.side != side || old.color != color; }