stage2
This commit is contained in:
+114
-29
@@ -1,6 +1,7 @@
|
||||
import 'dart:io';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../services/app_settings.dart';
|
||||
import '../services/target_repository.dart';
|
||||
import '../theme/app_theme.dart';
|
||||
@@ -44,7 +45,60 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
_load();
|
||||
_restoreSettings().then((_) => _load());
|
||||
}
|
||||
|
||||
// The view settings survive leaving the screen and restarting the app.
|
||||
// Which month the graph is scrolled to is not a setting: it opens on the latest.
|
||||
static const _prefix = 'book.';
|
||||
|
||||
Future<void> _restoreSettings() async {
|
||||
final p = await SharedPreferences.getInstance();
|
||||
T pick<T extends Enum>(List<T> values, String key, T fallback) {
|
||||
final i = p.getInt(_prefix + key);
|
||||
return i != null && i >= 0 && i < values.length ? values[i] : fallback;
|
||||
}
|
||||
|
||||
final start = p.getInt('${_prefix}customStart');
|
||||
final end = p.getInt('${_prefix}customEnd');
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_filter = pick(_Filter.values, 'filter', _filter);
|
||||
_period = pick(_Period.values, 'period', _period);
|
||||
_shots = p.getInt('${_prefix}shots');
|
||||
_sortByScore = p.getBool('${_prefix}sortByScore') ?? _sortByScore;
|
||||
_chartByYear = p.getBool('${_prefix}chartByYear') ?? _chartByYear;
|
||||
if (start != null && end != null) {
|
||||
_custom = DateTimeRange(
|
||||
start: DateTime.fromMillisecondsSinceEpoch(start),
|
||||
end: DateTime.fromMillisecondsSinceEpoch(end));
|
||||
}
|
||||
// A custom period without its range can't be shown
|
||||
if (_period == _Period.custom && _custom == null) _period = _Period.year;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _saveSettings() async {
|
||||
final p = await SharedPreferences.getInstance();
|
||||
await p.setInt('${_prefix}filter', _filter.index);
|
||||
await p.setInt('${_prefix}period', _period.index);
|
||||
if (_shots == null) {
|
||||
await p.remove('${_prefix}shots');
|
||||
} else {
|
||||
await p.setInt('${_prefix}shots', _shots!);
|
||||
}
|
||||
await p.setBool('${_prefix}sortByScore', _sortByScore);
|
||||
await p.setBool('${_prefix}chartByYear', _chartByYear);
|
||||
if (_custom != null) {
|
||||
await p.setInt('${_prefix}customStart', _custom!.start.millisecondsSinceEpoch);
|
||||
await p.setInt('${_prefix}customEnd', _custom!.end.millisecondsSinceEpoch);
|
||||
}
|
||||
}
|
||||
|
||||
// setState for a view setting, then remember it
|
||||
void _change(VoidCallback update) {
|
||||
setState(update);
|
||||
_saveSettings();
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -124,7 +178,7 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
|
||||
if (picked == null) return;
|
||||
_custom = picked;
|
||||
}
|
||||
setState(() {
|
||||
_change(() {
|
||||
_period = p;
|
||||
_shots = null;
|
||||
});
|
||||
@@ -260,7 +314,7 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
|
||||
BarTab(s.t('Tournaments'), Icons.emoji_events_rounded),
|
||||
],
|
||||
selected: _filter.index,
|
||||
onSelect: (i) => setState(() {
|
||||
onSelect: (i) => _change(() {
|
||||
_filter = _Filter.values[i];
|
||||
_shots = null;
|
||||
_chartAt = null;
|
||||
@@ -293,7 +347,7 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
|
||||
selected: n == selected,
|
||||
empty: !formats.contains(n),
|
||||
onTap: formats.contains(n)
|
||||
? () => setState(() => _shots = n)
|
||||
? () => _change(() => _shots = n)
|
||||
: null),
|
||||
),
|
||||
],
|
||||
@@ -533,7 +587,7 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
|
||||
labels: [s.t('Month'), s.t('Year')],
|
||||
selected: _chartByYear ? 1 : 0,
|
||||
color: s.bulletColor,
|
||||
onSelect: (i) => setState(() {
|
||||
onSelect: (i) => _change(() {
|
||||
_chartByYear = i == 1;
|
||||
_chartAt = at;
|
||||
}),
|
||||
@@ -624,14 +678,15 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
|
||||
icon: Icon(
|
||||
_sortByScore ? Icons.leaderboard_rounded : Icons.event_rounded,
|
||||
color: surf.textSecondary),
|
||||
onPressed: () => setState(() => _sortByScore = !_sortByScore),
|
||||
onPressed: () => _change(() => _sortByScore = !_sortByScore),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Date block left; average per shot right, with how far it is from [average].
|
||||
// Date block left; points (Skupek) and average per shot right, the average
|
||||
// with how far it is from [average].
|
||||
// Tap shows this session's targets on one target; long press opens details.
|
||||
Widget _sessionCard(Session session, double? average) {
|
||||
final s = AppSettings.instance;
|
||||
@@ -683,7 +738,7 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
|
||||
),
|
||||
const SizedBox(height: 3),
|
||||
Text(
|
||||
'${targetCount(session.targets.length)} · ${s.t('Total').toLowerCase()} ${session.totalScore}',
|
||||
targetCount(session.targets.length),
|
||||
style: TextStyle(
|
||||
fontSize: 12, color: surf.textSecondary),
|
||||
),
|
||||
@@ -691,27 +746,14 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
|
||||
),
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 10),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
Text(
|
||||
avg?.toStringAsFixed(2) ?? '–',
|
||||
style: TextStyle(
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: surf.textPrimary),
|
||||
),
|
||||
if (delta != null)
|
||||
Text(_signed(delta),
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: _deltaColor(delta))),
|
||||
],
|
||||
),
|
||||
_CardFigure(
|
||||
label: s.t('Sum'), value: '${session.totalScore}'),
|
||||
const SizedBox(width: 14),
|
||||
_CardFigure(
|
||||
label: s.t('Average'),
|
||||
value: avg?.toStringAsFixed(2) ?? '–',
|
||||
note: delta == null ? null : _signed(delta),
|
||||
noteColor: delta == null ? null : _deltaColor(delta),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: s.t('Details'),
|
||||
@@ -1015,6 +1057,49 @@ class _Toggle extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
/// One figure on a history card: small uppercase label over a bold number,
|
||||
/// with an optional coloured note underneath.
|
||||
class _CardFigure extends StatelessWidget {
|
||||
final String label;
|
||||
final String value;
|
||||
final String? note;
|
||||
final Color? noteColor;
|
||||
|
||||
const _CardFigure(
|
||||
{required this.label, required this.value, this.note, this.noteColor});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final surf = Surfaces.current;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 10),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
Text(label.toUpperCase(),
|
||||
style: TextStyle(
|
||||
fontSize: 9,
|
||||
fontWeight: FontWeight.bold,
|
||||
letterSpacing: 1,
|
||||
color: surf.textSecondary)),
|
||||
Text(value,
|
||||
style: TextStyle(
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: surf.textPrimary)),
|
||||
if (note != null)
|
||||
Text(note!,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: noteColor)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Small pill on the dark bar: white when selected, outlined otherwise.
|
||||
class _BarPill extends StatelessWidget {
|
||||
final String label;
|
||||
|
||||
@@ -490,8 +490,9 @@ class _CalendarScreenState extends State<CalendarScreen> {
|
||||
|
||||
String _timeText(CalendarEvent event) {
|
||||
final startTime = event.startTime;
|
||||
if (event.isAllDay || startTime == null || event.endTime == null)
|
||||
if (event.isAllDay || startTime == null || event.endTime == null) {
|
||||
return _t('All day');
|
||||
}
|
||||
return '${DateFormat('HH:mm').format(startTime.toLocal())} – ${DateFormat('HH:mm').format(event.endTime!.toLocal())}';
|
||||
}
|
||||
|
||||
|
||||
@@ -194,7 +194,7 @@ class _CameraScreenState extends State<CameraScreen> {
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
print('Error taking picture: $e');
|
||||
debugPrint('Error taking picture: $e');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+17
-232
@@ -12,89 +12,6 @@ import 'dart:math';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../utils/translations.dart';
|
||||
|
||||
// DEBUG: Set to true to show scoring rings visualization
|
||||
const bool _DEBUG_SHOW_SCORING_RINGS = false;
|
||||
|
||||
class ScoringRingsPainter extends CustomPainter {
|
||||
final Offset center;
|
||||
final double scaleX;
|
||||
final double scaleY;
|
||||
final double targetScaleFactorX;
|
||||
final double targetScaleFactorY;
|
||||
|
||||
ScoringRingsPainter({
|
||||
required this.center,
|
||||
required this.scaleX,
|
||||
required this.scaleY,
|
||||
required this.targetScaleFactorX,
|
||||
required this.targetScaleFactorY,
|
||||
});
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
// Colors for each ring (10 to 1)
|
||||
final List<Color> ringColors = [
|
||||
Colors.red, // 10
|
||||
Colors.orange, // 9
|
||||
Colors.yellow, // 8
|
||||
Colors.lime, // 7
|
||||
Colors.green, // 6
|
||||
Colors.cyan, // 5
|
||||
Colors.blue, // 4
|
||||
Colors.indigo, // 3
|
||||
Colors.purple, // 2
|
||||
Colors.pink, // 1
|
||||
];
|
||||
|
||||
// Scoring rings distances from center (in default 1200x1200 space)
|
||||
// Must match the rings in _generatePositionForScore
|
||||
final List<double> rings = [14, 68, 123, 177, 232, 286, 342, 397, 455, 510];
|
||||
|
||||
// The canvas is already positioned at the image location
|
||||
// Center should be scaled by target scale factors first (default 1200x1200 to actual target size)
|
||||
// then by display scale factors (target image to screen)
|
||||
final scaledCenter = Offset(
|
||||
center.dx * targetScaleFactorX,
|
||||
center.dy * targetScaleFactorY,
|
||||
);
|
||||
final displayCenter = Offset(
|
||||
scaledCenter.dx * scaleX,
|
||||
scaledCenter.dy * scaleY,
|
||||
);
|
||||
|
||||
// Draw each scoring ring with a different color
|
||||
for (int i = 0; i < rings.length; i++) {
|
||||
final paint = Paint()
|
||||
..color = ringColors[i].withValues(alpha: 0.5)
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 2;
|
||||
|
||||
final ringRadius = rings[i];
|
||||
// Scale by target scale factors (default 1200x1200 to actual target size)
|
||||
// then by display scale factors (target image to screen)
|
||||
final scaledRadiusX = ringRadius * targetScaleFactorX * scaleX;
|
||||
final scaledRadiusY = ringRadius * targetScaleFactorY * scaleY;
|
||||
final scaledRadius = (scaledRadiusX + scaledRadiusY) / 2;
|
||||
canvas.drawCircle(displayCenter, scaledRadius, paint);
|
||||
}
|
||||
|
||||
// Draw center point
|
||||
final centerPaint = Paint()
|
||||
..color = Colors.red
|
||||
..style = PaintingStyle.fill;
|
||||
canvas.drawCircle(displayCenter, 4, centerPaint);
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(ScoringRingsPainter oldDelegate) {
|
||||
return center != oldDelegate.center ||
|
||||
scaleX != oldDelegate.scaleX ||
|
||||
scaleY != oldDelegate.scaleY ||
|
||||
targetScaleFactorX != oldDelegate.targetScaleFactorX ||
|
||||
targetScaleFactorY != oldDelegate.targetScaleFactorY;
|
||||
}
|
||||
}
|
||||
|
||||
class PreviewScreen extends StatefulWidget {
|
||||
final String imagePath;
|
||||
final List<DetectionResult> detections;
|
||||
@@ -122,7 +39,6 @@ class _PreviewScreenState extends State<PreviewScreen> {
|
||||
img.Image? _realImageDecoded;
|
||||
img.Image? _targetImageDecoded;
|
||||
Future<img.Image?>? _targetImageFuture;
|
||||
Offset? _targetImageCenterForScoring;
|
||||
|
||||
Uint8List? _cachedTargetImage;
|
||||
Uint8List? _cachedRealImage;
|
||||
@@ -136,8 +52,6 @@ class _PreviewScreenState extends State<PreviewScreen> {
|
||||
double _scaleFactorX = 1.0;
|
||||
double _scaleFactorY = 1.0;
|
||||
img.Image? _defaultTargetDecoded; // Default target for reference dimensions
|
||||
Offset?
|
||||
_scaledTargetCenterForScoring; // Scaled center for scoring with display target
|
||||
|
||||
int? _highlightedBulletIndex;
|
||||
|
||||
@@ -193,7 +107,7 @@ class _PreviewScreenState extends State<PreviewScreen> {
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
print("Error loading current folder info: $e");
|
||||
debugPrint("Error loading current folder info: $e");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -258,19 +172,11 @@ class _PreviewScreenState extends State<PreviewScreen> {
|
||||
if (_defaultTargetDecoded == null || _targetImageDecoded == null) {
|
||||
_scaleFactorX = 1.0;
|
||||
_scaleFactorY = 1.0;
|
||||
_scaledTargetCenterForScoring = null;
|
||||
return;
|
||||
}
|
||||
_scaleFactorX = _targetImageDecoded!.width / _defaultTargetDecoded!.width;
|
||||
_scaleFactorY = _targetImageDecoded!.height / _defaultTargetDecoded!.height;
|
||||
|
||||
// Scale the center point for scoring
|
||||
if (_targetImageCenterForScoring != null) {
|
||||
_scaledTargetCenterForScoring = Offset(
|
||||
_targetImageCenterForScoring!.dx * _scaleFactorX,
|
||||
_targetImageCenterForScoring!.dy * _scaleFactorY,
|
||||
);
|
||||
}
|
||||
debugPrint(
|
||||
"📏 Scale factors calculated: X=$_scaleFactorX, Y=$_scaleFactorY");
|
||||
}
|
||||
@@ -366,15 +272,7 @@ class _PreviewScreenState extends State<PreviewScreen> {
|
||||
Future<img.Image?> _loadAndDecodeTargetImage() async {
|
||||
final byteData = await rootBundle.load(targetAssetPath);
|
||||
final bytes = byteData.buffer.asUint8List();
|
||||
final tempDir = await getTemporaryDirectory();
|
||||
final targetFile = File('${tempDir.path}/target.png');
|
||||
await targetFile.writeAsBytes(bytes);
|
||||
final decoded = img.decodeImage(bytes);
|
||||
if (decoded != null) {
|
||||
_targetImageCenterForScoring =
|
||||
Offset(decoded.width / 2, decoded.height / 2 - 1);
|
||||
}
|
||||
return decoded;
|
||||
return img.decodeImage(bytes);
|
||||
}
|
||||
|
||||
Future<void> _runDetectionAndMapping() async {
|
||||
@@ -468,109 +366,6 @@ class _PreviewScreenState extends State<PreviewScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
void _manualScoreEntry() {
|
||||
final missingCount = widget.bulletCount - _mappedBullets.length;
|
||||
final controllers =
|
||||
List.generate(missingCount, (_) => TextEditingController());
|
||||
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) {
|
||||
return Dialog(
|
||||
backgroundColor: Colors.grey[900],
|
||||
shape:
|
||||
RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24.0),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
_t('Enter Missing Bullet Scores'),
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxHeight: 300),
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
children: List.generate(missingCount, (index) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 6),
|
||||
child: TextField(
|
||||
controller: controllers[index],
|
||||
keyboardType: TextInputType.number,
|
||||
style: const TextStyle(color: Colors.white),
|
||||
decoration: InputDecoration(
|
||||
labelText:
|
||||
'${_t('Bullet Score')} ${_mappedBullets.length + index + 1}',
|
||||
labelStyle:
|
||||
const TextStyle(color: Colors.white54),
|
||||
filled: true,
|
||||
fillColor: Colors.grey[800],
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide.none,
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide(color: _bulletColor),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: ElevatedButton(
|
||||
onPressed: () {
|
||||
final scores = controllers
|
||||
.map((c) => int.tryParse(c.text.trim()) ?? 0)
|
||||
.toList();
|
||||
|
||||
setState(() {
|
||||
for (final score in scores) {
|
||||
final offset = _generatePositionForScore(score);
|
||||
// Scale position from default coordinate system to display target size
|
||||
final scaledOffset = Offset(
|
||||
offset.dx * _scaleFactorX,
|
||||
offset.dy * _scaleFactorY,
|
||||
);
|
||||
_mappedBullets.add(scaledOffset);
|
||||
_manualBulletScores.add(score);
|
||||
}
|
||||
});
|
||||
|
||||
Navigator.pop(context);
|
||||
},
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: _bulletColor,
|
||||
foregroundColor: Colors.white,
|
||||
padding: const EdgeInsets.symmetric(vertical: 14),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child: Text(_t('Add Bullets')),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
void _showMissingBulletDialog(int bulletNum) {
|
||||
showDialog(
|
||||
context: context,
|
||||
@@ -761,7 +556,7 @@ class _PreviewScreenState extends State<PreviewScreen> {
|
||||
|
||||
await _performSave(lastFolder, false);
|
||||
} catch (e) {
|
||||
print("Error saving to last folder: $e");
|
||||
debugPrint("Error saving to last folder: $e");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -788,7 +583,7 @@ class _PreviewScreenState extends State<PreviewScreen> {
|
||||
|
||||
await _performSave(selectedFolder, isTournament);
|
||||
} catch (e) {
|
||||
print("Error saving target data: $e");
|
||||
debugPrint("Error saving target data: $e");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -839,15 +634,17 @@ class _PreviewScreenState extends State<PreviewScreen> {
|
||||
await jsonFile.writeAsString(jsonEncode(targetData));
|
||||
|
||||
// Close preview and signal refresh
|
||||
if (!mounted) return;
|
||||
Navigator.pop(context, true);
|
||||
} catch (e) {
|
||||
print("Error performing save: $e");
|
||||
debugPrint("Error performing save: $e");
|
||||
}
|
||||
}
|
||||
|
||||
Widget _buildEditController() {
|
||||
if (!_isEditMode || _selectedBulletIndexInEdit == null)
|
||||
if (!_isEditMode || _selectedBulletIndexInEdit == null) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
return Positioned(
|
||||
bottom: 20,
|
||||
@@ -986,6 +783,7 @@ class _PreviewScreenState extends State<PreviewScreen> {
|
||||
final String nextTraining = '$trainingWord $trainingCount';
|
||||
final String nextTournament = '$tournamentWord $tournamentCount';
|
||||
|
||||
if (!mounted) return null;
|
||||
return showDialog<String>(
|
||||
context: context,
|
||||
builder: (context) {
|
||||
@@ -1164,8 +962,11 @@ class _PreviewScreenState extends State<PreviewScreen> {
|
||||
int get _totalScore {
|
||||
// Score is based on the default target coordinate system (1200x1200)
|
||||
// since bullets were mapped to that system and then scaled for display
|
||||
// Manual bullets are appended after the detected ones and scored below,
|
||||
// so take only the detected ones here (at most the remaining shot slots).
|
||||
final detected = _mappedBullets.length - _manualBulletScores.length;
|
||||
final autoScore = _mappedBullets
|
||||
.take(widget.bulletCount - _manualBulletScores.length)
|
||||
.take(min(detected, widget.bulletCount - _manualBulletScores.length))
|
||||
.map((b) {
|
||||
// Scale bullet back to default coordinate system for scoring
|
||||
final defaultTargetBullet = Offset(
|
||||
@@ -1358,24 +1159,7 @@ class _PreviewScreenState extends State<PreviewScreen> {
|
||||
),
|
||||
),
|
||||
);
|
||||
}).toList(),
|
||||
// DEBUG: Show scoring rings in both modes to verify alignment
|
||||
if (_DEBUG_SHOW_SCORING_RINGS)
|
||||
Positioned(
|
||||
left: offsetX,
|
||||
top: offsetY,
|
||||
width: displayWidth,
|
||||
height: displayHeight,
|
||||
child: CustomPaint(
|
||||
painter: ScoringRingsPainter(
|
||||
center: fixedRingTargetCenter,
|
||||
scaleX: scaleX,
|
||||
scaleY: scaleY,
|
||||
targetScaleFactorX: _scaleFactorX,
|
||||
targetScaleFactorY: _scaleFactorY,
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
if (_mode == PreviewMode.mappedTarget)
|
||||
..._mappedBullets
|
||||
.asMap()
|
||||
@@ -1434,14 +1218,15 @@ class _PreviewScreenState extends State<PreviewScreen> {
|
||||
),
|
||||
),
|
||||
);
|
||||
}).toList(),
|
||||
}),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
if (_mappedBullets.isNotEmpty)
|
||||
// Shown even with no detections, so missed shots can be scored by hand
|
||||
if (widget.bulletCount > 0)
|
||||
Column(
|
||||
children: [
|
||||
// Score buttons for detected and missing bullets
|
||||
|
||||
@@ -17,7 +17,7 @@ class SpectatorScreen extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _SpectatorScreenState extends State<SpectatorScreen> {
|
||||
List<bool> _selectedCameras = List.generate(6, (_) => true); // All selected by default
|
||||
final List<bool> _selectedCameras = List.generate(6, (_) => true); // All selected by default
|
||||
List<bool> _enabledCameras = List.generate(6, (_) => false); // Which cameras have IPs configured
|
||||
List<Map<String, dynamic>> _cameras = [];
|
||||
Color _bulletColor = Colors.blue; // default/fallback bullet color
|
||||
|
||||
+46
-200
@@ -1,15 +1,8 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/foundation.dart' show compute, Uint8List;
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:screenshot/screenshot.dart';
|
||||
import 'dart:io';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_mjpeg/flutter_mjpeg.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:image/image.dart' as img;
|
||||
import 'yolo_detector.dart';
|
||||
import 'preview_screen.dart';
|
||||
import 'package:wakelock_plus/wakelock_plus.dart';
|
||||
import '../utils/translations.dart';
|
||||
import '../services/app_settings.dart';
|
||||
@@ -18,17 +11,6 @@ import '../widgets/help_sheet.dart';
|
||||
import '../widgets/image_settings.dart';
|
||||
import '../services/wifi_binding.dart';
|
||||
|
||||
// Top-level: runs in background isolate via compute().
|
||||
// Crops the capture to a square; filters are already baked into the screenshot.
|
||||
Uint8List _processStreamImage(Uint8List bytes) {
|
||||
final decoded = img.decodeImage(bytes)!;
|
||||
final w = decoded.width, h = decoded.height;
|
||||
final size = w < h ? w : h;
|
||||
final cropped = img.copyCrop(decoded,
|
||||
x: (w - size) ~/ 2, y: (h - size) ~/ 2, width: size, height: size);
|
||||
return Uint8List.fromList(img.encodeJpg(cropped));
|
||||
}
|
||||
|
||||
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
|
||||
@@ -51,19 +33,12 @@ class _CameraStreamScreenState extends State<CameraStreamScreen>
|
||||
with TickerProviderStateMixin {
|
||||
String? _streamUrl;
|
||||
bool _isError = false;
|
||||
bool _isCapturing = false;
|
||||
final ScreenshotController _screenshotController = ScreenshotController();
|
||||
final TransformationController _transformationController =
|
||||
TransformationController();
|
||||
ImageAdjustments _image = const ImageAdjustments();
|
||||
|
||||
late YOLODetector _yoloDetector;
|
||||
int _numberOfBullets = 5;
|
||||
|
||||
late AnimationController _zoomAnimController;
|
||||
Animation<Matrix4>? _zoomAnimation;
|
||||
Matrix4? _originalMatrix;
|
||||
|
||||
Color _bulletColor = Colors.blue;
|
||||
String _selectedLanguage = 'English';
|
||||
|
||||
@@ -177,18 +152,11 @@ class _CameraStreamScreenState extends State<CameraStreamScreen>
|
||||
_wifiReady = WifiBinding.acquire();
|
||||
_loadAllPrefs();
|
||||
|
||||
YOLODetector.create().then((detector) => _yoloDetector = detector);
|
||||
|
||||
_setSystemBarStyle();
|
||||
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
|
||||
|
||||
_keepScreenAwake();
|
||||
|
||||
_zoomAnimController = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 200),
|
||||
);
|
||||
|
||||
_shootProgressController = AnimationController(vsync: this);
|
||||
_reloadProgressController = AnimationController(vsync: this);
|
||||
_waitProgressController = AnimationController(vsync: this);
|
||||
@@ -280,108 +248,6 @@ class _CameraStreamScreenState extends State<CameraStreamScreen>
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _captureAndPreviewImage() async {
|
||||
if (_streamUrl == null || _isCapturing) return;
|
||||
|
||||
setState(() => _isCapturing = true);
|
||||
_originalMatrix = _transformationController.value;
|
||||
|
||||
try {
|
||||
final targetMatrix = Matrix4.identity()..scale(1.0);
|
||||
final isZoomedIn = !_matrixEquals(_originalMatrix!, targetMatrix);
|
||||
|
||||
if (isZoomedIn) {
|
||||
_zoomAnimController.reset();
|
||||
_zoomAnimation = Matrix4Tween(
|
||||
begin: _originalMatrix,
|
||||
end: targetMatrix,
|
||||
).animate(CurvedAnimation(
|
||||
parent: _zoomAnimController,
|
||||
curve: Curves.easeOut,
|
||||
));
|
||||
|
||||
void updateZoom() {
|
||||
_transformationController.value = _zoomAnimation!.value;
|
||||
}
|
||||
|
||||
_zoomAnimController.addListener(updateZoom);
|
||||
await _zoomAnimController.forward();
|
||||
_zoomAnimController.removeListener(updateZoom);
|
||||
}
|
||||
|
||||
await Future.delayed(const Duration(milliseconds: 100));
|
||||
final imageBytes = await _screenshotController.capture();
|
||||
if (imageBytes == null || imageBytes.isEmpty) return;
|
||||
|
||||
final dir = await getApplicationDocumentsDirectory();
|
||||
final path = '${dir.path}/ip_capture_temp.jpg';
|
||||
|
||||
final processedBytes = await compute(_processStreamImage, imageBytes);
|
||||
final file = File(path)..writeAsBytesSync(processedBytes);
|
||||
|
||||
// Detect objects in the image using YOLO
|
||||
final detections = await _yoloDetector.detect(file);
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
// Navigate to the preview screen
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (_) => PreviewScreen(
|
||||
imagePath: file.path,
|
||||
detections: detections,
|
||||
bulletCount: _numberOfBullets,
|
||||
),
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint("❌ Capture error: $e");
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text("Capture failed: $e")),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
_zoomAnimController.reset();
|
||||
_zoomAnimation = Matrix4Tween(
|
||||
begin: _transformationController.value,
|
||||
end: _originalMatrix!,
|
||||
).animate(CurvedAnimation(
|
||||
parent: _zoomAnimController,
|
||||
curve: Curves.easeIn,
|
||||
));
|
||||
|
||||
void restoreZoom() {
|
||||
_transformationController.value = _zoomAnimation!.value;
|
||||
}
|
||||
|
||||
_zoomAnimController.addListener(restoreZoom);
|
||||
await _zoomAnimController.forward();
|
||||
_zoomAnimController.removeListener(restoreZoom);
|
||||
|
||||
setState(() => _isCapturing = false);
|
||||
}
|
||||
}
|
||||
|
||||
img.Image invertImage(img.Image source) {
|
||||
final result = img.Image.from(source);
|
||||
for (int y = 0; y < result.height; y++) {
|
||||
for (int x = 0; x < result.width; x++) {
|
||||
final pixel = result.getPixel(x, y);
|
||||
result.setPixelRgb(x, y, 255 - pixel.r, 255 - pixel.g, 255 - pixel.b);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool _matrixEquals(Matrix4 a, Matrix4 b) {
|
||||
for (int i = 0; i < 16; i++) {
|
||||
if ((a.storage[i] - b.storage[i]).abs() > 0.001) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void _showImageSettingsDialog() {
|
||||
showImageSettingsSheet(
|
||||
context,
|
||||
@@ -462,8 +328,6 @@ class _CameraStreamScreenState extends State<CameraStreamScreen>
|
||||
_reloadProgressController.dispose();
|
||||
_waitProgressController.dispose();
|
||||
_flashController.dispose();
|
||||
_zoomAnimController.dispose();
|
||||
_yoloDetector.close();
|
||||
WifiBinding.release();
|
||||
_restoreScreenSettings();
|
||||
_setSystemBarStyle();
|
||||
@@ -873,8 +737,9 @@ class _CameraStreamScreenState extends State<CameraStreamScreen>
|
||||
|
||||
// Manual counter dots — shown at top when timer not running
|
||||
Widget _buildManualDotsOverlay() {
|
||||
if (!_showManualCounter || _numberOfBullets <= 1)
|
||||
if (!_showManualCounter || _numberOfBullets <= 1) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return Positioned(
|
||||
top: 8,
|
||||
left: 0,
|
||||
@@ -1291,75 +1156,55 @@ class _CameraStreamScreenState extends State<CameraStreamScreen>
|
||||
backgroundColor: Colors.black,
|
||||
body: Stack(
|
||||
children: [
|
||||
Screenshot(
|
||||
controller: _screenshotController,
|
||||
child: 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 SizedBox.expand(
|
||||
child: Container(color: Colors.black),
|
||||
);
|
||||
},
|
||||
),
|
||||
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 SizedBox.expand(
|
||||
child: Container(color: Colors.black),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
|
||||
if (_isCapturing)
|
||||
Positioned.fill(
|
||||
child: Container(
|
||||
color: Colors.black.withValues(alpha: 0.4),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const CircularProgressIndicator(color: Colors.white),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
_t("Processing image..."),
|
||||
style: const TextStyle(color: Colors.white, fontSize: 16),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
_buildManualDotsOverlay(),
|
||||
_buildCountdownOverlay(),
|
||||
// Phase-change flash overlay
|
||||
@@ -1476,8 +1321,9 @@ class _CameraStreamScreenState extends State<CameraStreamScreen>
|
||||
onTap: () async {
|
||||
setState(() {
|
||||
_manualCounterEnabled = !_manualCounterEnabled;
|
||||
if (_manualCounterEnabled)
|
||||
if (_manualCounterEnabled) {
|
||||
_manualShotsLeft = _numberOfBullets;
|
||||
}
|
||||
});
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setBool(
|
||||
|
||||
@@ -26,7 +26,7 @@ class TargetViewScreen extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _TargetViewScreenState extends State<TargetViewScreen> {
|
||||
int _currentIndex = 0;
|
||||
final int _currentIndex = 0;
|
||||
List<Offset> _bullets = [];
|
||||
List<Offset> _scaledBullets = []; // Bullets scaled to display target size
|
||||
int _totalScore = 0;
|
||||
@@ -144,7 +144,7 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
|
||||
img.Image? defaultTargetDecoded = img.decodeImage(defaultBytes);
|
||||
|
||||
if (defaultTargetDecoded == null) {
|
||||
print("Failed to decode default target image.");
|
||||
debugPrint("Failed to decode default target image.");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -160,7 +160,7 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
|
||||
_targetImageDecoded = img.decodeImage(displayBytes);
|
||||
|
||||
if (_targetImageDecoded == null) {
|
||||
print("Failed to decode display target image.");
|
||||
debugPrint("Failed to decode display target image.");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -275,7 +275,7 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
|
||||
|
||||
setState(() {});
|
||||
} catch (e) {
|
||||
print("Error loading JSON or image: $e");
|
||||
debugPrint("Error loading JSON or image: $e");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -293,13 +293,15 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
|
||||
try {
|
||||
final file = File(_targetFilePath);
|
||||
await file.delete();
|
||||
widget.refreshFolders();
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Target deleted')),
|
||||
);
|
||||
widget.refreshFolders();
|
||||
Navigator.pop(context);
|
||||
} catch (e) {
|
||||
print("Error deleting target: $e");
|
||||
debugPrint("Error deleting target: $e");
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Failed to delete target')),
|
||||
);
|
||||
@@ -311,18 +313,38 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
|
||||
return Scaffold(
|
||||
backgroundColor: _backgroundColor,
|
||||
appBar: AppBar(
|
||||
title: Row(
|
||||
// Score on top, where it is read first; the date sits in the bottom bar
|
||||
// Same look as the SKUPAJ total on the preview screen
|
||||
title: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Icon(Icons.calendar_today, size: 20, color: Colors.white),
|
||||
const SizedBox(width: 8),
|
||||
Text(_date, style: const TextStyle(color: Colors.white)),
|
||||
Text(
|
||||
_t('Total score').replaceAll(':', '').toUpperCase(),
|
||||
style: const TextStyle(
|
||||
fontSize: 11,
|
||||
letterSpacing: 1.5,
|
||||
color: Colors.white54,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
"$_totalScore",
|
||||
style: const TextStyle(
|
||||
fontSize: 26,
|
||||
height: 1.1,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
backgroundColor: Colors.grey[900],
|
||||
centerTitle: true,
|
||||
iconTheme: const IconThemeData(color: Colors.white),
|
||||
actions: [
|
||||
// The combined view shows a whole session; deleting would remove an
|
||||
// arbitrary one of its targets. Sessions are deleted from the Book list.
|
||||
if (!widget.isCombinedView)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.delete),
|
||||
color: Colors.red,
|
||||
@@ -487,7 +509,7 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
|
||||
),
|
||||
),
|
||||
);
|
||||
}).toList(),
|
||||
}),
|
||||
],
|
||||
);
|
||||
},
|
||||
@@ -517,33 +539,20 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
// Total score
|
||||
// Date
|
||||
Row(
|
||||
children: [
|
||||
const Icon(Icons.track_changes,
|
||||
const Icon(Icons.calendar_today,
|
||||
size: 20, color: Colors.white),
|
||||
const SizedBox(width: 12),
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Text(
|
||||
_t('Total score'),
|
||||
style: const TextStyle(
|
||||
fontSize: 11,
|
||||
color: Colors.white54,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
"$_totalScore",
|
||||
style: const TextStyle(
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
],
|
||||
Text(
|
||||
// Saved targets store dd/MM/yyyy; show it the Slovenian way
|
||||
_date.replaceAll('/', '.'),
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
@@ -43,9 +43,6 @@ class YOLODetector {
|
||||
final inputShape = inputTensor.shape;
|
||||
inputHeight = inputShape[1];
|
||||
inputWidth = inputShape[2];
|
||||
|
||||
print("📐 Model input shape: $inputShape");
|
||||
print("📦 Model input type: ${inputTensor.type}");
|
||||
}
|
||||
|
||||
Future<List<DetectionResult>> detect(File imageFile) async {
|
||||
@@ -66,8 +63,6 @@ class YOLODetector {
|
||||
final numDetections = outputShape[1];
|
||||
final outputBuffer = List.generate(1, (_) =>
|
||||
List.generate(numDetections, (_) => List.filled(6, 0.0)));
|
||||
|
||||
print("🚀 Running inference...");
|
||||
_interpreter.run(inputBuffer, outputBuffer);
|
||||
|
||||
final rawDetections = outputBuffer[0];
|
||||
@@ -102,8 +97,6 @@ class YOLODetector {
|
||||
classId,
|
||||
));
|
||||
}
|
||||
|
||||
print("🎯 Detections found: ${results.length}");
|
||||
return results;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user