Files
SDKmuta/lib/screens/preview_screen.dart
T
2026-11-27 14:37:44 +01:00

696 lines
26 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show HapticFeedback;
import 'package:intl/intl.dart';
import 'package:path_provider/path_provider.dart';
import '../services/app_settings.dart';
import '../services/target_repository.dart';
import '../theme/app_theme.dart';
import '../utils/target_scoring.dart';
import '../widgets/help_sheet.dart';
import '../widgets/section.dart';
import '../widgets/target_face.dart';
import '../widgets/ui.dart';
import 'yolo_detector.dart';
/// "Preveri zadetke": the detected hits on the chosen target design. Tap a
/// tile to pick a hit, then hold and drag on the target to move it; add or
/// remove hits; choose where to save; save.
class PreviewScreen extends StatefulWidget {
final String imagePath;
final List<DetectionResult> detections;
final int bulletCount;
const PreviewScreen({super.key, required this.imagePath, required this.detections, required this.bulletCount});
@override
State<PreviewScreen> createState() => _PreviewScreenState();
}
/// A folder to save into: an existing session or a new one.
class _SaveTarget {
final String name;
final bool isTournament;
final bool isNew;
final DateTime? date;
const _SaveTarget(this.name, this.isTournament, {this.isNew = false, this.date});
}
class _PreviewScreenState extends State<PreviewScreen> {
bool _isLoading = true;
bool _showPhoto = false; // the photo with the raw detections instead of the target
List<Offset> _hits = []; // in target space (see TargetScoring)
int? _selected;
bool _dragging = false;
bool _saving = false;
Uint8List? _photo;
Size? _photoSize;
// Size of the detected black (zones 7–10) on the target, for the mapping
static const Size _ringOnTarget = Size(355.94, 359.27);
List<Session> _sessions = [];
bool _tournament = false;
_SaveTarget? _saveTo;
String _t(String key) => AppSettings.instance.t(key);
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
await Future.wait([_loadFolders(), _runDetectionAndMapping()]);
if (mounted) setState(() => _isLoading = false);
}
// Default: the folder saved into last (most recently changed), like before
Future<void> _loadFolders() async {
final sessions = await TargetRepository.loadSessions();
final dir = Directory('${(await getApplicationDocumentsDirectory()).path}/saved_images');
String? last;
if (await dir.exists()) {
final folders = dir.listSync().whereType<Directory>().toList()
..sort((a, b) => b.statSync().changed.compareTo(a.statSync().changed));
if (folders.isNotEmpty) last = folders.first.path.split('/').last;
}
final lastSession = sessions.where((x) => x.name == last).firstOrNull;
_sessions = sessions;
_tournament = lastSession?.isTournament ?? false;
_saveTo = lastSession != null
? _SaveTarget(lastSession.name, lastSession.isTournament, date: lastSession.date)
: _newFolder(_tournament);
}
// Next "Trening 19" / "Tekmovanje 4"; numbering continues across languages
_SaveTarget _newFolder(bool tournament) {
var training = 1, tournaments = 1;
for (final x in _sessions) {
final tr = RegExp(r'^(?:Training|Trening) (\d+)$').firstMatch(x.name);
if (tr != null) training = max(training, int.parse(tr.group(1)!) + 1);
final to = RegExp(r'^(?:Tournament|Tekmovanje|Wettkampf) (\d+)$').firstMatch(x.name);
if (to != null) tournaments = max(tournaments, int.parse(to.group(1)!) + 1);
}
return tournament
? _SaveTarget('${_t('Tournament')} $tournaments', true, isNew: true)
: _SaveTarget('${_t('Training')} $training', false, isNew: true);
}
Future<void> _runDetectionAndMapping() async {
try {
final bytes = await File(widget.imagePath).readAsBytes();
_photo = bytes;
_photoSize = await _imageSize(bytes);
final ring = _getRingCenterSize(widget.detections);
if (ring == null) {
debugPrint('⚠️ Ring (classId 2) not detected in real image.');
return;
}
final (ringCenter, ringSize) = ring;
// Bullets (class 0) mapped from the photo onto the target, by the black's
// position and size
final scored = [
for (final r in widget.detections.where((r) => r.classId == 0))
_mapToTarget(Offset((r.x1 + r.x2) / 2, (r.y1 + r.y2) / 2), ringCenter, ringSize),
]..sort((a, b) => TargetScoring.scoreAt(b).compareTo(TargetScoring.scoreAt(a)));
// More found than shot: drop the highest-scoring ones (extra detections
// are usually holes counted twice in the centre)
while (scored.length > widget.bulletCount) {
scored.removeAt(0);
}
_hits = scored;
} catch (e, stack) {
debugPrint('❌ Error during detection mapping: $e');
debugPrint(stack.toString());
_hits = [];
}
}
// Width and height from the image header, without decoding the pixels
static Future<Size?> _imageSize(Uint8List bytes) async {
try {
final buffer = await ui.ImmutableBuffer.fromUint8List(bytes);
final descriptor = await ui.ImageDescriptor.encoded(buffer);
final size = Size(descriptor.width.toDouble(), descriptor.height.toDouble());
descriptor.dispose();
buffer.dispose();
return size;
} catch (_) {
return null;
}
}
(Offset, Size)? _getRingCenterSize(List<DetectionResult> results) {
final ring = results.where((r) => r.classId == 2).firstOrNull;
if (ring == null) return null;
return (Offset((ring.x1 + ring.x2) / 2, (ring.y1 + ring.y2) / 2), Size(ring.x2 - ring.x1, ring.y2 - ring.y1));
}
Offset _mapToTarget(Offset bulletCam, Offset ringCam, Size sizeCam) {
final scaleX = _ringOnTarget.width / sizeCam.width;
final scaleY = _ringOnTarget.height / sizeCam.height;
return Offset(
(bulletCam.dx - ringCam.dx) * scaleX + TargetScoring.center.dx,
(bulletCam.dy - ringCam.dy) * scaleY + TargetScoring.center.dy,
);
}
int _scoreAt(int i) => TargetScoring.scoreAt(_hits[i]);
int get _total => [for (int i = 0; i < _hits.length; i++) _scoreAt(i)].fold(0, (a, b) => a + b);
// A hand-entered shot goes where it scores exactly [score]; the angle spreads them
Offset _positionForScore(int score) {
final step = 360.0 / widget.bulletCount;
final angle = step * _hits.length + (Random().nextDouble() - 0.5) * step * 0.5;
return TargetScoring.positionFor(score, angle * pi / 180);
}
void _addHit() {
if (_hits.length >= widget.bulletCount) return;
final c = Palette.current;
showAppSheet(
context,
title: _t('Add hit'),
subtitle: _t('Its value; then drag it to where it hit.'),
builder: (sheet) => GridView.count(
crossAxisCount: 4,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
mainAxisSpacing: 10,
crossAxisSpacing: 10,
childAspectRatio: 1.25,
children: [
for (final score in [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
Material(
color: score == 10 ? c.goldSoft : c.tile,
borderRadius: BorderRadius.circular(14),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: () {
Navigator.pop(sheet);
setState(() {
_hits.add(_positionForScore(score));
_selected = _hits.length - 1;
});
},
child: Center(
child: Text('$score',
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.w700,
color: score == 10 ? (c.isDark ? c.goldInk : c.goldInk) : c.ink,
fontFeatures: AppTheme.tnum)),
),
),
),
],
),
);
}
void _removeHit() {
final i = _selected;
if (i == null) return;
setState(() {
_hits.removeAt(i);
_selected = null;
});
}
void _moveSelected(Offset delta) {
final i = _selected;
if (i == null) return;
setState(() {
final p = _hits[i] + delta;
// Keep it on the canvas
_hits[i] = Offset(p.dx.clamp(0, TargetScoring.size), p.dy.clamp(0, TargetScoring.size));
});
}
void _pickFolder() {
final c = Palette.current;
final kind = [for (final x in _sessions) if (x.isTournament == _tournament) x];
final fresh = _newFolder(_tournament);
showAppSheet(
context,
title: _t('Save to folder'),
subtitle: _t(_tournament ? 'Tournaments' : 'Trainings'),
builder: (sheet) => Column(
children: [
SheetOption(
label: fresh.name,
subtitle: _t('New folder'),
leading: IconBadge(Icons.create_new_folder_outlined, size: 34),
selected: _saveTo?.isNew == true && _saveTo?.name == fresh.name,
showDivider: false,
onTap: () {
Navigator.pop(sheet);
setState(() => _saveTo = fresh);
},
),
for (final x in kind.take(20))
SheetOption(
label: x.name,
subtitle: '${DateFormat('d. M. yyyy').format(x.date)} · ${x.targets.length}',
leading: Icon(Icons.folder_outlined, color: c.muted),
selected: _saveTo?.name == x.name && _saveTo?.isNew != true,
onTap: () {
Navigator.pop(sheet);
setState(() => _saveTo = _SaveTarget(x.name, x.isTournament, date: x.date));
},
),
],
),
);
}
void _setKind(bool tournament) {
if (tournament == _tournament) return;
setState(() {
_tournament = tournament;
// Latest folder of that kind, or a new one
final latest = _sessions.where((x) => x.isTournament == tournament).firstOrNull;
_saveTo = latest == null ? _newFolder(tournament) : _SaveTarget(latest.name, tournament, date: latest.date);
});
}
Future<void> _save() async {
final to = _saveTo;
if (to == null || _saving) return;
setState(() => _saving = true);
try {
final directory = await getApplicationDocumentsDirectory();
final saveDirectory = Directory('${directory.path}/saved_images/${to.name}');
if (!await saveDirectory.exists()) {
await saveDirectory.create(recursive: true);
await File('${saveDirectory.path}/metadata.json').writeAsString(jsonEncode({
'isTournament': to.isTournament,
'createdAt': DateTime.now().toIso8601String(),
}));
}
// Use timestamp for a unique file name
final now = DateTime.now();
final dateString = "${now.day.toString().padLeft(2, '0')}/${now.month.toString().padLeft(2, '0')}/${now.year}";
final fileName = 'target_${now.year}-${now.month}-${now.day}_${now.hour}-${now.minute}-${now.second}.json';
final scores = [for (int i = 0; i < _hits.length; i++) _scoreAt(i)];
await File('${saveDirectory.path}/$fileName').writeAsString(jsonEncode({
'date': dateString,
'totalScore': scores.fold(0, (a, b) => a + b),
'bulletCount': widget.bulletCount, // shots fired; missed ones are absent from 'bullets'
'bullets': [for (final b in _hits) {'x': b.dx, 'y': b.dy}],
'scores': scores,
}));
TargetRepository.notifyChanged();
if (!mounted) return;
Navigator.pop(context, true);
} catch (e) {
debugPrint('Error performing save: $e');
if (mounted) setState(() => _saving = false);
}
}
void _showHelp() {
showHelpSheet(context, t: _t, items: const [
(Icons.touch_app_outlined, 'Tap a value below to pick that hit; it gets a red border.'),
(Icons.open_with_rounded, 'Hold and drag on the target to move the picked hit; a magnifier shows where it is.'),
(Icons.add_rounded, 'Add hit: for a shot that was not found. Remove hit: deletes the picked one.'),
(Icons.folder_outlined, 'Save to: training or tournament, and which folder. The last one is chosen for you.'),
(Icons.photo_outlined, 'Photo icon: see the photo with what was detected.'),
]);
}
@override
Widget build(BuildContext context) {
final s = AppSettings.instance;
final c = Palette.current;
final found = widget.detections.where((r) => r.classId == 0).length;
return Scaffold(
body: Column(
children: [
BackHeader(
title: _t('Check hits'),
subtitle: _t('{n} hits detected · correct them if needed').replaceAll('{n}', '${min(found, widget.bulletCount)}'),
actions: [CircleButton(icon: Icons.info_outline_rounded, onTap: _showHelp)],
),
if (_isLoading)
const Expanded(child: Center(child: CircularProgressIndicator()))
else ...[
Padding(
padding: const EdgeInsets.fromLTRB(AppTheme.edge, 4, AppTheme.edge, 0),
child: _saveCard(c),
),
Expanded(
child: Stack(
children: [
Positioned.fill(child: _showPhoto ? _photoView(c) : _targetView(s, c)),
// The photo with what the model saw, for checking
Positioned(
top: 8,
right: AppTheme.edge,
child: CircleButton(
icon: _showPhoto ? Icons.track_changes_rounded : Icons.photo_outlined,
size: 36,
iconSize: 18,
tooltip: _t(_showPhoto ? 'Show Mapped Target' : 'Show Camera Detections'),
onTap: () => setState(() => _showPhoto = !_showPhoto),
),
),
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(AppTheme.edge, 0, AppTheme.edge, 0),
child: _tiles(c),
),
Padding(
padding: const EdgeInsets.fromLTRB(AppTheme.edge, 12, AppTheme.edge, 0),
child: Row(
children: [
Expanded(
child: SoftButton(
label: _t('Add hit'),
icon: Icons.add_rounded,
onTap: _hits.length < widget.bulletCount ? _addHit : null,
),
),
const SizedBox(width: 10),
Expanded(
child: SoftButton(
label: _t('Remove hit'),
icon: Icons.delete_outline_rounded,
destructive: _selected != null,
onTap: _selected == null ? null : _removeHit,
),
),
],
),
),
Padding(
padding: EdgeInsets.fromLTRB(AppTheme.edge, 16, AppTheme.edge, 12 + MediaQuery.paddingOf(context).bottom),
child: PrimaryButton(
label: '${_t('Save target')} · $_total',
icon: Icons.check_rounded,
busy: _saving,
onTap: _save,
),
),
],
],
),
);
}
Widget _saveCard(Palette c) {
final to = _saveTo;
final when = to == null
? ''
: to.isNew
? _t('new')
: DateUtils.isSameDay(to.date, DateTime.now())
? '${_t('today')} ${DateFormat('HH:mm').format(to.date!)}'
: DateFormat('d. M.').format(to.date ?? DateTime.now());
return AppCard(
padding: const EdgeInsets.fromLTRB(12, 12, 12, 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Kicker(_t('Save to'), padding: const EdgeInsets.only(left: 2, bottom: 8)),
SegmentedTabs(
height: 40,
items: [SegmentItem(_t('Training')), SegmentItem(_t('Tournament'))],
selected: _tournament ? 1 : 0,
onSelect: (i) => _setKind(i == 1),
),
const SizedBox(height: 8),
Material(
color: c.isDark ? c.card : c.card,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12), side: BorderSide(color: c.line)),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: _pickFolder,
child: SizedBox(
height: 42,
child: Row(
children: [
const SizedBox(width: 12),
Icon(Icons.folder_outlined, size: 18, color: c.accent),
const SizedBox(width: 10),
Flexible(
child: Text(to?.name ?? '',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: c.ink)),
),
Text(' · $when', style: TextStyle(fontSize: 12.5, color: c.muted)),
const Spacer(),
Icon(Icons.expand_more_rounded, size: 20, color: c.muted),
const SizedBox(width: 8),
],
),
),
),
),
],
),
);
}
// The target with the hits; hold and drag moves the picked hit
Widget _targetView(AppSettings s, Palette c) {
return LayoutBuilder(builder: (context, box) {
final side = min(box.maxWidth, box.maxHeight) - 8;
if (side <= 0) return const SizedBox();
final scale = side / TargetScoring.size;
final i = _selected;
final picked = i == null || i >= _hits.length ? null : _hits[i] * scale;
return Center(
child: SizedBox.square(
dimension: side,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTapUp: (d) => _pickAt(d.localPosition / scale),
onPanStart: (d) {
// Starting on another hit picks that one
final near = _nearest(d.localPosition / scale);
if (near != null) _selected = near;
if (_selected == null) return;
HapticFeedback.selectionClick();
setState(() => _dragging = true);
},
onPanUpdate: (d) => _moveSelected(d.delta / scale),
onPanEnd: (_) => setState(() => _dragging = false),
onPanCancel: () => setState(() => _dragging = false),
child: Stack(
clipBehavior: Clip.none,
children: [
Positioned.fill(
child: TargetFace(
style: s.target,
hits: _hits,
hitColor: s.bulletColor,
highlighted: i == null ? const {} : {i},
),
),
if (picked != null && !_dragging)
Positioned(
left: (picked.dx - 70).clamp(0, side - 140),
top: min(picked.dy + 26, side - 30),
child: IgnorePointer(
child: Container(
width: 140,
height: 30,
alignment: Alignment.center,
decoration: BoxDecoration(
color: c.isDark ? c.card : c.ink,
borderRadius: BorderRadius.circular(15),
border: c.isDark ? Border.all(color: c.line) : null,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.open_with_rounded, size: 15, color: c.accent),
const SizedBox(width: 6),
Text(_t('Hold and drag'),
style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: c.isDark ? c.ink : Colors.white)),
],
),
),
),
),
if (picked != null && _dragging) _loupe(picked, side),
],
),
),
),
);
});
}
int? _nearest(Offset p) {
int? best;
var bestD = 60.0; // target units: a little more than a hit's radius
for (int i = 0; i < _hits.length; i++) {
final d = (_hits[i] - p).distance;
if (d < bestD) {
bestD = d;
best = i;
}
}
return best;
}
void _pickAt(Offset p) => setState(() => _selected = _nearest(p) ?? _selected);
// Magnifier above the picked hit while it is dragged
Widget _loupe(Offset at, double side) {
const size = 120.0;
const gap = size / 2 + 36;
final cy = at.dy - gap - size / 2 >= -40 ? at.dy - gap : at.dy + gap;
return Positioned(
left: at.dx - size / 2,
top: cy - size / 2,
child: IgnorePointer(
child: RawMagnifier(
size: const Size(size, size),
magnificationScale: 2.5,
focalPointOffset: Offset(0, at.dy - cy),
decoration: const MagnifierDecoration(
shape: CircleBorder(side: BorderSide(color: Colors.white, width: 3)),
shadows: [BoxShadow(color: Colors.black54, blurRadius: 10)],
),
child: const Center(child: Icon(Icons.add, color: Colors.red, size: 22)),
),
),
);
}
// The photo with every detection box, for checking what the model saw
Widget _photoView(Palette c) {
final photo = _photo;
final size = _photoSize;
if (photo == null || size == null) return Center(child: Text(_t('Image not available'), style: TextStyle(color: c.muted)));
return Padding(
padding: const EdgeInsets.all(12),
child: Center(
child: AspectRatio(
aspectRatio: size.width / size.height,
child: LayoutBuilder(builder: (context, box) {
final k = box.maxWidth / size.width;
return ClipRRect(
borderRadius: BorderRadius.circular(14),
child: Stack(
children: [
Positioned.fill(child: Image.memory(photo, fit: BoxFit.fill)),
for (final d in widget.detections)
Positioned(
left: d.x1 * k,
top: d.y1 * k,
width: (d.x2 - d.x1) * k,
height: (d.y2 - d.y1) * k,
child: DecoratedBox(
decoration: BoxDecoration(border: Border.all(color: d.classId == 0 ? c.accent : c.pos, width: 2)),
child: Align(
alignment: Alignment.topLeft,
child: Container(
color: (d.classId == 0 ? c.accent : c.pos).withValues(alpha: 0.7),
padding: const EdgeInsets.symmetric(horizontal: 3),
child: Text('${d.classId} ${(d.confidence * 100).round()}%',
style: const TextStyle(color: Colors.black, fontSize: 9, fontWeight: FontWeight.w700)),
),
),
),
),
],
),
);
}),
),
),
);
}
// One tile per shot (missing ones as +), then the total
Widget _tiles(Palette c) {
final missing = widget.bulletCount - _hits.length;
return Row(
children: [
for (int i = 0; i < _hits.length; i++) ...[
if (i > 0) const SizedBox(width: 8),
Expanded(
child: _HitTile(
value: '${_scoreAt(i)}',
selected: i == _selected,
gold: _scoreAt(i) == 10,
onTap: () => setState(() => _selected = i == _selected ? null : i),
),
),
],
for (int k = 0; k < missing; k++) ...[
if (_hits.isNotEmpty || k > 0) const SizedBox(width: 8),
Expanded(child: _HitTile(value: '+', missing: true, onTap: _addHit)),
],
const SizedBox(width: 8),
Container(
width: 66,
height: 58,
decoration: BoxDecoration(color: c.ink, borderRadius: BorderRadius.circular(14)),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(_t('Total').toUpperCase(),
style: TextStyle(fontSize: 8.5, fontWeight: FontWeight.w800, letterSpacing: 0.8, color: c.bg.withValues(alpha: 0.7))),
Text('$_total',
style: TextStyle(fontSize: 21, height: 1.15, fontWeight: FontWeight.w800, color: c.bg, fontFeatures: AppTheme.tnum)),
],
),
),
],
);
}
}
class _HitTile extends StatelessWidget {
final String value;
final bool selected;
final bool missing;
final bool gold;
final VoidCallback onTap;
const _HitTile({required this.value, this.selected = false, this.missing = false, this.gold = false, required this.onTap});
@override
Widget build(BuildContext context) {
final c = Palette.current;
final Color bg = selected ? c.accent : (c.isDark ? c.tile : c.card);
final Color fg = selected ? c.onAccent : (missing ? c.faint : (gold ? (c.isDark ? c.goldInk : c.goldInk) : c.ink));
return GestureDetector(
onTap: onTap,
child: AnimatedContainer(
duration: const Duration(milliseconds: 150),
height: 58,
alignment: Alignment.center,
decoration: BoxDecoration(
color: missing ? Colors.transparent : bg,
borderRadius: BorderRadius.circular(14),
border: missing ? Border.all(color: c.line, width: 1.5) : (c.isDark || selected ? null : Border.all(color: c.line2)),
),
child: Text(value, style: TextStyle(fontSize: 21, fontWeight: FontWeight.w700, color: fg, fontFeatures: AppTheme.tnum)),
),
);
}
}