new UI + new targets.

This commit is contained in:
Jan Pleterski
2026-11-27 14:37:44 +01:00
parent 5f9e2a3b86
commit 2fc741a9f6
113 changed files with 6861 additions and 7381 deletions
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+265 -245
View File
@@ -7,11 +7,12 @@ import 'package:camera/camera.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'yolo_detector.dart';
import 'preview_screen.dart';
import '../utils/translations.dart';
import '../utils/target_colors.dart';
import '../theme/app_theme.dart';
import '../utils/format.dart';
import '../services/app_settings.dart';
import '../widgets/camera_sheet.dart';
import '../widgets/help_sheet.dart';
import '../widgets/ui.dart';
class CameraScreen extends StatefulWidget {
const CameraScreen({super.key});
@@ -25,12 +26,9 @@ class _CameraScreenState extends State<CameraScreen> {
Future<void>? _initializeControllerFuture;
YOLODetector? _yoloDetector; // null until the model has loaded
bool _processing = false; // a photo is being analysed
Color _bulletColor = Colors.blue; // default fallback
// The variable to hold the number of bullets entered by the user (default set to 5)
int _numberOfBullets = 5;
String _selectedLanguage = 'English';
late Color _backgroundColor;
// Real camera controls (they change the photo itself)
double _exposure = 0, _minExposure = 0, _maxExposure = 0;
@@ -40,13 +38,8 @@ class _CameraScreenState extends State<CameraScreen> {
@override
void initState() {
super.initState();
// Initialize with default target background color
_backgroundColor = TargetColors.getBackgroundColor('assets/target.png');
_loadBulletCount();
_initCamera();
_loadBulletColor(); // 👈
_loadLanguage();
_loadSelectedTargetColor();
YOLODetector.create().then((detector) {
if (mounted) {
_yoloDetector = detector;
@@ -56,70 +49,7 @@ class _CameraScreenState extends State<CameraScreen> {
});
}
String _t(String key) {
return AppTranslations.translate(key, _selectedLanguage);
}
Future<void> _loadLanguage() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
_selectedLanguage = prefs.getString('language') ?? 'Slovenian';
});
}
Future<void> _loadSelectedTargetColor() async {
final prefs = await SharedPreferences.getInstance();
final selectedTarget =
prefs.getString('selectedTarget') ?? 'assets/target.png';
setState(() {
_backgroundColor = TargetColors.getBackgroundColor(selectedTarget);
});
}
Future<void> _loadBulletColor() async {
final prefs = await SharedPreferences.getInstance();
final selected = prefs.getString('bulletColor') ?? 'Blue';
setState(() {
_bulletColor = _getColorFromName(selected);
});
}
Color _getColorFromName(String colorName) {
switch (colorName.toLowerCase()) {
case 'blue':
return Colors.blue;
case 'green':
return Colors.green;
case 'yellow':
return Colors.yellow;
case 'purple':
return Colors.purple;
case 'cyan':
return Colors.cyan;
case 'teal':
return Colors.teal;
case 'indigo':
return Colors.indigo;
case 'pink':
return Colors.pink;
case 'lime':
return Colors.lime;
case 'mint':
return Colors.greenAccent;
case 'orange':
return Colors.orange;
case 'violet':
return Colors.deepPurpleAccent;
case 'amber':
return Colors.amber;
case 'brown':
return Colors.brown;
case 'grey':
return Colors.grey;
default:
return Colors.blue; // fallback
}
}
String _t(String key) => AppSettings.instance.t(key);
Future<void> _loadBulletCount() async {
final prefs = await SharedPreferences.getInstance();
@@ -191,6 +121,8 @@ class _CameraScreenState extends State<CameraScreen> {
if (!kReleaseMode) await _compareWithDartDecoder(detector, bytes, detections);
if (!mounted) return;
// The check screen follows the app theme; the camera is dark again after it
AppSettings.instance.releaseDark();
await Navigator.push(
context,
MaterialPageRoute(
@@ -201,6 +133,7 @@ class _CameraScreenState extends State<CameraScreen> {
),
),
);
AppSettings.instance.holdDark();
} catch (e) {
debugPrint('Error taking picture: $e');
} finally {
@@ -237,22 +170,25 @@ class _CameraScreenState extends State<CameraScreen> {
builder: (sheet) => StatefulBuilder(
builder: (context, setSheetState) => Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
CameraSheetHeader(
title: _t('Select the number of bullets'),
subtitle:
'${AppSettings.minBullets} – ${AppSettings.maxBullets}'),
subtitle: _t('{a}–{b} shots per target')
.replaceAll('{a}', '${AppSettings.minBullets}')
.replaceAll('{b}', '${AppSettings.maxBullets}')),
SheetStepper(
value: _numberOfBullets,
min: AppSettings.minBullets,
max: AppSettings.maxBullets,
accent: _bulletColor,
onChanged: (n) {
_selectBulletCount(n);
setSheetState(() {});
},
),
const SizedBox(height: 8),
const SizedBox(height: 14),
Text(_t('Statistics in the Book only compare targets with the same number of shots.'),
style: TextStyle(fontSize: 12, color: Palette.current.muted)),
],
),
),
@@ -260,42 +196,49 @@ class _CameraScreenState extends State<CameraScreen> {
}
void _showHelpDialog() {
showHelpSheet(context, accent: _bulletColor, t: _t, items: const [
(Icons.crop_square, 'Align the target inside the square frame.'),
(
Icons.camera_alt,
'Camera button: take a photo. Bullets are detected and you can check and save the result.'
),
(Icons.filter_5_rounded, 'Number bottom left: shots per target (1–5).'),
(Icons.tune, 'Settings icon: exposure, zoom and flashlight.'),
showHelpSheet(context, t: _t, clearBarrier: true, items: const [
(Icons.center_focus_strong_outlined, 'Align the target inside the square frame.'),
(Icons.photo_camera_outlined, 'Camera button: take a photo. Bullets are detected and you can check and save the result.'),
(Icons.grid_view_rounded, 'Number bottom left: shots per target (1–5).'),
(Icons.tune_rounded, 'Settings icon: exposure, zoom and flashlight.'),
]);
}
Future<void> _applyCamera(VoidCallback change, Future<void> Function() camera) async {
setState(change);
try {
await camera();
} catch (_) {} // control not supported on this phone
}
void _setZoom(double z) =>
_applyCamera(() => _zoom = z.clamp(_minZoom, _maxZoom), () => _controller!.setZoomLevel(_zoom));
void _toggleTorch() => _applyCamera(
() => _torch = !_torch,
() => _controller!.setFlashMode(_torch ? FlashMode.torch : FlashMode.off),
);
void _showCameraControls() {
showCameraSheet(
context,
builder: (sheet) => StatefulBuilder(
builder: (context, setSheetState) {
Future<void> apply(
VoidCallback change, Future<void> Function() camera) async {
setState(change);
Future<void> apply(VoidCallback change, Future<void> Function() camera) async {
await _applyCamera(change, camera);
setSheetState(() {});
try {
await camera();
} catch (_) {} // control not supported on this phone
}
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
CameraSheetHeader(
title: _t('Image Settings'),
trailing: TextButton.icon(
style: TextButton.styleFrom(foregroundColor: Colors.white70),
icon: const Icon(Icons.restart_alt_rounded, size: 18),
label: Text(_t('Reset')),
onPressed: () => apply(() {
title: _t('Camera settings'),
subtitle: _t('Exposure, zoom and flashlight'),
trailing: ResetPill(
label: _t('Reset'),
onTap: () => apply(() {
_exposure = 0;
_zoom = _minZoom;
}, () async {
@@ -306,45 +249,33 @@ class _CameraScreenState extends State<CameraScreen> {
),
if (_maxExposure > _minExposure)
SheetSlider(
icon: Icons.exposure_rounded,
icon: Icons.light_mode_outlined,
label: _t('Exposure'),
valueText:
'${_exposure >= 0 ? '+' : ''}${_exposure.toStringAsFixed(1)}',
valueText: '${_exposure >= 0 ? '+' : '−'}${dec(_exposure.abs(), 1)}',
value: _exposure,
min: _minExposure,
max: _maxExposure,
accent: _bulletColor,
onChanged: (v) => apply(() => _exposure = v,
() => _controller!.setExposureOffset(v)),
onChanged: (v) => apply(() => _exposure = v, () => _controller!.setExposureOffset(v)),
),
if (_maxZoom > _minZoom)
SheetSlider(
icon: Icons.zoom_in_rounded,
label: _t('Zoom'),
valueText: '${_zoom.toStringAsFixed(1)}×',
valueText: '${dec(_zoom, 1)}×',
value: _zoom,
min: _minZoom,
max: _maxZoom,
accent: _bulletColor,
onChanged: (v) => apply(
() => _zoom = v, () => _controller!.setZoomLevel(v)),
onChanged: (v) => apply(() => _zoom = v, () => _controller!.setZoomLevel(v)),
),
const SizedBox(height: 8),
SizedBox(
width: double.infinity,
child: SheetToggle(
icon: _torch
? Icons.flashlight_on_rounded
: Icons.flashlight_off_rounded,
label: _t('Flashlight'),
active: _torch,
accent: _bulletColor,
onTap: () => apply(
() => _torch = !_torch,
() => _controller!
.setFlashMode(_torch ? FlashMode.torch : FlashMode.off),
),
),
SheetToggle(
icon: Icons.flashlight_on_outlined,
label: _t('Flashlight'),
active: _torch,
onTap: () async {
_toggleTorch();
setSheetState(() {});
},
),
],
);
@@ -362,137 +293,226 @@ class _CameraScreenState extends State<CameraScreen> {
@override
Widget build(BuildContext context) {
if (_controller == null || _initializeControllerFuture == null) {
return const Scaffold(
body: Center(child: CircularProgressIndicator()),
);
}
final c = Palette.current;
final ready = _controller != null && _initializeControllerFuture != null;
return Scaffold(
backgroundColor: _backgroundColor,
extendBody: true,
appBar: AppBar(
backgroundColor: Colors.grey[900],
title: Text(
_t("Align the target inside the square"),
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.white,
backgroundColor: Colors.black,
body: Column(
children: [
// Header: back, the instruction in a pill, help
Padding(
padding: EdgeInsets.fromLTRB(12, MediaQuery.paddingOf(context).top + 8, 12, 8),
child: Row(
children: [
CircleButton(icon: Icons.chevron_left_rounded, iconSize: 26, onTap: () => Navigator.pop(context)),
const SizedBox(width: 10),
Expanded(
child: Container(
height: 40,
alignment: Alignment.center,
padding: const EdgeInsets.symmetric(horizontal: 14),
decoration: BoxDecoration(color: c.tile, borderRadius: BorderRadius.circular(20)),
child: Text(
_t('Align the target inside the square'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: c.ink),
),
),
),
const SizedBox(width: 10),
CircleButton(icon: Icons.info_outline_rounded, onTap: _showHelpDialog),
],
),
),
),
leading: IconButton(
icon: const Icon(Icons.arrow_back, color: Colors.white),
onPressed: () => Navigator.pop(context),
),
centerTitle: true,
actions: [
IconButton(
icon: const Icon(Icons.info_outline_rounded, color: Colors.white),
onPressed: _showHelpDialog,
Expanded(
child: !ready
? const Center(child: CircularProgressIndicator())
: FutureBuilder(
future: _initializeControllerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const Center(child: CircularProgressIndicator());
}
return LayoutBuilder(builder: (context, box) {
// Same square as before: 90 % of the screen width, centred
final side = MediaQuery.sizeOf(context).width * 0.9;
return Stack(
fit: StackFit.expand,
children: [
ClipRect(
child: FittedBox(
fit: BoxFit.cover,
child: SizedBox(
width: _controller!.value.previewSize!.height,
height: _controller!.value.previewSize!.width,
child: CameraPreview(_controller!),
),
),
),
IgnorePointer(child: CustomPaint(painter: _FramePainter(side: side, color: c.accent))),
Positioned(
left: 0,
right: 0,
bottom: 18,
child: Center(child: _processing ? _searchingPill(c) : _zoomChips(c)),
),
],
);
});
},
),
),
// Bottom bar: shots per target, shutter, flashlight, settings
Container(
color: c.bg,
padding: EdgeInsets.fromLTRB(20, 18, 20, 18 + MediaQuery.paddingOf(context).bottom),
child: Row(
children: [
Material(
color: c.tile,
borderRadius: BorderRadius.circular(14),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: _showBulletDialog,
child: SizedBox(
width: 78,
height: 56,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('$_numberOfBullets',
style: TextStyle(fontSize: 20, height: 1.1, fontWeight: FontWeight.w800, color: c.ink)),
Text(_t('shots'), style: TextStyle(fontSize: 10.5, color: c.muted)),
],
),
),
),
),
const Spacer(),
_shutter(c),
const Spacer(),
SquareButton(
icon: _torch ? Icons.flashlight_on_rounded : Icons.flashlight_off_outlined,
color: _torch ? c.accent : c.ink,
tooltip: _t('Flashlight'),
onTap: ready ? _toggleTorch : null,
),
const SizedBox(width: 10),
SquareButton(icon: Icons.tune_rounded, tooltip: _t('Camera settings'), onTap: ready ? _showCameraControls : null),
],
),
),
const SizedBox(width: 16),
],
),
bottomNavigationBar: BottomAppBar(
color: Colors.grey[900],
shape: const CircularNotchedRectangle(),
notchMargin: 8.0,
child: SizedBox(
height: 60,
child: Row(
children: [
// Left - Bullet count (just number)
Expanded(
child: Align(
alignment: Alignment.centerLeft,
child: Padding(
padding: const EdgeInsets.only(left: 16.0),
child: InkWell(
onTap: _showBulletDialog,
child: Text(
'$_numberOfBullets',
style: const TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
),
),
);
}
// White shutter in a ring; while the photo is analysed the ring turns
Widget _shutter(Palette c) {
return GestureDetector(
onTap: _processing ? null : _takePicture,
child: SizedBox.square(
dimension: 76,
child: Stack(
alignment: Alignment.center,
children: [
if (_processing)
SizedBox.square(
dimension: 72,
child: CircularProgressIndicator(strokeWidth: 4, color: c.ink, backgroundColor: c.tile),
)
else
Container(
decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: c.ink, width: 4)),
),
// Center space for FAB
const SizedBox(width: 80),
// Right section - Brightness
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
IconButton(
icon:
const Icon(Icons.tune, color: Colors.white, size: 24),
onPressed: _showCameraControls,
),
],
),
),
],
),
AnimatedContainer(
duration: const Duration(milliseconds: 150),
width: _processing ? 0 : 58,
height: _processing ? 0 : 58,
decoration: BoxDecoration(color: c.ink, shape: BoxShape.circle),
),
],
),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.white,
onPressed: _processing ? null : _takePicture,
child: _processing
? const SizedBox(
width: 24,
height: 24,
child: CircularProgressIndicator(
strokeWidth: 3, color: Colors.black),
)
: const Icon(Icons.camera_alt, color: Colors.black),
),
body: FutureBuilder(
future: _initializeControllerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
final screenSize = MediaQuery.of(context).size;
return Stack(
children: [
Positioned.fill(
child: Container(
color: Colors.black, // covers any empty space
child: FittedBox(
fit: BoxFit.cover,
child: SizedBox(
width: _controller!.value.previewSize!.height,
height: _controller!.value.previewSize!.width,
child: CameraPreview(_controller!),
),
),
),
);
}
Widget _searchingPill(Palette c) => Container(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
decoration: BoxDecoration(color: c.tile, borderRadius: BorderRadius.circular(20)),
child: Text(_t('Looking for hits …'), style: TextStyle(fontSize: 13.5, fontWeight: FontWeight.w600, color: c.ink)),
);
// 1× 2× 3× quick zoom, the ones this camera can do
Widget _zoomChips(Palette c) {
final steps = [for (final z in [1.0, 2.0, 3.0]) if (z >= _minZoom && z <= _maxZoom) z];
if (steps.length < 2) return const SizedBox.shrink();
return Container(
padding: const EdgeInsets.all(4),
decoration: BoxDecoration(color: Colors.black.withValues(alpha: 0.45), borderRadius: BorderRadius.circular(20)),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
for (final z in steps)
GestureDetector(
onTap: () => _setZoom(z),
child: Container(
width: 34,
height: 30,
alignment: Alignment.center,
decoration: BoxDecoration(
color: (_zoom - z).abs() < 0.05 ? c.tile : Colors.transparent,
shape: BoxShape.circle,
),
Center(
child: Container(
width: screenSize.width * 0.9,
height: screenSize.width * 0.9,
decoration: BoxDecoration(
border: Border.all(
color: _bulletColor.withValues(alpha: 0.9),
width: 3,
),
),
),
),
],
);
} else {
return const Center(child: CircularProgressIndicator());
}
},
child: Text('${z.round()}×',
style: TextStyle(
fontSize: 11.5,
fontWeight: FontWeight.w700,
color: (_zoom - z).abs() < 0.05 ? c.ink : c.muted)),
),
),
],
),
);
}
}
/// Dims the image outside the centred square and draws accent corners on it.
class _FramePainter extends CustomPainter {
final double side;
final Color color;
const _FramePainter({required this.side, required this.color});
@override
void paint(Canvas canvas, Size size) {
final rect = Rect.fromCenter(center: size.center(Offset.zero), width: side, height: side);
canvas.drawPath(
Path.combine(PathOperation.difference, Path()..addRect(Offset.zero & size), Path()..addRect(rect)),
Paint()..color = Colors.black.withValues(alpha: 0.45),
);
final p = Paint()
..color = color
..style = PaintingStyle.stroke
..strokeWidth = 4
..strokeCap = StrokeCap.round;
const l = 34.0;
for (final (corner, dx, dy) in [
(rect.topLeft, 1.0, 1.0),
(rect.topRight, -1.0, 1.0),
(rect.bottomLeft, 1.0, -1.0),
(rect.bottomRight, -1.0, -1.0),
]) {
canvas.drawPath(
Path()
..moveTo(corner.dx, corner.dy + dy * l)
..lineTo(corner.dx, corner.dy)
..lineTo(corner.dx + dx * l, corner.dy),
p,
);
}
}
@override
bool shouldRepaint(_FramePainter old) => old.side != side || old.color != color;
}
+78 -78
View File
@@ -4,6 +4,7 @@ import '../services/app_settings.dart';
import '../theme/app_theme.dart';
import '../widgets/section.dart';
import '../widgets/text_prompt.dart';
import '../widgets/ui.dart';
/// Locations (strelišča), number of positions, and the camera IP of every
/// position at every location.
@@ -18,92 +19,81 @@ class CameraSettingsScreen extends StatelessWidget {
final s = AppSettings.instance;
final t = s.t;
final setup = s.cameras;
final surf = Surfaces.current;
final c = Palette.current;
const firstPort = CameraSetup.firstPort;
return Scaffold(
backgroundColor: s.backgroundColor,
appBar: AppBar(
title: Text(t('Cameras'), style: const TextStyle(color: Colors.white)),
backgroundColor: AppTheme.bar,
iconTheme: const IconThemeData(color: Colors.white),
scrolledUnderElevation: 0,
),
body: ListView(
// Keep the last row clear of the system gesture bar (edge-to-edge)
padding: EdgeInsets.fromLTRB(16, 4, 16, 24 + MediaQuery.paddingOf(context).bottom),
body: Column(
children: [
SectionHeader(t('Locations')),
GroupCard(children: [
for (final location in setup.locations)
SettingsTile(
leading: Icon(
location == setup.clubLocation ? Icons.verified_rounded : Icons.place_rounded,
color: location == setup.clubLocation ? Colors.green : s.bulletColor,
),
title: location,
subtitle: location == setup.clubLocation ? t('Added with the club code') : null,
value: t('{n} cameras').replaceAll('{n}', '${setup.camerasIn(location)}'),
onTap: () => _editLocation(context, location),
),
SettingsTile(
leading: Icon(Icons.add_rounded, color: surf.textSecondary),
title: t('Add location'),
onTap: () => _addLocation(context),
),
]),
SectionHeader(t('Positions')),
GroupCard(children: [
SettingsTile(
title: t('Number of positions'),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: const Icon(Icons.remove_rounded),
color: surf.textPrimary,
onPressed: setup.positions > 1 ? () => s.setPositionCount(setup.positions - 1) : null,
BackHeader(title: t('Cameras'), subtitle: t('Locations, positions and camera addresses')),
Expanded(
child: ListView(
// Keep the last row clear of the system gesture bar (edge-to-edge)
padding: EdgeInsets.fromLTRB(AppTheme.edge, 0, AppTheme.edge, 24 + MediaQuery.paddingOf(context).bottom),
children: [
SectionHeader(t('Locations')),
GroupCard(children: [
for (final location in setup.locations)
SettingsTile(
icon: location == setup.clubLocation ? Icons.verified_user_outlined : Icons.place_outlined,
iconColor: location == setup.clubLocation ? c.accent : c.muted,
title: location,
subtitle: location == setup.clubLocation ? t('Added with the club code') : null,
value: _cameraCount(s, setup.camerasIn(location)),
onTap: () => _editLocation(context, location),
),
SettingsTile(
icon: Icons.add_rounded,
title: t('Add location'),
titleColor: c.muted,
showChevron: false,
onTap: () => _addLocation(context),
),
SizedBox(
width: 28,
child: Text(
'${setup.positions}',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: surf.textPrimary),
]),
SectionHeader(t('Positions')),
GroupCard(children: [
SettingsTile(
title: t('Number of positions'),
trailing: Stepper3(
value: '${setup.positions}',
valueWidth: 44,
onMinus: setup.positions > 1 ? () => s.setPositionCount(setup.positions - 1) : null,
onPlus: setup.positions < CameraSetup.maxPositions ? () => s.setPositionCount(setup.positions + 1) : null,
),
),
IconButton(
icon: const Icon(Icons.add_rounded),
color: surf.textPrimary,
onPressed: setup.positions < CameraSetup.maxPositions
? () => s.setPositionCount(setup.positions + 1)
: null,
),
],
),
),
]),
for (final location in setup.locations) ...[
SectionHeader(location),
GroupCard(children: [
SettingsTile(
leading: Icon(Icons.bolt_rounded, color: s.bulletColor),
title: t('Set all cameras from one IP'),
subtitle: t('Ports {from}–{to}')
.replaceAll('{from}', '$firstPort')
.replaceAll('{to}', '${firstPort + setup.positions - 1}'),
onTap: () => _editHost(context, location),
),
for (int p = 1; p <= setup.positions; p++)
SettingsTile(
title: '${t('Camera')} $p',
value: setup.ipFor(p, location).isEmpty ? '—' : setup.ipFor(p, location),
onTap: () => _editCamera(context, p, location),
]),
Padding(
padding: const EdgeInsets.fromLTRB(4, 10, 4, 0),
child: Text(t('One tile on the Shooting screen for each position.'),
style: TextStyle(fontSize: 12, color: c.muted)),
),
]),
],
for (final location in setup.locations) ...[
SectionHeader(location),
GroupCard(children: [
SettingsTile(
icon: Icons.bolt_rounded,
iconColor: c.accent,
title: t('Set all cameras from one IP'),
subtitle: t('Ports {from}–{to}')
.replaceAll('{from}', '$firstPort')
.replaceAll('{to}', '${firstPort + setup.positions - 1}'),
onTap: () => _editHost(context, location),
),
for (int p = 1; p <= setup.positions; p++)
SettingsTile(
title: '${t('Camera')} $p',
value: setup.ipFor(p, location).isEmpty ? t('Not set up') : setup.ipFor(p, location),
mono: setup.ipFor(p, location).isNotEmpty,
valueColor: setup.ipFor(p, location).isEmpty ? c.faint : c.ink2,
onTap: () => _editCamera(context, p, location),
),
]),
],
],
),
),
],
),
);
@@ -111,6 +101,14 @@ class CameraSettingsScreen extends StatelessWidget {
);
}
static String _cameraCount(AppSettings s, int n) {
if (s.language == 'Slovenian') {
final mod = n % 100;
return '$n ${mod == 1 ? 'kamera' : mod == 2 ? 'kameri' : (mod == 3 || mod == 4) ? 'kamere' : 'kamer'}';
}
return s.t('{n} cameras').replaceAll('{n}', '$n');
}
Future<void> _addLocation(BuildContext context) async {
final s = AppSettings.instance;
final name = await showTextPrompt(context, title: s.t('Add location'), hint: s.t('e.g. Home'));
@@ -139,6 +137,7 @@ class CameraSettingsScreen extends StatelessWidget {
context,
title: '${s.t('Set all cameras from one IP')} · $location',
initial: first.split(':').first,
mono: true,
hint: '192.168.0.10',
keyboardType: TextInputType.url,
);
@@ -151,6 +150,7 @@ class CameraSettingsScreen extends StatelessWidget {
context,
title: '${s.t('Camera')} $position · $location',
initial: s.cameras.ipFor(position, location),
mono: true,
hint: '192.168.0.10:${CameraSetup.firstPort + position - 1}',
keyboardType: TextInputType.url,
resetLabel: s.t('Remove'),
+14 -48
View File
@@ -5,12 +5,12 @@ import 'settings_screen.dart';
import 'target_screen.dart';
import '../widgets/bottom_nav.dart';
import 'camera_screen.dart';
import 'spectator_screen.dart';
import '../services/app_settings.dart';
import '../theme/app_theme.dart';
enum AppTab { book, shooting, camera, calendar, settings }
/// The five tabs. Every page draws its own large title (see PageHeader);
/// the camera opens as its own screen.
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@@ -29,12 +29,12 @@ class _HomeScreenState extends State<HomeScreen> {
AppTab.settings: 'Settings',
};
static const Map<AppTab, IconData> _icons = {
AppTab.book: Icons.book,
AppTab.shooting: Icons.my_location,
AppTab.camera: Icons.camera_alt,
AppTab.calendar: Icons.calendar_today,
AppTab.settings: Icons.settings,
static const Map<AppTab, (IconData, IconData)> _icons = {
AppTab.book: (Icons.menu_book_outlined, Icons.menu_book_rounded),
AppTab.shooting: (Icons.gps_fixed_rounded, Icons.gps_fixed_rounded),
AppTab.camera: (Icons.photo_camera_outlined, Icons.photo_camera_rounded),
AppTab.calendar: (Icons.calendar_today_outlined, Icons.calendar_today_rounded),
AppTab.settings: (Icons.tune_rounded, Icons.tune_rounded),
};
// Calendar is only shown to club members (see Settings > Club code)
@@ -67,10 +67,13 @@ class _HomeScreenState extends State<HomeScreen> {
// When returning from the camera screen, always land on the Shooting tab
void _openCameraScan() async {
// The photo camera is dark in both themes
AppSettings.instance.holdDark();
await Navigator.of(context).push(
MaterialPageRoute(builder: (context) => const CameraScreen()),
);
setState(() => _selected = AppTab.shooting);
AppSettings.instance.releaseDark();
if (mounted) setState(() => _selected = AppTab.shooting);
}
@override
@@ -83,49 +86,12 @@ class _HomeScreenState extends State<HomeScreen> {
if (!tabs.contains(_selected)) _selected = AppTab.settings; // calendar was just locked
return Scaffold(
appBar: AppBar(
title: Text(
settings.t(_titles[_selected]!),
style: const TextStyle(color: Colors.white),
),
backgroundColor: AppTheme.bar,
iconTheme: const IconThemeData(color: Colors.white),
automaticallyImplyLeading: false,
scrolledUnderElevation: 0, // For Material 3 (Flutter 3.7+)
actions: [
if (_selected == AppTab.book)
IconButton(
tooltip: settings.t('Help'),
icon: const Icon(Icons.info_outline_rounded, color: Colors.white),
onPressed: () => showBookHelp(context),
),
if (_selected == AppTab.shooting)
IconButton(
icon: const Icon(Icons.visibility_rounded, color: Colors.white),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SpectatorScreen(
selectedLanguage: settings.language,
),
),
);
},
),
],
),
backgroundColor: settings.backgroundColor,
body: _page(_selected),
body: KeyedSubtree(key: ValueKey(_selected), child: _page(_selected)),
bottomNavigationBar: BottomNavBar(
selectedIndex: tabs.indexOf(_selected),
onItemTapped: (i) => _onTabTapped(tabs[i]),
items: [
for (final tab in tabs)
BottomNavigationBarItem(
icon: Icon(_icons[tab]),
label: settings.t(_titles[tab]!),
),
for (final tab in tabs) NavItem(_icons[tab]!.$1, _icons[tab]!.$2, settings.t(_titles[tab]!)),
],
),
);
File diff suppressed because it is too large Load Diff
+142 -118
View File
@@ -3,7 +3,10 @@ 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/section.dart';
import '../widgets/target_face.dart';
import '../widgets/ui.dart';
import 'target_view.dart';
/// One training or tournament: its stats, its targets, and edit/delete actions.
@@ -18,6 +21,20 @@ class SessionScreen extends StatefulWidget {
class _SessionScreenState extends State<SessionScreen> {
late Session _session = widget.session;
Map<String, TargetHits> _hits = {}; // file path -> hits, for the thumbnails
@override
void initState() {
super.initState();
_loadHits();
}
Future<void> _loadHits() async {
final files = _session.files;
final all = await TargetRepository.readAllHits(files);
if (!mounted) return;
setState(() => _hits = {for (int i = 0; i < files.length; i++) files[i].path: all[i]});
}
Future<void> _reload() async {
final sessions = await TargetRepository.loadSessions();
@@ -27,6 +44,7 @@ class _SessionScreenState extends State<SessionScreen> {
Navigator.pop(context); // session no longer exists
} else {
setState(() => _session = updated.first);
_loadHits();
}
}
@@ -59,14 +77,14 @@ class _SessionScreenState extends State<SessionScreen> {
Future<void> _delete() async {
final s = AppSettings.instance;
final message = '${s.t('Are you sure you want to delete the folder')} "${_session.name}" ${s.t('and all of its contents?')}';
if (await confirmDelete(context, message) != true) return;
final message = '${s.t('Are you sure you want to delete the folder')} »${_session.name}« ${s.t('and all of its contents?')}';
if (!await confirmDelete(context, message)) return;
await TargetRepository.deleteSession(_session);
if (mounted) Navigator.pop(context);
}
Future<void> _deleteTarget(TargetRecord target) async {
if (await confirmDelete(context, AppSettings.instance.t('Are you sure you want to delete this file?')) != true) return;
if (!await confirmDelete(context, AppSettings.instance.t('Are you sure you want to delete this file?'))) return;
await TargetRepository.deleteTarget(target);
_reload();
}
@@ -78,71 +96,106 @@ class _SessionScreenState extends State<SessionScreen> {
builder: (context, _) {
final s = AppSettings.instance;
final t = s.t;
final surf = Surfaces.current;
final c = Palette.current;
final session = _session;
final stats = ShooterStats.of([session]);
final best = session.targets.isEmpty ? null : session.targets.map((x) => x.score).reduce((a, b) => a > b ? a : b);
return Scaffold(
backgroundColor: s.backgroundColor,
appBar: AppBar(
title: Text(session.name, style: const TextStyle(color: Colors.white)),
backgroundColor: AppTheme.bar,
iconTheme: const IconThemeData(color: Colors.white),
scrolledUnderElevation: 0,
actions: [
IconButton(icon: const Icon(Icons.edit), tooltip: t('Edit'), onPressed: _edit),
IconButton(icon: const Icon(Icons.delete, color: Colors.red), tooltip: t('Delete'), onPressed: _delete),
],
),
body: ListView(
// Keep the last row clear of the system gesture bar (edge-to-edge)
padding: EdgeInsets.fromLTRB(16, 4, 16, 24 + MediaQuery.paddingOf(context).bottom),
body: Column(
children: [
SectionHeader(
'${session.isTournament ? t('Tournament') : t('Training')} · ${DateFormat('d. M. yyyy').format(session.date)}',
BackHeader(
title: session.name,
actions: [
CircleButton(icon: Icons.edit_outlined, tooltip: t('Edit'), onTap: _edit),
CircleButton(
icon: Icons.delete_outline_rounded,
tooltip: t('Delete'),
color: c.red,
background: c.redSoft,
onTap: _delete,
),
],
),
StatGrid(tiles: [
StatTile(label: t('Total'), value: '${session.totalScore}', caption: targetCount(session.targets.length)),
StatTile(
label: t('Average per shot'),
value: stats.averagePerShot?.toStringAsFixed(2) ?? '–',
caption: shotCount(stats.shots),
),
]),
SectionHeader(t('Targets')),
if (session.targets.isEmpty)
Padding(
padding: const EdgeInsets.all(16),
child: Text(t('No targets in this folder'), style: TextStyle(color: surf.textSecondary)),
)
else
GroupCard(children: [
for (int i = 0; i < session.targets.length; i++)
SettingsTile(
title: '${t('Target')} ${i + 1}',
subtitle: '${DateFormat('HH:mm').format(session.targets[i].shotAt)} · ${shotCount(session.targets[i].shots)}',
onTap: () => _openTargets([session.targets[i]]),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'${session.targets[i].score}',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: surf.textPrimary),
),
IconButton(
icon: const Icon(Icons.delete, color: Colors.red, size: 20),
onPressed: () => _deleteTarget(session.targets[i]),
),
],
),
Expanded(
child: ListView(
// Keep the last row clear of the system gesture bar (edge-to-edge)
padding: EdgeInsets.fromLTRB(AppTheme.edge, 4, AppTheme.edge, 24 + MediaQuery.paddingOf(context).bottom),
children: [
Kicker(
'${session.isTournament ? t('Tournament') : t('Training')} · ${DateFormat('d. M. yyyy').format(session.date)}',
padding: const EdgeInsets.only(bottom: 10),
),
]),
StatGrid(tiles: [
StatTile(label: t('Total'), value: '${session.totalScore}', caption: targetCount(session.targets.length)),
StatTile(
label: t('Average per shot'),
value: stats.averagePerShot == null ? '–' : dec(stats.averagePerShot!),
caption: shotCount(stats.shots),
),
]),
SectionHeader(t('Targets')),
if (session.targets.isEmpty)
Padding(
padding: const EdgeInsets.all(16),
child: Text(t('No targets in this folder'), style: TextStyle(color: c.muted)),
)
else
for (int i = 0; i < session.targets.length; i++)
Padding(
padding: const EdgeInsets.only(bottom: 10),
child: _targetRow(s, c, i, session.targets[i], session.targets[i].score == best),
),
],
),
),
],
),
);
},
);
}
Widget _targetRow(AppSettings s, Palette c, int i, TargetRecord target, bool isBest) {
return AppCard(
padding: const EdgeInsets.fromLTRB(10, 10, 4, 10),
onTap: () => _openTargets([target]),
child: Row(
children: [
SizedBox.square(
dimension: 44,
child: TargetFace(
style: s.target,
hits: _hits[target.file.path]?.bullets ?? const [],
hitColor: s.bulletColor,
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('${s.t('Target')} ${i + 1}', style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: c.ink)),
const SizedBox(height: 2),
Text('${DateFormat('HH:mm').format(target.shotAt)} · ${shotCount(target.shots)}',
style: TextStyle(fontSize: 12, color: c.muted)),
],
),
),
Text('${target.score}',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w800,
color: isBest ? (c.isDark ? c.gold : c.goldInk) : c.ink,
fontFeatures: AppTheme.tnum)),
IconButton(
icon: Icon(Icons.delete_outline_rounded, color: c.red, size: 20),
onPressed: () => _deleteTarget(target),
),
],
),
);
}
}
/// "1 target" / "5 targets", with Slovenian dual and plural forms.
@@ -165,26 +218,10 @@ String shotCount(int n) {
return '$n $word';
}
Future<bool?> confirmDelete(BuildContext context, String message) {
/// "Potrdi brisanje" dialog. True when confirmed.
Future<bool> confirmDelete(BuildContext context, String message) {
final s = AppSettings.instance;
return showDialog<bool>(
context: context,
builder: (dialog) => AlertDialog(
title: Text(s.t('Confirm Deletion')),
content: Text(message),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialog, false),
child: Text(s.t('Cancel'), style: const TextStyle(color: Colors.white70)),
),
FilledButton(
style: FilledButton.styleFrom(backgroundColor: Colors.red[700]),
onPressed: () => Navigator.pop(dialog, true),
child: Text(s.t('Yes, delete')),
),
],
),
);
return confirmDialog(context, title: s.t('Confirm Deletion'), message: message, confirm: s.t('Yes, delete'));
}
class SessionEdit {
@@ -194,7 +231,7 @@ class SessionEdit {
const SessionEdit(this.name, this.isTournament);
}
/// Rename a session and choose training/tournament.
/// Rename a session and choose training/tournament ("Nastavitve mape").
Future<SessionEdit?> showEditSessionDialog(BuildContext context, Session session) {
final s = AppSettings.instance;
final controller = TextEditingController(text: session.name);
@@ -203,52 +240,39 @@ Future<SessionEdit?> showEditSessionDialog(BuildContext context, Session session
return showDialog<SessionEdit>(
context: context,
builder: (dialog) => StatefulBuilder(
builder: (context, setDialogState) => AlertDialog(
title: Text(s.t('Folder Settings')),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: controller,
style: const TextStyle(color: Colors.white),
cursorColor: s.bulletColor,
decoration: InputDecoration(
filled: true,
fillColor: Colors.white10,
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide.none),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: s.bulletColor),
),
builder: (context, setDialogState) {
final c = Palette.current;
return AppDialog(
title: s.t('Folder Settings'),
content: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextField(controller: controller, style: TextStyle(color: c.ink, fontSize: 15)),
const SizedBox(height: 12),
ToggleRow(
icon: Icons.emoji_events_outlined,
label: s.t('Tournament'),
value: isTournament,
onChanged: (v) => setDialogState(() => isTournament = v),
),
),
const SizedBox(height: 8),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: Text(s.t('Tournament'), style: const TextStyle(color: Colors.white)),
secondary: Icon(Icons.emoji_events, color: isTournament ? s.bulletColor : Colors.white54),
value: isTournament,
activeTrackColor: s.bulletColor,
onChanged: (v) => setDialogState(() => isTournament = v),
const SizedBox(height: 10),
Text(s.t('Rename the session or move it to tournaments.'), style: TextStyle(fontSize: 12, color: c.muted)),
],
),
actions: [
DialogTextButton(s.t('Cancel'), onTap: () => Navigator.pop(dialog)),
PrimaryButton(
label: s.t('Save'),
height: 46,
onTap: () {
final name = controller.text.trim();
if (name.isEmpty || name.contains('/')) return;
Navigator.pop(dialog, SessionEdit(name, isTournament));
},
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialog),
child: Text(s.t('Cancel'), style: const TextStyle(color: Colors.white70)),
),
FilledButton(
style: FilledButton.styleFrom(backgroundColor: s.bulletColor),
onPressed: () {
final name = controller.text.trim();
if (name.isEmpty || name.contains('/')) return;
Navigator.pop(dialog, SessionEdit(name, isTournament));
},
child: Text(s.t('Save')),
),
],
),
);
},
),
);
}
+441 -336
View File
@@ -1,13 +1,18 @@
import 'package:flutter/foundation.dart' show kDebugMode;
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../models/holiday_theme.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.dart';
import '../models/target_style.dart';
import '../services/app_settings.dart';
import '../utils/translations.dart';
import '../services/notification_service.dart';
import '../theme/app_theme.dart';
import '../utils/target_colors.dart';
import '../widgets/section.dart';
import '../widgets/target_face.dart';
import '../widgets/text_prompt.dart';
import '../widgets/ui.dart';
import 'camera_settings_screen.dart';
class SettingsScreen extends StatelessWidget {
@@ -24,127 +29,152 @@ class SettingsScreen extends StatelessWidget {
builder: (context, _) {
final s = AppSettings.instance;
final t = s.t;
final language = AppSettings.languages.firstWhere(
(l) => l['name'] == s.language,
orElse: () => AppSettings.languages.first,
);
final c = Palette.current;
return ListView(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 24),
padding: EdgeInsets.zero,
children: [
SectionHeader(t('Language')),
GroupCard(children: [
SettingsTile(
title: t(language['name']!),
onTap: () => _pickLanguage(context),
),
]),
SectionHeader(t('Appearance')),
GroupCard(children: [
SettingsTile(
title: t('Bullet color'),
valueLeading: _ColorDot(s.bulletColor, size: 18),
value: t(s.bulletColorName),
onTap: () => _pickBulletColor(context),
),
SettingsTile(
title: t('Target'),
valueLeading: _TargetThumb(s.selectedTarget, size: 30),
value: s.targetName(s.selectedTarget),
onTap: () => _pickTarget(context),
),
]),
SectionHeader(t('Club')),
GroupCard(children: [
if (s.clubUnlocked)
SettingsTile(
leading: const Icon(Icons.verified_rounded, color: Colors.green),
title: t('Member access'),
subtitle: t('Calendar and contacts unlocked'),
value: t('Remove'),
onTap: () => _confirmLock(context),
)
else
SettingsTile(
leading: Icon(Icons.lock_outline_rounded, color: Surfaces.current.textSecondary),
title: t('Club code'),
subtitle: t('Unlocks calendar and contacts'),
onTap: () => _enterClubCode(context),
),
]),
PageHeader(title: t('Settings')),
Padding(
padding: const EdgeInsets.fromLTRB(4, 8, 4, 0),
child: Text(
t('Member access is currently available only for SD Kovinar Muta. Support for other clubs may be added in the future.'),
style: TextStyle(fontSize: 12, color: Surfaces.current.textSecondary),
),
),
padding: const EdgeInsets.fromLTRB(AppTheme.edge, 0, AppTheme.edge, 28),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SectionHeader(t('Language')),
GroupCard(children: [
SettingsTile(
icon: Icons.language_rounded,
title: t('Language'),
value: t(s.language),
onTap: () => _pickLanguage(context),
),
]),
if (s.clubUnlocked) ...[
SectionHeader(t('Notifications')),
GroupCard(children: [
SettingsSwitchTile(
title: t('Dežuranje'),
value: s.notifyDezuranje,
activeColor: s.bulletColor,
onChanged: (v) => s.setNotifyDezuranje(v).then((_) => _reschedule()),
),
SettingsSwitchTile(
title: t('Sestanek'),
value: s.notifySestanek,
activeColor: s.bulletColor,
onChanged: (v) => s.setNotifySestanek(v).then((_) => _reschedule()),
),
SettingsSwitchTile(
title: t('Tekma'),
value: s.notifyTekma,
activeColor: s.bulletColor,
onChanged: (v) => s.setNotifyTekma(v).then((_) => _reschedule()),
),
SettingsTile(
title: t('Remind me'),
value: _hoursBefore(s.reminderHours),
onTap: () => _pickReminder(context),
),
]),
],
SectionHeader(t('Appearance')),
GroupCard(children: [
SettingsTile(
icon: Icons.dark_mode_outlined,
title: t('Theme'),
trailing: SizedBox(
width: 196,
child: SegmentedTabs(
height: 36,
accentSelected: true,
items: [SegmentItem(t('System')), SegmentItem(t('Light')), SegmentItem(t('Dark'))],
selected: AppSettings.themeModes.indexOf(s.themeMode),
onSelect: (i) => s.setThemeMode(AppSettings.themeModes[i]),
),
),
),
// Hit colour and target design are picked in one sheet
SettingsTile(
icon: Icons.track_changes_rounded,
title: t('Hits and target'),
valueLeading: Row(
mainAxisSize: MainAxisSize.min,
children: [
_ColorDot(s.bulletColor, size: 16),
const SizedBox(width: 8),
TargetThumb(s.target, size: 26),
],
),
value: s.target.name(s.language),
onTap: () => showAppearanceSheet(context),
),
]),
SectionHeader(t('Cameras')),
GroupCard(children: [
SettingsTile(
title: t('Camera Settings'),
value: _camerasSummary(s),
onTap: () => Navigator.of(context).push(
MaterialPageRoute(builder: (_) => const CameraSettingsScreen()),
),
),
]),
SectionHeader('${t('Club')} · SD Kovinar Muta'),
GroupCard(children: [
if (s.clubUnlocked)
SettingsTile(
icon: Icons.verified_user_outlined,
title: t('Member access'),
value: t('Unlocked'),
valueColor: c.pos,
showChevron: false,
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(t('Unlocked'), style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500, color: c.pos)),
const SizedBox(width: 8),
Container(
width: 22,
height: 22,
decoration: BoxDecoration(color: c.pos, shape: BoxShape.circle),
child: Icon(Icons.check_rounded, size: 15, color: Palette.onColor(c.pos)),
),
],
),
onTap: () => _confirmLock(context),
)
else
SettingsTile(
icon: Icons.lock_outline_rounded,
title: t('Club code'),
subtitle: t('Unlocks calendar and contacts'),
onTap: () => _enterClubCode(context),
),
]),
if (!s.clubUnlocked)
Padding(
padding: const EdgeInsets.fromLTRB(4, 10, 4, 0),
child: Text(
t('Member access is currently available only for SD Kovinar Muta. Support for other clubs may be added in the future.'),
style: TextStyle(fontSize: 12, height: 1.35, color: c.muted),
),
),
SectionHeader(t('About')),
GroupCard(children: [
SettingsTile(
title: t('Privacy policy'),
onTap: () => launchUrl(
Uri.parse(_privacyPolicyUrl),
mode: LaunchMode.externalApplication,
),
),
]),
if (s.clubUnlocked) ...[
SectionHeader(t('Notifications')),
GroupCard(children: notificationTiles(context)),
],
const SizedBox(height: 28),
FutureBuilder<PackageInfo>(
future: _packageInfo,
builder: (context, snap) {
final info = snap.data;
if (info == null) return const SizedBox.shrink();
return Text(
'${info.appName} ${info.version}',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 12, color: Surfaces.current.textSecondary),
);
},
SectionHeader(t('Cameras')),
GroupCard(children: [
SettingsTile(
icon: Icons.videocam_outlined,
title: t('Camera Settings'),
value: _camerasSummary(s),
onTap: () => Navigator.of(context).push(
MaterialPageRoute(builder: (_) => const CameraSettingsScreen()),
),
),
]),
SectionHeader(t('About')),
GroupCard(children: [
SettingsTile(
icon: Icons.shield_outlined,
title: t('Privacy policy'),
chevron: Icons.open_in_new_rounded,
onTap: () => launchUrl(Uri.parse(_privacyPolicyUrl), mode: LaunchMode.externalApplication),
),
FutureBuilder<PackageInfo>(
future: _packageInfo,
// Debug builds: long press previews a holiday
builder: (context, snap) => SettingsTile(
icon: Icons.info_outline_rounded,
title: t('Version'),
value: snap.data?.version ?? '',
),
),
]),
// Debug builds only (never in a release): check the holiday looks
if (kDebugMode) ...[
const SectionHeader('Debug'),
GroupCard(children: [
SettingsTile(
icon: Icons.celebration_outlined,
title: 'Holiday preview',
subtitle: 'Shows the app as on a day of the holiday',
value: s.debugToday == null ? 'Today' : (s.holiday?.name ?? 'Today'),
onTap: () => _previewHoliday(context),
),
]),
],
],
),
),
],
);
@@ -154,13 +184,91 @@ class SettingsScreen extends StatelessWidget {
static void _reschedule() => NotificationService().rescheduleFromCalendar();
// Debug: see the app as on a day of each holiday (Nastavitve → Debug)
static void _previewHoliday(BuildContext context) {
final s = AppSettings.instance;
final year = DateTime.now().year;
showAppSheet(
context,
title: 'Holiday preview (debug)',
builder: (sheet) => Column(
children: [
SheetOption(
label: 'Today',
selected: s.debugToday == null,
showDivider: false,
onTap: () {
s.previewDay(null);
Navigator.pop(sheet);
},
),
for (final h in HolidayTheme.all)
Builder(builder: (_) {
// First day of the holiday this year
final day = h.easter != null
? HolidayTheme.easterDay(year, h.easter!.$1)
: DateTime(year, h.from!.$1, h.from!.$2);
final (start, end) = h.window(day);
return SheetOption(
label: h.name,
subtitle: '${DateFormat('d. M.').format(start)} – ${DateFormat('d. M.').format(end)}',
leading: TargetThumb(TargetStyle.byId(h.targetId), size: 32),
selected: s.holiday == h && s.debugToday != null,
onTap: () {
s.previewDay(day);
Navigator.pop(sheet);
},
);
}),
],
),
);
}
/// Dežuranje, Sestanki, Tekme and "Opomni me"; also shown from the calendar's bell.
static List<Widget> notificationTiles(BuildContext context) {
final s = AppSettings.instance;
final t = s.t;
return [
SettingsSwitchTile(
icon: Icons.shield_outlined,
title: t('Dežuranje'),
value: s.notifyDezuranje,
onChanged: (v) => s.setNotifyDezuranje(v).then((_) => _reschedule()),
),
SettingsSwitchTile(
icon: Icons.person_add_alt_outlined,
title: t('Sestanek'),
value: s.notifySestanek,
onChanged: (v) => s.setNotifySestanek(v).then((_) => _reschedule()),
),
SettingsSwitchTile(
icon: Icons.emoji_events_outlined,
title: t('Tekma'),
value: s.notifyTekma,
onChanged: (v) => s.setNotifyTekma(v).then((_) => _reschedule()),
),
SettingsTile(
icon: Icons.notifications_none_rounded,
title: t('Remind me'),
value: hoursBefore(s.reminderHours),
onTap: () => pickReminder(context),
),
];
}
Future<void> _enterClubCode(BuildContext context) async {
final s = AppSettings.instance;
final code = await showTextPrompt(
context,
title: s.t('Club code'),
message: s.t('Unlocks calendar and contacts'),
message: s.t('Unlocks calendar and contacts.'),
titleIcon: Icons.lock_outline_rounded,
fieldIcon: Icons.key_rounded,
mono: true,
note: s.t('Member access is currently available only for SD Kovinar Muta.'),
confirmLabel: s.t('Unlock'),
confirmIcon: Icons.key_rounded,
);
if (code == null || code.isEmpty || !context.mounted) return;
@@ -175,222 +283,245 @@ class SettingsScreen extends StatelessWidget {
Navigator.of(context).pop();
if (ok) _reschedule();
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(s.t(ok ? 'Club access unlocked' : 'Wrong club code')),
backgroundColor: ok ? Colors.green[700] : Colors.red[700],
));
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(s.t(ok ? 'Club access unlocked' : 'Wrong club code'))));
}
Future<void> _confirmLock(BuildContext context) async {
final s = AppSettings.instance;
final confirmed = await showDialog<bool>(
context: context,
builder: (dialog) => AlertDialog(
title: Text(s.t('Member access')),
content: Text(s.t('Remove club access from this phone?')),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialog, false),
child: Text(s.t('Cancel'), style: const TextStyle(color: Colors.white70)),
),
FilledButton(
style: FilledButton.styleFrom(backgroundColor: Colors.red[700]),
onPressed: () => Navigator.pop(dialog, true),
child: Text(s.t('Remove')),
),
],
),
final confirmed = await confirmDialog(
context,
title: s.t('Member access'),
message: s.t('Remove club access from this phone?'),
confirm: s.t('Remove'),
);
if (confirmed == true) {
if (confirmed) {
await s.lockClub();
_reschedule(); // cancels reminders
}
}
static String _hoursBefore(int hours) =>
AppSettings.instance.t('{n} h before').replaceAll('{n}', '$hours');
static String hoursBefore(int hours) => AppSettings.instance.t('{n} h before').replaceAll('{n}', '$hours');
// Location names (e.g. "Kovinar · Doma"), or a hint when nothing is set up yet.
// "2 strelišči", or a hint when nothing is set up yet.
static String _camerasSummary(AppSettings s) {
final locations = s.cameras.locations;
return locations.isEmpty ? s.t('Not set up') : locations.join(' · ');
final n = s.cameras.locations.length;
if (n == 0) return s.t('Not set up');
if (s.language == 'Slovenian') {
final mod = n % 100;
return '$n ${mod == 1 ? 'strelišče' : mod == 2 ? 'strelišči' : (mod == 3 || mod == 4) ? 'strelišča' : 'strelišč'}';
}
return s.cameras.locations.join(' · ');
}
void _pickLanguage(BuildContext context) {
final s = AppSettings.instance;
showModalBottomSheet(
context: context,
builder: (sheet) => SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
_SheetTitle(s.t('Select Language')),
// Each language in its own name, so it can be found from any language
for (final lang in AppSettings.languages)
SheetOption(
label: AppTranslations.translate(lang['name']!, lang['name']!),
selected: lang['name'] == s.language,
selectedColor: s.bulletColor,
onTap: () {
s.setLanguage(lang['name']!);
Navigator.pop(sheet);
},
),
const SizedBox(height: 8),
],
),
),
);
}
void _pickReminder(BuildContext context) {
final s = AppSettings.instance;
showModalBottomSheet(
context: context,
// 7 options exceed the default 9/16 height cap on smaller phones
isScrollControlled: true,
builder: (sheet) => SafeArea(
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
_SheetTitle(s.t('Remind me')),
for (final h in AppSettings.reminderHourOptions)
SheetOption(
label: _hoursBefore(h),
selected: h == s.reminderHours,
selectedColor: s.bulletColor,
onTap: () {
s.setReminderHours(h).then((_) => _reschedule());
Navigator.pop(sheet);
},
),
const SizedBox(height: 8),
],
),
),
),
);
}
void _pickBulletColor(BuildContext context) {
final s = AppSettings.instance;
showModalBottomSheet(
context: context,
builder: (sheet) => SafeArea(
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 20),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
_SheetTitle(s.t('Bullet color')),
Wrap(
spacing: 16,
runSpacing: 16,
alignment: WrapAlignment.center,
children: [
for (final entry in AppSettings.bulletColors.entries)
GestureDetector(
onTap: () {
s.setBulletColor(entry.key);
Navigator.pop(sheet);
},
child: _ColorDot(
entry.value,
size: 48,
selected: entry.key == s.bulletColorName,
),
),
],
),
],
),
),
),
);
}
void _pickTarget(BuildContext context) {
final s = AppSettings.instance;
showModalBottomSheet(
context: context,
isScrollControlled: true,
builder: (sheet) => DraggableScrollableSheet(
expand: false,
initialChildSize: 0.75,
maxChildSize: 0.95,
builder: (context, scroll) => Column(
children: [
_SheetTitle(s.t('Target')),
Expanded(
child: GridView.builder(
controller: scroll,
padding: EdgeInsets.fromLTRB(16, 0, 16, 24 + MediaQuery.paddingOf(context).bottom),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
mainAxisSpacing: 12,
crossAxisSpacing: 12,
childAspectRatio: 0.8,
),
itemCount: AppSettings.targets.length,
itemBuilder: (context, i) {
final path = AppSettings.targets[i];
final selected = path == s.selectedTarget;
return GestureDetector(
onTap: () {
s.setTarget(path);
Navigator.pop(sheet);
},
child: Column(
children: [
Expanded(
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: selected ? s.bulletColor : Colors.transparent,
width: 3,
),
),
child: _TargetThumb(path, radius: 9),
),
),
const SizedBox(height: 6),
Text(
s.targetName(path),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12,
color: selected ? Colors.white : Colors.white70,
fontWeight: selected ? FontWeight.bold : FontWeight.normal,
),
),
],
),
);
},
),
showAppSheet(
context,
title: s.t('Select Language'),
builder: (sheet) => Column(
children: [
// Each language in its own name, so it can be found from any language
for (final lang in AppSettings.languages)
SheetOption(
label: AppTranslations.translate(lang['name']!, lang['name']!),
leading: Text(lang['flag']!, style: const TextStyle(fontSize: 22)),
selected: lang['name'] == s.language,
onTap: () {
s.setLanguage(lang['name']!);
Navigator.pop(sheet);
},
),
],
),
],
),
);
}
static void pickReminder(BuildContext context) {
final s = AppSettings.instance;
showAppSheet(
context,
title: s.t('Remind me'),
builder: (sheet) => Column(
children: [
for (final h in AppSettings.reminderHourOptions)
SheetOption(
label: hoursBefore(h),
selected: h == s.reminderHours,
onTap: () {
s.setReminderHours(h).then((_) => _reschedule());
Navigator.pop(sheet);
},
),
],
),
);
}
}
class _SheetTitle extends StatelessWidget {
final String text;
/// Videz: hit colour (the accent of the whole app) and the target design.
void showAppearanceSheet(BuildContext context) {
final s = AppSettings.instance;
showAppSheet(
context,
builder: (sheet) => ListenableBuilder(
listenable: s,
builder: (context, _) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SheetTitle(s.t('Appearance'), trailing: TargetThumb(s.target, size: 52)),
Kicker(s.t('Bullet color'), padding: const EdgeInsets.only(bottom: 12)),
LayoutBuilder(builder: (context, box) {
const perRow = 8;
final size = ((box.maxWidth - (perRow - 1) * 10) / perRow).clamp(28.0, 40.0);
return Wrap(
spacing: 10,
runSpacing: 12,
children: [
// During a holiday its colour comes first (and is the one in use)
if (s.holiday != null)
GestureDetector(
onTap: s.useHolidayColor,
child: Tooltip(
message: s.holiday!.name,
child: _ColorDot(s.holiday!.color, size: size, selected: s.holidayColorActive),
),
),
for (final name in AppSettings.bulletColors.keys)
GestureDetector(
onTap: () => s.setBulletColor(name),
child: Tooltip(
message: s.t(name),
child: _ColorDot(s.colorFor(name), size: size,
selected: !s.holidayColorActive && name == s.bulletColorName),
),
),
],
);
}),
Kicker(s.t('Target style'), padding: const EdgeInsets.only(top: 22, bottom: 12)),
if (s.holiday != null) _HolidayCard(holiday: s.holiday!) else const _TargetGrid(styles: TargetStyle.all),
],
);
},
),
);
}
const _SheetTitle(this.text);
/// Three target designs per row; the chosen one has an accent border and a check.
class _TargetGrid extends StatelessWidget {
final List<TargetStyle> styles;
const _TargetGrid({required this.styles});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Text(
text,
style: const TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold),
final s = AppSettings.instance;
final c = Palette.current;
return LayoutBuilder(builder: (context, box) {
final w = (box.maxWidth - 2 * 10) / 3;
return Wrap(
spacing: 10,
runSpacing: 14,
children: [
for (final style in styles)
SizedBox(
width: w,
child: GestureDetector(
onTap: () => s.setTarget(style),
child: Column(
children: [
Stack(
children: [
Container(
height: w * 0.92,
width: w,
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: c.isDark ? c.card2 : c.tile,
borderRadius: BorderRadius.circular(14),
border: Border.all(color: style == s.target ? c.accent : Colors.transparent, width: 2),
),
child: Center(child: TargetThumb(style, size: w * 0.92 - 16)),
),
if (style == s.target)
Positioned(
top: 6,
right: 6,
child: Container(
width: 20,
height: 20,
decoration: BoxDecoration(color: c.accent, shape: BoxShape.circle),
child: Icon(Icons.check_rounded, size: 14, color: c.onAccent),
),
),
],
),
const SizedBox(height: 6),
Text(
style.name(s.language),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12,
fontWeight: style == s.target ? FontWeight.w700 : FontWeight.w500,
color: style == s.target ? c.ink : c.muted,
),
),
],
),
),
),
],
);
});
}
}
/// In the Videz sheet during a holiday: its target, locked until the holiday ends.
class _HolidayCard extends StatelessWidget {
final HolidayTheme holiday;
const _HolidayCard({required this.holiday});
@override
Widget build(BuildContext context) {
final s = AppSettings.instance;
final c = Palette.current;
final (_, end) = holiday.window(s.today);
return AppCard(
color: c.isDark ? c.card2 : c.card,
borderColor: holiday.color.withValues(alpha: 0.5),
padding: const EdgeInsets.all(14),
child: Row(
children: [
TargetThumb(TargetStyle.byId(holiday.targetId), size: 72),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(Icons.celebration_outlined, size: 18, color: holiday.color),
const SizedBox(width: 6),
Flexible(
child: Text(holiday.name,
style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: c.ink)),
),
],
),
const SizedBox(height: 4),
Text(
'${s.t('Holiday target until')} ${DateFormat('d. M.').format(end)}',
style: TextStyle(fontSize: 12.5, height: 1.35, fontWeight: FontWeight.w600, color: c.ink2),
),
Text(s.t('You can still change the hit colour.'),
style: TextStyle(fontSize: 12.5, height: 1.35, color: c.muted)),
],
),
),
const SizedBox(width: 6),
Icon(Icons.lock_outline_rounded, size: 18, color: c.faint),
],
),
);
}
@@ -405,44 +536,18 @@ class _ColorDot extends StatelessWidget {
@override
Widget build(BuildContext context) {
final c = Palette.current;
return Container(
width: size,
height: size,
padding: EdgeInsets.all(selected ? 3 : 0),
decoration: BoxDecoration(
color: color,
shape: BoxShape.circle,
border: Border.all(
color: selected ? Colors.white : Colors.black26,
width: selected ? 3 : 1,
),
border: selected ? Border.all(color: c.ink, width: 2) : null,
),
child: selected ? const Icon(Icons.check_rounded, color: Colors.white) : null,
);
}
}
class _TargetThumb extends StatelessWidget {
final String path;
final double? size;
final double radius;
const _TargetThumb(this.path, {this.size, this.radius = 6});
@override
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: BorderRadius.circular(radius),
child: Container(
width: size,
height: size,
color: TargetColors.getBackgroundColor(path),
padding: const EdgeInsets.all(2),
child: Image.asset(
path,
fit: BoxFit.contain,
cacheWidth: 300,
errorBuilder: (_, __, ___) => const Icon(Icons.image_not_supported, color: Colors.white54),
),
decoration: BoxDecoration(color: color, shape: BoxShape.circle),
child: selected ? Icon(Icons.check_rounded, size: size * 0.5, color: Palette.onColor(color)) : null,
),
);
}
+177 -355
View File
@@ -1,34 +1,34 @@
import 'package:flutter/material.dart';
import 'package:flutter_mjpeg/flutter_mjpeg.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../utils/translations.dart';
import '../services/app_settings.dart';
import '../services/wifi_binding.dart';
import '../theme/app_theme.dart';
import '../widgets/ui.dart';
import 'stream_screen.dart';
/// Opazuj: every chosen camera of the current location live, two per row.
class SpectatorScreen extends StatefulWidget {
final String selectedLanguage;
const SpectatorScreen({
super.key,
required this.selectedLanguage,
});
const SpectatorScreen({super.key, required this.selectedLanguage});
@override
State<SpectatorScreen> createState() => _SpectatorScreenState();
}
class _SpectatorScreenState extends State<SpectatorScreen> {
final List<bool> _selectedCameras = List.generate(6, (_) => true); // All selected by default
List<bool> _enabledCameras = List.generate(6, (_) => false); // Which cameras have IPs configured
List<Map<String, dynamic>> _cameras = [];
Color _bulletColor = Colors.blue; // default/fallback bullet color
final Set<int> _hidden = {}; // positions switched off in "Izberi kamere"
late final Future<void> _wifiReady;
bool _ready = false;
@override
void initState() {
super.initState();
_wifiReady = WifiBinding.acquire();
_loadCameras();
_loadBulletColor();
// Streams must start after traffic is pinned to Wi-Fi
_wifiReady.then((_) {
if (mounted) setState(() => _ready = true);
});
}
@override
@@ -37,376 +37,198 @@ class _SpectatorScreenState extends State<SpectatorScreen> {
super.dispose();
}
String _t(String key) {
return AppTranslations.translate(key, widget.selectedLanguage);
String _t(String key) => AppSettings.instance.t(key);
String? get _location {
final cams = AppSettings.instance.cameras;
if (cams.locations.isEmpty) return null;
return cams.locations.contains(cams.activeLocation) ? cams.activeLocation : cams.locations.first;
}
Future<void> _loadCameras() async {
await _wifiReady; // streams must start after traffic is pinned to Wi-Fi
final prefs = await SharedPreferences.getInstance();
List<Map<String, dynamic>> cameras = [];
List<bool> enabledCameras = List.generate(6, (_) => false);
for (int i = 0; i < 6; i++) {
String? ip = prefs.getString('cameraIP_${i + 1}');
if (ip != null && ip.isNotEmpty && ip != 'Not Set') {
cameras.add({
'index': i + 1,
'ip': ip,
});
enabledCameras[i] = true; // Mark camera as enabled
}
}
if (mounted) {
setState(() {
_cameras = cameras;
_enabledCameras = enabledCameras;
});
}
}
Future<void> _loadBulletColor() async {
final prefs = await SharedPreferences.getInstance();
final selected = prefs.getString('bulletColor') ?? 'Blue';
setState(() {
_bulletColor = _getColorFromName(selected);
});
}
Color _getColorFromName(String colorName) {
switch (colorName.toLowerCase()) {
case 'blue':
return Colors.blue;
case 'green':
return Colors.green;
case 'yellow':
return Colors.yellow;
case 'purple':
return Colors.purple;
case 'cyan':
return Colors.cyan;
case 'teal':
return Colors.teal;
case 'indigo':
return Colors.indigo;
case 'pink':
return Colors.pink;
case 'lime':
return Colors.lime;
case 'mint':
return Colors.greenAccent;
case 'orange':
return Colors.orange;
case 'violet':
return Colors.deepPurpleAccent;
case 'amber':
return Colors.amber;
case 'brown':
return Colors.brown;
case 'grey':
return Colors.grey;
default:
return Colors.blue;
}
// Positions with a camera at the location, with their address
List<(int, String)> get _cameras {
final s = AppSettings.instance;
final location = _location;
if (location == null) return const [];
return [
for (int p = 1; p <= s.cameras.positions; p++)
if (s.cameras.ipFor(p, location).isNotEmpty) (p, s.cameras.ipFor(p, location)),
];
}
void _showCameraSelection() {
showDialog(
context: context,
builder: (context) => StatefulBuilder(
builder: (context, setModalState) => Dialog(
backgroundColor: Colors.grey[900],
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
child: Container(
padding: const EdgeInsets.fromLTRB(24, 20, 24, 20),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
_t('Select Cameras'),
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 24),
// Row 1: Cameras 1-3
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: List.generate(3, (index) {
final cameraNum = index + 1;
final isSelected = _selectedCameras[index];
final isEnabled = _enabledCameras[index];
final c = Palette.current;
final s = AppSettings.instance;
showAppSheet(
context,
title: _t('Select Cameras'),
subtitle: _location,
builder: (sheet) => StatefulBuilder(
builder: (context, setSheet) => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (int p = 1; p <= s.cameras.positions; p++)
Builder(builder: (_) {
final ip = _location == null ? '' : s.cameras.ipFor(p, _location!);
final enabled = ip.isNotEmpty;
final on = enabled && !_hidden.contains(p);
void toggle() {
if (!enabled) return;
setState(() => on ? _hidden.add(p) : _hidden.remove(p));
setSheet(() {});
}
return GestureDetector(
onTap: isEnabled
? () {
// Update both modal and parent state simultaneously
_selectedCameras[index] = !_selectedCameras[index];
setModalState(() {});
if (mounted) {
setState(() {});
}
}
: null,
child: Container(
width: 50,
height: 50,
decoration: BoxDecoration(
color: !isEnabled
? Colors.grey[700]
: (isSelected ? _bulletColor : Colors.grey[800]),
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: !isEnabled
? Colors.grey[600]!
: (isSelected ? _bulletColor : Colors.grey[700]!),
width: 2,
),
return InkWell(
onTap: toggle,
child: Container(
height: 52,
decoration: BoxDecoration(border: p > 1 ? Border(top: BorderSide(color: c.line2)) : null),
child: Row(
children: [
SizedBox.square(
dimension: 24,
child: Checkbox(value: on, onChanged: enabled ? (_) => toggle() : null),
),
child: Center(
child: Text(
'$cameraNum',
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
const SizedBox(width: 14),
Expanded(
child: Text('${_t('Camera')} $p',
style: TextStyle(fontSize: 15, fontWeight: FontWeight.w500, color: enabled ? c.ink : c.faint)),
),
),
);
}),
),
const SizedBox(height: 16),
// Row 2: Cameras 4-6
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: List.generate(3, (index) {
final cameraNum = index + 4;
final arrayIndex = index + 3;
final isSelected = _selectedCameras[arrayIndex];
final isEnabled = _enabledCameras[arrayIndex];
return GestureDetector(
onTap: isEnabled
? () {
// Update both modal and parent state simultaneously
_selectedCameras[arrayIndex] = !_selectedCameras[arrayIndex];
setModalState(() {});
if (mounted) {
setState(() {});
}
}
: null,
child: Container(
width: 50,
height: 50,
decoration: BoxDecoration(
color: !isEnabled
? Colors.grey[700]
: (isSelected ? _bulletColor : Colors.grey[800]),
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: !isEnabled
? Colors.grey[600]!
: (isSelected ? _bulletColor : Colors.grey[700]!),
width: 2,
),
),
child: Center(
child: Text(
'$cameraNum',
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
),
),
);
}),
),
const SizedBox(height: 24),
Container(
padding: const EdgeInsets.only(top: 16),
decoration: BoxDecoration(
border: Border(
top: BorderSide(color: Colors.grey[700]!, width: 1),
Text(enabled ? ip.split(':').first : _t('Not set up'),
style: TextStyle(
fontSize: 12, fontFamily: enabled ? AppTheme.mono : null, color: enabled ? c.muted : c.faint)),
],
),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(height: 16),
SizedBox(
width: double.infinity,
height: 40,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: _bulletColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
onPressed: () => Navigator.pop(context),
child: Text(
_t('Done'),
style: const TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.w600,
),
),
),
),
],
),
),
],
),
),
);
}),
const SizedBox(height: 16),
PrimaryButton(label: _t('Done'), onTap: () => Navigator.pop(sheet)),
],
),
),
);
}
String _cameraCount(int n) {
if (AppSettings.instance.language == 'Slovenian') {
final mod = n % 100;
return '$n ${mod == 1 ? 'kamera' : mod == 2 ? 'kameri' : (mod == 3 || mod == 4) ? 'kamere' : 'kamer'}';
}
return _t('{n} cameras').replaceAll('{n}', '$n');
}
@override
Widget build(BuildContext context) {
final visibleCameras = <Map<String, dynamic>>[];
for (int i = 0; i < _cameras.length; i++) {
if (_selectedCameras[_cameras[i]['index'] - 1]) {
visibleCameras.add(_cameras[i]);
}
}
final c = Palette.current;
final visible = [for (final cam in _cameras) if (!_hidden.contains(cam.$1)) cam];
final location = _location;
// Portrait list view
return Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
title: Text(
_t('Spectate'),
style: const TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.w600,
body: Column(
children: [
BackHeader(
title: _t('Spectate'),
subtitle: [_cameraCount(visible.length), if (location != null) location].join(' · '),
actions: [
Material(
color: c.tile,
borderRadius: BorderRadius.circular(12),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: _showCameraSelection,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
child: Row(
children: [
Icon(Icons.grid_view_rounded, size: 17, color: c.ink),
const SizedBox(width: 6),
Text(_t('Choose'), style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: c.ink)),
],
),
),
),
),
],
),
),
backgroundColor: Colors.grey[900],
elevation: 0,
scrolledUnderElevation: 0,
leading: IconButton(
icon: const Icon(Icons.arrow_back, color: Colors.white),
onPressed: () => Navigator.pop(context),
),
actions: [
IconButton(
icon: const Icon(Icons.settings, color: Colors.white),
onPressed: _showCameraSelection,
Expanded(
child: !_ready
? const Center(child: CircularProgressIndicator())
: LayoutBuilder(builder: (context, box) {
final w = (box.maxWidth - 2 * AppTheme.edge - 12) / 2;
return SingleChildScrollView(
padding: EdgeInsets.fromLTRB(AppTheme.edge, 4, AppTheme.edge, 24 + MediaQuery.paddingOf(context).bottom),
child: Wrap(
spacing: 12,
runSpacing: 12,
children: [
for (final (p, ip) in visible) SizedBox(width: w, child: _cameraCard(c, p, ip, location!)),
],
),
);
}),
),
],
),
body: visibleCameras.isEmpty
? Center(
child: Text(
_t('No cameras selected'),
style: const TextStyle(
color: Colors.white,
fontSize: 16,
),
),
)
: ListView.builder(
padding: const EdgeInsets.fromLTRB(4, 4, 4, 16),
itemCount: visibleCameras.length,
itemBuilder: (context, index) {
final camera = visibleCameras[index];
final cameraIndex = camera['index'] as int;
final cameraIp = camera['ip'] as String;
);
}
final streamUrl = cameraIp.startsWith(RegExp(r"https?://"))
? cameraIp
: "http://$cameraIp";
// 4:3 aspect ratio = width / height (640x480 stream)
return Container(
margin: const EdgeInsets.only(bottom: 4),
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: Colors.grey[800]!, width: 1),
),
child: AspectRatio(
aspectRatio: 4 / 3,
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Stack(
children: [
Mjpeg(
stream: streamUrl,
isLive: true,
fit: BoxFit.cover,
error: (context, error, stackTrace) => Container(
color: Colors.grey[700],
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.videocam_off,
color: Colors.white,
size: 32,
),
const SizedBox(height: 8),
Text(
"${_t('Camera')} $cameraIndex",
style: const TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.w600,
),
textAlign: TextAlign.center,
),
],
),
),
),
),
// Camera number circle - top right (with bullet color)
Positioned(
top: 8,
right: 8,
child: Container(
width: 36,
height: 36,
decoration: BoxDecoration(
color: _bulletColor,
shape: BoxShape.circle,
),
child: Center(
child: Text(
'$cameraIndex',
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
),
),
),
],
),
Widget _cameraCard(Palette c, int position, String ip, String location) {
final url = ip.startsWith(RegExp(r'https?://')) ? ip : 'http://$ip';
void open() => Navigator.push(
context,
MaterialPageRoute(builder: (_) => CameraStreamScreen(cameraIndex: position, ip: ip, location: location)),
);
return AppCard(
padding: EdgeInsets.zero,
onTap: open,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
AspectRatio(
aspectRatio: 0.78,
child: Stack(
fit: StackFit.expand,
children: [
ColoredBox(
color: Colors.black,
child: Mjpeg(
stream: url,
isLive: true,
fit: BoxFit.cover,
error: (context, error, stackTrace) => ColoredBox(
color: c.tile,
child: Icon(Icons.videocam_off_outlined, color: c.muted, size: 30),
),
),
);
},
),
Positioned(
top: 10,
left: 10,
child: StatusChip(label: _t('Live'), dot: true, color: c.red, background: Colors.black.withValues(alpha: 0.55)),
),
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(12, 10, 10, 12),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('${_t('Camera')} $position', style: TextStyle(fontSize: 14.5, fontWeight: FontWeight.w700, color: c.ink)),
Text(location, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 11.5, color: c.muted)),
],
),
),
Icon(Icons.open_in_new_rounded, size: 17, color: c.muted),
],
),
),
],
),
);
}
}
File diff suppressed because it is too large Load Diff
+249 -95
View File
@@ -1,66 +1,88 @@
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';
/// Shooting: one tile per position. A position with cameras at several
/// locations asks where we are shooting before opening the stream.
class TargetScreen extends StatelessWidget {
/// 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});
void _openPosition(BuildContext context, int position) {
@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 cameras = s.cameras.camerasAt(position);
if (cameras.isEmpty) {
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;
}
if (cameras.length == 1) {
_openStream(context, position, cameras.keys.first, cameras.values.first);
return;
}
showModalBottomSheet(
context: context,
builder: (sheet) => SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
s.t('Where are we shooting?'),
style: const TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold),
),
Text(
'${s.t('Camera')} $position',
style: const TextStyle(color: Colors.white54, fontSize: 12),
),
const SizedBox(height: 8),
for (final entry in cameras.entries)
ListTile(
leading: Icon(Icons.place_rounded, color: s.bulletColor),
title: Text(entry.key, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w600)),
subtitle: Text(entry.value, style: const TextStyle(color: Colors.white54)),
trailing: entry.key == s.cameras.activeLocation
? Icon(Icons.check_rounded, color: s.bulletColor)
: const Icon(Icons.chevron_right, color: Colors.white38),
onTap: () {
Navigator.pop(sheet);
_openStream(context, position, entry.key, entry.value);
},
),
const SizedBox(height: 8),
],
),
),
Navigator.push(
context,
MaterialPageRoute(builder: (_) => CameraStreamScreen(cameraIndex: position, ip: ip, location: location)),
);
}
void _openStream(BuildContext context, int position, String location, String ip) {
AppSettings.instance.setActiveLocation(location);
void _openLast() {
final last = _last;
if (last == null) return;
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => CameraStreamScreen(cameraIndex: position, ip: ip, location: location),
builder: (_) => TargetViewScreen(jsonFiles: last.files, refreshFolders: _load, isCombinedView: true),
),
);
}
@@ -71,63 +93,195 @@ class TargetScreen extends StatelessWidget {
listenable: AppSettings.instance,
builder: (context, _) {
final s = AppSettings.instance;
final c = Palette.current;
final setup = s.cameras;
final location = _location(s);
return GridView.builder(
padding: const EdgeInsets.fromLTRB(24, 32, 24, 32),
itemCount: setup.positions,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 16,
crossAxisSpacing: 16,
),
itemBuilder: (context, i) {
final position = i + 1;
final locations = setup.camerasAt(position).keys.toList();
final enabled = locations.isNotEmpty;
final surf = Surfaces.current;
return Material(
color: enabled ? Colors.grey[900] : surf.card,
borderRadius: BorderRadius.circular(16),
child: InkWell(
borderRadius: BorderRadius.circular(16),
onTap: () => _openPosition(context, position),
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
enabled ? Icons.videocam_rounded : Icons.videocam_off_rounded,
color: enabled ? Colors.white : surf.textSecondary,
size: 36,
),
const SizedBox(height: 12),
Text(
'${s.t('Camera')} $position',
style: TextStyle(
color: enabled ? Colors.white : surf.textSecondary,
fontSize: 20,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 4),
Text(
enabled ? locations.join(' · ') : s.t('Not set up'),
textAlign: TextAlign.center,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, color: enabled ? Colors.white60 : surf.textSecondary),
),
],
// 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))),
],
),
],
),
);
}
}
+330 -1060
View File
File diff suppressed because it is too large Load Diff