794 lines
30 KiB
Dart
794 lines
30 KiB
Dart
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.
|
||
///
|
||
/// [PreviewScreen.edit] opens a saved target the same way: its hits, no photo
|
||
/// and no folder choice; saving overwrites that target's file.
|
||
class PreviewScreen extends StatefulWidget {
|
||
final String? imagePath;
|
||
final List<DetectionResult> detections;
|
||
final int bulletCount;
|
||
final File? editFile; // the saved target being edited
|
||
final List<Offset> initialHits;
|
||
|
||
const PreviewScreen({super.key, required String this.imagePath, required this.detections, required this.bulletCount})
|
||
: editFile = null,
|
||
initialHits = const [];
|
||
|
||
const PreviewScreen.edit({super.key, required File file, required List<Offset> hits, required this.bulletCount})
|
||
: imagePath = null,
|
||
detections = const [],
|
||
editFile = file,
|
||
initialHits = hits;
|
||
|
||
bool get isEdit => editFile != null;
|
||
|
||
@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 {
|
||
if (widget.isEdit) {
|
||
_hits = [...widget.initialHits];
|
||
} else {
|
||
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(() {
|
||
// Keep it within the target's square
|
||
_hits[i] = TargetScoring.shown(_hits[i] + delta);
|
||
});
|
||
}
|
||
|
||
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);
|
||
});
|
||
}
|
||
|
||
// Edit: the same file with the new hits; everything else in it is kept
|
||
Future<void> _saveEdit() async {
|
||
final file = widget.editFile!;
|
||
if (_saving) return;
|
||
setState(() => _saving = true);
|
||
try {
|
||
final data = jsonDecode(await file.readAsString()) as Map<String, dynamic>;
|
||
final scores = [for (int i = 0; i < _hits.length; i++) _scoreAt(i)];
|
||
data['totalScore'] = scores.fold(0, (a, b) => a + b);
|
||
data['bulletCount'] = widget.bulletCount;
|
||
data['bullets'] = [for (final b in _hits) {'x': b.dx, 'y': b.dy}];
|
||
data['scores'] = scores;
|
||
await file.writeAsString(jsonEncode(data));
|
||
TargetRepository.notifyChanged();
|
||
if (!mounted) return;
|
||
Navigator.pop(context, true);
|
||
} catch (e) {
|
||
debugPrint('Error saving edited target: $e');
|
||
if (mounted) setState(() => _saving = false);
|
||
}
|
||
}
|
||
|
||
Future<void> _save() async {
|
||
if (widget.isEdit) return _saveEdit();
|
||
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_box_outlined, '+ tile: for a shot that was not found. Bin: deletes the picked hit.'),
|
||
(Icons.emoji_events_outlined, 'Button bottom left: training or tournament. The folder on top: where it is saved; 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;
|
||
// The picked target's own background (a holiday's wins)
|
||
return AppBackground(
|
||
target: true,
|
||
child: Scaffold(
|
||
// Laid out on the target background's zones: header and "save to" above
|
||
// its first line, the target in the window between the lines, the hits
|
||
// and buttons below the second one
|
||
body: Stack(
|
||
children: [
|
||
if (!_isLoading)
|
||
TargetWindow(
|
||
child: Stack(
|
||
children: [
|
||
Positioned.fill(child: _showPhoto ? _photoView(c) : _targetView(s, c)),
|
||
// The photo with what the model saw, for checking (a saved
|
||
// target has no photo): the window's top right corner
|
||
if (!widget.isEdit)
|
||
Positioned(
|
||
top: 10,
|
||
right: AppTheme.edge,
|
||
child: CircleButton(
|
||
icon: _showPhoto ? Icons.track_changes_rounded : Icons.photo_outlined,
|
||
size: 40,
|
||
iconSize: 19,
|
||
tooltip: _t(_showPhoto ? 'Show Mapped Target' : 'Show Camera Detections'),
|
||
onTap: () => setState(() => _showPhoto = !_showPhoto),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
// The folder it is saved to sits on the target window's upper line
|
||
if (!_isLoading && !widget.isEdit)
|
||
Positioned.fill(
|
||
child: LayoutBuilder(builder: (context, box) {
|
||
// From under the header (60 + the status bar) down to just
|
||
// above the line: it grows with the room the screen has
|
||
final (line, _) = TargetWindow.lines(box.biggest);
|
||
final bottom = line - 12;
|
||
final top = min(MediaQuery.paddingOf(context).top + 60 + 6, bottom - 56);
|
||
return Stack(children: [
|
||
Positioned(left: AppTheme.edge, right: AppTheme.edge, top: top, height: bottom - top, child: _saveCard(c)),
|
||
]);
|
||
}),
|
||
),
|
||
Column(
|
||
children: [
|
||
BackHeader(
|
||
title: _t(widget.isEdit ? 'Edit target' : 'Check hits'),
|
||
subtitle: widget.isEdit
|
||
? widget.editFile!.parent.path.split('/').last
|
||
: _t('{n} hits detected').replaceAll('{n}', '${min(found, widget.bulletCount)}'),
|
||
actions: [
|
||
CircleButton(icon: Icons.info_outline_rounded, onTap: _showHelp),
|
||
],
|
||
),
|
||
if (_isLoading)
|
||
const Expanded(child: Center(child: CircularProgressIndicator()))
|
||
else ...[
|
||
const Spacer(),
|
||
Padding(
|
||
padding: const EdgeInsets.fromLTRB(AppTheme.edge, 8, AppTheme.edge, 0),
|
||
child: _tiles(c),
|
||
),
|
||
_actions(c),
|
||
],
|
||
],
|
||
),
|
||
],
|
||
),
|
||
),
|
||
);
|
||
}
|
||
|
||
// Like the result page: a square button either side of the main one
|
||
Widget _actions(Palette c) {
|
||
return Padding(
|
||
padding: EdgeInsets.fromLTRB(AppTheme.edge, 16, AppTheme.edge, 12 + MediaQuery.paddingOf(context).bottom),
|
||
child: Row(
|
||
children: [
|
||
// Training or tournament: one tap switches (and the folder with it)
|
||
if (!widget.isEdit) ...[
|
||
SquareButton(
|
||
size: 52,
|
||
icon: _tournament ? Icons.emoji_events_outlined : Icons.track_changes_rounded,
|
||
color: _tournament ? c.gold : c.accent,
|
||
background: _tournament ? c.goldSoft : c.accentSoft,
|
||
tooltip: _t(_tournament ? 'Tournament' : 'Training'),
|
||
onTap: () {
|
||
HapticFeedback.selectionClick();
|
||
_setKind(!_tournament);
|
||
},
|
||
),
|
||
const SizedBox(width: 10),
|
||
],
|
||
Expanded(
|
||
child: PrimaryButton(
|
||
label: '${_t(widget.isEdit ? 'Save changes' : 'Save target')} · $_total',
|
||
icon: Icons.check_rounded,
|
||
busy: _saving,
|
||
onTap: _save,
|
||
),
|
||
),
|
||
const SizedBox(width: 10),
|
||
SquareButton(
|
||
size: 52,
|
||
icon: Icons.delete_outline_rounded,
|
||
tooltip: _t('Remove hit'),
|
||
color: _selected == null ? c.faint : c.red,
|
||
background: _selected == null ? null : c.redSoft,
|
||
onTap: _selected == null ? null : _removeHit,
|
||
),
|
||
],
|
||
),
|
||
);
|
||
}
|
||
|
||
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());
|
||
// The folder, with the kind above its name (switched by the button
|
||
// bottom left); fills the room between the header and the line
|
||
final tint = _tournament ? c.gold : c.accent;
|
||
return Material(
|
||
color: c.card,
|
||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16), side: BorderSide(color: c.line)),
|
||
clipBehavior: Clip.antiAlias,
|
||
child: InkWell(
|
||
onTap: _pickFolder,
|
||
child: LayoutBuilder(builder: (context, box) {
|
||
final roomy = box.maxHeight >= 76;
|
||
return Padding(
|
||
padding: const EdgeInsets.symmetric(horizontal: 14),
|
||
child: Row(
|
||
children: [
|
||
Container(
|
||
width: roomy ? 48 : 34,
|
||
height: roomy ? 48 : 34,
|
||
decoration: BoxDecoration(
|
||
color: _tournament ? c.goldSoft : c.accentSoft,
|
||
borderRadius: BorderRadius.circular(roomy ? 14 : 10),
|
||
),
|
||
child: Icon(Icons.folder_outlined, size: roomy ? 24 : 18, color: tint),
|
||
),
|
||
const SizedBox(width: 12),
|
||
Expanded(
|
||
child: Column(
|
||
mainAxisAlignment: MainAxisAlignment.center,
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
Text('${_t('Save to')} · ${_t(_tournament ? 'Tournament' : 'Training')}'.toUpperCase(),
|
||
maxLines: 1,
|
||
overflow: TextOverflow.ellipsis,
|
||
style: AppTheme.kicker(c).copyWith(fontSize: roomy ? 10.5 : 9.5)),
|
||
SizedBox(height: roomy ? 4 : 2),
|
||
Text(to?.name ?? '',
|
||
maxLines: 1,
|
||
overflow: TextOverflow.ellipsis,
|
||
style: TextStyle(fontSize: roomy ? 19 : 15, height: 1.15, fontWeight: FontWeight.w700, color: c.ink)),
|
||
if (roomy && when.isNotEmpty) ...[
|
||
const SizedBox(height: 3),
|
||
Text(when, maxLines: 1, style: TextStyle(fontSize: 12.5, color: c.muted)),
|
||
],
|
||
],
|
||
),
|
||
),
|
||
if (!roomy && when.isNotEmpty) ...[Text(when, style: TextStyle(fontSize: 12, color: c.muted)), const SizedBox(width: 4)],
|
||
Container(
|
||
width: 32,
|
||
height: 32,
|
||
decoration: BoxDecoration(color: c.tile, shape: BoxShape.circle),
|
||
child: Icon(Icons.unfold_more_rounded, size: 18, color: c.ink2),
|
||
),
|
||
],
|
||
),
|
||
);
|
||
}),
|
||
),
|
||
);
|
||
}
|
||
|
||
// 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;
|
||
Offset toTarget(Offset screen) => screen / scale;
|
||
final i = _selected;
|
||
final picked = i == null || i >= _hits.length ? null : TargetScoring.shown(_hits[i]) * scale;
|
||
return Center(
|
||
child: SizedBox.square(
|
||
dimension: side,
|
||
child: GestureDetector(
|
||
behavior: HitTestBehavior.opaque,
|
||
onTapUp: (d) => _pickAt(toTarget(d.localPosition)),
|
||
onPanStart: (d) {
|
||
// Starting on another hit picks that one
|
||
final near = _nearest(toTarget(d.localPosition));
|
||
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 = (TargetScoring.shown(_hits[i]) - p).distance; // where it is drawn
|
||
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)),
|
||
),
|
||
);
|
||
}
|
||
}
|