UI fixes and league

This commit is contained in:
Jan Pleterski
2026-11-28 12:22:02 +01:00
parent 2fc741a9f6
commit 258303deb8
118 changed files with 1439 additions and 537 deletions
+207 -109
View File
@@ -20,12 +20,27 @@ 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 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 this.imagePath, required this.detections, required this.bulletCount});
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();
@@ -68,7 +83,11 @@ class _PreviewScreenState extends State<PreviewScreen> {
}
Future<void> _load() async {
await Future.wait([_loadFolders(), _runDetectionAndMapping()]);
if (widget.isEdit) {
_hits = [...widget.initialHits];
} else {
await Future.wait([_loadFolders(), _runDetectionAndMapping()]);
}
if (mounted) setState(() => _isLoading = false);
}
@@ -106,7 +125,7 @@ class _PreviewScreenState extends State<PreviewScreen> {
Future<void> _runDetectionAndMapping() async {
try {
final bytes = await File(widget.imagePath).readAsBytes();
final bytes = await File(widget.imagePath!).readAsBytes();
_photo = bytes;
_photoSize = await _imageSize(bytes);
@@ -232,9 +251,8 @@ class _PreviewScreenState extends State<PreviewScreen> {
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));
// Keep it within the target's square
_hits[i] = TargetScoring.shown(_hits[i] + delta);
});
}
@@ -285,7 +303,30 @@ class _PreviewScreenState extends State<PreviewScreen> {
});
}
// 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);
@@ -327,8 +368,8 @@ class _PreviewScreenState extends State<PreviewScreen> {
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.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.'),
]);
}
@@ -338,77 +379,118 @@ class _PreviewScreenState extends State<PreviewScreen> {
final s = AppSettings.instance;
final c = Palette.current;
final found = widget.detections.where((r) => r.classId == 0).length;
return Scaffold(
body: Column(
// 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: [
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(
if (!_isLoading)
TargetWindow(
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),
// 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),
),
),
),
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(AppTheme.edge, 0, AppTheme.edge, 0),
child: _tiles(c),
// 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)),
]);
}),
),
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,
),
),
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);
},
),
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,
),
),
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,
),
],
),
);
@@ -423,48 +505,63 @@ class _PreviewScreenState extends State<PreviewScreen> {
: 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 ?? '',
// 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: 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),
],
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),
),
],
),
),
],
);
}),
),
);
}
@@ -475,17 +572,18 @@ class _PreviewScreenState extends State<PreviewScreen> {
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 : _hits[i] * scale;
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(d.localPosition / scale),
onTapUp: (d) => _pickAt(toTarget(d.localPosition)),
onPanStart: (d) {
// Starting on another hit picks that one
final near = _nearest(d.localPosition / scale);
final near = _nearest(toTarget(d.localPosition));
if (near != null) _selected = near;
if (_selected == null) return;
HapticFeedback.selectionClick();
@@ -544,7 +642,7 @@ class _PreviewScreenState extends State<PreviewScreen> {
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;
final d = (TargetScoring.shown(_hits[i]) - p).distance; // where it is drawn
if (d < bestD) {
bestD = d;
best = i;