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

411 lines
13 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:io';
import 'package:flutter/foundation.dart' show kDebugMode;
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../services/app_settings.dart';
import '../services/target_repository.dart';
import '../theme/app_theme.dart';
import '../utils/format.dart';
import '../widgets/bar_list.dart';
import '../widgets/result_share.dart';
import '../widgets/target_face.dart';
import '../widgets/ui.dart';
import 'session_screen.dart' show targetCount, shotCount, confirmDelete;
/// The result of one target, or of a whole session on one target
/// ([isCombinedView]): the score, the target with every hit, the hits grouped
/// by value, sharing, and for a session a bar chart of its targets.
class TargetViewScreen extends StatefulWidget {
final List<File> jsonFiles;
final Function refreshFolders;
final bool isCombinedView;
const TargetViewScreen({
super.key,
required this.jsonFiles,
required this.refreshFolders,
this.isCombinedView = false,
});
@override
State<TargetViewScreen> createState() => _TargetViewScreenState();
}
class _TargetViewScreenState extends State<TargetViewScreen> {
List<TargetHits>? _targets; // one per file, in the order given
TargetHits _all = TargetHits.empty;
int? _number; // 1-based number of a single target in its session
DateTime? _date;
int? _pressedValue; // tile held down: its hits are highlighted
bool _showChart = false;
bool _showScoring = false; // debug builds: long press the target
final _zoom = TransformationController();
String get _folder => widget.jsonFiles.first.parent.path.split('/').last;
@override
void initState() {
super.initState();
_load();
}
@override
void dispose() {
_zoom.dispose();
super.dispose();
}
Future<void> _load() async {
final targets = await TargetRepository.readAllHits(widget.jsonFiles);
int? number;
DateTime? date;
final sessions = await TargetRepository.loadSessions();
final session = sessions.where((x) => x.name == _folder).firstOrNull;
if (session != null) {
date = session.date;
if (!widget.isCombinedView) {
final i = session.targets
.indexWhere((t) => t.file.path == widget.jsonFiles.first.path);
if (i >= 0) {
number = i + 1;
date = session.targets[i].shotAt;
}
}
}
date ??= _parseDate(targets.isEmpty ? '' : targets.last.date);
if (!mounted) return;
setState(() {
_targets = targets;
_all = TargetHits.combine(targets);
_number = number;
_date = date;
});
}
// Saved targets store dd/MM/yyyy
static DateTime? _parseDate(String raw) {
final p = raw.split('/');
if (p.length != 3) return null;
return DateTime.tryParse(
'${p[2]}-${p[1].padLeft(2, '0')}-${p[0].padLeft(2, '0')}');
}
Future<void> _deleteTarget() async {
final s = AppSettings.instance;
final ok = await confirmDelete(context, s.t('Are you sure you want to delete this target?'));
if (!ok) return;
try {
await File(widget.jsonFiles.first.path).delete();
TargetRepository.notifyChanged();
widget.refreshFolders();
if (mounted) Navigator.pop(context);
} catch (e) {
debugPrint('Error deleting target: $e');
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(s.t('Failed to delete target'))));
}
}
// Values shown as tiles: 10 down to 7 always (so a missing 10 shows as 0×),
// plus any lower value that was hit; at most 6 tiles.
List<(int value, int count)> _groups() {
final counts = <int, int>{};
for (final v in _all.scores) {
counts[v] = (counts[v] ?? 0) + 1;
}
final values = {10, 9, 8, 7, ...counts.keys}.toList()
..sort((a, b) => b.compareTo(a));
return [for (final v in values.take(6)) (v, counts[v] ?? 0)];
}
String get _title => widget.isCombinedView
? _folder
: '${AppSettings.instance.t('Target')} ${_number ?? ''}'.trim();
String _subtitle(AppSettings s) {
final date = _date;
if (widget.isCombinedView) {
return [
if (date != null) dayDate(date, year: true),
targetCount(widget.jsonFiles.length),
shotCount(_all.shots),
].join(' · ');
}
return [_folder, if (date != null) DateFormat('d. M. yyyy').format(date)]
.join(' · ');
}
void _share() {
final s = AppSettings.instance;
final targets = _targets;
if (targets == null) return;
final best = targets.isEmpty
? 0
: targets.map((t) => t.total).reduce((a, b) => a > b ? a : b);
shareResult(
context,
ResultShareData(
title: _title,
subtitle: _subtitle(s),
total: _all.total,
averagePerShot: _all.shots == 0 ? null : _all.total / _all.shots,
style: s.target,
hits: _all.bullets,
tiles: widget.isCombinedView
? [for (final (v, n) in _groups()) ('$n×', '$v', n > 0)]
: [
for (final v in [
..._all.scores
]..sort((a, b) => b.compareTo(a)))
(null, '$v', true),
],
chartTitle:
s.t(widget.isCombinedView ? 'Points per target' : 'Hits by value'),
bars: widget.isCombinedView
? [
for (int i = 0; i < targets.length; i++)
BarEntry('T${i + 1}', targets[i].total.toDouble(),
'${targets[i].total}',
highlight: targets[i].total == best),
]
: [
for (final v in [10, 9, 8, 7, 6])
BarEntry(
'$v',
_all.scores.where((x) => x == v).length.toDouble(),
'${_all.scores.where((x) => x == v).length}×',
highlight: v == 10,
goldLabel: v == 10),
],
barMax: widget.isCombinedView
? _perTargetMax(targets)
: _all.shots.toDouble().clamp(1, 1000),
t: s.t,
),
);
}
// Top of the per-target chart: the most a target of this session can score
double _perTargetMax(List<TargetHits> targets) {
final shots = targets.isEmpty
? 5
: targets.map((t) => t.shots).reduce((a, b) => a > b ? a : b);
return (shots * 10).toDouble().clamp(10, 1000);
}
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: AppSettings.instance,
builder: (context, _) {
final s = AppSettings.instance;
final c = Palette.current;
final loaded = _targets != null;
return Scaffold(
body: Column(
children: [
BackHeader(
title: loaded ? _title : '',
subtitle: loaded ? _subtitle(s) : null,
centered: true),
if (!loaded)
const Expanded(
child: Center(child: CircularProgressIndicator()))
else ...[
_scoreRow(s, c),
Expanded(child: _showChart ? _chart(s, c) : _target(s)),
if (!_showChart) _tiles(c),
_actions(s, c),
],
],
),
);
},
);
}
Widget _scoreRow(AppSettings s, Palette c) {
final avg = _all.shots == 0 ? null : _all.total / _all.shots;
return Padding(
padding: const EdgeInsets.fromLTRB(AppTheme.edge, 12, AppTheme.edge, 0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text('${_all.total}',
style: TextStyle(
fontSize: 56,
height: 1,
fontWeight: FontWeight.w800,
letterSpacing: -1.5,
color: c.ink,
fontFeatures: AppTheme.tnum)),
const SizedBox(width: 8),
Padding(
padding: const EdgeInsets.only(bottom: 6),
child: Text(
widget.isCombinedView
? s.t('total').toLowerCase()
: '/ ${_all.shots * 10}',
style: TextStyle(
fontSize: widget.isCombinedView ? 15 : 20,
fontWeight: FontWeight.w600,
color: c.muted),
),
),
const Spacer(),
if (avg != null)
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(dec(avg),
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w700,
color: c.ink,
fontFeatures: AppTheme.tnum)),
Text(s.t('per shot'),
style: TextStyle(fontSize: 12, color: c.muted)),
],
),
],
),
);
}
// The target fills the free space; pinch to zoom in (the default target is
// vectors, so its lines stay sharp), double tap to zoom back out.
Widget _target(AppSettings s) {
final pressed = _pressedValue;
final scores = _all.scores;
return GestureDetector(
onDoubleTap: () => _zoom.value = Matrix4.identity(),
child: InteractiveViewer(
transformationController: _zoom,
minScale: 1,
maxScale: 6,
child: Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 8),
// Debug builds only: long press shows the scoring radii over the design
child: GestureDetector(
onLongPress: kDebugMode
? () => setState(() => _showScoring = !_showScoring)
: null,
child: TargetFace(
style: s.target,
hits: _all.bullets,
hitColor: s.bulletColor,
showScoring: _showScoring,
highlighted: pressed == null
? const {}
: {
for (int i = 0; i < scores.length; i++)
if (scores[i] == pressed) i
},
),
),
),
),
),
);
}
Widget _tiles(Palette c) {
final groups = _groups();
return Padding(
padding: const EdgeInsets.fromLTRB(AppTheme.edge, 8, AppTheme.edge, 0),
child: Row(
children: [
for (int i = 0; i < groups.length; i++) ...[
if (i > 0) const SizedBox(width: 10),
Expanded(
child: ScoreTile(
top: '${groups[i].$2}×',
value: '${groups[i].$1}',
filled: groups[i].$2 > 0,
height: 64,
onTapDown: groups[i].$2 == 0
? null
: (_) => setState(() => _pressedValue = groups[i].$1),
onTapEnd: () => setState(() => _pressedValue = null),
),
),
],
],
),
);
}
Widget _chart(AppSettings s, Palette c) {
final targets = _targets!;
final best = targets.isEmpty
? 0
: targets.map((t) => t.total).reduce((a, b) => a > b ? a : b);
final max = _perTargetMax(targets);
return Padding(
padding: const EdgeInsets.fromLTRB(AppTheme.edge, 16, AppTheme.edge, 0),
child: AppCard(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Kicker(s.t('Points per target'),
padding: const EdgeInsets.only(bottom: 14)),
Expanded(
child: BarList(
entries: [
for (int i = 0; i < targets.length; i++)
BarEntry('T${i + 1}', targets[i].total.toDouble(),
'${targets[i].total}',
highlight: targets[i].total == best),
],
max: max,
ticks: [0, max / 2, max],
),
),
const SizedBox(height: 8),
Text(s.t('Gold = best target of the session'),
style: TextStyle(fontSize: 11.5, color: c.muted)),
],
),
),
);
}
Widget _actions(AppSettings s, Palette c) {
return Padding(
padding: EdgeInsets.fromLTRB(AppTheme.edge, 16, AppTheme.edge,
12 + MediaQuery.paddingOf(context).bottom),
child: Row(
children: [
Expanded(
child: PrimaryButton(
label: s.t('Share result'),
icon: Icons.share_outlined,
onTap: _share)),
const SizedBox(width: 10),
if (widget.isCombinedView)
SquareButton(
size: 52,
icon: _showChart ? Icons.image_outlined : Icons.bar_chart_rounded,
tooltip: s.t(_showChart ? 'Target' : 'Chart'),
onTap: () => setState(() => _showChart = !_showChart),
)
else
// The combined view shows a whole session; deleting would remove an
// arbitrary one of its targets. Sessions are deleted from Knjiga.
SquareButton(
size: 52,
icon: Icons.delete_outline_rounded,
color: c.red,
background: c.redSoft,
tooltip: s.t('Delete'),
onTap: _deleteTarget,
),
],
),
);
}
}