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 '../utils/translations.dart'; import '../utils/target_colors.dart'; import '../services/app_settings.dart'; import '../widgets/camera_sheet.dart'; import '../widgets/help_sheet.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 Color _bulletColor = Colors.blue; // default fallback // The variable to hold the number of bullets entered by the user (default set to 5) int _numberOfBullets = 5; String _selectedLanguage = 'English'; late Color _backgroundColor; // 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(); // Initialize with default target background color _backgroundColor = TargetColors.getBackgroundColor('assets/target.png'); _loadBulletCount(); _initCamera(); _loadBulletColor(); // 👈 _loadLanguage(); _loadSelectedTargetColor(); YOLODetector.create().then((detector) { if (mounted) { _yoloDetector = detector; } else { detector.close(); // screen closed while the model was loading } }); } String _t(String key) { return AppTranslations.translate(key, _selectedLanguage); } Future _loadLanguage() async { final prefs = await SharedPreferences.getInstance(); setState(() { _selectedLanguage = prefs.getString('language') ?? 'Slovenian'; }); } Future _loadSelectedTargetColor() async { final prefs = await SharedPreferences.getInstance(); final selectedTarget = prefs.getString('selectedTarget') ?? 'assets/target.png'; setState(() { _backgroundColor = TargetColors.getBackgroundColor(selectedTarget); }); } Future _loadBulletColor() async { final prefs = await SharedPreferences.getInstance(); final selected = prefs.getString('bulletColor') ?? 'Blue'; setState(() { _bulletColor = _getColorFromName(selected); }); } Color _getColorFromName(String colorName) { switch (colorName.toLowerCase()) { case 'blue': return Colors.blue; case 'green': return Colors.green; case 'yellow': return Colors.yellow; case 'purple': return Colors.purple; case 'cyan': return Colors.cyan; case 'teal': return Colors.teal; case 'indigo': return Colors.indigo; case 'pink': return Colors.pink; case 'lime': return Colors.lime; case 'mint': return Colors.greenAccent; case 'orange': return Colors.orange; case 'violet': return Colors.deepPurpleAccent; case 'amber': return Colors.amber; case 'brown': return Colors.brown; case 'grey': return Colors.grey; default: return Colors.blue; // fallback } } 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; await Navigator.push( context, MaterialPageRoute( builder: (context) => PreviewScreen( imagePath: squarePath, detections: detections, bulletCount: _numberOfBullets, // Pass the bullet count ), ), ); } 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, children: [ CameraSheetHeader( title: _t('Select the number of bullets'), subtitle: '${AppSettings.minBullets} – ${AppSettings.maxBullets}'), SheetStepper( value: _numberOfBullets, min: AppSettings.minBullets, max: AppSettings.maxBullets, accent: _bulletColor, onChanged: (n) { _selectBulletCount(n); setSheetState(() {}); }, ), const SizedBox(height: 8), ], ), ), ); } void _showHelpDialog() { showHelpSheet(context, accent: _bulletColor, t: _t, items: const [ (Icons.crop_square, 'Align the target inside the square frame.'), ( Icons.camera_alt, 'Camera button: take a photo. Bullets are detected and you can check and save the result.' ), (Icons.filter_5_rounded, 'Number bottom left: shots per target (1–5).'), (Icons.tune, 'Settings icon: exposure, zoom and flashlight.'), ]); } void _showCameraControls() { showCameraSheet( context, builder: (sheet) => StatefulBuilder( builder: (context, setSheetState) { Future apply( VoidCallback change, Future Function() camera) async { setState(change); setSheetState(() {}); try { await camera(); } catch (_) {} // control not supported on this phone } return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ CameraSheetHeader( title: _t('Image Settings'), trailing: TextButton.icon( style: TextButton.styleFrom(foregroundColor: Colors.white70), icon: const Icon(Icons.restart_alt_rounded, size: 18), label: Text(_t('Reset')), onPressed: () => apply(() { _exposure = 0; _zoom = _minZoom; }, () async { await _controller!.setExposureOffset(0); await _controller!.setZoomLevel(_minZoom); }), ), ), if (_maxExposure > _minExposure) SheetSlider( icon: Icons.exposure_rounded, label: _t('Exposure'), valueText: '${_exposure >= 0 ? '+' : ''}${_exposure.toStringAsFixed(1)}', value: _exposure, min: _minExposure, max: _maxExposure, accent: _bulletColor, onChanged: (v) => apply(() => _exposure = v, () => _controller!.setExposureOffset(v)), ), if (_maxZoom > _minZoom) SheetSlider( icon: Icons.zoom_in_rounded, label: _t('Zoom'), valueText: '${_zoom.toStringAsFixed(1)}×', value: _zoom, min: _minZoom, max: _maxZoom, accent: _bulletColor, onChanged: (v) => apply( () => _zoom = v, () => _controller!.setZoomLevel(v)), ), const SizedBox(height: 8), SizedBox( width: double.infinity, child: SheetToggle( icon: _torch ? Icons.flashlight_on_rounded : Icons.flashlight_off_rounded, label: _t('Flashlight'), active: _torch, accent: _bulletColor, onTap: () => apply( () => _torch = !_torch, () => _controller! .setFlashMode(_torch ? FlashMode.torch : FlashMode.off), ), ), ), ], ); }, ), ); } void _selectBulletCount(int number) { setState(() { _numberOfBullets = number; // Update the selected number }); _saveBulletCount(number); // Save the selected number } @override Widget build(BuildContext context) { if (_controller == null || _initializeControllerFuture == null) { return const Scaffold( body: Center(child: CircularProgressIndicator()), ); } return Scaffold( backgroundColor: _backgroundColor, extendBody: true, appBar: AppBar( backgroundColor: Colors.grey[900], title: Text( _t("Align the target inside the square"), style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold, color: Colors.white, ), ), leading: IconButton( icon: const Icon(Icons.arrow_back, color: Colors.white), onPressed: () => Navigator.pop(context), ), centerTitle: true, actions: [ IconButton( icon: const Icon(Icons.info_outline_rounded, color: Colors.white), onPressed: _showHelpDialog, ), const SizedBox(width: 16), ], ), bottomNavigationBar: BottomAppBar( color: Colors.grey[900], shape: const CircularNotchedRectangle(), notchMargin: 8.0, child: SizedBox( height: 60, child: Row( children: [ // Left - Bullet count (just number) Expanded( child: Align( alignment: Alignment.centerLeft, child: Padding( padding: const EdgeInsets.only(left: 16.0), child: InkWell( onTap: _showBulletDialog, child: Text( '$_numberOfBullets', style: const TextStyle( fontSize: 24, fontWeight: FontWeight.bold, color: Colors.white, ), ), ), ), ), ), // Center space for FAB const SizedBox(width: 80), // Right section - Brightness Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.end, children: [ IconButton( icon: const Icon(Icons.tune, color: Colors.white, size: 24), onPressed: _showCameraControls, ), ], ), ), ], ), ), ), floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, floatingActionButton: FloatingActionButton( backgroundColor: Colors.white, onPressed: _processing ? null : _takePicture, child: _processing ? const SizedBox( width: 24, height: 24, child: CircularProgressIndicator( strokeWidth: 3, color: Colors.black), ) : const Icon(Icons.camera_alt, color: Colors.black), ), body: FutureBuilder( future: _initializeControllerFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { final screenSize = MediaQuery.of(context).size; return Stack( children: [ Positioned.fill( child: Container( color: Colors.black, // covers any empty space child: FittedBox( fit: BoxFit.cover, child: SizedBox( width: _controller!.value.previewSize!.height, height: _controller!.value.previewSize!.width, child: CameraPreview(_controller!), ), ), ), ), Center( child: Container( width: screenSize.width * 0.9, height: screenSize.width * 0.9, decoration: BoxDecoration( border: Border.all( color: _bulletColor.withValues(alpha: 0.9), width: 3, ), ), ), ), ], ); } else { return const Center(child: CircularProgressIndicator()); } }, ), ); } }