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
+35 -38
View File
@@ -22,16 +22,7 @@ void main() async {
DeviceOrientation.portraitDown,
]);
// Set system UI overlay style globally for the app
SystemChrome.setSystemUIOverlayStyle(
SystemUiOverlayStyle(
statusBarColor: Colors.grey[900],
systemNavigationBarColor: Colors.grey[900],
systemNavigationBarIconBrightness: Brightness.light,
// No grey scrim behind 3-button navigation; we paint the strip ourselves
systemNavigationBarContrastEnforced: false,
),
);
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
runApp(const MyApp());
}
@@ -41,37 +32,43 @@ class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'SD Kovinar',
debugShowCheckedModeBanner: false,
theme: AppTheme.light(),
darkTheme: AppTheme.dark(),
builder: (context, child) {
final originalTextScaler = MediaQuery.of(context).textScaler;
final clampedScale =
originalTextScaler.clamp(minScaleFactor: 0.8, maxScaleFactor: 1.2);
// Edge-to-edge (Android 15+) ignores the navigation bar color, so paint
// the system bar strip ourselves on every screen, matching our bars.
final systemBar = MediaQuery.viewPaddingOf(context).bottom;
return MediaQuery(
data: MediaQuery.of(context).copyWith(
textScaler: clampedScale,
),
child: Stack(
children: [
child!,
Positioned(
left: 0,
right: 0,
bottom: 0,
height: systemBar,
child: IgnorePointer(child: ColoredBox(color: AppTheme.bar)),
// Theme (Sistem / Svetla / Temna) and the hit colour change the whole app live
return ListenableBuilder(
listenable: AppSettings.instance,
builder: (context, _) {
final palette = AppSettings.instance.palette;
return MaterialApp(
title: 'SD Kovinar',
debugShowCheckedModeBanner: false,
theme: AppTheme.theme(palette),
builder: (context, child) {
final originalTextScaler = MediaQuery.of(context).textScaler;
final clampedScale = originalTextScaler.clamp(minScaleFactor: 0.8, maxScaleFactor: 1.2);
// Edge-to-edge (Android 15+) ignores the navigation bar color, so paint
// the system bar strip ourselves on every screen, matching our bars.
final systemBar = MediaQuery.viewPaddingOf(context).bottom;
return AnnotatedRegion<SystemUiOverlayStyle>(
value: AppTheme.overlay(palette),
child: MediaQuery(
data: MediaQuery.of(context).copyWith(textScaler: clampedScale),
child: Stack(
children: [
child!,
Positioned(
left: 0,
right: 0,
bottom: 0,
height: systemBar,
child: IgnorePointer(child: ColoredBox(color: palette.nav)),
),
],
),
),
],
),
);
},
home: const HomeScreen(),
);
},
home: const HomeScreen(),
);
}
}
+3
View File
@@ -3,12 +3,14 @@ class Contact {
final String lastName;
final String phone;
final String email;
final String role; // "predsednik", "članica" …; empty when the club data has none
const Contact({
required this.firstName,
required this.lastName,
required this.phone,
required this.email,
this.role = '',
});
String get fullName => '$firstName $lastName';
@@ -18,5 +20,6 @@ class Contact {
lastName: json['lastName'] ?? '',
phone: json['phone'] ?? '',
email: json['email'] ?? '',
role: json['role'] ?? '',
);
}
+96
View File
@@ -0,0 +1,96 @@
import 'package:flutter/material.dart';
/// A holiday look (FigCraft Designs/holiday-themes/v2, themes.json): while a
/// holiday's window is on, the app shows its background, its target (locked)
/// and its hit colour (until the user picks another one). Afterwards everything
/// is back to the user's own settings. Saved targets are never changed.
class HolidayTheme {
final String id; // "01" … "10"; "00" is the everyday look
final String name; // Slovenian name, also shown in the app
final int targetId; // TargetStyle id (70–79)
final Color color; // hit colour, the same in dark and light
// Window: month-day range (inclusive, may cross the new year) …
final (int, int)? from;
final (int, int)? to;
// … or days relative to Easter Sunday (inclusive)
final (int, int)? easter;
const HolidayTheme(this.id, this.name, this.targetId, this.color, {this.from, this.to, this.easter});
String background(bool dark) => 'assets/backgrounds/bg${id}_${dark ? 'dark' : 'light'}.webp';
/// In the order of themes.json: when windows overlap, the first one wins.
static const List<HolidayTheme> all = [
HolidayTheme('01', 'Božič', 70, Color(0xFFF2C12E), from: (12, 1), to: (12, 26)),
HolidayTheme('02', 'Novo leto', 71, Color(0xFF2EC7FF), from: (12, 27), to: (1, 2)),
HolidayTheme('03', 'Valentinovo', 73, Color(0xFFFFD27A), from: (2, 12), to: (2, 15)),
HolidayTheme('04', 'Pust', 75, Color(0xFFFF2F6D), easter: (-52, -46)),
HolidayTheme('05', 'Velika noč', 72, Color(0xFFFF8A1A), easter: (-7, 1)),
HolidayTheme('06', 'Praznik dela', 77, Color(0xFF2F8CFF), from: (4, 30), to: (5, 2)),
HolidayTheme('07', 'Kresna noč', 78, Color(0xFF7FE0FF), from: (6, 21), to: (6, 23)),
HolidayTheme('08', 'Dan državnosti', 79, Color(0xFFF2C12E), from: (6, 24), to: (6, 26)),
HolidayTheme('09', 'Noč čarovnic', 74, Color(0xFF7CFF6B), from: (10, 25), to: (11, 1)),
HolidayTheme('10', 'Martinovo', 76, Color(0xFF2EC7FF), from: (11, 8), to: (11, 11)),
];
/// The holiday on [day], or null on an ordinary day.
static HolidayTheme? on(DateTime day) {
final d = DateTime(day.year, day.month, day.day);
for (final h in all) {
if (h.covers(d)) return h;
}
return null;
}
bool covers(DateTime d) {
final e = easter;
if (e != null) {
final first = easterDay(d.year, e.$1);
final last = easterDay(d.year, e.$2);
return !d.isBefore(first) && !d.isAfter(last);
}
final md = d.month * 100 + d.day;
final a = from!.$1 * 100 + from!.$2;
final b = to!.$1 * 100 + to!.$2;
return a <= b ? md >= a && md <= b : md >= a || md <= b; // crosses the new year
}
/// First and last day of this holiday's window around [today] (for "until …").
(DateTime, DateTime) window(DateTime today) {
final e = easter;
if (e != null) {
return (easterDay(today.year, e.$1), easterDay(today.year, e.$2));
}
final crosses = from!.$1 * 100 + from!.$2 > to!.$1 * 100 + to!.$2;
final startYear = crosses && today.month <= to!.$1 ? today.year - 1 : today.year;
final start = DateTime(startYear, from!.$1, from!.$2);
final end = DateTime(crosses ? startYear + 1 : startYear, to!.$1, to!.$2);
return (start, end);
}
/// The day [offset] days from Easter Sunday. Calendar days, not 24-hour
/// steps: those would land on the evening before across the March clock change.
static DateTime easterDay(int year, int offset) {
final e = easterSunday(year);
return DateTime(e.year, e.month, e.day + offset);
}
/// Easter Sunday (anonymous Gregorian algorithm).
static DateTime easterSunday(int year) {
final a = year % 19;
final b = year ~/ 100;
final c = year % 100;
final d = b ~/ 4;
final e = b % 4;
final f = (b + 8) ~/ 25;
final g = (b - f + 1) ~/ 3;
final h = (19 * a + b - d - g + 15) % 30;
final i = c ~/ 4;
final k = c % 4;
final l = (32 + 2 * e + 2 * i - h - k) % 7;
final m = (a + 11 * h + 22 * l) ~/ 451;
final month = (h + l - 7 * m + 114) ~/ 31;
final day = (h + l - 7 * m + 114) % 31 + 1;
return DateTime(year, month, day);
}
}
+66
View File
@@ -0,0 +1,66 @@
import 'package:flutter/material.dart';
/// Where a target design comes from (only used to order and group the picker).
enum TargetGroup { classic, design, holiday }
/// One target design of the v3 set (FigCraft Designs/target-designs/v3).
///
/// Every design has the same geometry in a 1200 × 1200 space: centre
/// (600, 600), ring 1 at r 510, the black at r 180; decoration and glow only
/// outside ring 1. Hits are stored in that space, so a hit lands on the same
/// ring whatever design is picked. The default ([id] 0) is drawn as vectors
/// (sharp at any zoom); the others are 1600 px WebP images with transparency.
class TargetStyle {
final int id; // 1–35 are the old Target<id>.jpg, so saved choices carry over
final String sl;
final String en;
final String de;
final TargetGroup group;
final Color glow; // outer glow colour, used for the picker's selection ring
const TargetStyle(this.id, this.sl, this.en, this.de, this.group, this.glow);
bool get isDefault => id == 0;
bool get isHoliday => group == TargetGroup.holiday;
/// Image asset; null for the vector default.
String? get asset => isDefault ? null : 'assets/targets/v3/t${id.toString().padLeft(2, '0')}.webp';
String name(String language) => switch (language) {
'Slovenian' => sl,
'German' => de,
_ => en,
};
static const TargetStyle fallback = TargetStyle(0, 'Privzeta', 'Default', 'Standard', TargetGroup.classic, Color(0xFF9FD8FF));
static TargetStyle byId(int? id) =>
[...all, ...holidays].firstWhere((t) => t.id == id, orElse: () => fallback);
/// Holiday targets: never in the picker, only shown (locked) during their
/// holiday – see HolidayTheme.
static const List<TargetStyle> holidays = [
TargetStyle(70, 'Božič', 'Christmas', 'Weihnachten', TargetGroup.holiday, Color(0xFFE2231A)),
TargetStyle(71, 'Novo leto', 'New Year', 'Neujahr', TargetGroup.holiday, Color(0xFF7A2CFF)),
TargetStyle(72, 'Velika noč', 'Easter', 'Ostern', TargetGroup.holiday, Color(0xFFB6E86E)),
TargetStyle(73, 'Valentinovo', 'Valentine\'s Day', 'Valentinstag', TargetGroup.holiday, Color(0xFFE2112F)),
TargetStyle(74, 'Noč čarovnic', 'Halloween', 'Halloween', TargetGroup.holiday, Color(0xFF7A2CFF)),
TargetStyle(75, 'Pust', 'Carnival', 'Fasching', TargetGroup.holiday, Color(0xFFFF2F6D)),
TargetStyle(76, 'Martinovo', 'St Martin\'s Day', 'Martinstag', TargetGroup.holiday, Color(0xFF7A1E4A)),
TargetStyle(77, 'Praznik dela', 'Labour Day', 'Tag der Arbeit', TargetGroup.holiday, Color(0xFFE2231A)),
TargetStyle(78, 'Kresna noč', 'Midsummer night', 'Johannisnacht', TargetGroup.holiday, Color(0xFFFF3D00)),
TargetStyle(79, 'Dan državnosti', 'Statehood Day', 'Staatsfeiertag', TargetGroup.holiday, Color(0xFF1C4FA0)),
];
/// The designs the app ships, in picker order. The rest of the v3 set
/// (FigCraft Designs/target-designs/v3) is not used for now; to bring one
/// back, add its line here and its webp to assets/targets/v3.
static const List<TargetStyle> all = [
fallback,
TargetStyle(1, 'Lovorov venec', 'Laurel wreath', 'Lorbeerkranz', TargetGroup.classic, Color(0xFF3E8A1E)),
TargetStyle(42, 'ISSF ecru', 'ISSF ecru', 'ISSF Ecru', TargetGroup.design, Color(0xFFE8D9B0)),
TargetStyle(5, 'Plameni', 'Flames', 'Flammen', TargetGroup.classic, Color(0xFFFF3D00)),
TargetStyle(8, 'Val', 'Wave', 'Welle', TargetGroup.classic, Color(0xFF0B8BD9)),
TargetStyle(7, 'Sončno rumena', 'Sunny yellow', 'Sonnengelb', TargetGroup.classic, Color(0xFFFFA000)),
];
}
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
+159 -48
View File
@@ -6,7 +6,9 @@ import 'package:shared_preferences/shared_preferences.dart';
import '../models/camera_setup.dart';
import '../models/contact.dart';
import 'club_crypto.dart';
import '../utils/target_colors.dart';
import '../models/holiday_theme.dart';
import '../models/target_style.dart';
import '../theme/app_theme.dart';
import '../utils/translations.dart';
/// Single source of truth for user settings. Loaded once in main(); widgets
@@ -14,11 +16,10 @@ import '../utils/translations.dart';
///
/// Writes the same SharedPreferences keys the rest of the app already reads,
/// so screens can migrate to this class one at a time.
class AppSettings extends ChangeNotifier {
class AppSettings extends ChangeNotifier with WidgetsBindingObserver {
AppSettings._();
static final AppSettings instance = AppSettings._();
static const String defaultTarget = 'assets/target.png';
// Shots per target, same limit for camera and stream capture
static const int minBullets = 1;
static const int maxBullets = 5;
@@ -31,38 +32,36 @@ class AppSettings extends ChangeNotifier {
];
static const String defaultLanguage = 'Slovenian';
static const Map<String, Color> bulletColors = {
'Blue': Colors.blue,
'Green': Colors.green,
'Yellow': Colors.yellow,
'Purple': Colors.purple,
'Cyan': Colors.cyan,
'Teal': Colors.teal,
'Indigo': Colors.indigo,
'Pink': Colors.pink,
'Lime': Colors.lime,
'Mint': Colors.greenAccent,
'Orange': Colors.orange,
'Violet': Colors.deepPurpleAccent,
'Amber': Colors.amber,
'Brown': Colors.brown,
'Grey': Colors.grey,
/// Hit colours, each tuned for the dark and the light theme. The chosen
/// one is the accent of the whole interface.
static const Map<String, (Color dark, Color light)> bulletColors = {
'Blue': (Color(0xFF4B8EF5), Color(0xFF2D6BD8)),
'Green': (Color(0xFF3CC764), Color(0xFF1E9A4C)),
'Yellow': (Color(0xFFF2C12E), Color(0xFFC08E00)),
'Purple': (Color(0xFFB45EE3), Color(0xFF8E3FBF)),
'Cyan': (Color(0xFF22C7E0), Color(0xFF12B4CE)),
'Teal': (Color(0xFF17B3A3), Color(0xFF0E9384)),
'Indigo': (Color(0xFF6E6CF2), Color(0xFF4F46E5)),
'Pink': (Color(0xFFF0457A), Color(0xFFD63366)),
'Lime': (Color(0xFFC9DC3C), Color(0xFF85A00E)),
'Mint': (Color(0xFF5EE6B0), Color(0xFF1FAE7A)),
'Orange': (Color(0xFFFF8A1F), Color(0xFFE06F00)),
'Violet': (Color(0xFF8E62F7), Color(0xFF7C3AED)),
'Amber': (Color(0xFFFFB020), Color(0xFFD18A00)),
'Brown': (Color(0xFFB07A55), Color(0xFF8A5536)),
'Grey': (Color(0xFFA3AAB2), Color(0xFF6F757C)),
};
static const String defaultBulletColor = 'Cyan';
// 13 was dropped earlier; 21 and 31–34 were Christmas / Easter themes
static const Set<int> removedTargets = {13, 21, 31, 32, 33, 34};
static final List<String> targets = [
defaultTarget,
for (int i = 1; i <= 35; i++)
if (!removedTargets.contains(i)) 'assets/targets/Target$i.jpg',
];
static const List<String> themeModes = ['system', 'light', 'dark'];
late SharedPreferences _prefs;
String _language = defaultLanguage;
String _bulletColorName = 'Blue';
String _selectedTarget = defaultTarget;
String _bulletColorName = defaultBulletColor;
String _themeMode = 'dark';
TargetStyle _target = TargetStyle.fallback;
Palette? _palette;
int _reminderHours = 1;
bool _notifyDezuranje = true;
bool _notifySestanek = true;
@@ -80,10 +79,96 @@ class AppSettings extends ChangeNotifier {
};
String get dateLocale => dateLocaleFor(_language);
String get bulletColorName => _bulletColorName;
Color get bulletColor => bulletColors[_bulletColorName] ?? Colors.blue;
String get selectedTarget => _selectedTarget;
Color get backgroundColor => TargetColors.getBackgroundColor(_selectedTarget);
bool get isLightBackground => backgroundColor.computeLuminance() > 0.4;
/// The hit colour in the current theme; also the interface accent.
Color get bulletColor => palette.accent;
// --- Holidays (a hidden easter egg, no setting) ---
// During a holiday's window the app shows that holiday's background and
// target (locked) and its hit colour, until the user picks a colour of their
// own for this holiday. Afterwards their own settings are back.
/// Debug builds only: pretend today is this day, to preview a holiday.
DateTime? debugToday;
DateTime get today => debugToday ?? DateTime.now();
HolidayTheme? get holiday => HolidayTheme.on(today);
/// True while a holiday decides the target.
bool get targetLocked => holiday != null;
// "<holiday id>-<first day>" of the holiday whose colour the user replaced
String? _holidayColorFor;
String _holidayKey(HolidayTheme h) {
final (start, _) = h.window(today);
return '${h.id}-${start.year}${start.month.toString().padLeft(2, '0')}${start.day.toString().padLeft(2, '0')}';
}
/// The holiday colour is in use (the user has not picked another one).
bool get holidayColorActive {
final h = holiday;
return h != null && _holidayColorFor != _holidayKey(h);
}
/// Back to the holiday's own colour (after picking another one).
Future<void> useHolidayColor() async {
_holidayColorFor = null;
notifyListeners();
await _prefs.remove('holidayColorFor');
}
/// The holiday's screen background (the everyday one is painted, see AppBackground).
String get background => holiday?.background(isDark) ?? '';
// A new day may start or end a holiday
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) notifyListeners();
}
/// Swatch of [name] in the current theme.
Color colorFor(String name) {
final pair = bulletColors[name] ?? bulletColors[defaultBulletColor]!;
return isDark ? pair.$1 : pair.$2;
}
String get themeMode => _themeMode;
int _forceDark = 0;
/// Screens that must stay dark whatever the theme (the photo camera) call
/// this while they are open, and [releaseDark] when they close.
void holdDark() {
_forceDark++;
if (_forceDark == 1) notifyListeners();
}
void releaseDark() {
if (_forceDark == 0) return;
_forceDark--;
if (_forceDark == 0) notifyListeners();
}
bool get isDark => _forceDark > 0 || switch (_themeMode) {
'light' => false,
'system' => WidgetsBinding.instance.platformDispatcher.platformBrightness == Brightness.dark,
_ => true,
};
Palette get palette {
final accent = holidayColorActive ? holiday!.color : colorFor(_bulletColorName);
final p = _palette;
if (p != null && p.isDark == isDark && p.accent == accent) return p;
return _palette = isDark ? Palette.dark(accent) : Palette.light(accent);
}
/// The target shown: the holiday's while one is on, otherwise the user's.
TargetStyle get target {
final h = holiday;
return h == null ? _target : TargetStyle.byId(h.targetId);
}
int get reminderHours => _reminderHours;
bool get notifyDezuranje => _notifyDezuranje;
bool get notifySestanek => _notifySestanek;
@@ -96,11 +181,6 @@ class AppSettings extends ChangeNotifier {
String t(String key) => AppTranslations.translate(key, _language);
String targetName(String path) {
if (path == defaultTarget) return t('Default Target');
return t(path.replaceAll('assets/targets/', '').replaceAll('.jpg', ''));
}
Future<void> load() async {
_prefs = await SharedPreferences.getInstance();
// New installs start in Slovenian. Whoever had "automatic" keeps the language
@@ -110,15 +190,21 @@ class AppSettings extends ChangeNotifier {
await _prefs.setString('language', _language); // other screens read this key
await _prefs.remove('languageFollowsSystem');
final color = _prefs.getString('bulletColor') ?? 'Blue';
_bulletColorName = bulletColors.containsKey(color) ? color : 'Blue';
final color = _prefs.getString('bulletColor') ?? defaultBulletColor;
_bulletColorName = bulletColors.containsKey(color) ? color : defaultBulletColor;
_holidayColorFor = _prefs.getString('holidayColorFor');
final mode = _prefs.getString('themeMode');
_themeMode = themeModes.contains(mode) ? mode! : 'dark';
WidgetsBinding.instance.addObserver(this);
_selectedTarget = _prefs.getString('selectedTarget') ?? defaultTarget;
if (!targets.contains(_selectedTarget)) {
// Target no longer shipped: fall back so screens reading prefs don't load a missing image
_selectedTarget = defaultTarget;
await _prefs.setString('selectedTarget', defaultTarget);
// v3 targets keep the numbers of the old skins (assets/targets/Target<n>.jpg)
var targetId = _prefs.getInt('targetStyle');
if (targetId == null) {
final old = RegExp(r'Target(\d+)\.jpg$').firstMatch(_prefs.getString('selectedTarget') ?? '');
targetId = old == null ? 0 : int.parse(old.group(1)!);
await _prefs.setInt('targetStyle', TargetStyle.byId(targetId).id);
}
_target = TargetStyle.byId(targetId);
_reminderHours = _prefs.getInt('notificationHours_single') ?? 1;
_notifyDezuranje = _prefs.getBool('notifyDezuranje') ?? true;
_notifySestanek = _prefs.getBool('notifySestanek') ?? true;
@@ -154,14 +240,39 @@ class AppSettings extends ChangeNotifier {
Future<void> setBulletColor(String name) async {
_bulletColorName = name;
// Picked during a holiday: this colour replaces the holiday's until it ends
final h = holiday;
if (h != null) {
_holidayColorFor = _holidayKey(h);
await _prefs.setString('holidayColorFor', _holidayColorFor!);
}
notifyListeners();
await _prefs.setString('bulletColor', name);
}
Future<void> setTarget(String path) async {
_selectedTarget = path;
Future<void> setTarget(TargetStyle style) async {
if (targetLocked) return; // the holiday decides
_target = style;
notifyListeners();
await _prefs.setString('selectedTarget', path);
await _prefs.setInt('targetStyle', style.id);
}
/// Debug: show the look of [day] (null = today).
void previewDay(DateTime? day) {
debugToday = day;
notifyListeners();
}
Future<void> setThemeMode(String mode) async {
_themeMode = mode;
notifyListeners();
await _prefs.setString('themeMode', mode);
}
// Theme "Sistem" follows the phone
@override
void didChangePlatformBrightness() {
if (_themeMode == 'system') notifyListeners();
}
Future<void> setReminderHours(int hours) async {
+66
View File
@@ -1,7 +1,10 @@
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'dart:ui' show Offset;
import 'package:flutter/foundation.dart' show ValueNotifier;
import 'package:path_provider/path_provider.dart';
import '../utils/target_scoring.dart';
/// One saved target (a JSON file written by the preview screen).
class TargetRecord {
@@ -17,6 +20,49 @@ class TargetRecord {
required this.shots});
}
/// The hits of one saved target, in target space (see [TargetScoring]).
class TargetHits {
final List<Offset> bullets;
final List<int> scores; // same order as [bullets]
final int total;
final int shots; // shots fired, misses included
final String date; // as saved: dd/MM/yyyy
const TargetHits({required this.bullets, required this.scores, required this.total, required this.shots, required this.date});
static const empty = TargetHits(bullets: [], scores: [], total: 0, shots: 0, date: '');
/// All hits of several targets on one target.
static TargetHits combine(List<TargetHits> list) => TargetHits(
bullets: [for (final t in list) ...t.bullets],
scores: [for (final t in list) ...t.scores],
total: list.fold(0, (a, t) => a + t.total),
shots: list.fold(0, (a, t) => a + t.shots),
date: list.isEmpty ? '' : list.last.date,
);
// Newer saves store each shot's score (hand-entered shots keep the score that
// was entered); older ones are scored from the positions, by the same rule.
factory TargetHits.fromJson(Map<String, dynamic> data) {
final bullets = [
for (final b in (data['bullets'] as List?) ?? const [])
Offset((b['x'] as num).toDouble(), (b['y'] as num).toDouble())
];
final saved = data['scores'];
final scores = saved is List && saved.length == bullets.length
? [for (final x in saved) (x as num).toInt()]
: [for (final b in bullets) TargetScoring.scoreAt(b)];
final total = data['totalScore'] is int ? data['totalScore'] as int : scores.fold(0, (a, b) => a + b);
return TargetHits(
bullets: bullets,
scores: scores,
total: total,
shots: (data['bulletCount'] as int?) ?? bullets.length,
date: data['date'] as String? ?? '',
);
}
}
/// A folder of targets: one training or tournament.
class Session {
final String name;
@@ -114,6 +160,11 @@ class ShooterStats {
class TargetRepository {
static Map<String, dynamic>? _index; // path in saved_images -> entry
/// Bumped whenever a target or session is saved, edited or deleted, so open
/// screens (Streljanje, Knjiga) reload.
static final ValueNotifier<int> changed = ValueNotifier(0);
static void notifyChanged() => changed.value++;
static Future<Directory> _root() async {
final dir = Directory(
'${(await getApplicationDocumentsDirectory()).path}/saved_images');
@@ -275,16 +326,31 @@ class TargetRepository {
'isTournament': isTournament,
'createdAt': meta['createdAt'] ?? session.date.toIso8601String(),
}));
notifyChanged();
return true;
}
/// Hits of a saved target file; empty when it can't be read.
static Future<TargetHits> readHits(File file) async {
try {
return TargetHits.fromJson(jsonDecode(await file.readAsString()) as Map<String, dynamic>);
} catch (_) {
return TargetHits.empty;
}
}
/// Hits of several targets, in the order given.
static Future<List<TargetHits>> readAllHits(List<File> files) => Future.wait(files.map(readHits));
static Future<void> deleteSession(Session session) async {
final folder = Directory('${(await _root()).path}/${session.name}');
if (await folder.exists()) await folder.delete(recursive: true);
notifyChanged();
}
static Future<void> deleteTarget(TargetRecord target) async {
if (await target.file.exists()) await target.file.delete();
notifyChanged();
}
}
+419 -58
View File
@@ -1,66 +1,427 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../services/app_settings.dart';
/// Shared colors and component styles. Prefer these over hardcoded
/// Colors.grey[...] so screens look alike and can be restyled in one place.
class AppTheme {
static final Color bar = Colors.grey[900]!; // app bar, bottom nav, sheets
static final Color sheet = Colors.grey[900]!;
/// Colour tokens of the V2 design (shooting-app-design/v2/gen_design.py).
///
/// The bullet colour the user picks (Nastavitve → Videz → Barva zadetkov) is
/// the accent of the whole interface. Real green ([pos]) stays only for
/// meaning: improvements, unlocked. Gold is the colour of a 10 everywhere.
class Palette {
final bool isDark;
final Color bg; // page
final Color card; // cards, sheets
final Color card2; // raised card inside a sheet
final Color field; // text fields
final Color tile; // buttons, chips, segmented selection
final Color line; // borders and dividers
final Color line2; // faint dividers inside cards
final Color ink; // main text
final Color ink2; // body text
final Color muted; // secondary text
final Color faint; // disabled
final Color pos; // improvement / unlocked
final Color posSoft;
final Color gold; // a 10
final Color goldSoft;
final Color goldInk;
final Color red;
final Color redSoft;
final Color amberSoft;
final Color amberInk;
final Color blue; // duty
final Color purple; // meeting
final Color nav; // bottom navigation
final Color accent; // the bullet colour
final List<BoxShadow> shadow; // cards (light only)
final List<BoxShadow> shadowLg; // dialogs
static ThemeData light() {
return ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.white),
useMaterial3: true,
bottomSheetTheme: BottomSheetThemeData(
backgroundColor: sheet,
showDragHandle: true,
dragHandleColor: Colors.white24,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
),
dialogTheme: DialogThemeData(
backgroundColor: sheet,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
titleTextStyle: const TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold),
contentTextStyle: const TextStyle(color: Colors.white70, fontSize: 14),
),
);
}
static ThemeData dark() {
return light().copyWith(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue, brightness: Brightness.dark),
);
}
}
/// Card and text colors that stay readable on the current target background
/// (which can be anything from white to red to black).
class Surfaces {
final Color card;
final Color divider;
final Color textPrimary;
final Color textSecondary;
const Surfaces._({
const Palette._({
required this.isDark,
required this.bg,
required this.card,
required this.divider,
required this.textPrimary,
required this.textSecondary,
required this.card2,
required this.field,
required this.tile,
required this.line,
required this.line2,
required this.ink,
required this.ink2,
required this.muted,
required this.faint,
required this.pos,
required this.posSoft,
required this.gold,
required this.goldSoft,
required this.goldInk,
required this.red,
required this.redSoft,
required this.amberSoft,
required this.amberInk,
required this.blue,
required this.purple,
required this.nav,
required this.accent,
required this.shadow,
required this.shadowLg,
});
static Surfaces get current => AppSettings.instance.isLightBackground
? Surfaces._(
card: Colors.grey[300]!, // same grey as calendar cards
divider: Colors.grey[400]!,
textPrimary: Colors.black87,
textSecondary: Colors.black54,
)
: Surfaces._(
card: Colors.grey[850]!,
divider: Colors.grey[700]!,
textPrimary: Colors.white,
textSecondary: Colors.white60,
);
factory Palette.dark(Color accent) => Palette._(
isDark: true,
bg: const Color(0xFF0E1012),
card: const Color(0xFF171A1D),
card2: const Color(0xFF1E2226),
field: const Color(0xFF1B1F22),
tile: const Color(0xFF23282C),
line: const Color(0xFF2A2F34),
line2: const Color(0xFF22272B),
ink: const Color(0xFFF2F3F0),
ink2: const Color(0xFFC6CBD0),
muted: const Color(0xFF8A9198),
faint: const Color(0xFF5B636A),
pos: const Color(0xFF34CF8E),
posSoft: const Color(0x1F34CF8E),
gold: const Color(0xFFF2C12E),
goldSoft: const Color(0x26F2C12E),
goldInk: const Color(0xFFF6D366),
red: const Color(0xFFF2706A),
redSoft: const Color(0x1FF2706A),
amberSoft: const Color(0x1FF5B33B),
amberInk: const Color(0xFFF7C66A),
blue: const Color(0xFF6EA8FF),
purple: const Color(0xFFB28CFF),
nav: const Color(0xFF121417),
accent: accent,
shadow: const [],
shadowLg: const [BoxShadow(color: Color(0x66000000), offset: Offset(0, 16), blurRadius: 40)],
);
factory Palette.light(Color accent) => Palette._(
isDark: false,
bg: const Color(0xFFF4F4F0),
card: const Color(0xFFFFFFFF),
card2: const Color(0xFFFAFAF7),
field: const Color(0xFFF7F7F4),
tile: const Color(0xFFEFF0EB),
line: const Color(0xFFE3E4DE),
line2: const Color(0xFFECEDE8),
ink: const Color(0xFF16181B),
ink2: const Color(0xFF3B4046),
muted: const Color(0xFF6F757C),
faint: const Color(0xFFA3A8AD),
pos: const Color(0xFF12855C),
posSoft: const Color(0xFFE2F2EA),
gold: const Color(0xFFF2C12E),
goldSoft: const Color(0xFFFDF3CF),
goldInk: const Color(0xFF7A5A00),
red: const Color(0xFFD0443E),
redSoft: const Color(0xFFFBEBEA),
amberSoft: const Color(0xFFFFF3DC),
amberInk: const Color(0xFF8A5A00),
blue: const Color(0xFF2D6BD8),
purple: const Color(0xFF7A4FD0),
nav: const Color(0xFFFFFFFF),
accent: accent,
shadow: const [
BoxShadow(color: Color(0x0A1A1D1F), offset: Offset(0, 1), blurRadius: 2),
BoxShadow(color: Color(0x0D1A1D1F), offset: Offset(0, 8), blurRadius: 24),
],
shadowLg: const [BoxShadow(color: Color(0x241A1D1F), offset: Offset(0, 18), blurRadius: 40)],
);
/// The palette for the current theme and bullet colour.
static Palette get current => AppSettings.instance.palette;
/// Accent with low alpha: selected chips, icon badges.
Color get accentSoft => accent.withValues(alpha: isDark ? 0.13 : 0.12);
/// Accent as text on [card]: lighter on dark, deeper on light.
Color get accentInk =>
isDark ? Color.lerp(accent, Colors.white, 0.45)! : Color.lerp(accent, Colors.black, 0.32)!;
/// Text and icons on an accent fill.
Color get onAccent => onColor(accent);
/// Readable text colour on [fill].
static Color onColor(Color fill) =>
fill.computeLuminance() > 0.36 ? const Color(0xFF0B0D0F) : Colors.white;
/// Up = green, down = red.
Color delta(double v) => v >= 0 ? pos : red;
}
/// Spacing, radii and text styles of the design, plus the ThemeData.
class AppTheme {
AppTheme._();
static const String font = 'Inter';
static const String mono = 'JetBrains Mono';
static const double edge = 20; // page edge
static const double radius = 16; // cards
static const List<FontFeature> tnum = [FontFeature.tabularFigures()];
/// Uppercase label above a group: "POVPREČJE NA STREL".
static TextStyle kicker(Palette c) =>
TextStyle(fontSize: 11, fontWeight: FontWeight.w700, letterSpacing: 1.1, color: c.muted);
static ThemeData theme(Palette c) {
final base = ThemeData(
useMaterial3: true,
brightness: c.isDark ? Brightness.dark : Brightness.light,
fontFamily: font,
);
final scheme = ColorScheme(
brightness: c.isDark ? Brightness.dark : Brightness.light,
primary: c.accent,
onPrimary: c.onAccent,
secondary: c.accent,
onSecondary: c.onAccent,
error: c.red,
onError: Colors.white,
surface: c.card,
onSurface: c.ink,
onSurfaceVariant: c.muted,
outline: c.line,
outlineVariant: c.line2,
surfaceContainerHighest: c.tile,
surfaceContainerHigh: c.card2,
surfaceContainer: c.card,
surfaceContainerLow: c.card,
surfaceContainerLowest: c.bg,
);
return base.copyWith(
colorScheme: scheme,
// Pages are see-through: every route is drawn on the app background
// (see _BackgroundTransitions), the everyday one or a holiday's
scaffoldBackgroundColor: Colors.transparent,
canvasColor: c.bg,
dividerColor: c.line,
splashFactory: InkSparkle.splashFactory,
textTheme: base.textTheme.apply(bodyColor: c.ink, displayColor: c.ink, fontFamily: font),
iconTheme: IconThemeData(color: c.ink),
dividerTheme: DividerThemeData(color: c.line2, thickness: 1, space: 1),
appBarTheme: AppBarTheme(
backgroundColor: c.bg,
foregroundColor: c.ink,
elevation: 0,
scrolledUnderElevation: 0,
titleTextStyle: TextStyle(fontFamily: font, fontSize: 17, fontWeight: FontWeight.w700, color: c.ink),
systemOverlayStyle: overlay(c),
),
bottomSheetTheme: BottomSheetThemeData(
backgroundColor: c.card,
modalBackgroundColor: c.card,
surfaceTintColor: Colors.transparent,
showDragHandle: true,
dragHandleColor: c.line,
dragHandleSize: const Size(40, 4),
modalBarrierColor: Colors.black.withValues(alpha: c.isDark ? 0.55 : 0.35),
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(24))),
),
dialogTheme: DialogThemeData(
backgroundColor: c.card,
surfaceTintColor: Colors.transparent,
barrierColor: Colors.black.withValues(alpha: c.isDark ? 0.6 : 0.35),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
side: c.isDark ? BorderSide(color: c.line) : BorderSide.none,
),
titleTextStyle: TextStyle(fontFamily: font, color: c.ink, fontSize: 20, fontWeight: FontWeight.w700),
contentTextStyle: TextStyle(fontFamily: font, color: c.muted, fontSize: 14, height: 1.35),
),
switchTheme: SwitchThemeData(
thumbColor: WidgetStateProperty.resolveWith(
(s) => s.contains(WidgetState.selected) ? (c.isDark ? const Color(0xFF0B0D0F) : Colors.white) : c.muted),
trackColor: WidgetStateProperty.resolveWith((s) => s.contains(WidgetState.selected) ? c.accent : c.tile),
trackOutlineColor: WidgetStateProperty.resolveWith(
(s) => s.contains(WidgetState.selected) ? c.accent : (c.isDark ? c.tile : c.line)),
thumbIcon: const WidgetStatePropertyAll(null),
),
sliderTheme: SliderThemeData(
activeTrackColor: c.accent,
inactiveTrackColor: c.tile,
thumbColor: c.accent,
overlayColor: c.accent.withValues(alpha: 0.16),
trackHeight: 4,
thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 8),
),
checkboxTheme: CheckboxThemeData(
fillColor: WidgetStateProperty.resolveWith((s) => s.contains(WidgetState.selected) ? c.accent : Colors.transparent),
checkColor: WidgetStatePropertyAll(c.onAccent),
side: BorderSide(color: c.faint, width: 1.5),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
),
progressIndicatorTheme: ProgressIndicatorThemeData(color: c.accent, circularTrackColor: c.tile, linearTrackColor: c.tile),
textSelectionTheme: TextSelectionThemeData(
cursorColor: c.accent,
selectionColor: c.accent.withValues(alpha: 0.3),
selectionHandleColor: c.accent,
),
inputDecorationTheme: InputDecorationTheme(
filled: true,
fillColor: c.field,
hintStyle: TextStyle(color: c.faint),
contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14),
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: c.line)),
enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: c.line)),
focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: c.accent, width: 2)),
),
snackBarTheme: SnackBarThemeData(
behavior: SnackBarBehavior.floating,
backgroundColor: c.isDark ? c.tile : c.ink,
contentTextStyle: TextStyle(fontFamily: font, color: c.isDark ? c.ink : Colors.white, fontSize: 14),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
),
textButtonTheme: TextButtonThemeData(
style: TextButton.styleFrom(
foregroundColor: c.ink,
textStyle: const TextStyle(fontFamily: font, fontSize: 15, fontWeight: FontWeight.w600),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
),
),
filledButtonTheme: FilledButtonThemeData(
style: FilledButton.styleFrom(
backgroundColor: c.accent,
foregroundColor: c.onAccent,
minimumSize: const Size(0, 48),
textStyle: const TextStyle(fontFamily: font, fontSize: 15, fontWeight: FontWeight.w600),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
),
),
datePickerTheme: DatePickerThemeData(
backgroundColor: c.card,
surfaceTintColor: Colors.transparent,
headerBackgroundColor: c.card,
headerForegroundColor: c.ink,
rangeSelectionBackgroundColor: c.accent.withValues(alpha: 0.18),
rangePickerBackgroundColor: c.bg,
rangePickerHeaderBackgroundColor: c.bg,
rangePickerHeaderForegroundColor: c.ink,
dayForegroundColor: WidgetStateProperty.resolveWith((s) => s.contains(WidgetState.selected) ? c.onAccent : c.ink),
dayBackgroundColor: WidgetStateProperty.resolveWith((s) => s.contains(WidgetState.selected) ? c.accent : null),
todayForegroundColor: WidgetStatePropertyAll(c.accent),
todayBorder: BorderSide(color: c.accent),
),
pageTransitionsTheme: PageTransitionsTheme(builders: {
TargetPlatform.android: _BackgroundTransitions(FadeForwardsPageTransitionsBuilder(backgroundColor: c.bg)),
TargetPlatform.iOS: const _BackgroundTransitions(ZoomPageTransitionsBuilder()),
TargetPlatform.linux: const _BackgroundTransitions(ZoomPageTransitionsBuilder()),
}),
);
}
/// Status and navigation bar for [c]: transparent status bar, nav bar in the nav colour.
static SystemUiOverlayStyle overlay(Palette c) => SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
statusBarIconBrightness: c.isDark ? Brightness.light : Brightness.dark,
statusBarBrightness: c.isDark ? Brightness.dark : Brightness.light,
systemNavigationBarColor: c.nav,
systemNavigationBarIconBrightness: c.isDark ? Brightness.light : Brightness.dark,
systemNavigationBarContrastEnforced: false,
);
}
/// The screen background of the design (holiday-themes/v2, "ozadje"): the
/// everyday one in dark or light, or the current holiday's.
class AppBackground extends StatelessWidget {
final Widget child;
const AppBackground({super.key, required this.child});
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: AppSettings.instance,
builder: (context, child) {
final s = AppSettings.instance;
return Stack(
fit: StackFit.expand,
children: [
ColoredBox(color: s.palette.bg),
// Holidays have their drawn backgrounds; the everyday one is
// painted here, cleaner than the design's busier image
if (s.holiday != null)
Image.asset(s.background, fit: BoxFit.cover, gaplessPlayback: true, filterQuality: FilterQuality.medium)
else
CustomPaint(painter: _EverydayBackground(dark: s.isDark)),
child!,
],
);
},
child: child,
);
}
}
/// [inner]'s transitions, with every page drawn on [AppBackground], so a page
/// stays opaque while it slides and fades.
class _BackgroundTransitions extends PageTransitionsBuilder {
final PageTransitionsBuilder inner;
const _BackgroundTransitions(this.inner);
@override
Duration get transitionDuration => inner.transitionDuration;
@override
Duration get reverseTransitionDuration => inner.reverseTransitionDuration;
@override
DelegatedTransitionBuilder? get delegatedTransition => inner.delegatedTransition;
@override
Widget buildTransitions<T>(PageRoute<T> route, BuildContext context, Animation<double> animation,
Animation<double> secondaryAnimation, Widget child) =>
inner.buildTransitions(route, context, animation, secondaryAnimation, AppBackground(child: child));
}
/// The everyday background ("00 Privzeto", holiday-themes/v2) in a calmer
/// version: the same gradient and two corners of target rings, but three
/// widely spaced, faint rings per corner and a few fine dots.
class _EverydayBackground extends CustomPainter {
final bool dark;
const _EverydayBackground({required this.dark});
@override
void paint(Canvas canvas, Size size) {
final rect = Offset.zero & size;
canvas.drawRect(
rect,
Paint()
..shader = LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: dark ? const [Color(0xFF15191C), Color(0xFF0B0D0F)] : const [Color(0xFFFAFAF7), Color(0xFFECEDE7)],
).createShader(rect),
);
// Design units: a 390 × 844 screen
final k = size.width / 390;
final ink = dark ? Colors.white : const Color(0xFF16181B);
final ring = Paint()
..style = PaintingStyle.stroke
..isAntiAlias = true;
void rings(Offset c, List<double> radii) {
for (int i = 0; i < radii.length; i++) {
ring
..strokeWidth = (i == radii.length - 1 ? 1.6 : 1.1) * k
..color = ink.withValues(alpha: dark ? (i == radii.length - 1 ? 0.09 : 0.06) : (i == radii.length - 1 ? 0.08 : 0.05));
canvas.drawCircle(c, radii[i] * k, ring);
}
}
rings(Offset(size.width + 40 * k, -30 * k), const [150, 260, 380]);
rings(Offset(-60 * k, size.height + 40 * k), const [140, 250]);
// A few fine dots, always in the same places
final dot = Paint()..color = ink.withValues(alpha: dark ? 0.16 : 0.12);
const spots = [
(0.12, 0.08), (0.78, 0.18), (0.34, 0.31), (0.88, 0.44), (0.07, 0.52),
(0.62, 0.61), (0.25, 0.74), (0.91, 0.83), (0.48, 0.92), (0.70, 0.36),
];
for (int i = 0; i < spots.length; i++) {
final (x, y) = spots[i];
canvas.drawCircle(Offset(x * size.width, y * size.height), (i.isEven ? 1.4 : 1.0) * k, dot);
}
}
@override
bool shouldRepaint(_EverydayBackground old) => old.dark != dark;
}
+18
View File
@@ -0,0 +1,18 @@
import 'package:intl/intl.dart';
import '../services/app_settings.dart';
/// Decimal number the way the language writes it: 8,49 (sl, de) or 8.49 (en).
String dec(double v, [int digits = 2]) {
final s = v.toStringAsFixed(digits);
return AppSettings.instance.language == 'English' ? s : s.replaceAll('.', ',');
}
/// Signed difference: "+0,21" / "−0,06".
String signedDec(double v, [int digits = 2]) => '${v >= 0 ? '+' : '−'}${dec(v.abs(), digits)}';
/// "čet, 12. 11." (or with the year): weekday without the locale's dot.
String dayDate(DateTime d, {bool year = false}) {
final s = AppSettings.instance;
final weekday = DateFormat('EEE', s.dateLocale).format(d).replaceAll('.', '');
return '$weekday, ${DateFormat(year ? 'd. M. yyyy' : 'd. M.').format(d)}';
}
-40
View File
@@ -1,40 +0,0 @@
import 'package:flutter/material.dart';
class TargetColors {
static const Map<String, Color> targetBackgroundColors = {
'assets/target.png': Color(0xFFFFFFFF), // White
'assets/targets/Target1.jpg': Color(0xFFE8ECD5), // Light beige
'assets/targets/Target2.jpg': Color(0xFFC1DF87), // Light green
'assets/targets/Target3.jpg': Color(0xFFFEFEFE), // Off-white
'assets/targets/Target4.jpg': Color(0xFFD42931), // Red
'assets/targets/Target5.jpg': Color(0xFF02050A), // Very dark blue/black
'assets/targets/Target6.jpg': Color(0xFFF3E7D1), // Light beige
'assets/targets/Target7.jpg': Color(0xFFFFD454), // Bright yellow
'assets/targets/Target8.jpg': Color(0xFF1E5E81), // Dark teal blue
'assets/targets/Target9.jpg': Color(0xFFFEFEFC), // Off-white
'assets/targets/Target10.jpg': Color(0xFF98926E), // Olive green
'assets/targets/Target11.jpg': Color(0xFF13132B), // Dark blue
'assets/targets/Target12.jpg': Color(0xFFF5F4EF), // Off-white
'assets/targets/Target14.jpg': Color(0xFFFEE05E), // Light yellow
'assets/targets/Target15.jpg': Color(0xFFFFFFFF), // White
'assets/targets/Target16.jpg': Color(0xFF000000), // Black
'assets/targets/Target17.jpg': Color(0xFF21304D), // Dark blue
'assets/targets/Target18.jpg': Color(0xFF050608), // Very dark gray
'assets/targets/Target19.jpg': Color(0xFFF68527), // Warm orange
'assets/targets/Target20.jpg': Color(0xFFA9D9EF), // Light blue
'assets/targets/Target22.jpg': Color(0xFFFBFAF6), // Off-white
'assets/targets/Target23.jpg': Color(0xFF000000), // Black
'assets/targets/Target24.jpg': Color(0xFF646462), // Grey
'assets/targets/Target25.jpg': Color(0xFF040308), // Very dark gray
'assets/targets/Target26.jpg': Color(0xFF161C2C), // Dark blue-gray
'assets/targets/Target27.jpg': Color(0xFF28A5DF), // Blue
'assets/targets/Target28.jpg': Color(0xFFFFFFFF), // White
'assets/targets/Target29.jpg': Color(0xFF180E27), // Dark purple
'assets/targets/Target30.jpg': Color(0xFFFDFDFB), // Off-white
'assets/targets/Target35.jpg': Color(0xFFFFC5C4), // Light salmon
};
static Color getBackgroundColor(String targetPath) {
return targetBackgroundColors[targetPath] ?? Colors.grey[900]!;
}
}
+25 -5
View File
@@ -1,9 +1,10 @@
import 'dart:math';
import 'dart:ui';
/// The one scoring rule for a shot on the default target (assets/target.png,
/// 1200x1200). Saving, the preview and the target view all use it, so a shot
/// scores the same everywhere.
/// The one scoring rule for a shot, in the 1200 × 1200 space every target
/// design shares (target-designs/v3: centre 600/600, ring 1 at r 510, the
/// black at r 180). Saving, the preview and the target view all use it, so a
/// shot scores the same everywhere and on every design.
///
/// A shot counts for the best ring its edge touches: the distance from the
/// centre to the bullet's centre, minus the bullet's radius, is compared with
@@ -11,12 +12,31 @@ import 'dart:ui';
class TargetScoring {
TargetScoring._();
static const Offset center = Offset(601, 598);
static const double size = 1200;
static const Offset center = Offset(600, 600);
static const double bulletRadius = 25;
static const double bulletDiameter = 53; // drawn size of a hit
/// Outer edge of ring 10, 9, ... 1, measured from [center].
///
/// A shot touching a ring line counts the higher value, so each edge is the
/// outer edge of its printed line: the line's centre radius plus half its
/// width. Lines in the v3 designs: 5 px white at r 70 and 125 (rings 9, 8),
/// 3 px on the paper at r 235 … 510 (rings 6 … 1). Ring 7 is the edge of
/// the black and 10 the centre dot, with no line of their own.
static const double _paperLine = 3;
static const double _blackLine = 5;
static const List<double> rings = [
14, 70, 125, 180, 235, 290, 345, 400, 455, 510,
15, // 10: centre dot
70 + _blackLine / 2, // 9
125 + _blackLine / 2, // 8
180, // 7: edge of the black
235 + _paperLine / 2, // 6
290 + _paperLine / 2, // 5
345 + _paperLine / 2, // 4
400 + _paperLine / 2, // 3
455 + _paperLine / 2, // 2
510 + _paperLine / 2, // 1
];
/// Score of a shot whose centre is at [bullet] (default target coordinates).
+4
View File
@@ -1,3 +1,5 @@
import 'translations_v2.dart';
class AppTranslations {
static Map<String, Map<String, String>> translations = {
// Language names
@@ -1263,6 +1265,8 @@ class AppTranslations {
};
static String translate(String key, String language) {
final v2 = translationsV2[key]?[language];
if (v2 != null) return v2;
if (translations.containsKey(key) &&
translations[key]!.containsKey(language)) {
return translations[key]![language]!;
+161
View File
@@ -0,0 +1,161 @@
/// Strings of the V2 design (shooting-app-design/v2). Looked up before
/// [AppTranslations.translations], so an entry here also replaces an older
/// wording there (e.g. "Kontakti" instead of "Stiki").
const Map<String, Map<String, String>> translationsV2 = {
// Changed wording
'Contacts': {'English': 'Contacts', 'Slovenian': 'Kontakti', 'German': 'Kontakte'},
'COMPETITION': {'English': 'COMPETITION', 'Slovenian': 'TEKMA', 'German': 'WETTKAMPF'},
// Streljanje
'Where are we shooting today?': {'English': 'Where are we shooting today?', 'Slovenian': 'Kje streljamo danes?', 'German': 'Wo schießen wir heute?'},
'Last session': {'English': 'Last session', 'Slovenian': 'Zadnje streljanje', 'German': 'Letztes Schießen'},
'per shot': {'English': 'per shot', 'Slovenian': 'na strel', 'German': 'pro Schuss'},
'Live': {'English': 'Live', 'Slovenian': 'V živo', 'German': 'Live'},
'Choose': {'English': 'Choose', 'Slovenian': 'Izberi', 'German': 'Wählen'},
// Knjiga
'Applies to Statistics and History': {'English': 'Applies to Statistics and History', 'Slovenian': 'Velja za Statistiko in Zgodovino', 'German': 'Gilt für Statistik und Verlauf'},
'since the first saved target': {'English': 'since the first saved target', 'Slovenian': 'od prve shranjene tarče', 'German': 'seit der ersten gespeicherten Scheibe'},
'choose dates …': {'English': 'choose dates …', 'Slovenian': 'izberi datume …', 'German': 'Daten wählen …'},
'Best training / tournament in the bottom card: tap to open its targets.': {
'English': 'Best training / tournament in the bottom card: tap to open its targets.',
'Slovenian': 'Najboljši trening / tekmovanje v spodnji kartici: tapni za prikaz njegovih tarč.',
'German': 'Bestes Training / bester Wettkampf in der unteren Karte: tippen, um die Scheiben zu öffnen.',
},
'Sort: tap to switch between date order and best average per shot. The coloured number shows how far a session is from your average.': {
'English': 'Sort: tap to switch between date order and best average per shot. The coloured number shows how far a session is from your average.',
'Slovenian': 'Razvrščanje: tapni za preklop med vrstnim redom po datumu in po najboljšem povprečju na strel. Barvna številka pokaže, koliko seja odstopa od tvojega povprečja.',
'German': 'Sortierung: tippen, um zwischen Datum und bestem Schnitt pro Schuss zu wechseln. Die farbige Zahl zeigt, wie weit eine Einheit von deinem Schnitt abweicht.',
},
'Shots per target': {'English': 'Shots per target', 'Slovenian': 'Streli na tarčo', 'German': 'Schüsse pro Scheibe'},
// Rezultat
'total': {'English': 'total', 'Slovenian': 'skupaj', 'German': 'gesamt'},
'Share result': {'English': 'Share result', 'Slovenian': 'Deli rezultat', 'German': 'Ergebnis teilen'},
'Points per target': {'English': 'Points per target', 'Slovenian': 'Točke po tarčah', 'German': 'Punkte pro Scheibe'},
'Hits by value': {'English': 'Hits by value', 'Slovenian': 'Zadetki po vrednosti', 'German': 'Treffer nach Wert'},
'Gold = best target of the session': {'English': 'Gold = best target of the session', 'Slovenian': 'Zlata = najboljša tarča seje', 'German': 'Gold = beste Scheibe der Einheit'},
'Chart': {'English': 'Chart', 'Slovenian': 'Graf', 'German': 'Diagramm'},
'Failed to delete target': {'English': 'Failed to delete target', 'Slovenian': 'Tarče ni bilo mogoče izbrisati', 'German': 'Scheibe konnte nicht gelöscht werden'},
'Rename the session or move it to tournaments.': {'English': 'Rename the session or move it to tournaments.', 'Slovenian': 'Preimenuj sejo ali jo premakni med tekmovanja.', 'German': 'Einheit umbenennen oder zu den Wettkämpfen verschieben.'},
// Fotografiraj
'Camera settings': {'English': 'Camera settings', 'Slovenian': 'Nastavitve kamere', 'German': 'Kameraeinstellungen'},
'Exposure, zoom and flashlight': {'English': 'Exposure, zoom and flashlight', 'Slovenian': 'Osvetlitev, povečava in svetilka', 'German': 'Belichtung, Zoom und Taschenlampe'},
'Looking for hits …': {'English': 'Looking for hits …', 'Slovenian': 'Iščem zadetke …', 'German': 'Suche Treffer …'},
'{a}–{b} shots per target': {'English': '{a}–{b} shots per target', 'Slovenian': '{a}–{b} strelov na tarčo', 'German': '{a}–{b} Schüsse pro Scheibe'},
'Statistics in the Book only compare targets with the same number of shots.': {
'English': 'Statistics in the Book only compare targets with the same number of shots.',
'Slovenian': 'Statistika v Knjigi primerja le tarče z enakim številom strelov.',
'German': 'Die Statistik im Buch vergleicht nur Scheiben mit gleicher Schusszahl.',
},
// Preveri zadetke
'Check hits': {'English': 'Check hits', 'Slovenian': 'Preveri zadetke', 'German': 'Treffer prüfen'},
'{n} hits detected · correct them if needed': {'English': '{n} hits detected · correct them if needed', 'Slovenian': '{n} zadetkov zaznanih · popravi, če je treba', 'German': '{n} Treffer erkannt · bei Bedarf korrigieren'},
'Save to': {'English': 'Save to', 'Slovenian': 'Shrani v', 'German': 'Speichern in'},
'new': {'English': 'new', 'Slovenian': 'nova', 'German': 'neu'},
'today': {'English': 'today', 'Slovenian': 'danes', 'German': 'heute'},
'Add hit': {'English': 'Add hit', 'Slovenian': 'Dodaj zadetek', 'German': 'Treffer hinzufügen'},
'Remove hit': {'English': 'Remove hit', 'Slovenian': 'Odstrani zadetek', 'German': 'Treffer entfernen'},
'Save target': {'English': 'Save target', 'Slovenian': 'Shrani tarčo', 'German': 'Scheibe speichern'},
'Hold and drag': {'English': 'Hold and drag', 'Slovenian': 'Drži in povleci', 'German': 'Halten und ziehen'},
'Its value; then drag it to where it hit.': {'English': 'Its value; then drag it to where it hit.', 'Slovenian': 'Njegova vrednost; nato ga povleci na mesto zadetka.', 'German': 'Sein Wert; dann an die Trefferstelle ziehen.'},
'Image not available': {'English': 'Image not available', 'Slovenian': 'Slika ni na voljo', 'German': 'Bild nicht verfügbar'},
'Tap a value below to pick that hit; it gets a red border.': {
'English': 'Tap a value below to pick that hit; it gets a red border.',
'Slovenian': 'Tapni vrednost spodaj, da izbereš ta zadetek; dobi rdeč rob.',
'German': 'Tippe unten auf einen Wert, um den Treffer zu wählen; er bekommt einen roten Rand.',
},
'Hold and drag on the target to move the picked hit; a magnifier shows where it is.': {
'English': 'Hold and drag on the target to move the picked hit; a magnifier shows where it is.',
'Slovenian': 'Drži in povleci po tarči, da premakneš izbrani zadetek; povečevalo pokaže, kje je.',
'German': 'Halten und auf der Scheibe ziehen, um den gewählten Treffer zu verschieben; eine Lupe zeigt, wo er liegt.',
},
'Add hit: for a shot that was not found. Remove hit: deletes the picked one.': {
'English': 'Add hit: for a shot that was not found. Remove hit: deletes the picked one.',
'Slovenian': 'Dodaj zadetek: za strel, ki ni bil najden. Odstrani zadetek: izbriše izbranega.',
'German': 'Treffer hinzufügen: für einen nicht gefundenen Schuss. Treffer entfernen: löscht den gewählten.',
},
'Save to: training or tournament, and which folder. The last one is chosen for you.': {
'English': 'Save to: training or tournament, and which folder. The last one is chosen for you.',
'Slovenian': 'Shrani v: trening ali tekmovanje in katera mapa. Zadnja je že izbrana.',
'German': 'Speichern in: Training oder Wettkampf und welcher Ordner. Der letzte ist vorausgewählt.',
},
'Photo icon: see the photo with what was detected.': {
'English': 'Photo icon: see the photo with what was detected.',
'Slovenian': 'Ikona fotografije: pokaže fotografijo z zaznanim.',
'German': 'Foto-Symbol: zeigt das Foto mit dem Erkannten.',
},
// Kamera v živo
'of': {'English': 'of', 'Slovenian': 'od', 'German': 'von'},
'paused': {'English': 'paused', 'Slovenian': 'premor', 'German': 'pausiert'},
'Wait': {'English': 'Waiting', 'Slovenian': 'Čakanje', 'German': 'Warten'},
'Reload phase': {'English': 'Reload', 'Slovenian': 'Polnjenje', 'German': 'Laden'},
'Signal at the end': {'English': 'Signal at the end', 'Slovenian': 'Signal ob koncu', 'German': 'Signal am Ende'},
'tap for a new target': {'English': 'tap for a new target', 'Slovenian': 'tapni za novo tarčo', 'German': 'tippen für neue Scheibe'},
'Shot counter': {'English': 'Shot counter', 'Slovenian': 'Števec strelov', 'German': 'Schusszähler'},
'Start timer': {'English': 'Start timer', 'Slovenian': 'Začni časovnik', 'German': 'Timer starten'},
'Cycle: shot → reload → wait. On a full target »Change target!« is shown.': {
'English': 'Cycle: shot → reload → wait. On a full target »Change target!« is shown.',
'Slovenian': 'Cikel: strel → polnjenje → čakanje. Ob polni tarči se pokaže »Zamenjaj tarčo!«.',
'German': 'Ablauf: Schuss → Laden → Warten. Bei voller Scheibe erscheint »Scheibe wechseln!«.',
},
'saved for this camera': {'English': 'saved for this camera', 'Slovenian': 'shranjeno za to kamero', 'German': 'für diese Kamera gespeichert'},
'Timer: set shoot, reload and wait times in the timer card or with the timer button. While it runs, the button pauses it and the card stops it.': {
'English': 'Timer: set shoot, reload and wait times in the timer card or with the timer button. While it runs, the button pauses it and the card stops it.',
'Slovenian': 'Časovnik: čas streljanja, polnjenja in čakanja nastaviš v kartici časovnika ali z gumbom. Ko teče, ga gumb ustavi za premor, kartica pa ustavi.',
'German': 'Timer: Schuss-, Lade- und Wartezeit in der Timer-Karte oder mit der Timer-Taste einstellen. Läuft er, pausiert ihn die Taste und die Karte stoppt ihn.',
},
'Play / pause: control the timer.': {'English': 'Play / pause: control the timer.', 'Slovenian': 'Predvajaj / premor: upravljanje časovnika.', 'German': 'Start / Pause: steuert den Timer.'},
'Big + button: shot counter. Tap after each shot; when the target is full you get a "Change target!" warning. The dot next to it switches the counter on or off.': {
'English': 'Big + button: shot counter. Tap after each shot; when the target is full you get a "Change target!" warning. The dot next to it switches the counter on or off.',
'Slovenian': 'Velik gumb +: števec strelov. Po vsakem strelu tapni +; ko je tarča polna, se prikaže opozorilo »Zamenjaj tarčo!«. Pika ob njem števec vklopi ali izklopi.',
'German': 'Große +-Taste: Schusszähler. Nach jedem Schuss tippen; ist die Scheibe voll, erscheint »Scheibe wechseln!«. Der Punkt daneben schaltet den Zähler ein oder aus.',
},
'Picture icon: brightness, contrast, filters and rotation, saved for each camera.': {
'English': 'Picture icon: brightness, contrast, filters and rotation, saved for each camera.',
'Slovenian': 'Ikona slike: svetlost, kontrast, filtri in vrtenje, shranjeno za vsako kamero.',
'German': 'Bild-Symbol: Helligkeit, Kontrast, Filter und Drehung, für jede Kamera gespeichert.',
},
// Koledar, Kontakti
'Members': {'English': 'Members', 'Slovenian': 'Člani', 'German': 'Mitglieder'},
'Search members …': {'English': 'Search members …', 'Slovenian': 'Išči člana …', 'German': 'Mitglied suchen …'},
'Could not load the calendar': {'English': 'Could not load the calendar', 'Slovenian': 'Koledarja ni bilo mogoče naložiti', 'German': 'Kalender konnte nicht geladen werden'},
// Nastavitve
'Hits and target': {'English': 'Hits and target', 'Slovenian': 'Zadetki in tarča', 'German': 'Treffer und Scheibe'},
'Holiday target until': {'English': 'Holiday target until', 'Slovenian': 'Praznična tarča do', 'German': 'Feiertagsscheibe bis'},
'You can still change the hit colour.': {
'English': 'You can still change the hit colour.',
'Slovenian': 'Barvo zadetkov lahko še vedno zamenjaš.',
'German': 'Die Trefferfarbe kannst du trotzdem ändern.',
},
'Theme': {'English': 'Theme', 'Slovenian': 'Tema', 'German': 'Design'},
'System': {'English': 'System', 'Slovenian': 'Sistem', 'German': 'System'},
'Light': {'English': 'Light', 'Slovenian': 'Svetla', 'German': 'Hell'},
'Dark': {'English': 'Dark', 'Slovenian': 'Temna', 'German': 'Dunkel'},
'Unlocked': {'English': 'Unlocked', 'Slovenian': 'Odklenjeno', 'German': 'Freigeschaltet'},
'Unlocks calendar and contacts.': {'English': 'Unlocks calendar and contacts.', 'Slovenian': 'Odklene koledar in kontakte.', 'German': 'Schaltet Kalender und Kontakte frei.'},
'Member access is currently available only for SD Kovinar Muta.': {
'English': 'Member access is currently available only for SD Kovinar Muta.',
'Slovenian': 'Članski dostop je trenutno na voljo samo za SD Kovinar Muta.',
'German': 'Mitgliederzugang gibt es derzeit nur für SD Kovinar Muta.',
},
'Version': {'English': 'Version', 'Slovenian': 'Različica', 'German': 'Version'},
'Target style': {'English': 'Target style', 'Slovenian': 'Slog tarče', 'German': 'Scheibenstil'},
'All targets': {'English': 'All targets', 'Slovenian': 'Vse tarče', 'German': 'Alle Scheiben'},
'holiday': {'English': 'holiday', 'Slovenian': 'prazničnih', 'German': 'Feiertage'},
'Classic': {'English': 'Classic', 'Slovenian': 'Klasične', 'German': 'Klassisch'},
'Club designs': {'English': 'Club designs', 'Slovenian': 'Naši dizajni', 'German': 'Vereinsdesigns'},
'Holidays': {'English': 'Holidays', 'Slovenian': 'Praznične', 'German': 'Feiertage'},
'Locations, positions and camera addresses': {'English': 'Locations, positions and camera addresses', 'Slovenian': 'Strelišča, pozicije in naslovi kamer', 'German': 'Schießstände, Positionen und Kameraadressen'},
'One tile on the Shooting screen for each position.': {
'English': 'One tile on the Shooting screen for each position.',
'Slovenian': 'Ena ploščica na zaslonu Streljanje za vsako pozicijo.',
'German': 'Eine Kachel auf dem Schießen-Bildschirm pro Position.',
},
};
+120
View File
@@ -0,0 +1,120 @@
import 'package:flutter/material.dart';
import '../theme/app_theme.dart';
class BarEntry {
final String label;
final double value;
final String valueText;
final bool highlight; // drawn in gold (best target, the 10s)
final bool goldLabel;
const BarEntry(this.label, this.value, this.valueText, {this.highlight = false, this.goldLabel = false});
}
/// Horizontal bars, one per row: label, bar on a track, value. Ticks along the
/// bottom. The rows share the height they get.
class BarList extends StatelessWidget {
final List<BarEntry> entries;
final double max;
final List<double> ticks;
final double labelWidth;
final double valueWidth;
final double scale; // text size factor (share image)
final Palette? palette;
const BarList({
super.key,
required this.entries,
required this.max,
this.ticks = const [],
this.labelWidth = 32,
this.valueWidth = 40,
this.scale = 1,
this.palette,
});
@override
Widget build(BuildContext context) {
final c = palette ?? Palette.current;
String tick(double v) => v == v.roundToDouble() ? '${v.round()}' : v.toStringAsFixed(1);
return LayoutBuilder(builder: (context, box) {
final barWidth = box.maxWidth - labelWidth - valueWidth;
return Column(
children: [
Expanded(
child: Column(
children: [
for (final e in entries)
Expanded(
child: Row(
children: [
SizedBox(
width: labelWidth,
child: Text(e.label,
style: TextStyle(
fontSize: 12 * scale,
fontWeight: FontWeight.w600,
color: e.goldLabel ? c.gold : c.muted)),
),
SizedBox(
width: barWidth,
child: Stack(
alignment: Alignment.centerLeft,
children: [
Container(
height: 26 * scale,
decoration: BoxDecoration(color: c.tile, borderRadius: BorderRadius.circular(7 * scale)),
),
FractionallySizedBox(
widthFactor: max <= 0 ? 0 : (e.value / max).clamp(0.0, 1.0),
child: Container(
height: 26 * scale,
decoration: BoxDecoration(
color: e.highlight ? c.gold : c.accent,
borderRadius: BorderRadius.circular(7 * scale),
),
),
),
],
),
),
SizedBox(
width: valueWidth,
child: Padding(
padding: EdgeInsets.only(left: 10 * scale),
child: Text(e.valueText,
maxLines: 1,
style: TextStyle(
fontSize: 15 * scale,
fontWeight: FontWeight.w700,
color: e.highlight ? c.gold : (e.value == 0 ? c.faint : c.ink),
fontFeatures: AppTheme.tnum)),
),
),
],
),
),
],
),
),
if (ticks.isNotEmpty)
Padding(
padding: EdgeInsets.only(left: labelWidth, right: valueWidth, top: 6 * scale),
child: SizedBox(
height: 14 * scale,
child: Stack(
children: [
for (final t in ticks)
Align(
alignment: Alignment(max <= 0 ? -1 : (t / max) * 2 - 1, 0),
child: Text(tick(t), style: TextStyle(fontSize: 10 * scale, color: c.faint, fontFeatures: AppTheme.tnum)),
),
],
),
),
),
],
);
});
}
}
+9 -45
View File
@@ -1,5 +1,6 @@
import 'package:flutter/material.dart';
import '../theme/app_theme.dart';
import 'ui.dart';
class BarTab {
final String label;
@@ -8,65 +9,28 @@ class BarTab {
const BarTab(this.label, this.icon);
}
/// Tab strip that continues the dark app bar (Koledar/Stiki, Knjiga filters).
/// The selected tab is a white pill; [trailing] sits at the right end.
/// The two views of a tab page (Statistika | Zgodovina, Koledar | Kontakti):
/// a segmented control under the page title.
class BarTabs extends StatelessWidget {
final List<BarTab> tabs;
final int selected;
final ValueChanged<int> onSelect;
final Widget? trailing;
const BarTabs({
super.key,
required this.tabs,
required this.selected,
required this.onSelect,
this.trailing,
});
@override
Widget build(BuildContext context) {
return Container(
color: AppTheme.bar,
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
child: Row(
children: [
for (int i = 0; i < tabs.length; i++) ...[
if (i > 0) const SizedBox(width: 6),
Expanded(child: _tab(tabs[i], i == selected, () => onSelect(i))),
],
if (trailing != null) trailing!,
],
),
);
}
Widget _tab(BarTab tab, bool active, VoidCallback onTap) {
final color = active ? Colors.black : Colors.grey[400];
return GestureDetector(
onTap: onTap,
child: Container(
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 8),
decoration: BoxDecoration(
color: active ? Colors.white : Colors.transparent,
borderRadius: BorderRadius.circular(10),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
Icon(tab.icon, color: color, size: 18),
const SizedBox(width: 6),
Flexible(
child: Text(
tab.label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: color),
),
),
],
),
return Padding(
padding: const EdgeInsets.fromLTRB(AppTheme.edge, 0, AppTheme.edge, 12),
child: SegmentedTabs(
items: [for (final t in tabs) SegmentItem(t.label, t.icon)],
selected: selected,
onSelect: onSelect,
),
);
}
+57 -18
View File
@@ -1,10 +1,19 @@
import 'package:flutter/material.dart';
import '../theme/app_theme.dart';
class NavItem {
final IconData icon;
final IconData selectedIcon;
final String label;
const NavItem(this.icon, this.selectedIcon, this.label);
}
/// Bottom navigation of the design: icon + label, the selected one on a soft
/// accent pill. Paints the gesture-bar strip below it too (edge-to-edge).
class BottomNavBar extends StatelessWidget {
final int selectedIndex;
final ValueChanged<int> onItemTapped;
final List<BottomNavigationBarItem> items;
final List<NavItem> items;
const BottomNavBar({
super.key,
@@ -15,29 +24,59 @@ class BottomNavBar extends StatelessWidget {
@override
Widget build(BuildContext context) {
// Paint the gesture-bar strip below the nav too (edge-to-edge since targetSdk 35),
// otherwise the target background color shows through as a thin line.
return ColoredBox(
color: AppTheme.bar,
final c = Palette.current;
return DecoratedBox(
decoration: BoxDecoration(
color: c.nav,
border: Border(top: BorderSide(color: c.line2)),
),
child: SafeArea(
top: false,
child: SizedBox(
height: 80,
child: BottomNavigationBar(
backgroundColor: AppTheme.bar,
currentIndex: selectedIndex,
onTap: onItemTapped,
showSelectedLabels: true,
showUnselectedLabels: true,
type: BottomNavigationBarType.fixed,
selectedFontSize: 12,
unselectedFontSize: 12,
selectedItemColor: Colors.white,
unselectedItemColor: Colors.white70,
items: items,
height: 66,
child: Row(
children: [
for (int i = 0; i < items.length; i++)
Expanded(child: _item(c, items[i], i == selectedIndex, () => onItemTapped(i))),
],
),
),
),
);
}
Widget _item(Palette c, NavItem item, bool selected, VoidCallback onTap) {
return InkWell(
onTap: onTap,
splashFactory: NoSplash.splashFactory,
highlightColor: Colors.transparent,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
AnimatedContainer(
duration: const Duration(milliseconds: 200),
curve: Curves.easeOut,
width: 52,
height: 30,
decoration: BoxDecoration(
color: selected ? c.accentSoft : Colors.transparent,
borderRadius: BorderRadius.circular(15),
),
child: Icon(selected ? item.selectedIcon : item.icon, size: 22, color: selected ? c.accent : c.muted),
),
const SizedBox(height: 4),
Text(
item.label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 11,
fontWeight: selected ? FontWeight.w700 : FontWeight.w500,
color: selected ? c.ink : c.muted,
),
),
],
),
);
}
}
+84 -185
View File
@@ -1,183 +1,47 @@
import 'package:flutter/material.dart';
import '../theme/app_theme.dart';
import 'ui.dart';
/// Bottom sheet used by every menu on the camera stream: the live image stays
/// Bottom sheet used by every menu on a camera screen: the live image stays
/// visible and undimmed above it, so changes can be judged immediately.
Future<T?> showCameraSheet<T>(BuildContext context,
{required WidgetBuilder builder}) {
return showModalBottomSheet<T>(
context: context,
barrierColor: Colors.transparent,
backgroundColor: Colors.grey[900],
isScrollControlled:
true, // tall content (timer) may use more than half the screen
builder: (sheet) => SafeArea(
child: ConstrainedBox(
constraints:
BoxConstraints(maxHeight: MediaQuery.sizeOf(sheet).height * 0.75),
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 16),
child: builder(sheet),
),
),
),
);
}
Future<T?> showCameraSheet<T>(BuildContext context, {required WidgetBuilder builder}) =>
showAppSheet<T>(context, clearBarrier: true, maxHeightFactor: 0.75, builder: builder);
/// Title (+ optional subtitle) on the left, optional action on the right.
class CameraSheetHeader extends StatelessWidget {
final String title;
final String? subtitle;
final IconData? icon;
final Color? iconColor;
final Widget? trailing;
const CameraSheetHeader({
super.key,
required this.title,
this.subtitle,
this.icon,
this.iconColor,
this.trailing,
});
const CameraSheetHeader({super.key, required this.title, this.subtitle, this.trailing});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 14),
child: Row(
children: [
if (icon != null) ...[
Icon(icon, color: iconColor ?? Colors.white, size: 22),
const SizedBox(width: 8),
],
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title,
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold)),
if (subtitle != null)
Text(subtitle!,
style:
const TextStyle(color: Colors.white54, fontSize: 12)),
],
),
),
if (trailing != null) trailing!,
],
),
);
}
Widget build(BuildContext context) => SheetTitle(title, subtitle: subtitle, trailing: trailing);
}
/// Icon, label, slider and current value in one row.
class SheetSlider extends StatelessWidget {
final IconData icon;
/// "Ponastavi" pill in a sheet header.
class ResetPill extends StatelessWidget {
final String label;
final String valueText;
final double value;
final double min;
final double max;
final Color accent;
final ValueChanged<double> onChanged;
const SheetSlider({super.key,
required this.icon,
required this.label,
required this.valueText,
required this.value,
required this.min,
required this.max,
required this.accent,
required this.onChanged,
});
@override
Widget build(BuildContext context) {
return Row(
children: [
Icon(icon, color: Colors.white54, size: 20),
const SizedBox(width: 8),
SizedBox(
width: 72,
child: Text(label,
style: const TextStyle(color: Colors.white, fontSize: 13)),
),
Expanded(
child: Slider(
value: value.clamp(min, max),
min: min,
max: max,
activeColor: accent,
inactiveColor: Colors.white24,
onChanged: onChanged,
),
),
SizedBox(
width: 46,
child: Text(
valueText,
textAlign: TextAlign.right,
style: const TextStyle(
color: Colors.white70,
fontSize: 13,
fontFeatures: [FontFeature.tabularFigures()]),
),
),
],
);
}
}
/// Wide button that shows an on/off state with the accent color.
class SheetToggle extends StatelessWidget {
final IconData icon;
final String label;
final bool active;
final Color accent;
final VoidCallback onTap;
const SheetToggle({super.key,
required this.icon,
required this.label,
required this.active,
required this.accent,
required this.onTap,
});
const ResetPill({super.key, required this.label, required this.onTap});
@override
Widget build(BuildContext context) {
final c = Palette.current;
return Material(
color: active
? accent.withValues(alpha: 0.18)
: Colors.white.withValues(alpha: 0.06),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
side:
BorderSide(color: active ? accent : Colors.transparent, width: 1.5),
),
color: c.tile,
shape: const StadiumBorder(),
clipBehavior: Clip.antiAlias,
child: InkWell(
borderRadius: BorderRadius.circular(12),
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 10),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 18, color: active ? accent : Colors.white70),
Icon(Icons.refresh_rounded, size: 16, color: c.ink),
const SizedBox(width: 6),
Flexible(
child: Text(
label,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13,
color: active ? Colors.white : Colors.white70),
),
),
Text(label, style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: c.ink)),
],
),
),
@@ -186,50 +50,85 @@ class SheetToggle extends StatelessWidget {
}
}
/// Big number with − / + buttons, used for the bullet count.
class SheetStepper extends StatelessWidget {
final int value;
final int min;
final int max;
final Color accent;
final ValueChanged<int> onChanged;
/// Icon, label, value and a slider.
class SheetSlider extends StatelessWidget {
final IconData icon;
final String label;
final String valueText;
final double value;
final double min;
final double max;
final ValueChanged<double> onChanged;
const SheetStepper({
const SheetSlider({
super.key,
required this.icon,
required this.label,
required this.valueText,
required this.value,
required this.min,
required this.max,
required this.accent,
required this.onChanged,
});
@override
Widget build(BuildContext context) {
Widget button(IconData icon, bool enabled, int next) => IconButton(
onPressed: enabled ? () => onChanged(next) : null,
icon: Icon(icon, color: Colors.white, size: 28),
style: IconButton.styleFrom(
backgroundColor:
Colors.white.withValues(alpha: enabled ? 0.12 : 0.04),
shape: const CircleBorder(),
minimumSize: const Size(56, 56),
),
);
Widget build(BuildContext context) => LabeledSlider(
icon: icon, label: label, valueText: valueText, value: value, min: min, max: max, onChanged: onChanged);
}
/// On/off row with a switch (flashlight).
class SheetToggle extends StatelessWidget {
final IconData icon;
final String label;
final bool active;
final VoidCallback onTap;
const SheetToggle({super.key, required this.icon, required this.label, required this.active, required this.onTap});
@override
Widget build(BuildContext context) =>
ToggleRow(icon: icon, label: label, value: active, onChanged: (_) => onTap());
}
/// The numbers [min]..[max] as big square buttons; the chosen one in the accent.
class SheetStepper extends StatelessWidget {
final int value;
final int min;
final int max;
final ValueChanged<int> onChanged;
const SheetStepper({super.key, required this.value, required this.min, required this.max, required this.onChanged});
@override
Widget build(BuildContext context) {
final c = Palette.current;
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
button(Icons.remove, value > min, value - 1),
SizedBox(
width: 120,
child: Text(
'$value',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 56, fontWeight: FontWeight.bold, color: accent),
for (int n = min; n <= max; n++) ...[
if (n > min) const SizedBox(width: 10),
Expanded(
child: AspectRatio(
aspectRatio: 1,
child: Material(
color: n == value ? c.accent : c.tile,
borderRadius: BorderRadius.circular(14),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: () => onChanged(n),
child: Center(
child: Text('$n',
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.w700,
color: n == value ? c.onAccent : c.ink,
fontFeatures: AppTheme.tnum,
)),
),
),
),
),
),
),
button(Icons.add, value < max, value + 1),
],
],
);
}
+10 -46
View File
@@ -1,57 +1,21 @@
import 'package:flutter/material.dart';
import 'ui.dart';
/// Help bottom sheet: one icon + sentence per control, close button at the end.
/// Help bottom sheet: one icon + sentence per control.
/// Shared by Knjiga, camera and stream so their info buttons look the same.
void showHelpSheet(
BuildContext context, {
required List<(IconData, String)> items,
required Color accent,
required String Function(String) t,
bool clearBarrier = false,
}) {
showModalBottomSheet(
context: context,
isScrollControlled: true,
builder: (sheet) => SafeArea(
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(24, 8, 24, 16),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(t('Help'),
style: const TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold)),
const SizedBox(height: 16),
for (final (icon, text) in items)
Padding(
padding: const EdgeInsets.only(bottom: 14),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(icon, color: accent, size: 20),
const SizedBox(width: 12),
Expanded(
child: Text(t(text),
style: const TextStyle(
color: Colors.white, fontSize: 14, height: 1.3)),
),
],
),
),
const SizedBox(height: 4),
SizedBox(
width: double.infinity,
child: FilledButton(
style: FilledButton.styleFrom(backgroundColor: accent),
onPressed: () => Navigator.pop(sheet),
child: Text(t('Close')),
),
),
],
),
),
showAppSheet(
context,
title: t('Help'),
clearBarrier: clearBarrier,
builder: (sheet) => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [for (final (icon, text) in items) HelpRow(icon, t(text))],
),
);
}
+43 -62
View File
@@ -1,6 +1,9 @@
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../theme/app_theme.dart';
import '../utils/format.dart';
import 'camera_sheet.dart';
import 'ui.dart';
enum ImageFilterType { none, greyscale, invert, highContrast }
@@ -104,7 +107,6 @@ Future<void> showImageSettingsSheet(
required ImageAdjustments initial,
required String settingsId,
required String cameraLabel,
required Color accent,
required String Function(String) t,
required ValueChanged<ImageAdjustments> onChanged,
}) {
@@ -113,6 +115,7 @@ Future<void> showImageSettingsSheet(
context,
builder: (sheet) => StatefulBuilder(
builder: (context, setSheetState) {
final c = Palette.current;
void update(ImageAdjustments next) {
setSheetState(() => value = next);
onChanged(next);
@@ -121,37 +124,20 @@ Future<void> showImageSettingsSheet(
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
CameraSheetHeader(
title: t('Image Settings'),
subtitle: '$cameraLabel · ${t('Saved for this camera')}',
trailing: TextButton.icon(
style: TextButton.styleFrom(foregroundColor: Colors.white70),
icon: const Icon(Icons.restart_alt_rounded, size: 18),
label: Text(t('Reset')),
onPressed: () => update(value.resetPicture()),
),
subtitle: '$cameraLabel · ${t('saved for this camera')}',
trailing: ResetPill(label: t('Reset'), onTap: () => update(value.resetPicture())),
),
Row(
children: [
for (final (f, icon, label) in [
(ImageFilterType.none, Icons.image_outlined, 'None'),
(
ImageFilterType.greyscale,
Icons.filter_b_and_w_rounded,
'Greyscale'
),
(
ImageFilterType.highContrast,
Icons.contrast_rounded,
'High contrast'
),
(
ImageFilterType.invert,
Icons.invert_colors_rounded,
'Invert'
),
(ImageFilterType.greyscale, Icons.contrast_rounded, 'Greyscale'),
(ImageFilterType.highContrast, Icons.wb_sunny_outlined, 'High contrast'),
(ImageFilterType.invert, Icons.visibility_outlined, 'Invert'),
]) ...[
if (f != ImageFilterType.none) const SizedBox(width: 8),
Expanded(
@@ -159,43 +145,51 @@ Future<void> showImageSettingsSheet(
icon: icon,
label: t(label),
selected: value.filter == f,
accent: accent,
onTap: () => update(value.copyWith(filter: f)),
),
),
],
],
),
const SizedBox(height: 14),
const SizedBox(height: 16),
SheetSlider(
icon: Icons.brightness_6_rounded,
icon: Icons.light_mode_outlined,
label: t('Brightness'),
valueText:
'${value.brightness >= 0 ? '+' : ''}${(value.brightness * 100).round()}',
valueText: '${value.brightness >= 0 ? '+' : '−'}${(value.brightness.abs() * 100).round()}',
value: value.brightness,
min: -1,
max: 1,
accent: accent,
onChanged: (v) => update(value.copyWith(brightness: v)),
),
SheetSlider(
icon: Icons.tonality_rounded,
icon: Icons.contrast_rounded,
label: t('Contrast'),
valueText: '${(value.contrast * 100).round()} %',
valueText: dec(value.contrast, 1),
value: value.contrast,
min: 0.5,
max: 2,
accent: accent,
onChanged: (v) => update(value.copyWith(contrast: v)),
),
const SizedBox(height: 8),
SheetToggle(
icon: Icons.rotate_90_degrees_cw_rounded,
label: '${t('Rotate')} · ${value.quarterTurns * 90}°',
active: value.quarterTurns != 0,
accent: accent,
onTap: () => update(
value.copyWith(quarterTurns: (value.quarterTurns + 1) % 4)),
AppCard(
color: c.isDark ? c.card2 : c.card,
padding: const EdgeInsets.fromLTRB(16, 8, 8, 8),
onTap: () => update(value.copyWith(quarterTurns: (value.quarterTurns + 1) % 4)),
child: Row(
children: [
Icon(Icons.rotate_right_rounded, size: 20, color: c.muted),
const SizedBox(width: 12),
Expanded(
child: Text('${t('Rotate')} · ${value.quarterTurns * 90}°',
style: TextStyle(fontSize: 14.5, fontWeight: FontWeight.w500, color: c.ink)),
),
CircleButton(
icon: Icons.rotate_right_rounded,
size: 36,
onTap: () => update(value.copyWith(quarterTurns: (value.quarterTurns + 1) % 4)),
),
],
),
),
],
);
@@ -208,46 +202,33 @@ class _FilterTile extends StatelessWidget {
final IconData icon;
final String label;
final bool selected;
final Color accent;
final VoidCallback onTap;
const _FilterTile({
required this.icon,
required this.label,
required this.selected,
required this.accent,
required this.onTap,
});
const _FilterTile({required this.icon, required this.label, required this.selected, required this.onTap});
@override
Widget build(BuildContext context) {
final c = Palette.current;
return Material(
color: selected
? accent.withValues(alpha: 0.18)
: Colors.white.withValues(alpha: 0.06),
color: selected ? c.accentSoft : (c.isDark ? c.card2 : c.tile),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14),
side:
BorderSide(color: selected ? accent : Colors.transparent, width: 2),
side: BorderSide(color: selected ? c.accent : Colors.transparent, width: 1.5),
),
clipBehavior: Clip.antiAlias,
child: InkWell(
borderRadius: BorderRadius.circular(14),
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 4),
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 2),
child: Column(
children: [
Icon(icon, color: selected ? accent : Colors.white70, size: 26),
const SizedBox(height: 4),
Icon(icon, color: selected ? c.accent : c.muted, size: 22),
const SizedBox(height: 6),
Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: selected ? Colors.white : Colors.white70,
),
style: TextStyle(fontSize: 10.5, fontWeight: FontWeight.w600, color: selected ? c.ink : c.muted),
),
],
),
+25 -9
View File
@@ -27,6 +27,9 @@ class ProgressChart extends StatefulWidget {
final List<ChartSeries> series; // legend and tooltip order
final Color textColor;
final Color gridColor;
final Color surfaceColor; // ring around points
final Color tooltipColor;
final Color tooltipTextColor;
// true: the graph takes all the height its parent gives it (inside an
// Expanded); false: a fixed 190 px
final bool expand;
@@ -37,6 +40,9 @@ class ProgressChart extends StatefulWidget {
required this.series,
required this.textColor,
required this.gridColor,
this.surfaceColor = Colors.white,
this.tooltipColor = const Color(0xFF212121),
this.tooltipTextColor = Colors.white,
this.expand = false,
});
@@ -97,6 +103,9 @@ class _ProgressChartState extends State<ProgressChart> {
series: widget.series,
textColor: widget.textColor,
gridColor: widget.gridColor,
surfaceColor: widget.surfaceColor,
tooltipColor: widget.tooltipColor,
tooltipTextColor: widget.tooltipTextColor,
selected: _selected,
),
),
@@ -120,9 +129,9 @@ class _ProgressChartState extends State<ProgressChart> {
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 14,
height: 3,
decoration: BoxDecoration(color: s.color, borderRadius: BorderRadius.circular(2)),
width: 8,
height: 8,
decoration: BoxDecoration(color: s.color, shape: BoxShape.circle),
),
const SizedBox(width: 6),
Text(s.name, style: TextStyle(fontSize: 12, color: widget.textColor)),
@@ -148,6 +157,9 @@ class _ChartPainter extends CustomPainter {
final List<ChartSeries> series;
final Color textColor;
final Color gridColor;
final Color surfaceColor;
final Color tooltipColor;
final Color tooltipTextColor;
final int? selected;
_ChartPainter({
@@ -155,6 +167,9 @@ class _ChartPainter extends CustomPainter {
required this.series,
required this.textColor,
required this.gridColor,
required this.surfaceColor,
required this.tooltipColor,
required this.tooltipTextColor,
required this.selected,
});
@@ -225,7 +240,7 @@ class _ChartPainter extends CustomPainter {
for (int i = 0; i < n; i++) {
final isSel = i == selected;
final p = Offset(xAt(i), yAt(s.values[i], r));
canvas.drawCircle(p, isSel ? 6 : 4.5, Paint()..color = Colors.white);
canvas.drawCircle(p, isSel ? 6 : 4.5, Paint()..color = surfaceColor);
canvas.drawCircle(p, isSel ? 4.5 : 3.5, Paint()..color = s.color);
}
}
@@ -236,13 +251,13 @@ class _ChartPainter extends CustomPainter {
canvas.drawLine(Offset(xAt(i), plot.top), Offset(xAt(i), plot.bottom), grid);
final tp = TextPainter(
text: TextSpan(
style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Colors.white),
style: TextStyle(fontFamily: 'Inter', fontSize: 12, fontWeight: FontWeight.w600, color: tooltipTextColor),
children: [
TextSpan(text: labels[i]),
for (final s in series)
TextSpan(
text: ' ${s.format(s.values[i])}',
style: TextStyle(color: Color.lerp(s.color, Colors.white, 0.35)),
style: TextStyle(color: Color.lerp(s.color, tooltipTextColor, 0.25)),
),
],
),
@@ -252,7 +267,7 @@ class _ChartPainter extends CustomPainter {
final left = (xAt(i) - w / 2).clamp(0.0, size.width - w);
canvas.drawRRect(
RRect.fromRectAndRadius(Rect.fromLTWH(left, 2, w, 24), const Radius.circular(6)),
Paint()..color = Colors.grey[900]!,
Paint()..color = tooltipColor,
);
tp.paint(canvas, Offset(left + 8, 2 + (24 - tp.height) / 2));
}
@@ -260,7 +275,7 @@ class _ChartPainter extends CustomPainter {
void _text(Canvas canvas, String text, Offset at, double size, Color color, {bool alignRight = false}) {
final tp = TextPainter(
text: TextSpan(text: text, style: TextStyle(fontSize: size, color: color)),
text: TextSpan(text: text, style: TextStyle(fontFamily: 'Inter', fontSize: size, color: color, fontFeatures: const [FontFeature.tabularFigures()])),
textDirection: TextDirection.ltr,
)..layout();
tp.paint(canvas, alignRight ? at.translate(-tp.width, 0) : at);
@@ -271,5 +286,6 @@ class _ChartPainter extends CustomPainter {
old.labels != labels ||
old.series != series ||
old.selected != selected ||
old.textColor != textColor;
old.textColor != textColor ||
old.surfaceColor != surfaceColor;
}
+141 -242
View File
@@ -1,45 +1,41 @@
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';
import '../screens/target_view.dart' show BarChartPainter;
import '../models/target_style.dart';
import '../theme/app_theme.dart';
import '../utils/format.dart';
import 'bar_list.dart';
import 'target_face.dart';
import 'ui.dart';
/// Everything the share image shows, taken from the target view as it is.
/// Everything the share image shows, taken from the result screen as it is.
class ResultShareData {
final String title; // session (folder) name
final String date; // already formatted, e.g. 12.11.2026
final String countsLine; // e.g. "7 tarč · 35 strelov"
final String title; // "Trening 18" or "Tarča 3"
final String subtitle; // date, counts
final int total;
final double? averagePerShot;
final Uint8List targetImage; // the selected target design
final Size targetImageSize;
final List<Offset> bullets; // in targetImage pixels
final double bulletDiameter; // in targetImage pixels
final Color bulletColor;
final Color targetBackground; // matches the target design
final List<(String top, String bottom)> tiles; // e.g. ("6x", "10")
final List<MapEntry<int, int>> chart; // bar label number -> points
final bool chartPerShot; // bars are shots of one target, not targets of a session
final TargetStyle style;
final List<Offset> hits; // in target space
final List<(String? top, String value, bool filled)> tiles;
final String chartTitle;
final List<BarEntry> bars;
final double barMax;
final String Function(String) t;
const ResultShareData({
required this.title,
required this.date,
required this.countsLine,
required this.subtitle,
required this.total,
required this.averagePerShot,
required this.targetImage,
required this.targetImageSize,
required this.bullets,
required this.bulletDiameter,
required this.bulletColor,
required this.targetBackground,
required this.style,
required this.hits,
required this.tiles,
required this.chart,
required this.chartPerShot,
required this.chartTitle,
required this.bars,
required this.barMax,
required this.t,
});
}
@@ -56,7 +52,8 @@ Future<void> shareResult(BuildContext context, ResultShareData data) async {
OverlayEntry? entry;
try {
// Decode the target first so it is in the very first frame
await precacheImage(MemoryImage(data.targetImage), context);
final asset = data.style.asset;
if (asset != null) await precacheImage(AssetImage(asset), context);
// Laid out and painted, but outside the screen
entry = OverlayEntry(
@@ -81,8 +78,7 @@ Future<void> shareResult(BuildContext context, ResultShareData data) async {
entry = null;
final dir = await getTemporaryDirectory();
final file = File(
'${dir.path}/sdk_kovinar_${DateTime.now().millisecondsSinceEpoch}.png');
final file = File('${dir.path}/sdk_kovinar_${DateTime.now().millisecondsSinceEpoch}.png');
await file.writeAsBytes(png!.buffer.asUint8List());
await SharePlus.instance.share(ShareParams(
files: [XFile(file.path, mimeType: 'image/png')],
@@ -97,8 +93,8 @@ Future<void> shareResult(BuildContext context, ResultShareData data) async {
}
}
/// The 960x540 image: header with the result, target with score tiles on the
/// left, the bar chart with every value on the right.
/// The 960×540 image: the result in the header, the target with its tiles on
/// the left, the bar chart with every value on the right.
class ResultShareCard extends StatelessWidget {
static const Size size = Size(960, 540);
final ResultShareData data;
@@ -106,256 +102,159 @@ class ResultShareCard extends StatelessWidget {
@override
Widget build(BuildContext context) {
final c = Palette.current;
final t = data.t;
final accent = data.bulletColor;
return SizedBox.fromSize(
size: size,
child: Material(
color: const Color(0xFF1B1E21),
child: Padding(
padding: const EdgeInsets.fromLTRB(28, 22, 28, 22),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Header
Row(
crossAxisAlignment: CrossAxisAlignment.end,
color: c.bg,
child: Stack(
children: [
// Faint rings behind the header, like a target in the corner
Positioned(
right: -260,
top: -330,
child: CustomPaint(size: const Size(700, 700), painter: _Rings(c.line2)),
),
Padding(
padding: const EdgeInsets.fromLTRB(32, 26, 32, 32),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('SD KOVINAR',
style: TextStyle(
color: accent,
fontSize: 12,
fontWeight: FontWeight.w800,
letterSpacing: 2.5)),
const SizedBox(height: 2),
Text(data.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: Colors.white,
fontSize: 28,
fontWeight: FontWeight.w800)),
const SizedBox(height: 2),
Text('${data.date} · ${data.countsLine}',
style: const TextStyle(
color: Colors.white60, fontSize: 14)),
],
),
),
if (data.averagePerShot != null)
_HeaderFigure(
label: t('Average per shot'),
value: data.averagePerShot!.toStringAsFixed(2),
size: 40),
const SizedBox(width: 28),
_HeaderFigure(
label: t('Total score').replaceAll(':', ''),
value: '${data.total}',
size: 40,
color: accent),
],
),
const SizedBox(height: 16),
Expanded(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Target and score tiles
Container(
width: 380,
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: data.targetBackground,
borderRadius: BorderRadius.circular(18),
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('SD KOVINAR MUTA',
style: TextStyle(color: c.accent, fontSize: 12, fontWeight: FontWeight.w800, letterSpacing: 2.2)),
const SizedBox(height: 4),
Text(data.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: c.ink, fontSize: 30, fontWeight: FontWeight.w700, height: 1.15)),
const SizedBox(height: 4),
Text(data.subtitle, style: TextStyle(color: c.muted, fontSize: 14)),
],
),
),
child: Column(
children: [
Expanded(
child: Center(
child: AspectRatio(
aspectRatio: data.targetImageSize.width /
data.targetImageSize.height,
child: _TargetWithHits(data: data),
),
),
),
const SizedBox(height: 10),
SizedBox(
height: 58,
child: Row(
if (data.averagePerShot != null)
_HeaderFigure(label: t('Average per shot'), value: dec(data.averagePerShot!), color: c.ink),
const SizedBox(width: 40),
_HeaderFigure(label: t('Total'), value: '${data.total}', color: c.accent),
],
),
const SizedBox(height: 20),
Expanded(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SizedBox(
width: 400,
child: AppCard(
padding: const EdgeInsets.fromLTRB(14, 10, 14, 14),
child: Column(
children: [
for (final (top, bottom) in data.tiles)
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 3),
child: _Tile(
top: top,
bottom: bottom,
color: accent),
),
Expanded(
child: Center(
child: TargetFace(style: data.style, hits: data.hits, hitColor: c.accent),
),
),
const SizedBox(height: 10),
Row(
children: [
for (int i = 0; i < data.tiles.length; i++) ...[
if (i > 0) const SizedBox(width: 6),
Expanded(
child: ScoreTile(
top: data.tiles[i].$1,
value: data.tiles[i].$2,
filled: data.tiles[i].$3,
height: 60,
),
),
],
],
),
],
),
),
],
),
),
const SizedBox(width: 16),
// Chart with every value
Expanded(
child: Container(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 4),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(18),
),
child: CustomPaint(
size: Size.infinite,
painter: BarChartPainter(
data: data.chart,
maxScore: _chartMax(data),
bulletColor: accent,
isShotView: data.chartPerShot,
backgroundColor: Colors.white,
translateFunc: t,
xAxisLabelKey: data.chartPerShot ? 'Points' : null,
const SizedBox(width: 20),
Expanded(
child: AppCard(
padding: const EdgeInsets.fromLTRB(20, 20, 20, 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Kicker(data.chartTitle, padding: const EdgeInsets.only(bottom: 14)),
Expanded(
child: BarList(
entries: data.bars,
max: data.barMax,
ticks: [0, data.barMax / 2, data.barMax],
labelWidth: 36,
valueWidth: 56,
scale: 1.1,
),
),
],
),
),
),
),
],
),
],
),
),
],
),
],
),
),
],
),
),
);
}
}
static double _chartMax(ResultShareData d) {
final max = d.chart.isEmpty
? 0
: d.chart.map((e) => e.value).reduce((a, b) => a > b ? a : b);
return max <= 0 ? 1 : max.toDouble();
class _Rings extends CustomPainter {
final Color color;
const _Rings(this.color);
@override
void paint(Canvas canvas, Size size) {
final p = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 1.5
..color = color;
for (double r = 80; r < size.width / 2; r += 55) {
canvas.drawCircle(size.center(Offset.zero), r, p);
}
}
@override
bool shouldRepaint(_Rings old) => old.color != color;
}
class _HeaderFigure extends StatelessWidget {
final String label;
final String value;
final double size;
final Color color;
const _HeaderFigure(
{required this.label,
required this.value,
required this.size,
this.color = Colors.white});
const _HeaderFigure({required this.label, required this.value, required this.color});
@override
Widget build(BuildContext context) {
final c = Palette.current;
return Column(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: [
Text(label.toUpperCase(),
style: const TextStyle(
color: Colors.white54,
fontSize: 11,
fontWeight: FontWeight.w700,
letterSpacing: 1.5)),
Text(label.toUpperCase(), style: AppTheme.kicker(c).copyWith(letterSpacing: 1.5)),
const SizedBox(height: 4),
Text(value,
style: TextStyle(
color: color,
fontSize: size,
height: 1.05,
fontWeight: FontWeight.w800,
fontFeatures: const [FontFeature.tabularFigures()])),
color: color, fontSize: 44, height: 1.05, fontWeight: FontWeight.w800, fontFeatures: AppTheme.tnum)),
],
);
}
}
class _TargetWithHits extends StatelessWidget {
final ResultShareData data;
const _TargetWithHits({required this.data});
@override
Widget build(BuildContext context) {
return LayoutBuilder(builder: (context, c) {
final scale = c.maxWidth / data.targetImageSize.width;
final d = data.bulletDiameter * scale;
return Stack(
children: [
Positioned.fill(
child: Image.memory(data.targetImage,
fit: BoxFit.fill, gaplessPlayback: true)),
for (final b in data.bullets)
Positioned(
left: b.dx * scale - d / 2,
top: b.dy * scale - d / 2,
width: d,
height: d,
child: DecoratedBox(
decoration: BoxDecoration(
color: data.bulletColor.withValues(alpha: 0.85),
shape: BoxShape.circle,
border: Border.all(color: Colors.black, width: 1),
),
),
),
],
);
});
}
}
class _Tile extends StatelessWidget {
final String top;
final String bottom;
final Color color;
const _Tile({required this.top, required this.bottom, required this.color});
@override
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Column(
children: [
Container(
height: 20,
width: double.infinity,
color: const Color(0xFF2C2F33),
alignment: Alignment.center,
child: FittedBox(
child: Text(top,
style: const TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w700)),
),
),
Expanded(
child: Container(
width: double.infinity,
color: color.withValues(alpha: 0.9),
alignment: Alignment.center,
child: FittedBox(
child: Text(bottom,
style: const TextStyle(
color: Colors.white,
fontSize: 22,
fontWeight: FontWeight.w800)),
),
),
),
],
),
);
}
}
+130 -79
View File
@@ -4,21 +4,20 @@ import '../theme/app_theme.dart';
/// Small uppercase label above a group, e.g. "OBVESTILA".
class SectionHeader extends StatelessWidget {
final String label;
final Widget? trailing;
const SectionHeader(this.label, {super.key});
const SectionHeader(this.label, {super.key, this.trailing});
@override
Widget build(BuildContext context) {
final c = Palette.current;
return Padding(
padding: const EdgeInsets.fromLTRB(4, 20, 4, 8),
child: Text(
label.toUpperCase(),
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
letterSpacing: 1.4,
color: Surfaces.current.textSecondary,
),
padding: const EdgeInsets.fromLTRB(0, 22, 0, 10),
child: Row(
children: [
Expanded(child: Text(label.toUpperCase(), style: AppTheme.kicker(c))),
if (trailing != null) trailing!,
],
),
);
}
@@ -27,20 +26,26 @@ class SectionHeader extends StatelessWidget {
/// Rounded group of rows with thin dividers between them.
class GroupCard extends StatelessWidget {
final List<Widget> children;
final bool indentDividers;
const GroupCard({super.key, required this.children});
const GroupCard({super.key, required this.children, this.indentDividers = true});
@override
Widget build(BuildContext context) {
final s = Surfaces.current;
return ClipRRect(
borderRadius: BorderRadius.circular(14),
final c = Palette.current;
return DecoratedBox(
decoration: BoxDecoration(borderRadius: BorderRadius.circular(AppTheme.radius), boxShadow: c.shadow),
child: Material(
color: s.card,
color: c.card,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(AppTheme.radius),
side: BorderSide(color: c.line2),
),
clipBehavior: Clip.antiAlias,
child: Column(
children: [
for (int i = 0; i < children.length; i++) ...[
if (i > 0) Divider(height: 1, thickness: 1, indent: 16, color: s.divider),
if (i > 0) Divider(height: 1, thickness: 1, indent: indentDividers ? 16 : 0, endIndent: indentDividers ? 16 : 0, color: c.line2),
children[i],
],
],
@@ -50,50 +55,65 @@ class GroupCard extends StatelessWidget {
}
}
/// One settings row: title (+ optional subtitle) on the left, current value and
/// a chevron on the right. Pass [trailing] to replace value + chevron (e.g. a Switch).
/// One settings row: icon, title (+ subtitle) on the left, current value and a
/// chevron on the right. [trailing] replaces value + chevron (e.g. a switch).
class SettingsTile extends StatelessWidget {
final String title;
final String? subtitle;
final IconData? icon;
final Color? iconColor;
final Widget? leading;
final String? value;
final Color? valueColor;
final Widget? valueLeading;
final Widget? trailing;
final VoidCallback? onTap;
final bool mono; // value in the monospace font (IP addresses)
final bool showChevron;
final IconData chevron;
final Color? titleColor;
const SettingsTile({
super.key,
required this.title,
this.subtitle,
this.icon,
this.iconColor,
this.leading,
this.value,
this.valueColor,
this.valueLeading,
this.trailing,
this.onTap,
this.mono = false,
this.showChevron = true,
this.chevron = Icons.chevron_right_rounded,
this.titleColor,
});
@override
Widget build(BuildContext context) {
final s = Surfaces.current;
final c = Palette.current;
return InkWell(
onTap: onTap,
child: ConstrainedBox(
constraints: const BoxConstraints(minHeight: 52),
constraints: const BoxConstraints(minHeight: 56),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
padding: const EdgeInsets.fromLTRB(16, 9, 12, 9),
child: Row(
children: [
if (leading != null) ...[leading!, const SizedBox(width: 12)],
if (leading != null) ...[leading!, const SizedBox(width: 14)]
else if (icon != null) ...[Icon(icon, size: 21, color: iconColor ?? c.muted), const SizedBox(width: 14)],
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(title, style: TextStyle(fontSize: 15, color: s.textPrimary)),
Text(title, style: TextStyle(fontSize: 15.5, fontWeight: FontWeight.w500, color: titleColor ?? c.ink)),
if (subtitle != null)
Padding(
padding: const EdgeInsets.only(top: 2),
child: Text(subtitle!, style: TextStyle(fontSize: 12, color: s.textSecondary)),
child: Text(subtitle!, style: TextStyle(fontSize: 12, color: c.muted)),
),
],
),
@@ -104,14 +124,22 @@ class SettingsTile extends StatelessWidget {
if (valueLeading != null) ...[valueLeading!, const SizedBox(width: 8)],
if (value != null)
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 170),
constraints: const BoxConstraints(maxWidth: 190),
child: Text(
value!,
style: TextStyle(fontSize: 14, color: s.textSecondary),
style: TextStyle(
fontSize: mono ? 13 : 14,
fontFamily: mono ? AppTheme.mono : null,
color: valueColor ?? c.muted,
fontFeatures: AppTheme.tnum,
),
overflow: TextOverflow.ellipsis,
),
),
if (onTap != null) Icon(Icons.chevron_right, color: s.textSecondary),
if (onTap != null && showChevron) ...[
const SizedBox(width: 4),
Icon(chevron, size: 20, color: c.faint),
],
],
],
),
@@ -124,68 +152,87 @@ class SettingsTile extends StatelessWidget {
/// Settings row with a switch on the right; tapping the row toggles it.
class SettingsSwitchTile extends StatelessWidget {
final String title;
final IconData? icon;
final bool value;
final ValueChanged<bool> onChanged;
final Color activeColor;
const SettingsSwitchTile({
super.key,
required this.title,
this.icon,
required this.value,
required this.onChanged,
required this.activeColor,
});
@override
Widget build(BuildContext context) {
return SettingsTile(
title: title,
icon: icon,
onTap: () => onChanged(!value),
trailing: SizedBox(
height: 32,
child: FittedBox(
child: Switch(
value: value,
onChanged: onChanged,
activeTrackColor: activeColor,
activeThumbColor: Colors.white,
),
),
),
trailing: SizedBox(height: 32, child: FittedBox(child: Switch(value: value, onChanged: onChanged))),
);
}
}
/// Row used inside dark bottom-sheet pickers, with a check on the selected one.
/// Row of a picker sheet, with a check on the selected one.
class SheetOption extends StatelessWidget {
final String label;
final String? subtitle;
final Widget? leading;
final bool selected;
final Color selectedColor;
final VoidCallback onTap;
final bool showDivider;
const SheetOption({
super.key,
required this.label,
this.subtitle,
this.leading,
required this.selected,
required this.selectedColor,
required this.onTap,
this.showDivider = true,
});
@override
Widget build(BuildContext context) {
return ListTile(
final c = Palette.current;
return InkWell(
onTap: onTap,
leading: leading,
title: Text(
label,
style: TextStyle(
color: Colors.white,
fontWeight: selected ? FontWeight.bold : FontWeight.normal,
borderRadius: BorderRadius.circular(12),
child: Container(
constraints: const BoxConstraints(minHeight: 56),
padding: const EdgeInsets.symmetric(vertical: 10),
decoration: BoxDecoration(
border: showDivider ? Border(top: BorderSide(color: c.line2)) : null,
),
child: Row(
children: [
if (leading != null) ...[leading!, const SizedBox(width: 12)],
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(label, style: TextStyle(fontSize: 15.5, fontWeight: selected ? FontWeight.w600 : FontWeight.w500, color: c.ink)),
if (subtitle != null)
Padding(
padding: const EdgeInsets.only(top: 3),
child: Text(subtitle!, style: TextStyle(fontSize: 12, color: c.muted)),
),
],
),
),
if (selected)
Container(
width: 24,
height: 24,
decoration: BoxDecoration(color: c.accent, shape: BoxShape.circle),
child: Icon(Icons.check_rounded, size: 16, color: c.onAccent),
),
],
),
),
trailing: selected ? Icon(Icons.check_rounded, color: selectedColor) : null,
);
}
}
@@ -200,24 +247,22 @@ class StatTile extends StatelessWidget {
@override
Widget build(BuildContext context) {
final s = Surfaces.current;
return Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 12, 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label, style: TextStyle(fontSize: 12, color: s.textSecondary)),
const SizedBox(height: 2),
Text(value, style: TextStyle(fontSize: 26, fontWeight: FontWeight.bold, color: s.textPrimary)),
if (caption != null)
Text(caption!, style: TextStyle(fontSize: 11, color: s.textSecondary), maxLines: 1, overflow: TextOverflow.ellipsis),
],
),
final c = Palette.current;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label, style: TextStyle(fontSize: 12, color: c.muted)),
const SizedBox(height: 2),
Text(value,
style: TextStyle(fontSize: 28, fontWeight: FontWeight.w800, height: 1.15, color: c.ink, fontFeatures: AppTheme.tnum)),
if (caption != null)
Text(caption!, style: TextStyle(fontSize: 11.5, color: c.muted), maxLines: 1, overflow: TextOverflow.ellipsis),
],
);
}
}
/// Grid of [StatTile]s, two per row, on one card.
/// [StatTile]s two per row, each on its own card.
class StatGrid extends StatelessWidget {
final List<StatTile> tiles;
@@ -225,24 +270,30 @@ class StatGrid extends StatelessWidget {
@override
Widget build(BuildContext context) {
final s = Surfaces.current;
final c = Palette.current;
final rows = <Widget>[];
for (int i = 0; i < tiles.length; i += 2) {
if (i > 0) rows.add(Divider(height: 1, thickness: 1, color: s.divider));
rows.add(IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(child: tiles[i]),
VerticalDivider(width: 1, thickness: 1, color: s.divider),
Expanded(child: i + 1 < tiles.length ? tiles[i + 1] : const SizedBox()),
if (i > 0) rows.add(const SizedBox(height: 10));
rows.add(Row(
children: [
for (final t in [tiles[i], if (i + 1 < tiles.length) tiles[i + 1]]) ...[
if (t != tiles[i]) const SizedBox(width: 10),
Expanded(
child: Container(
padding: const EdgeInsets.fromLTRB(14, 12, 12, 12),
decoration: BoxDecoration(
color: c.card,
borderRadius: BorderRadius.circular(AppTheme.radius),
border: Border.all(color: c.line2),
boxShadow: c.shadow,
),
child: t,
),
),
],
),
],
));
}
return ClipRRect(
borderRadius: BorderRadius.circular(14),
child: ColoredBox(color: s.card, child: Column(children: rows)),
);
return Column(children: rows);
}
}
+258
View File
@@ -0,0 +1,258 @@
import 'package:flutter/material.dart';
import '../models/target_style.dart';
import '../utils/target_scoring.dart';
/// A target design with hits on it, drawn in the shared 1200 × 1200 space and
/// scaled to the space it gets (always square).
///
/// The default target is painted as vectors, so its rings and numbers stay
/// sharp at any size or zoom; the other designs are their v3 images.
class TargetFace extends StatelessWidget {
final TargetStyle style;
final List<Offset> hits; // in target space (0–1200)
final Color hitColor;
final Set<int> highlighted; // indexes of [hits] drawn with a ring
final Set<int> dimmed; // indexes drawn faded (e.g. other values while one is pressed)
final bool showScoring; // debug: the radii the scoring uses, over the design
const TargetFace({
super.key,
required this.style,
this.hits = const [],
this.hitColor = const Color(0xFF22C7E0),
this.highlighted = const {},
this.dimmed = const {},
this.showScoring = false,
});
@override
Widget build(BuildContext context) {
final asset = style.asset;
return AspectRatio(
aspectRatio: 1,
child: Stack(
fit: StackFit.expand,
children: [
if (asset == null)
const RepaintBoundary(child: CustomPaint(painter: DefaultTargetPainter(glow: true)))
else
Image.asset(asset, fit: BoxFit.contain, filterQuality: FilterQuality.medium, gaplessPlayback: true),
if (showScoring) const CustomPaint(painter: ScoringRingsPainter()),
if (hits.isNotEmpty)
CustomPaint(
painter: HitsPainter(hits: hits, color: hitColor, highlighted: highlighted, dimmed: dimmed),
),
],
),
);
}
}
/// Small preview of a design, for the pickers and the settings row.
class TargetThumb extends StatelessWidget {
final TargetStyle style;
final double size;
const TargetThumb(this.style, {super.key, required this.size});
@override
Widget build(BuildContext context) {
final asset = style.asset;
return SizedBox.square(
dimension: size,
child: asset == null
? CustomPaint(painter: DefaultTargetPainter(glow: true, numbers: size >= 60))
: Image.asset(
asset,
fit: BoxFit.contain,
cacheWidth: (size * MediaQuery.devicePixelRatioOf(context)).round().clamp(64, 600),
filterQuality: FilterQuality.medium,
),
);
}
}
/// The default target ("00 Privzeta · brez sijaja") in vectors: white paper
/// ending on ring 1, black 7–10, numbers 1–8 on the four axes. [glow] adds a
/// small glow (white rim, short light-blue halo).
class DefaultTargetPainter extends CustomPainter {
final bool glow;
final bool numbers;
const DefaultTargetPainter({this.glow = false, this.numbers = true});
static const double _paper = 510;
static const Color _glowOuter = Color(0xFF9FD8FF);
// Outer radius of score zone k (1–9); zone 10 is the centre dot
static double ring(int k) => k == 10 ? 15 : 15 + 55 * (10 - k).toDouble();
@override
void paint(Canvas canvas, Size size) {
final s = size.shortestSide / TargetScoring.size;
canvas.save();
canvas.translate((size.width - size.shortestSide) / 2, (size.height - size.shortestSide) / 2);
canvas.scale(s);
const c = TargetScoring.center;
if (glow) {
// figcraft drop-shadow "radius" is the blur; Flutter wants sigma ≈ blur / 2
void blurDisc(double r, Color color, double blur) => canvas.drawCircle(
c, r, Paint()..color = color..maskFilter = MaskFilter.blur(BlurStyle.normal, blur / 2));
// A small glow: a short light-blue halo and a white rim
blurDisc(_paper + 2, _glowOuter.withValues(alpha: 0.55), 40);
blurDisc(_paper + 1, Colors.white.withValues(alpha: 0.7), 10);
}
// Paper, then the black (zones 7–10)
canvas.drawCircle(c, _paper, Paint()..color = Colors.white);
canvas.drawCircle(c, ring(7), Paint()..color = Colors.black);
final line = Paint()
..style = PaintingStyle.stroke
..isAntiAlias = true;
for (int k = 1; k <= 6; k++) {
canvas.drawCircle(c, ring(k), line..color = Colors.black..strokeWidth = 3);
}
for (final k in [8, 9]) {
canvas.drawCircle(c, ring(k), line..color = Colors.white..strokeWidth = 5);
}
canvas.drawCircle(c, ring(10), Paint()..color = Colors.white);
if (numbers) {
for (int k = 1; k <= 8; k++) {
final tp = TextPainter(
text: TextSpan(
text: '$k',
style: TextStyle(
fontFamily: 'Inter',
fontSize: 33,
fontWeight: FontWeight.w700,
height: 1,
color: k <= 6 ? Colors.black : Colors.white,
),
),
textDirection: TextDirection.ltr,
)..layout();
final mid = ring(k) - 27.5;
for (final d in const [Offset(-1, 0), Offset(1, 0), Offset(0, -1), Offset(0, 1)]) {
final at = c + d * mid;
// Centre the cap height (≈ 0.73 em of Inter) on the zone
tp.paint(canvas, Offset(at.dx - tp.width / 2, at.dy - tp.height / 2 + 33 * 0.03));
}
}
}
canvas.restore();
}
@override
bool shouldRepaint(DefaultTargetPainter old) => old.glow != glow || old.numbers != numbers;
}
/// Hits in target space: a filled dot of [TargetScoring.bulletDiameter] with a
/// dark rim, semi-transparent so overlapping hits stay visible. Highlighted
/// ones are drawn on top with a red border on their own edge.
class HitsPainter extends CustomPainter {
final List<Offset> hits;
final Color color;
final Set<int> highlighted;
final Set<int> dimmed;
static const Color selectedColor = Color(0xFFE5322D);
const HitsPainter({required this.hits, required this.color, this.highlighted = const {}, this.dimmed = const {}});
@override
void paint(Canvas canvas, Size size) {
final s = size.shortestSide / TargetScoring.size;
canvas.save();
canvas.translate((size.width - size.shortestSide) / 2, (size.height - size.shortestSide) / 2);
canvas.scale(s);
const r = TargetScoring.bulletDiameter / 2;
final rim = Color.lerp(color, Colors.black, 0.6)!;
// Highlighted last so they sit on top
final order = [
for (int i = 0; i < hits.length; i++)
if (!highlighted.contains(i)) i,
for (int i = 0; i < hits.length; i++)
if (highlighted.contains(i)) i,
];
for (final i in order) {
final p = hits[i];
final selected = highlighted.contains(i);
final faded = dimmed.contains(i);
// Semi-transparent, so overlapping hits and the rings under them show through
canvas.drawCircle(p + const Offset(0, 2), r,
Paint()..color = Colors.black.withValues(alpha: faded ? 0.05 : 0.18)..maskFilter = const MaskFilter.blur(BlurStyle.normal, 3));
canvas.drawCircle(p, r, Paint()..color = color.withValues(alpha: faded ? 0.25 : (selected ? 0.9 : 0.78)));
canvas.drawCircle(
p,
r - 1.5,
Paint()
..style = PaintingStyle.stroke
..strokeWidth = 3
..color = rim.withValues(alpha: faded ? 0.2 : 0.8));
// Selected: a red border on the hit's own edge, nothing around it
if (selected) {
canvas.drawCircle(
p,
r - 3,
Paint()
..style = PaintingStyle.stroke
..strokeWidth = 6
..color = selectedColor);
}
}
canvas.restore();
}
@override
bool shouldRepaint(HitsPainter old) =>
old.hits != hits || old.color != color || old.highlighted != highlighted || old.dimmed != dimmed;
}
/// Debug overlay: the outer edge of every score zone exactly as
/// [TargetScoring] uses it, and the centre cross. The red's outer side is the
/// edge: a hole whose edge touches it (or lies inside) scores that ring.
class ScoringRingsPainter extends CustomPainter {
const ScoringRingsPainter();
@override
void paint(Canvas canvas, Size size) {
final s = size.shortestSide / TargetScoring.size;
canvas.save();
canvas.translate((size.width - size.shortestSide) / 2, (size.height - size.shortestSide) / 2);
canvas.scale(s);
const c = TargetScoring.center;
final line = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 1 / s // 1 screen pixel at any size
..color = const Color(0xFFFF1744);
// Drawn just inside each edge: the red's outer side is the exact scoring
// edge, so it covers the printed line and nothing outside it
for (final r in TargetScoring.rings) {
canvas.drawCircle(c, r - line.strokeWidth / 2, line);
}
canvas.drawLine(c - const Offset(30, 0), c + const Offset(30, 0), line);
canvas.drawLine(c - const Offset(0, 30), c + const Offset(0, 30), line);
// Ring values just inside each edge, on the diagonal
for (int i = 0; i < TargetScoring.rings.length; i++) {
final r = TargetScoring.rings[i];
if (r < 40) continue;
final tp = TextPainter(
text: TextSpan(
text: '${10 - i}',
style: const TextStyle(fontFamily: 'Inter', fontSize: 22, fontWeight: FontWeight.w800, color: Color(0xFFFF1744)),
),
textDirection: TextDirection.ltr,
)..layout();
final at = c + Offset(1, 1) / 1.41421 * (r - 16);
tp.paint(canvas, at - Offset(tp.width / 2, tp.height / 2));
}
canvas.restore();
}
@override
bool shouldRepaint(ScoringRingsPainter old) => false;
}
+65 -52
View File
@@ -1,14 +1,23 @@
import 'package:flutter/material.dart';
import '../services/app_settings.dart';
import '../theme/app_theme.dart';
import 'ui.dart';
/// Dark dialog with one text field. Returns the trimmed text, or null if cancelled.
/// [onReset] adds a secondary button ([resetLabel], default "Reset to Default") that closes the dialog.
/// Dialog with one text field. Returns the trimmed text, or null if cancelled.
/// [onReset] adds a secondary red text button ([resetLabel], default "Reset to
/// Default") that closes the dialog.
Future<String?> showTextPrompt(
BuildContext context, {
required String title,
String? message,
String initial = '',
String? hint,
String? note, // small text under the field
IconData? fieldIcon,
IconData? titleIcon,
IconData? confirmIcon,
bool obscure = false,
bool mono = false,
TextInputType keyboardType = TextInputType.text,
String? confirmLabel,
String? resetLabel,
@@ -19,60 +28,64 @@ Future<String?> showTextPrompt(
return showDialog<String>(
context: context,
builder: (dialog) => AlertDialog(
title: Text(title),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (message != null) ...[
Text(message),
const SizedBox(height: 16),
],
TextField(
controller: controller,
autofocus: true,
keyboardType: keyboardType,
autocorrect: false,
style: const TextStyle(color: Colors.white),
cursorColor: s.bulletColor,
decoration: InputDecoration(
hintText: hint,
hintStyle: const TextStyle(color: Colors.white38),
filled: true,
fillColor: Colors.white10,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide.none,
builder: (dialog) {
final c = Palette.current;
return AppDialog(
title: title,
message: message,
titleTrailing: titleIcon == null ? null : IconBadge(titleIcon, size: 40),
content: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextField(
controller: controller,
autofocus: true,
keyboardType: keyboardType,
autocorrect: false,
obscureText: obscure,
style: TextStyle(
color: c.ink,
fontSize: 15,
fontFamily: mono ? AppTheme.mono : null,
letterSpacing: mono ? 0.5 : null,
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: s.bulletColor),
decoration: InputDecoration(
hintText: hint,
prefixIcon: fieldIcon == null ? null : Icon(fieldIcon, size: 19, color: c.muted),
),
onSubmitted: (v) => Navigator.pop(dialog, v.trim()),
),
onSubmitted: (v) => Navigator.pop(dialog, v.trim()),
if (note != null) ...[
const SizedBox(height: 10),
Text(note, style: TextStyle(fontSize: 12, height: 1.35, color: c.muted)),
],
if (onReset != null) ...[
const SizedBox(height: 6),
Align(
alignment: Alignment.centerLeft,
child: TextButton.icon(
style: TextButton.styleFrom(foregroundColor: c.red, padding: const EdgeInsets.symmetric(horizontal: 4)),
icon: const Icon(Icons.delete_outline_rounded, size: 18),
label: Text(resetLabel ?? s.t('Reset to Default')),
onPressed: () {
onReset();
Navigator.pop(dialog);
},
),
),
],
],
),
actions: [
DialogTextButton(s.t('Cancel'), onTap: () => Navigator.pop(dialog)),
PrimaryButton(
label: confirmLabel ?? s.t('Save'),
icon: confirmIcon,
height: 46,
onTap: () => Navigator.pop(dialog, controller.text.trim()),
),
],
),
actions: [
if (onReset != null)
TextButton(
onPressed: () {
onReset();
Navigator.pop(dialog);
},
child: Text(resetLabel ?? s.t('Reset to Default'), style: const TextStyle(color: Colors.white54)),
),
TextButton(
onPressed: () => Navigator.pop(dialog),
child: Text(s.t('Cancel'), style: const TextStyle(color: Colors.white70)),
),
FilledButton(
style: FilledButton.styleFrom(backgroundColor: s.bulletColor),
onPressed: () => Navigator.pop(dialog, controller.text.trim()),
child: Text(confirmLabel ?? s.t('Save')),
),
],
),
);
},
);
}
+971
View File
@@ -0,0 +1,971 @@
import 'package:flutter/material.dart';
import '../services/app_settings.dart';
import '../theme/app_theme.dart';
// Building blocks of the V2 design. Screens use these instead of styling
// Material widgets one by one, so every screen looks alike.
/// Large page title of a tab ("Knjiga", "Streljanje"), with an optional
/// subtitle and a round action button on the right.
class PageHeader extends StatelessWidget {
final String title;
final String? subtitle;
final Widget? action;
const PageHeader({super.key, required this.title, this.subtitle, this.action});
@override
Widget build(BuildContext context) {
final c = Palette.current;
return Padding(
padding: EdgeInsets.fromLTRB(AppTheme.edge, MediaQuery.paddingOf(context).top + 14, 16, 12),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 30, fontWeight: FontWeight.w700, height: 1.15, letterSpacing: -0.4, color: c.ink)),
if (subtitle != null)
Padding(
padding: const EdgeInsets.only(top: 2),
child: Text(subtitle!, style: TextStyle(fontSize: 14, color: c.muted)),
),
],
),
),
if (action != null) Padding(padding: const EdgeInsets.only(top: 2), child: action!),
],
),
);
}
}
/// Header of a pushed screen: round back button, title and subtitle, actions.
/// [centered] puts the title in the middle (result screens).
class BackHeader extends StatelessWidget {
final String title;
final String? subtitle;
final List<Widget> actions;
final bool centered;
final VoidCallback? onBack;
final Color? background;
const BackHeader({
super.key,
required this.title,
this.subtitle,
this.actions = const [],
this.centered = false,
this.onBack,
this.background,
});
@override
Widget build(BuildContext context) {
final c = Palette.current;
final titles = Column(
crossAxisAlignment: centered ? CrossAxisAlignment.center : CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: centered ? 15 : 17, fontWeight: FontWeight.w700, color: c.ink)),
if (subtitle != null)
Text(subtitle!,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, color: c.muted, fontFeatures: AppTheme.tnum)),
],
);
return Container(
color: background,
padding: EdgeInsets.fromLTRB(12, MediaQuery.paddingOf(context).top + 8, 12, 8),
child: SizedBox(
height: 44,
child: Row(
children: [
CircleButton(icon: Icons.chevron_left_rounded, size: 40, iconSize: 26, onTap: onBack ?? () => Navigator.maybePop(context)),
const SizedBox(width: 12),
Expanded(child: centered ? Center(child: titles) : titles),
if (centered && actions.isEmpty) const SizedBox(width: 52),
for (final a in actions) ...[const SizedBox(width: 8), a],
],
),
),
);
}
}
/// Round icon button on a tile background (header actions, back).
class CircleButton extends StatelessWidget {
final IconData icon;
final VoidCallback? onTap;
final double size;
final double iconSize;
final Color? color;
final Color? background;
final String? tooltip;
const CircleButton({
super.key,
required this.icon,
this.onTap,
this.size = 40,
this.iconSize = 20,
this.color,
this.background,
this.tooltip,
});
@override
Widget build(BuildContext context) {
final c = Palette.current;
final button = Material(
color: background ?? c.tile,
shape: const CircleBorder(),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: onTap,
child: SizedBox.square(dimension: size, child: Icon(icon, size: iconSize, color: color ?? c.ink)),
),
);
return tooltip == null ? button : Tooltip(message: tooltip!, child: button);
}
}
/// Rounded-square icon button (camera bars, share row).
class SquareButton extends StatelessWidget {
final IconData? icon;
final Widget? child;
final VoidCallback? onTap;
final double size;
final Color? color;
final Color? background;
final String? tooltip;
const SquareButton({super.key, this.icon, this.child, this.onTap, this.size = 48, this.color, this.background, this.tooltip});
@override
Widget build(BuildContext context) {
final c = Palette.current;
final button = Material(
color: background ?? c.tile,
borderRadius: BorderRadius.circular(14),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: onTap,
child: SizedBox.square(
dimension: size,
child: Center(child: child ?? Icon(icon, size: 22, color: color ?? c.ink)),
),
),
);
return tooltip == null ? button : Tooltip(message: tooltip!, child: button);
}
}
class SegmentItem {
final String label;
final IconData? icon;
const SegmentItem(this.label, [this.icon]);
}
/// Two or three equal segments in a card ("Statistika | Zgodovina").
class SegmentedTabs extends StatelessWidget {
final List<SegmentItem> items;
final int selected;
final ValueChanged<int> onSelect;
final double height;
final bool accentSelected; // selected segment filled with the accent
const SegmentedTabs({
super.key,
required this.items,
required this.selected,
required this.onSelect,
this.height = 44,
this.accentSelected = false,
});
@override
Widget build(BuildContext context) {
final c = Palette.current;
return Container(
height: height,
padding: const EdgeInsets.all(4),
decoration: BoxDecoration(
color: c.isDark ? c.card : c.tile,
borderRadius: BorderRadius.circular(14),
border: c.isDark ? Border.all(color: c.line) : null,
),
child: Row(
// The selected pill fills the bar's height
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (int i = 0; i < items.length; i++)
Expanded(
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => onSelect(i),
child: AnimatedContainer(
duration: const Duration(milliseconds: 180),
curve: Curves.easeOut,
decoration: BoxDecoration(
color: i == selected ? (accentSelected ? c.accent : (c.isDark ? c.tile : c.card)) : Colors.transparent,
borderRadius: BorderRadius.circular(10),
boxShadow: i == selected && !c.isDark ? c.shadow : null,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (items[i].icon != null) ...[
Icon(items[i].icon, size: 16, color: _fg(c, i)),
const SizedBox(width: 8),
],
Flexible(
child: Text(
items[i].label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: _fg(c, i)),
),
),
],
),
),
),
),
],
),
);
}
Color _fg(Palette c, int i) => i != selected ? c.muted : (accentSelected ? c.onAccent : c.ink);
}
/// Stadium chip: accent when selected ("Treningi", "Vse").
class ChoicePill extends StatelessWidget {
final String label;
final bool selected;
final VoidCallback? onTap;
final double height;
final EdgeInsets padding;
const ChoicePill({
super.key,
required this.label,
required this.selected,
this.onTap,
this.height = 32,
this.padding = const EdgeInsets.symmetric(horizontal: 14),
});
@override
Widget build(BuildContext context) {
final c = Palette.current;
return Material(
color: selected ? c.accent : c.tile,
shape: const StadiumBorder(),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: onTap,
child: Container(
height: height,
padding: padding,
alignment: Alignment.center,
child: Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
color: selected ? c.onAccent : (onTap == null ? c.faint : c.ink2),
),
),
),
),
);
}
}
/// Card surface: rounded, bordered on dark, shadowed on light.
class AppCard extends StatelessWidget {
final Widget child;
final EdgeInsetsGeometry padding;
final VoidCallback? onTap;
final VoidCallback? onLongPress;
final double radius;
final Color? color;
final Color? borderColor;
final bool dashed;
const AppCard({
super.key,
required this.child,
this.padding = const EdgeInsets.all(16),
this.onTap,
this.onLongPress,
this.radius = AppTheme.radius,
this.color,
this.borderColor,
this.dashed = false,
});
@override
Widget build(BuildContext context) {
final c = Palette.current;
final shape = RoundedRectangleBorder(
borderRadius: BorderRadius.circular(radius),
side: dashed ? BorderSide.none : BorderSide(color: borderColor ?? (c.isDark ? c.line2 : c.line2)),
);
Widget content = Padding(padding: padding, child: child);
if (onTap != null || onLongPress != null) {
content = InkWell(onTap: onTap, onLongPress: onLongPress, child: content);
}
Widget card = Material(
color: dashed ? Colors.transparent : (color ?? c.card),
shape: shape,
clipBehavior: Clip.antiAlias,
child: content,
);
if (dashed) {
card = CustomPaint(painter: _DashedBorder(color: c.line, radius: radius), child: card);
} else if (!c.isDark && color == null) {
card = DecoratedBox(
decoration: BoxDecoration(borderRadius: BorderRadius.circular(radius), boxShadow: c.shadow),
child: card,
);
}
return card;
}
}
class _DashedBorder extends CustomPainter {
final Color color;
final double radius;
const _DashedBorder({required this.color, required this.radius});
@override
void paint(Canvas canvas, Size size) {
final path = Path()
..addRRect(RRect.fromRectAndRadius(Offset.zero & size, Radius.circular(radius)).deflate(0.75));
final paint = Paint()
..color = color
..style = PaintingStyle.stroke
..strokeWidth = 1.5;
for (final m in path.computeMetrics()) {
for (double d = 0; d < m.length; d += 10) {
canvas.drawPath(m.extractPath(d, d + 5), paint);
}
}
}
@override
bool shouldRepaint(_DashedBorder old) => old.color != color;
}
/// Uppercase label: "TARČE", "ČLANI · 7".
class Kicker extends StatelessWidget {
final String text;
final Color? color;
final EdgeInsetsGeometry padding;
const Kicker(this.text, {super.key, this.color, this.padding = EdgeInsets.zero});
@override
Widget build(BuildContext context) {
final c = Palette.current;
return Padding(
padding: padding,
child: Text(text.toUpperCase(), style: AppTheme.kicker(c).copyWith(color: color)),
);
}
}
/// Main action of a screen: full width, accent fill, 52 high.
class PrimaryButton extends StatelessWidget {
final String label;
final IconData? icon;
final VoidCallback? onTap;
final Color? color;
final double height;
final bool busy;
const PrimaryButton({super.key, required this.label, this.icon, this.onTap, this.color, this.height = 52, this.busy = false});
@override
Widget build(BuildContext context) {
final c = Palette.current;
final fill = color ?? c.accent;
final fg = Palette.onColor(fill);
return Material(
color: onTap == null ? fill.withValues(alpha: 0.4) : fill,
borderRadius: BorderRadius.circular(14),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: busy ? null : onTap,
child: SizedBox(
height: height,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (busy)
SizedBox.square(dimension: 18, child: CircularProgressIndicator(strokeWidth: 2.5, color: fg))
else if (icon != null)
Icon(icon, size: 19, color: fg),
if (busy || icon != null) const SizedBox(width: 8),
Flexible(
child: Text(label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600, color: fg, fontFeatures: AppTheme.tnum)),
),
],
),
),
),
);
}
}
/// Secondary action on a tile (or red-soft for destructive).
class SoftButton extends StatelessWidget {
final String label;
final IconData? icon;
final VoidCallback? onTap;
final bool destructive;
final double height;
const SoftButton({super.key, required this.label, this.icon, this.onTap, this.destructive = false, this.height = 44});
@override
Widget build(BuildContext context) {
final c = Palette.current;
final fg = destructive ? c.red : c.ink;
return Material(
color: destructive ? c.redSoft : c.tile,
borderRadius: BorderRadius.circular(12),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: onTap,
child: SizedBox(
height: height,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (icon != null) ...[Icon(icon, size: 17, color: fg), const SizedBox(width: 6)],
Flexible(
child: Text(label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: fg)),
),
],
),
),
),
);
}
}
/// Score tile: a small count on top ("3×") and the value.
/// [filled] uses [color] (the accent by default); otherwise a dim tile.
class ScoreTile extends StatelessWidget {
final String? top;
final String value;
final bool filled;
final Color? color;
final double height;
final VoidCallback? onTap;
final GestureTapDownCallback? onTapDown;
final VoidCallback? onTapEnd;
final bool outlined;
const ScoreTile({
super.key,
this.top,
required this.value,
this.filled = true,
this.color,
this.height = 64,
this.onTap,
this.onTapDown,
this.onTapEnd,
this.outlined = false,
});
@override
Widget build(BuildContext context) {
final c = Palette.current;
final fill = filled ? (color ?? c.accent) : c.tile;
final fg = filled ? Palette.onColor(fill) : c.faint;
return GestureDetector(
onTap: onTap,
onTapDown: onTapDown,
onTapUp: onTapEnd == null ? null : (_) => onTapEnd!(),
onTapCancel: onTapEnd,
child: AnimatedContainer(
duration: const Duration(milliseconds: 150),
height: height,
decoration: BoxDecoration(
color: fill,
borderRadius: BorderRadius.circular(14),
border: outlined ? Border.all(color: c.ink, width: 2) : null,
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (top != null)
Text(top!,
style: TextStyle(
fontSize: 10, fontWeight: FontWeight.w600, color: fg.withValues(alpha: 0.7), fontFeatures: AppTheme.tnum)),
FittedBox(
fit: BoxFit.scaleDown,
child: Text(value,
style: TextStyle(
fontSize: 22, height: 1.15, fontWeight: FontWeight.w700, color: fg, fontFeatures: AppTheme.tnum)),
),
],
),
),
);
}
}
/// Small coloured label: "TRENING", "TEKMOVANJE", "V ŽIVO".
class StatusChip extends StatelessWidget {
final String label;
final Color color; // text and icon
final Color background;
final IconData? icon;
final bool dot;
const StatusChip({super.key, required this.label, required this.color, required this.background, this.icon, this.dot = false});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
decoration: BoxDecoration(color: background, borderRadius: BorderRadius.circular(20)),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (dot) ...[
Container(width: 6, height: 6, decoration: BoxDecoration(color: color, shape: BoxShape.circle)),
const SizedBox(width: 5),
] else if (icon != null) ...[
Icon(icon, size: 11, color: color),
const SizedBox(width: 4),
],
Text(label.toUpperCase(),
style: TextStyle(fontSize: 9.5, fontWeight: FontWeight.w700, letterSpacing: 0.6, color: color)),
],
),
);
}
}
/// Accent icon on a soft accent square (help rows, camera tiles).
class IconBadge extends StatelessWidget {
final IconData icon;
final double size;
final Color? color;
const IconBadge(this.icon, {super.key, this.size = 36, this.color});
@override
Widget build(BuildContext context) {
final c = Palette.current;
final fg = color ?? c.accent;
return Container(
width: size,
height: size,
decoration: BoxDecoration(color: fg.withValues(alpha: c.isDark ? 0.14 : 0.12), borderRadius: BorderRadius.circular(size * 0.28)),
child: Icon(icon, size: size * 0.52, color: fg),
);
}
}
/// Bottom sheet in the design: drag handle, 22 bold title, optional subtitle
/// and action. [clearBarrier] keeps the screen behind undimmed (camera).
Future<T?> showAppSheet<T>(
BuildContext context, {
String? title,
String? subtitle,
Widget? trailing,
required WidgetBuilder builder,
bool clearBarrier = false,
bool scrollable = true,
double maxHeightFactor = 0.85,
EdgeInsets padding = const EdgeInsets.fromLTRB(AppTheme.edge, 0, AppTheme.edge, 16),
}) {
return showModalBottomSheet<T>(
context: context,
isScrollControlled: true,
useSafeArea: true, // never under the status bar, so there is always room to tap outside
barrierColor: clearBarrier ? Colors.transparent : null,
builder: (sheet) {
// The title (and its close button) stays put; only the content scrolls
final header = title == null
? null
: Padding(
padding: EdgeInsets.fromLTRB(padding.left, 0, padding.right, 0),
child: SheetTitle(title, subtitle: subtitle, trailing: trailing),
);
final content = builder(sheet);
return SafeArea(
child: ConstrainedBox(
constraints: BoxConstraints(maxHeight: MediaQuery.sizeOf(sheet).height * maxHeightFactor),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (header != null) header,
Flexible(
child: scrollable
? SingleChildScrollView(padding: padding, child: content)
: Padding(padding: padding, child: content),
),
],
),
),
);
},
);
}
/// Title row of a sheet.
class SheetTitle extends StatelessWidget {
final String title;
final String? subtitle;
final Widget? trailing;
const SheetTitle(this.title, {super.key, this.subtitle, this.trailing});
@override
Widget build(BuildContext context) {
final c = Palette.current;
return Padding(
padding: const EdgeInsets.only(bottom: 16),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title, style: TextStyle(fontSize: 22, fontWeight: FontWeight.w700, color: c.ink, height: 1.2)),
if (subtitle != null)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(subtitle!, style: TextStyle(fontSize: 13, color: c.muted)),
),
],
),
),
if (trailing != null) trailing!,
],
),
);
}
}
/// Dialog body in the design: title, message, optional content and buttons
/// (text "cancel" on the left, filled action on the right).
class AppDialog extends StatelessWidget {
final String title;
final String? message;
final Widget? content;
final Widget? titleTrailing;
final List<Widget> actions;
const AppDialog({super.key, required this.title, this.message, this.content, this.titleTrailing, this.actions = const []});
@override
Widget build(BuildContext context) {
final c = Palette.current;
return Dialog(
insetPadding: const EdgeInsets.symmetric(horizontal: 24),
child: Padding(
padding: const EdgeInsets.fromLTRB(24, 22, 24, 20),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(child: Text(title, style: TextStyle(fontSize: 20, fontWeight: FontWeight.w700, color: c.ink))),
if (titleTrailing != null) titleTrailing!,
],
),
if (message != null) ...[
const SizedBox(height: 8),
Text(message!, style: TextStyle(fontSize: 14, height: 1.4, color: c.muted)),
],
if (content != null) ...[const SizedBox(height: 18), content!],
if (actions.isNotEmpty) ...[
const SizedBox(height: 22),
Row(
children: [
for (int i = 0; i < actions.length; i++) ...[
if (i > 0) const SizedBox(width: 10),
Expanded(child: actions[i]),
],
],
),
],
],
),
),
);
}
}
/// Text button of a dialog ("Prekliči").
class DialogTextButton extends StatelessWidget {
final String label;
final VoidCallback? onTap;
const DialogTextButton(this.label, {super.key, this.onTap});
@override
Widget build(BuildContext context) {
final c = Palette.current;
return Material(
color: Colors.transparent,
borderRadius: BorderRadius.circular(12),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: onTap,
child: SizedBox(
height: 46,
child: Center(child: Text(label, style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600, color: c.ink))),
),
),
);
}
}
/// Asks to confirm a deletion. Returns true when confirmed.
Future<bool> confirmDialog(
BuildContext context, {
required String title,
required String message,
required String confirm,
bool destructive = true,
}) async {
final s = AppSettings.instance;
final c = Palette.current;
final ok = await showDialog<bool>(
context: context,
builder: (dialog) => AppDialog(
title: title,
message: message,
actions: [
SoftButton(label: s.t('Cancel'), height: 46, onTap: () => Navigator.pop(dialog, false)),
PrimaryButton(
label: confirm,
height: 46,
color: destructive ? c.red : null,
onTap: () => Navigator.pop(dialog, true),
),
],
),
);
return ok == true;
}
/// One help line: icon badge and a sentence.
class HelpRow extends StatelessWidget {
final IconData icon;
final String text;
const HelpRow(this.icon, this.text, {super.key});
@override
Widget build(BuildContext context) {
final c = Palette.current;
return Padding(
padding: const EdgeInsets.only(bottom: 14),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
IconBadge(icon, size: 32),
const SizedBox(width: 14),
Expanded(
child: Padding(
padding: const EdgeInsets.only(top: 6),
child: Text(text, style: TextStyle(fontSize: 13.5, height: 1.35, color: c.ink2)),
),
),
],
),
);
}
}
/// Empty state: icon in a soft circle, a line and a hint.
class EmptyState extends StatelessWidget {
final IconData icon;
final String title;
final String? hint;
final Widget? action;
const EmptyState({super.key, required this.icon, required this.title, this.hint, this.action});
@override
Widget build(BuildContext context) {
final c = Palette.current;
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
padding: const EdgeInsets.all(18),
decoration: BoxDecoration(color: c.accentSoft, shape: BoxShape.circle),
child: Icon(icon, size: 36, color: c.accent),
),
const SizedBox(height: 16),
Text(title, textAlign: TextAlign.center, style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: c.ink)),
if (hint != null) ...[
const SizedBox(height: 6),
Text(hint!, textAlign: TextAlign.center, style: TextStyle(fontSize: 13.5, height: 1.35, color: c.muted)),
],
if (action != null) ...[const SizedBox(height: 18), action!],
],
);
}
}
/// − value + stepper in a row (timer, positions).
class Stepper3 extends StatelessWidget {
final String value;
final VoidCallback? onMinus;
final VoidCallback? onPlus;
final double valueWidth;
final double buttonSize;
final TextStyle? style;
const Stepper3({
super.key,
required this.value,
this.onMinus,
this.onPlus,
this.valueWidth = 56,
this.buttonSize = 36,
this.style,
});
@override
Widget build(BuildContext context) {
final c = Palette.current;
Widget btn(IconData icon, VoidCallback? onTap) => CircleButton(
icon: icon,
size: buttonSize,
iconSize: 20,
onTap: onTap,
color: onTap == null ? c.faint : c.ink,
background: c.isDark ? c.tile : c.card,
);
return Row(
mainAxisSize: MainAxisSize.min,
children: [
btn(Icons.remove_rounded, onMinus),
SizedBox(
width: valueWidth,
child: Text(value,
textAlign: TextAlign.center,
style: style ?? TextStyle(fontSize: 18, fontWeight: FontWeight.w700, color: c.ink, fontFeatures: AppTheme.tnum)),
),
btn(Icons.add_rounded, onPlus),
],
);
}
}
/// Icon, label, value and a slider under them (camera and image settings).
class LabeledSlider extends StatelessWidget {
final IconData icon;
final String label;
final String valueText;
final double value;
final double min;
final double max;
final ValueChanged<double> onChanged;
const LabeledSlider({
super.key,
required this.icon,
required this.label,
required this.valueText,
required this.value,
required this.min,
required this.max,
required this.onChanged,
});
@override
Widget build(BuildContext context) {
final c = Palette.current;
return Padding(
padding: const EdgeInsets.only(bottom: 6),
child: Column(
children: [
Row(
children: [
Icon(icon, size: 18, color: c.muted),
const SizedBox(width: 10),
Expanded(child: Text(label, style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500, color: c.ink))),
Text(valueText, style: TextStyle(fontSize: 13, color: c.ink2, fontFeatures: AppTheme.tnum)),
],
),
SliderTheme(
data: SliderTheme.of(context).copyWith(
overlayShape: const RoundSliderOverlayShape(overlayRadius: 16),
trackShape: const RoundedRectSliderTrackShape(),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 0),
child: SizedBox(
height: 32,
child: Slider(value: value.clamp(min, max), min: min, max: max, onChanged: onChanged),
),
),
),
],
),
);
}
}
/// A row on a card with an icon, a label and a trailing control (switch tile).
class ToggleRow extends StatelessWidget {
final IconData? icon;
final String label;
final bool value;
final ValueChanged<bool> onChanged;
final Widget? extra; // between label and switch
const ToggleRow({super.key, this.icon, required this.label, required this.value, required this.onChanged, this.extra});
@override
Widget build(BuildContext context) {
final c = Palette.current;
return AppCard(
color: c.isDark ? c.card2 : c.card,
padding: const EdgeInsets.fromLTRB(16, 8, 10, 8),
onTap: () => onChanged(!value),
child: SizedBox(
height: 40,
child: Row(
children: [
if (icon != null) ...[Icon(icon, size: 19, color: c.muted), const SizedBox(width: 12)],
Expanded(child: Text(label, style: TextStyle(fontSize: 14.5, fontWeight: FontWeight.w500, color: c.ink))),
if (extra != null) extra!,
Switch(value: value, onChanged: onChanged),
],
),
),
);
}
}