485 lines
16 KiB
Dart
485 lines
16 KiB
Dart
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 'preview_screen.dart';
|
||
import 'session_screen.dart' show SessionScreen, 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> {
|
||
// The targets shown; deleting some from the session list shortens it
|
||
late List<File> _files = widget.jsonFiles;
|
||
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 => _files.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(_files);
|
||
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 == _files.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')}');
|
||
}
|
||
|
||
// The editor of "Check hits" on this target's hits; saving overwrites the
|
||
// file, then the result is read again
|
||
Future<void> _editTarget() async {
|
||
final target = _targets?.firstOrNull;
|
||
if (target == null) return;
|
||
final saved = await Navigator.push<bool>(
|
||
context,
|
||
MaterialPageRoute(
|
||
builder: (_) => PreviewScreen.edit(
|
||
file: _files.first,
|
||
hits: target.bullets,
|
||
bulletCount: target.shots < target.bullets.length ? target.bullets.length : target.shots,
|
||
),
|
||
),
|
||
);
|
||
if (saved != true || !mounted) return;
|
||
await _load();
|
||
widget.refreshFolders();
|
||
}
|
||
|
||
// Session view: its training or tournament, to see, edit and delete each
|
||
// target; back here, what is left of it is shown again
|
||
Future<void> _openSession() async {
|
||
final sessions = await TargetRepository.loadSessions();
|
||
final session = sessions.where((x) => x.name == _folder).firstOrNull;
|
||
if (session == null || !mounted) return;
|
||
await Navigator.push(context, MaterialPageRoute(builder: (_) => SessionScreen(session: session)));
|
||
if (!mounted) return;
|
||
widget.refreshFolders();
|
||
final left = [for (final f in _files) if (f.existsSync()) f];
|
||
if (left.isEmpty) {
|
||
Navigator.pop(context); // every target was deleted
|
||
return;
|
||
}
|
||
_files = left;
|
||
await _load();
|
||
}
|
||
|
||
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(_files.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'))));
|
||
}
|
||
}
|
||
|
||
// Every value from 10 down to 0
|
||
static const List<int> _values = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0];
|
||
|
||
// Only the values that were hit, best first: a tile each
|
||
List<(int value, int count)> _groups() {
|
||
final counts = <int, int>{};
|
||
for (final v in _all.scores) {
|
||
counts[v] = (counts[v] ?? 0) + 1;
|
||
}
|
||
return [for (final v in _values) if (counts[v] != null) (v, counts[v]!)];
|
||
}
|
||
|
||
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(_files.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 _groups())
|
||
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;
|
||
// The picked target's own background (a holiday's wins)
|
||
return AppBackground(
|
||
target: true,
|
||
child: Scaffold(
|
||
body: Stack(
|
||
children: [
|
||
// The target, zoomed or not, lives in the window the background
|
||
// draws for it: between its score line and its dock line
|
||
if (loaded && !_showChart) TargetWindow(child: _target(s)),
|
||
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) : const SizedBox()),
|
||
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 its window; 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
|
||
},
|
||
// The rest fade while a value is held, so its hits stand out
|
||
dimmed: pressed == null
|
||
? const {}
|
||
: {
|
||
for (int i = 0; i < scores.length; i++)
|
||
if (scores[i] != pressed) i
|
||
},
|
||
),
|
||
),
|
||
),
|
||
),
|
||
),
|
||
);
|
||
}
|
||
|
||
Widget _tiles(Palette c) {
|
||
final groups = _groups();
|
||
final many = groups.length > 6;
|
||
return Padding(
|
||
padding: const EdgeInsets.fromLTRB(AppTheme.edge, 8, AppTheme.edge, 0),
|
||
child: TileRow(
|
||
gap: many ? 4 : 10,
|
||
children: [
|
||
for (final (value, count) in groups)
|
||
ScoreTile(
|
||
top: '$count×',
|
||
value: '$value',
|
||
height: many ? 56 : 64,
|
||
radius: many ? 10 : 14,
|
||
onTapDown: (_) => setState(() => _pressedValue = value),
|
||
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: [
|
||
// A single target: delete on the left, out of the thumb's easy
|
||
// reach, and correcting its hits on the right. A session: its
|
||
// target list on the left (to see, edit and delete each one) and
|
||
// the chart toggle on the right. The combined view has no delete:
|
||
// it would remove an arbitrary one of its targets; sessions are
|
||
// deleted from Knjiga.
|
||
if (widget.isCombinedView)
|
||
SquareButton(
|
||
size: 52,
|
||
icon: Icons.edit_outlined,
|
||
tooltip: s.t('Edit'),
|
||
onTap: _openSession,
|
||
)
|
||
else
|
||
SquareButton(
|
||
size: 52,
|
||
icon: Icons.delete_outline_rounded,
|
||
color: c.red,
|
||
background: c.redSoft,
|
||
tooltip: s.t('Delete'),
|
||
onTap: _deleteTarget,
|
||
),
|
||
const SizedBox(width: 10),
|
||
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
|
||
SquareButton(
|
||
size: 52,
|
||
icon: Icons.edit_outlined,
|
||
tooltip: s.t('Edit target'),
|
||
onTap: _editTarget,
|
||
),
|
||
],
|
||
),
|
||
);
|
||
}
|
||
}
|