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

288 lines
10 KiB
Dart

import 'package:flutter/material.dart';
import '../services/app_settings.dart';
import '../services/target_repository.dart';
import '../theme/app_theme.dart';
import '../utils/format.dart';
import '../widgets/target_face.dart';
import '../widgets/ui.dart';
import 'camera_settings_screen.dart';
import 'session_screen.dart' show targetCount;
import 'spectator_screen.dart';
import 'stream_screen.dart';
import 'target_view.dart';
/// Streljanje: where we shoot today (location), one tile per position at that
/// location, and the last session underneath.
class TargetScreen extends StatefulWidget {
const TargetScreen({super.key});
@override
State<TargetScreen> createState() => _TargetScreenState();
}
class _TargetScreenState extends State<TargetScreen> {
Session? _last;
Session? _previous; // the one before it of the same kind, for the difference
TargetHits? _lastHits;
@override
void initState() {
super.initState();
TargetRepository.changed.addListener(_load);
_load();
}
@override
void dispose() {
TargetRepository.changed.removeListener(_load);
super.dispose();
}
Future<void> _load() async {
final sessions = (await TargetRepository.loadSessions()).where((x) => x.targets.isNotEmpty).toList();
if (sessions.isEmpty) {
if (mounted) setState(() => _last = null);
return;
}
final last = sessions.first;
final previous = sessions.skip(1).where((x) => x.isTournament == last.isTournament).firstOrNull;
final hits = TargetHits.combine(await TargetRepository.readAllHits(last.files));
if (!mounted) return;
setState(() {
_last = last;
_previous = previous;
_lastHits = hits;
});
}
String? _location(AppSettings s) {
final locations = s.cameras.locations;
if (locations.isEmpty) return null;
final active = s.cameras.activeLocation;
return locations.contains(active) ? active : locations.first;
}
void _openPosition(int position) {
final s = AppSettings.instance;
final location = _location(s);
final ip = location == null ? '' : s.cameras.ipFor(position, location);
if (location == null || ip.isEmpty) {
Navigator.push(context, MaterialPageRoute(builder: (_) => const CameraSettingsScreen()));
return;
}
Navigator.push(
context,
MaterialPageRoute(builder: (_) => CameraStreamScreen(cameraIndex: position, ip: ip, location: location)),
);
}
void _openLast() {
final last = _last;
if (last == null) return;
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => TargetViewScreen(jsonFiles: last.files, refreshFolders: _load, isCombinedView: true),
),
);
}
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: AppSettings.instance,
builder: (context, _) {
final s = AppSettings.instance;
final c = Palette.current;
final setup = s.cameras;
final location = _location(s);
// The tiles grow to fill the screen down to the bottom bar; on a
// small screen they keep their minimum height and the page scrolls
return CustomScrollView(
slivers: [
SliverToBoxAdapter(
child: PageHeader(
title: s.t('Shooting'),
subtitle: s.t('Where are we shooting today?'),
action: CircleButton(
icon: Icons.visibility_outlined,
tooltip: s.t('Spectate'),
onTap: () => Navigator.push(
context,
MaterialPageRoute(builder: (_) => SpectatorScreen(selectedLanguage: s.language)),
),
),
),
),
SliverFillRemaining(
hasScrollBody: false,
child: Padding(
padding: const EdgeInsets.fromLTRB(AppTheme.edge, 4, AppTheme.edge, 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (setup.locations.length > 1) ...[
_locations(s, location),
const SizedBox(height: 16),
],
Expanded(child: _grid(s, c, location)),
if (_last != null) ...[
const SizedBox(height: 12),
_lastCard(s, c, _last!),
],
],
),
),
),
],
);
},
);
}
Widget _locations(AppSettings s, String? active) {
final locations = s.cameras.locations;
IconData icon(String l) => l == s.cameras.clubLocation ? Icons.place_outlined : Icons.home_outlined;
if (locations.length <= 3) {
return SegmentedTabs(
items: [for (final l in locations) SegmentItem(l, icon(l))],
selected: locations.indexOf(active ?? locations.first),
onSelect: (i) => s.setActiveLocation(locations[i]),
);
}
return SizedBox(
height: 36,
child: ListView.separated(
scrollDirection: Axis.horizontal,
itemCount: locations.length,
separatorBuilder: (_, __) => const SizedBox(width: 8),
itemBuilder: (_, i) => ChoicePill(
label: locations[i],
height: 36,
selected: locations[i] == active,
onTap: () => s.setActiveLocation(locations[i]),
),
),
);
}
// Two tiles per row; every row shares the height equally (at least 104)
Widget _grid(AppSettings s, Palette c, String? location) {
final positions = s.cameras.positions;
bool ready(int p) => location != null && s.cameras.ipFor(p, location).isNotEmpty;
return Column(
children: [
for (int p = 1; p <= positions; p += 2) ...[
if (p > 1) const SizedBox(height: 12),
Expanded(
child: ConstrainedBox(
constraints: const BoxConstraints(minHeight: 104),
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(child: _cameraTile(s, c, p, ready(p))),
const SizedBox(width: 12),
Expanded(child: p + 1 <= positions ? _cameraTile(s, c, p + 1, ready(p + 1)) : const SizedBox()),
],
),
),
),
],
],
);
}
// A ready camera: the hit colour over the whole tile, a solid icon and the
// name in one colour. One not set up is dashed.
Widget _cameraTile(AppSettings s, Palette c, int position, bool ready) {
final name = '${s.t('Camera')} $position';
final fill = c.accent;
final fg = ready ? Palette.onColor(fill) : c.ink2;
final content = Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ready
? Icon(Icons.videocam_rounded, size: 36, color: fg)
: Container(
width: 48,
height: 48,
decoration: BoxDecoration(color: c.tile, borderRadius: BorderRadius.circular(14)),
child: Icon(Icons.add_rounded, size: 26, color: c.muted),
),
const SizedBox(height: 8),
Text(name, textAlign: TextAlign.center, style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: fg)),
if (!ready)
Text(s.t('Not set up'), textAlign: TextAlign.center, style: TextStyle(fontSize: 11.5, color: c.faint)),
],
),
);
return AppCard(
dashed: !ready,
color: ready ? fill : null,
borderColor: ready ? fill : null,
padding: const EdgeInsets.all(10),
onTap: () => _openPosition(position),
child: content,
);
}
Widget _lastCard(AppSettings s, Palette c, Session last) {
final avg = last.averagePerShot;
final prevAvg = _previous?.averagePerShot;
final delta = avg == null || prevAvg == null ? null : avg - prevAvg;
final date = dayDate(last.date);
return AppCard(
padding: const EdgeInsets.fromLTRB(12, 14, 16, 14),
onTap: _openLast,
child: Row(
children: [
SizedBox.square(
dimension: 72,
child: TargetFace(
style: s.target,
hits: _lastHits?.bullets ?? const [],
hitColor: s.bulletColor,
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(s.t('Last session').toUpperCase(), style: AppTheme.kicker(c).copyWith(fontSize: 10)),
const SizedBox(height: 3),
Text(last.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 17, fontWeight: FontWeight.w700, color: c.ink)),
const SizedBox(height: 2),
Text('$date · ${targetCount(last.targets.length)}',
maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 12, color: c.muted)),
const SizedBox(height: 6),
last.isTournament
? StatusChip(label: s.t('Tournament'), icon: Icons.emoji_events_outlined, color: c.gold, background: c.goldSoft)
: StatusChip(label: s.t('Training'), icon: Icons.track_changes_rounded, color: c.accentInk, background: c.accentSoft),
],
),
),
const SizedBox(width: 8),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text('${last.totalScore}',
style: TextStyle(fontSize: 26, fontWeight: FontWeight.w800, color: c.ink, fontFeatures: AppTheme.tnum)),
if (avg != null)
Text('${dec(avg)} ${s.t('per shot')}', style: TextStyle(fontSize: 12, color: c.muted)),
if (delta != null)
Text('${delta >= 0 ? '▲' : '▼'} ${dec(delta.abs())}',
style: TextStyle(fontSize: 12, fontWeight: FontWeight.w700, color: c.delta(delta))),
],
),
],
),
);
}
}