import 'dart:async'; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:flutter_mjpeg/flutter_mjpeg.dart'; import 'package:wakelock_plus/wakelock_plus.dart'; import '../theme/app_theme.dart'; import '../services/app_settings.dart'; import '../widgets/camera_sheet.dart'; import '../widgets/help_sheet.dart'; import '../widgets/image_settings.dart'; import '../widgets/ui.dart'; import '../services/wifi_binding.dart'; class CameraStreamScreen extends StatefulWidget { final int cameraIndex; // shooting position 1–6 final String? ip; // chosen camera; falls back to the saved IP of the position final String? location; // strelišče the camera belongs to const CameraStreamScreen( {super.key, required this.cameraIndex, this.ip, this.location}); // Image settings are kept per camera, i.e. per position and location String get settingsId => location == null ? '$cameraIndex' : '${cameraIndex}_$location'; String get title => location == null ? '$cameraIndex' : '$cameraIndex · $location'; @override State createState() => _CameraStreamScreenState(); } class _CameraStreamScreenState extends State with TickerProviderStateMixin { String? _streamUrl; bool _isError = false; final TransformationController _transformationController = TransformationController(); ImageAdjustments _image = const ImageAdjustments(); int _numberOfBullets = 5; Color get _bulletColor => AppSettings.instance.bulletColor; // --- Timer state --- bool _timerEnabled = false; int _shootSeconds = 30; int? _reloadSeconds; int? _waitSeconds; bool _fullTarget = false; // false = single shot, true = full target bool _isRunning = false; bool _isPaused = false; bool _isWaitPhase = false; bool _isReloadPhase = false; int _remaining = 0; int _shotsLeft = 0; Timer? _countdownTimer; // --- Manual bullet counter --- bool _manualCounterEnabled = false; int _manualShotsLeft = 0; // --- Change target overlay --- bool _showChangeTarget = false; bool _changeTargetOverlayEnabled = true; Timer? _changeTargetTimer; // --- Phase-change flash --- late AnimationController _flashController; late Animation _flashAnimation; bool _showFlash = false; Color _flashColor = Colors.white; // --- Phase progress bars (continuous, no per-second restart) --- late AnimationController _shootProgressController; late AnimationController _reloadProgressController; late AnimationController _waitProgressController; String _t(String key) => AppSettings.instance.t(key); // raw values always stored; null means "never configured" int? _reloadSecondsRaw; int? _waitSecondsRaw; bool _shootEnabled = false; bool _reloadEnabled = false; bool _waitEnabled = false; late final Future _wifiReady; Future _loadAllPrefs() async { await _wifiReady; // stream must start after traffic is pinned to Wi-Fi final prefs = await SharedPreferences.getInstance(); final image = await ImageAdjustments.load(widget.settingsId); final url = widget.ip ?? prefs.getString('cameraIP_${widget.cameraIndex}'); final streamUrl = (url != null && url.trim().isNotEmpty) ? (url.startsWith(RegExp(r"https?://")) ? url : "http://$url") : null; final savedShoot = prefs.getInt('timerShootSeconds'); final savedReload = prefs.getInt('timerReloadSeconds'); final savedWait = prefs.getInt('timerWaitSeconds'); final shootOn = prefs.getBool('timerShootEnabled') ?? false; final reloadOn = prefs.getBool('timerReloadEnabled') ?? false; final waitOn = prefs.getBool('timerWaitEnabled') ?? false; setState(() { // Older versions allowed up to 10 _numberOfBullets = (prefs.getInt('bulletCount') ?? AppSettings.maxBullets) .clamp(AppSettings.minBullets, AppSettings.maxBullets); _image = image; _streamUrl = streamUrl; _isError = streamUrl == null; if (savedShoot != null) _shootSeconds = savedShoot; _reloadSecondsRaw = savedReload; _waitSecondsRaw = savedWait; _shootEnabled = shootOn; _reloadEnabled = reloadOn; _waitEnabled = waitOn; _reloadSeconds = reloadOn ? savedReload : null; _waitSeconds = waitOn ? savedWait : null; _timerEnabled = shootOn || reloadOn || waitOn; _fullTarget = prefs.getBool('timerFullTarget') ?? false; _changeTargetOverlayEnabled = prefs.getBool('showChangeTargetOverlay') ?? true; _manualCounterEnabled = prefs.getBool('manualCounterEnabled') ?? false; // off until switched on _manualShotsLeft = _numberOfBullets; }); } Future _saveTimerPrefs() async { final prefs = await SharedPreferences.getInstance(); await prefs.setBool('timerEnabled', _timerEnabled); await prefs.setInt('timerShootSeconds', _shootSeconds); await prefs.setBool('timerFullTarget', _fullTarget); await prefs.setBool('timerShootEnabled', _shootEnabled); await prefs.setBool('timerReloadEnabled', _reloadEnabled); await prefs.setBool('timerWaitEnabled', _waitEnabled); if (_reloadSecondsRaw != null) { await prefs.setInt('timerReloadSeconds', _reloadSecondsRaw!); } if (_waitSecondsRaw != null) { await prefs.setInt('timerWaitSeconds', _waitSecondsRaw!); } } @override void initState() { super.initState(); _wifiReady = WifiBinding.acquire(); _loadAllPrefs(); _keepScreenAwake(); _shootProgressController = AnimationController(vsync: this); _reloadProgressController = AnimationController(vsync: this); _waitProgressController = AnimationController(vsync: this); _flashController = AnimationController( vsync: this, duration: const Duration(milliseconds: 600), ); _flashAnimation = Tween(begin: 0.0, end: 1.0).animate( CurvedAnimation(parent: _flashController, curve: Curves.easeInOut), ); _flashController.addStatusListener((status) { if (status == AnimationStatus.completed) { _flashController.reverse(); } else if (status == AnimationStatus.dismissed) { if (mounted) setState(() => _showFlash = false); } }); } Future _keepScreenAwake() async { try { await WakelockPlus.enable(); } catch (e) { debugPrint("⚠️ Could not keep screen awake: $e"); } } Future _loadStreamUrl() async { final prefs = await SharedPreferences.getInstance(); String? url = widget.ip ?? prefs.getString('cameraIP_${widget.cameraIndex}'); setState(() { _streamUrl = (url != null && url.trim().isNotEmpty) ? (url.startsWith(RegExp(r"https?://")) ? url : "http://$url") : null; _isError = _streamUrl == null; }); } void _showImageSettingsDialog() { showImageSettingsSheet( context, initial: _image, settingsId: widget.settingsId, cameraLabel: "${_t('Camera')} ${widget.cameraIndex}", t: _t, onChanged: (value) => setState(() => _image = value), ); } void _showBulletDialog() { showCameraSheet( context, builder: (sheet) => StatefulBuilder( builder: (context, setSheetState) { Future setCount(int count) async { final clamped = count.clamp(AppSettings.minBullets, AppSettings.maxBullets); setState(() => _numberOfBullets = clamped); setSheetState(() {}); final prefs = await SharedPreferences.getInstance(); await prefs.setInt('bulletCount', clamped); } return Column( mainAxisSize: MainAxisSize.min, 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: setCount, ), const SizedBox(height: 8), ], ); }, ), ); } void _showHelpDialog() { showHelpSheet(context, t: _t, clearBarrier: true, items: const [ (Icons.open_in_full_rounded, 'Pinch to zoom on the camera stream'), (Icons.grid_view_rounded, 'Number bottom left: shots per target (1–5).'), (Icons.timer_outlined, 'Timer: set shoot, reload and wait times in the timer card or with the timer button. While it runs, the button pauses it and the card stops it.'), (Icons.play_arrow_rounded, 'Play / pause: control the timer.'), (Icons.add_rounded, 'Big + button: shot counter. Tap after each shot; when the target is full you get a "Change target!" warning. The dot next to it switches the counter on or off.'), (Icons.tune_rounded, 'Picture icon: brightness, contrast, filters and rotation, saved for each camera.'), ]); } @override void dispose() { _countdownTimer?.cancel(); _changeTargetTimer?.cancel(); _shootProgressController.dispose(); _reloadProgressController.dispose(); _waitProgressController.dispose(); _flashController.dispose(); WifiBinding.release(); _restoreScreenSettings(); super.dispose(); } // --- Timer logic --- void _startTimer() { if (_isRunning) { _stopTimer(); return; } _shootProgressController.reset(); _reloadProgressController.reset(); _waitProgressController.reset(); final hasShoot = _shootEnabled && _shootSeconds > 0; final hasReload = _reloadSeconds != null && _reloadSeconds! > 0; final hasWait = _waitSeconds != null && _waitSeconds! > 0; final shots = _fullTarget ? _numberOfBullets : 1; if (hasShoot) { setState(() { _isRunning = true; _isWaitPhase = false; _isReloadPhase = false; _remaining = _shootSeconds; _shotsLeft = shots; _showFlash = true; _flashColor = _bulletColor; }); _flashController.forward(from: 0.0); _startShootProgress(_shootSeconds); } else if (hasReload) { setState(() { _isRunning = true; _isReloadPhase = true; _isWaitPhase = false; _remaining = _reloadSeconds!; _shotsLeft = shots; _showFlash = true; _flashColor = _reloadColor; }); _flashController.forward(from: 0.0); _startReloadProgress(_reloadSeconds!); } else if (hasWait) { setState(() { _isRunning = true; _isWaitPhase = true; _isReloadPhase = false; _remaining = _waitSeconds!; _shotsLeft = shots; _showFlash = true; _flashColor = _waitColor; }); _flashController.forward(from: 0.0); _startWaitProgress(_waitSeconds!); } else { return; // nothing configured } _tickDown(); } void _startShootProgress(int durationSeconds) { _shootProgressController.duration = Duration(seconds: durationSeconds); _shootProgressController.forward(from: 0.0); } void _startReloadProgress(int durationSeconds) { _reloadProgressController.duration = Duration(seconds: durationSeconds); _reloadProgressController.forward(from: 0.0); } void _startWaitProgress(int durationSeconds) { _waitProgressController.duration = Duration(seconds: durationSeconds); _waitProgressController.forward(from: 0.0); } void _stopTimer() { _countdownTimer?.cancel(); _shootProgressController.stop(); _shootProgressController.reset(); _reloadProgressController.stop(); _reloadProgressController.reset(); _waitProgressController.stop(); _waitProgressController.reset(); setState(() { _isRunning = false; _isPaused = false; _isWaitPhase = false; _isReloadPhase = false; _remaining = 0; _shotsLeft = 0; }); } void _pauseTimer() { _countdownTimer?.cancel(); _shootProgressController.stop(); _reloadProgressController.stop(); _waitProgressController.stop(); setState(() => _isPaused = true); } void _resumeTimer() { setState(() => _isPaused = false); if (_isWaitPhase) { final total = _waitSeconds ?? 1; final from = total > 0 ? (total - _remaining) / total : 0.0; _waitProgressController.duration = Duration(seconds: _remaining); _waitProgressController.forward(from: from); } else if (_isReloadPhase) { final total = _reloadSeconds ?? 1; final from = total > 0 ? (total - _remaining) / total : 0.0; _reloadProgressController.duration = Duration(seconds: _remaining); _reloadProgressController.forward(from: from); } else { final from = _shootSeconds > 0 ? (_shootSeconds - _remaining) / _shootSeconds : 0.0; _shootProgressController.duration = Duration(seconds: _remaining); _shootProgressController.forward(from: from); } _tickDown(); } void _tickDown() { _countdownTimer?.cancel(); _countdownTimer = Timer.periodic(const Duration(seconds: 1), (t) { if (!mounted) { t.cancel(); return; } setState(() => _remaining--); if (_remaining <= 0) { t.cancel(); _onPhaseComplete(); } }); } void _onPhaseComplete() { // Cycle order per shot: shoot → reload → wait → (next shot or done) // --- Wait phase ended: cycle complete, start next shoot --- if (_isWaitPhase) { if (_shotsLeft <= 0) { _stopTimer(); return; } // More shots remaining: start next shoot setState(() { _showFlash = true; _flashColor = _bulletColor; _isWaitPhase = false; _isReloadPhase = false; _remaining = _shootSeconds; }); _flashController.forward(from: 0.0); _startShootProgress(_shootSeconds); _tickDown(); return; } // --- Reload phase ended: go to wait if configured, else end cycle --- if (_isReloadPhase) { final hasWait = _waitSeconds != null && _waitSeconds! > 0; if (hasWait) { setState(() { _showFlash = true; _flashColor = _waitColor; _isReloadPhase = false; _isWaitPhase = true; _remaining = _waitSeconds!; }); _flashController.forward(from: 0.0); _startWaitProgress(_waitSeconds!); _tickDown(); } else { // No wait: cycle done if (_shotsLeft <= 0) { _stopTimer(); return; } setState(() { _showFlash = true; _flashColor = _bulletColor; _isReloadPhase = false; _remaining = _shootSeconds; }); _flashController.forward(from: 0.0); _startShootProgress(_shootSeconds); _tickDown(); } return; } // --- Shoot phase ended --- // Decrement shotsLeft now so the dot disappears immediately final newShotsLeft = _shotsLeft - 1; setState(() => _shotsLeft = newShotsLeft); final hasReload = _reloadSeconds != null && _reloadSeconds! > 0; final hasWait = _waitSeconds != null && _waitSeconds! > 0; // Last shot of a full target: skip reload+wait, show change target if (newShotsLeft <= 0 && _fullTarget) { _stopTimer(); _showChangeTargetOverlay(); return; } // Single shot or more shots remaining: play full reload+wait sequence if (hasReload) { setState(() { _showFlash = true; _flashColor = _reloadColor; _isReloadPhase = true; _remaining = _reloadSeconds!; }); _flashController.forward(from: 0.0); _startReloadProgress(_reloadSeconds!); _tickDown(); } else if (hasWait) { setState(() { _showFlash = true; _flashColor = _waitColor; _isWaitPhase = true; _remaining = _waitSeconds!; }); _flashController.forward(from: 0.0); _startWaitProgress(_waitSeconds!); _tickDown(); } else { // Shoot only if (newShotsLeft <= 0) { _stopTimer(); return; } setState(() { _showFlash = true; _flashColor = _bulletColor; _remaining = _shootSeconds; }); _flashController.forward(from: 0.0); _startShootProgress(_shootSeconds); _tickDown(); } } void _showChangeTargetOverlay() { if (!_changeTargetOverlayEnabled) return; setState(() => _showChangeTarget = true); _changeTargetTimer?.cancel(); _changeTargetTimer = Timer(const Duration(seconds: 5), () { if (mounted) setState(() => _showChangeTarget = false); }); } Future _restoreScreenSettings() async { try { await WakelockPlus.disable(); } catch (e) { debugPrint("⚠️ Could not restore screen settings: $e"); } } // --- Timer UI --- // Phase colours: shoot in the accent, reload amber, wait blue Color get _reloadColor => Palette.current.isDark ? const Color(0xFFF5B33B) : const Color(0xFFD18A00); Color get _waitColor => Palette.current.blue; static String _clock(int seconds) => '${seconds ~/ 60}:${(seconds % 60).toString().padLeft(2, '0')}'; bool get _hasActiveTimer => _timerEnabled && (_shootEnabled || _reloadEnabled || _waitEnabled); // Length of the phase that is running (or the first one, before the start) int get _phaseTotal { if (_isRunning && _isWaitPhase) return _waitSeconds ?? 0; if (_isRunning && _isReloadPhase) return _reloadSeconds ?? 0; if (_shootEnabled) return _shootSeconds; return _reloadSeconds ?? _waitSeconds ?? 0; } AnimationController get _phaseProgress => _isWaitPhase ? _waitProgressController : _isReloadPhase ? _reloadProgressController : _shootProgressController; String get _phaseName { if (_isRunning && _isWaitPhase) return _t('Wait time'); if (_isRunning && _isReloadPhase) return _t('Reload time'); return _t('Shoot time'); } Color get _phaseColor => _isRunning && _isWaitPhase ? _waitColor : _isRunning && _isReloadPhase ? _reloadColor : _bulletColor; // Ring with the time left, the phase name and the three phase lengths Widget _buildTimerCard(Palette c) { final total = _phaseTotal; final remaining = _isRunning ? _remaining : total; final color = _phaseColor; Widget chip(String label, int? seconds, bool active, bool enabled, Color tint) => Expanded( child: Container( height: 44, decoration: BoxDecoration( color: active ? tint.withValues(alpha: c.isDark ? 0.16 : 0.12) : c.tile, borderRadius: BorderRadius.circular(10), ), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(label, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 9.5, fontWeight: FontWeight.w600, color: active ? tint : c.muted)), Text(enabled && seconds != null ? _clock(seconds) : '–', style: TextStyle( fontSize: 14, fontWeight: FontWeight.w700, color: active ? tint : (enabled ? c.ink : c.faint), fontFeatures: AppTheme.tnum)), ], ), ), ); return AppCard( padding: const EdgeInsets.fromLTRB(14, 14, 14, 14), onTap: _isRunning ? null : _showTimerDialog, child: Row( children: [ SizedBox.square( dimension: 92, child: Stack( alignment: Alignment.center, children: [ SizedBox.expand( child: AnimatedBuilder( animation: _phaseProgress, builder: (_, __) => CircularProgressIndicator( value: _isRunning ? (1.0 - _phaseProgress.value).clamp(0.0, 1.0) : 1, strokeWidth: 7, strokeCap: StrokeCap.round, color: color, backgroundColor: c.tile, ), ), ), Column( mainAxisSize: MainAxisSize.min, children: [ Text(_clock(remaining.clamp(0, 5999)), style: TextStyle(fontSize: 22, fontWeight: FontWeight.w800, color: c.ink, fontFeatures: AppTheme.tnum)), Text('${_t('of')} ${_clock(total)}', style: TextStyle(fontSize: 10, color: c.muted)), ], ), ], ), ), const SizedBox(width: 14), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Expanded( child: Text(_isPaused ? '$_phaseName · ${_t('paused')}' : _phaseName, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: c.ink)), ), if (_isRunning) GestureDetector( onTap: _stopTimer, child: Container( width: 28, height: 28, decoration: BoxDecoration(color: c.redSoft, shape: BoxShape.circle), child: Icon(Icons.stop_rounded, size: 16, color: c.red), ), ), ], ), if (_fullTarget && _isRunning) Text('${_numberOfBullets - _shotsLeft} / $_numberOfBullets ${_t('shots')}', style: TextStyle(fontSize: 11.5, color: c.muted)), const SizedBox(height: 8), Row( children: [ chip(_t('Wait'), _waitSecondsRaw ?? 30, _isRunning && _isWaitPhase, _waitEnabled, _waitColor), const SizedBox(width: 6), chip(_t('Shooting'), _shootSeconds, _isRunning && !_isWaitPhase && !_isReloadPhase, _shootEnabled, _bulletColor), const SizedBox(width: 6), chip(_t('Reload phase'), _reloadSecondsRaw ?? 15, _isRunning && _isReloadPhase, _reloadEnabled, _reloadColor), ], ), if (_changeTargetOverlayEnabled) ...[ const SizedBox(height: 8), Text('${_t('Signal at the end')}: »${_t('Change target!')}«', maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 11, color: c.muted)), ], ], ), ), ], ), ); } // Shots left of the counter, as dots on the image Widget _buildBulletDots(Palette c) { if (!_showManualCounter || _numberOfBullets <= 1) return const SizedBox.shrink(); final left = _fullTarget && _isRunning ? _shotsLeft : _manualShotsLeft; return Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), decoration: BoxDecoration(color: Colors.black.withValues(alpha: 0.55), borderRadius: BorderRadius.circular(20)), child: Row( mainAxisSize: MainAxisSize.min, children: [ for (int i = 0; i < _numberOfBullets; i++) ...[ if (i > 0) const SizedBox(width: 6), Container( width: 10, height: 10, decoration: BoxDecoration( shape: BoxShape.circle, color: i < left ? _bulletColor : Colors.transparent, border: Border.all(color: i < left ? _bulletColor : Colors.white54, width: 1.5), ), ), ], ], ), ); } bool get _showManualCounter => _manualCounterEnabled && (!_timerEnabled || (!_fullTarget && _timerEnabled)); void _manualRegisterShot() { if (_manualShotsLeft <= 0) { // Already done — tap resets for next target setState(() { _manualShotsLeft = _numberOfBullets; _showChangeTarget = false; }); return; } final newLeft = _manualShotsLeft - 1; setState(() => _manualShotsLeft = newLeft); if (newLeft <= 0) { _showChangeTargetOverlay(); // Don't auto-reset — user taps again to reset } } void _showTimerDialog() { showCameraSheet( context, builder: (ctx) => _TimerSheet( shootSeconds: _shootSeconds, reloadSeconds: _reloadSecondsRaw, waitSeconds: _waitSecondsRaw, timerEnabled: _timerEnabled, shootEnabled: _shootEnabled, reloadEnabled: _reloadEnabled, waitEnabled: _waitEnabled, fullTarget: _fullTarget, changeTargetEnabled: _changeTargetOverlayEnabled, onChangeTargetToggle: (v) async { setState(() => _changeTargetOverlayEnabled = v); final prefs = await SharedPreferences.getInstance(); await prefs.setBool('showChangeTargetOverlay', v); }, onConfirm: (shoot, reload, reloadOn, wait, waitOn, fullTarget) { setState(() { _shootSeconds = shoot > 0 ? shoot : _shootSeconds; _shootEnabled = shoot > 0; _reloadSecondsRaw = reload; _waitSecondsRaw = wait; _reloadEnabled = reloadOn; _waitEnabled = waitOn; _reloadSeconds = reloadOn ? reload : null; _waitSeconds = waitOn ? wait : null; _fullTarget = fullTarget; _timerEnabled = _shootEnabled || _reloadEnabled || _waitEnabled; if (!_timerEnabled) _stopTimer(); }); _saveTimerPrefs(); }, onStart: () { Navigator.pop(ctx); if (!_isRunning) _startTimer(); }, translateFn: _t, ), ); } Future _toggleCounter() async { setState(() { _manualCounterEnabled = !_manualCounterEnabled; if (_manualCounterEnabled) _manualShotsLeft = _numberOfBullets; }); final prefs = await SharedPreferences.getInstance(); await prefs.setBool('manualCounterEnabled', _manualCounterEnabled); } @override Widget build(BuildContext context) { return ListenableBuilder( listenable: AppSettings.instance, builder: (context, _) { final c = Palette.current; return Scaffold( body: Column( children: [ BackHeader( title: "${_t('Camera')} ${widget.cameraIndex}", subtitle: widget.location, actions: [CircleButton(icon: Icons.info_outline_rounded, onTap: _showHelpDialog)], ), Expanded(child: _buildVideo(c)), if (_hasActiveTimer) Padding( padding: const EdgeInsets.fromLTRB(AppTheme.edge, 14, AppTheme.edge, 0), child: _buildTimerCard(c), ), _buildBottomBar(c), ], ), ); }, ); } Widget _buildVideo(Palette c) { return Container( margin: const EdgeInsets.only(top: 4), color: c.isDark ? const Color(0xFF0A0B0D) : const Color(0xFF17191C), child: Stack( children: [ LayoutBuilder( builder: (context, constraints) { return Center( child: (_isError || _streamUrl == null) ? _buildErrorContent() : InteractiveViewer( clipBehavior: Clip.hardEdge, constrained: false, boundaryMargin: EdgeInsets.zero, minScale: 1.0, maxScale: 5.0, transformationController: _transformationController, child: SizedBox( width: constraints.maxWidth, height: constraints.maxHeight, child: RepaintBoundary( child: ColorFiltered( colorFilter: _image.colorFilter, child: RotatedBox( quarterTurns: _image.quarterTurns, child: Mjpeg( key: ValueKey(_streamUrl), stream: _streamUrl!, isLive: true, fit: BoxFit.contain, error: (context, error, stackTrace) { // Mark as error so we can display error placeholder outside filters WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted) setState(() => _isError = true); }); return const SizedBox.expand(child: ColoredBox(color: Colors.black)); }, ), ), ), ), ), ), ); }, ), Positioned(top: 10, right: 12, child: IgnorePointer(child: _buildBulletDots(c))), // Phase-change flash overlay if (_showFlash) Positioned.fill( child: IgnorePointer( child: FadeTransition( opacity: _flashAnimation, child: Container(color: _flashColor.withValues(alpha: 0.45)), ), ), ), // Change target overlay; tap it for a new target if (_showChangeTarget) Positioned.fill( child: GestureDetector( onTap: () => setState(() { _showChangeTarget = false; _manualShotsLeft = _numberOfBullets; }), child: Center( child: Container( margin: const EdgeInsets.symmetric(horizontal: 32), padding: const EdgeInsets.fromLTRB(24, 24, 24, 22), decoration: BoxDecoration( color: _bulletColor, borderRadius: BorderRadius.circular(22), boxShadow: [BoxShadow(color: _bulletColor.withValues(alpha: 0.45), blurRadius: 30)], ), child: Column( mainAxisSize: MainAxisSize.min, children: [ Container( width: 46, height: 46, decoration: BoxDecoration( color: Palette.onColor(_bulletColor).withValues(alpha: 0.12), borderRadius: BorderRadius.circular(12), ), child: Icon(Icons.description_outlined, color: Palette.onColor(_bulletColor), size: 24), ), const SizedBox(height: 14), Text(_t('Change target!'), textAlign: TextAlign.center, style: TextStyle(color: Palette.onColor(_bulletColor), fontSize: 24, fontWeight: FontWeight.w800)), const SizedBox(height: 4), Text('$_numberOfBullets / $_numberOfBullets ${_t('shots')} · ${_t('tap for a new target')}', textAlign: TextAlign.center, style: TextStyle(color: Palette.onColor(_bulletColor).withValues(alpha: 0.75), fontSize: 12.5)), ], ), ), ), ), ), ], ), ); } // Shots per target, timer, the big counter button, counter on/off, image settings Widget _buildBottomBar(Palette c) { final IconData timerIcon; final VoidCallback timerAction; if (!_hasActiveTimer) { timerIcon = Icons.timer_outlined; timerAction = _showTimerDialog; } else if (!_isRunning) { timerIcon = Icons.play_arrow_rounded; timerAction = _startTimer; } else if (_isPaused) { timerIcon = Icons.play_arrow_rounded; timerAction = _resumeTimer; } else { timerIcon = Icons.pause_rounded; timerAction = _pauseTimer; } final full = _manualShotsLeft <= 0; return Padding( padding: EdgeInsets.fromLTRB(AppTheme.edge, 14, AppTheme.edge, 12 + MediaQuery.paddingOf(context).bottom), child: Row( children: [ SquareButton( size: 52, tooltip: _t('Select the number of bullets'), onTap: _showBulletDialog, child: Text('$_numberOfBullets', style: TextStyle(fontSize: 20, fontWeight: FontWeight.w800, color: c.ink, fontFeatures: AppTheme.tnum)), ), const SizedBox(width: 10), GestureDetector( onLongPress: _hasActiveTimer ? _showTimerDialog : null, child: SquareButton(size: 52, icon: timerIcon, tooltip: _t('Shooting Timer'), onTap: _isError ? null : timerAction), ), const Spacer(), if (_showManualCounter) // Counted shot: a wide button in the accent, the same height as the tiles Material( color: full ? c.red : _bulletColor, borderRadius: BorderRadius.circular(14), clipBehavior: Clip.antiAlias, child: InkWell( onTap: _manualRegisterShot, child: SizedBox( width: 96, height: 52, child: Icon(full ? Icons.refresh_rounded : Icons.add_rounded, size: 30, color: Palette.onColor(full ? c.red : _bulletColor)), ), ), ), const Spacer(), if (!(_timerEnabled && _fullTarget)) // Shot counter on/off: a tile like the others, tinted when on SquareButton( size: 52, tooltip: _t('Shot counter'), onTap: _toggleCounter, icon: Icons.exposure_plus_1_rounded, color: _manualCounterEnabled ? _bulletColor : c.ink, background: _manualCounterEnabled ? c.accentSoft : null, ), const SizedBox(width: 10), SquareButton(size: 52, icon: Icons.image_outlined, tooltip: _t('Image Settings'), onTap: _showImageSettingsDialog), ], ), ); } Widget _buildErrorContent() { final c = Palette.current; return Center( child: SingleChildScrollView( padding: const EdgeInsets.all(20), child: AppCard( padding: const EdgeInsets.fromLTRB(20, 24, 20, 20), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Center(child: IconBadge(Icons.videocam_off_outlined, size: 56, color: c.red)), const SizedBox(height: 14), Text(_t('Unable to load camera stream'), textAlign: TextAlign.center, style: TextStyle(color: c.ink, fontSize: 17, fontWeight: FontWeight.w700)), const SizedBox(height: 14), Text(_t('Please ensure:'), style: TextStyle(color: c.muted, fontSize: 13, fontWeight: FontWeight.w600)), const SizedBox(height: 8), HelpRow(Icons.wifi_rounded, _t('WiFi is enabled')), // Mobile data can stay on: the app pins camera traffic to Wi-Fi HelpRow(Icons.videocam_outlined, _t('Cameras and PC are switched on')), const SizedBox(height: 4), PrimaryButton(label: _t('Reload'), icon: Icons.refresh_rounded, height: 46, onTap: _loadStreamUrl), ], ), ), ), ); } } /// "Časovnik streljanja": single shot or full target, the three phase lengths, /// the change-target sign, and start. class _TimerSheet extends StatefulWidget { final int shootSeconds; final int? reloadSeconds; final int? waitSeconds; final bool timerEnabled; final bool shootEnabled; final bool reloadEnabled; final bool waitEnabled; final bool fullTarget; final bool changeTargetEnabled; final void Function(int shoot, int? reload, bool reloadOn, int? wait, bool waitOn, bool fullTarget) onConfirm; final void Function(bool) onChangeTargetToggle; final VoidCallback onStart; final String Function(String) translateFn; const _TimerSheet({ required this.shootSeconds, required this.reloadSeconds, required this.waitSeconds, required this.timerEnabled, required this.shootEnabled, required this.reloadEnabled, required this.waitEnabled, required this.fullTarget, required this.changeTargetEnabled, required this.onConfirm, required this.onChangeTargetToggle, required this.onStart, required this.translateFn, }); @override State<_TimerSheet> createState() => _TimerSheetState(); } class _TimerSheetState extends State<_TimerSheet> { late int _shoot; late int _reload; late int _wait; late bool _shootEnabled; late bool _reloadEnabled; late bool _waitEnabled; late bool _fullTarget; late bool _changeTargetEnabled; static const int _minSeconds = 5; static const int _maxSeconds = 300; static const int _step = 5; @override void initState() { super.initState(); _shoot = _clamp(widget.shootSeconds > 0 ? widget.shootSeconds : 30); _reload = _clamp(widget.reloadSeconds ?? 15); _wait = _clamp(widget.waitSeconds ?? 30); // A fresh timer starts with the shoot time on _shootEnabled = !widget.timerEnabled || widget.shootEnabled; _reloadEnabled = widget.timerEnabled && widget.reloadEnabled; _waitEnabled = widget.timerEnabled && widget.waitEnabled; _fullTarget = widget.fullTarget; _changeTargetEnabled = widget.changeTargetEnabled; } int _clamp(int v) => (((v / _step).round() * _step).clamp(_minSeconds, _maxSeconds)); String _t(String key) => widget.translateFn(key); void _notify() => widget.onConfirm( _shootEnabled || _fullTarget ? _shoot : 0, _reload, _reloadEnabled, _wait, _waitEnabled, _fullTarget, ); static String _clock(int s) => '${s ~/ 60}:${(s % 60).toString().padLeft(2, '0')}'; void _change(VoidCallback f) { setState(f); _notify(); } Widget _row({ required String label, IconData? icon, bool? enabled, // null: always on (shoot time) ValueChanged? onToggle, required int value, required ValueChanged onValue, }) { final c = Palette.current; final on = enabled ?? true; return AppCard( color: c.isDark ? c.card2 : c.card, padding: const EdgeInsets.fromLTRB(12, 8, 8, 8), child: SizedBox( height: 46, child: Row( children: [ if (enabled == null) SizedBox(width: 44, child: Icon(icon, size: 22, color: c.accent)) else SizedBox(width: 52, child: FittedBox(child: Switch(value: on, onChanged: onToggle))), const SizedBox(width: 8), Expanded( child: Text(label, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 14.5, fontWeight: FontWeight.w600, color: on ? c.ink : c.muted)), ), Stepper3( value: _clock(value), valueWidth: 54, onMinus: on && value > _minSeconds ? () => onValue(value - _step) : null, onPlus: on && value < _maxSeconds ? () => onValue(value + _step) : null, style: TextStyle( fontSize: 17, fontWeight: FontWeight.w700, color: on ? c.ink : c.faint, fontFeatures: AppTheme.tnum), ), ], ), ), ); } @override Widget build(BuildContext context) { final c = Palette.current; return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ CameraSheetHeader(title: _t('Shooting Timer')), SegmentedTabs( items: [ SegmentItem(_t('Single shot'), Icons.looks_one_outlined), SegmentItem(_t('Full target'), Icons.layers_outlined), ], selected: _fullTarget ? 1 : 0, onSelect: (i) => _change(() { _fullTarget = i == 1; if (_fullTarget) _shootEnabled = true; }), ), const SizedBox(height: 14), _row( label: _t('Shoot time'), icon: Icons.play_arrow_outlined, enabled: _fullTarget ? null : _shootEnabled, onToggle: (v) => _change(() => _shootEnabled = v), value: _shoot, onValue: (v) => _change(() => _shoot = v), ), const SizedBox(height: 10), _row( label: _t('Reload time'), enabled: _reloadEnabled, onToggle: (v) => _change(() => _reloadEnabled = v), value: _reload, onValue: (v) => _change(() => _reload = v), ), const SizedBox(height: 10), _row( label: _t('Wait time'), enabled: _waitEnabled, onToggle: (v) => _change(() => _waitEnabled = v), value: _wait, onValue: (v) => _change(() => _wait = v), ), const SizedBox(height: 10), ToggleRow( icon: Icons.description_outlined, label: _t('Change target sign'), value: _changeTargetEnabled, onChanged: (v) { setState(() => _changeTargetEnabled = v); widget.onChangeTargetToggle(v); }, ), const SizedBox(height: 10), Text(_t('Cycle: shot → reload → wait. On a full target »Change target!« is shown.'), style: TextStyle(fontSize: 12, height: 1.35, color: c.muted)), const SizedBox(height: 16), PrimaryButton( label: _t('Start timer'), icon: Icons.play_arrow_rounded, onTap: _shootEnabled || _reloadEnabled || _waitEnabled || _fullTarget ? () { _notify(); // what the sheet shows is what runs widget.onStart(); } : null, ), ], ); } }