diff --git a/assets/backgrounds/bg01_dark.webp b/assets/backgrounds/bg01_dark.webp new file mode 100644 index 0000000..4ba61a6 Binary files /dev/null and b/assets/backgrounds/bg01_dark.webp differ diff --git a/assets/backgrounds/bg01_light.webp b/assets/backgrounds/bg01_light.webp new file mode 100644 index 0000000..63a7d00 Binary files /dev/null and b/assets/backgrounds/bg01_light.webp differ diff --git a/assets/backgrounds/bg02_dark.webp b/assets/backgrounds/bg02_dark.webp new file mode 100644 index 0000000..1e1ed73 Binary files /dev/null and b/assets/backgrounds/bg02_dark.webp differ diff --git a/assets/backgrounds/bg02_light.webp b/assets/backgrounds/bg02_light.webp new file mode 100644 index 0000000..dcb061a Binary files /dev/null and b/assets/backgrounds/bg02_light.webp differ diff --git a/assets/backgrounds/bg03_dark.webp b/assets/backgrounds/bg03_dark.webp new file mode 100644 index 0000000..570db7f Binary files /dev/null and b/assets/backgrounds/bg03_dark.webp differ diff --git a/assets/backgrounds/bg03_light.webp b/assets/backgrounds/bg03_light.webp new file mode 100644 index 0000000..bd2f1fa Binary files /dev/null and b/assets/backgrounds/bg03_light.webp differ diff --git a/assets/backgrounds/bg04_dark.webp b/assets/backgrounds/bg04_dark.webp new file mode 100644 index 0000000..4c7f3de Binary files /dev/null and b/assets/backgrounds/bg04_dark.webp differ diff --git a/assets/backgrounds/bg04_light.webp b/assets/backgrounds/bg04_light.webp new file mode 100644 index 0000000..d5f1c6d Binary files /dev/null and b/assets/backgrounds/bg04_light.webp differ diff --git a/assets/backgrounds/bg05_dark.webp b/assets/backgrounds/bg05_dark.webp new file mode 100644 index 0000000..c37f7f2 Binary files /dev/null and b/assets/backgrounds/bg05_dark.webp differ diff --git a/assets/backgrounds/bg05_light.webp b/assets/backgrounds/bg05_light.webp new file mode 100644 index 0000000..8edb8d3 Binary files /dev/null and b/assets/backgrounds/bg05_light.webp differ diff --git a/assets/backgrounds/bg06_dark.webp b/assets/backgrounds/bg06_dark.webp new file mode 100644 index 0000000..d8f1b19 Binary files /dev/null and b/assets/backgrounds/bg06_dark.webp differ diff --git a/assets/backgrounds/bg06_light.webp b/assets/backgrounds/bg06_light.webp new file mode 100644 index 0000000..eddec40 Binary files /dev/null and b/assets/backgrounds/bg06_light.webp differ diff --git a/assets/backgrounds/bg07_dark.webp b/assets/backgrounds/bg07_dark.webp new file mode 100644 index 0000000..1b1b362 Binary files /dev/null and b/assets/backgrounds/bg07_dark.webp differ diff --git a/assets/backgrounds/bg07_light.webp b/assets/backgrounds/bg07_light.webp new file mode 100644 index 0000000..fdb7711 Binary files /dev/null and b/assets/backgrounds/bg07_light.webp differ diff --git a/assets/backgrounds/bg08_dark.webp b/assets/backgrounds/bg08_dark.webp new file mode 100644 index 0000000..d756848 Binary files /dev/null and b/assets/backgrounds/bg08_dark.webp differ diff --git a/assets/backgrounds/bg08_light.webp b/assets/backgrounds/bg08_light.webp new file mode 100644 index 0000000..12f1c1a Binary files /dev/null and b/assets/backgrounds/bg08_light.webp differ diff --git a/assets/backgrounds/bg09_dark.webp b/assets/backgrounds/bg09_dark.webp new file mode 100644 index 0000000..34f1242 Binary files /dev/null and b/assets/backgrounds/bg09_dark.webp differ diff --git a/assets/backgrounds/bg09_light.webp b/assets/backgrounds/bg09_light.webp new file mode 100644 index 0000000..8fb2ae1 Binary files /dev/null and b/assets/backgrounds/bg09_light.webp differ diff --git a/assets/backgrounds/bg10_dark.webp b/assets/backgrounds/bg10_dark.webp new file mode 100644 index 0000000..656872b Binary files /dev/null and b/assets/backgrounds/bg10_dark.webp differ diff --git a/assets/backgrounds/bg10_light.webp b/assets/backgrounds/bg10_light.webp new file mode 100644 index 0000000..defac22 Binary files /dev/null and b/assets/backgrounds/bg10_light.webp differ diff --git a/assets/fonts/Inter-Bold.ttf b/assets/fonts/Inter-Bold.ttf new file mode 100644 index 0000000..9fb9b75 Binary files /dev/null and b/assets/fonts/Inter-Bold.ttf differ diff --git a/assets/fonts/Inter-ExtraBold.ttf b/assets/fonts/Inter-ExtraBold.ttf new file mode 100644 index 0000000..0fdf1e0 Binary files /dev/null and b/assets/fonts/Inter-ExtraBold.ttf differ diff --git a/assets/fonts/Inter-LICENSE.txt b/assets/fonts/Inter-LICENSE.txt new file mode 100644 index 0000000..9b2ca37 --- /dev/null +++ b/assets/fonts/Inter-LICENSE.txt @@ -0,0 +1,92 @@ +Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION AND CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/assets/fonts/Inter-Medium.ttf b/assets/fonts/Inter-Medium.ttf new file mode 100644 index 0000000..458cd06 Binary files /dev/null and b/assets/fonts/Inter-Medium.ttf differ diff --git a/assets/fonts/Inter-Regular.ttf b/assets/fonts/Inter-Regular.ttf new file mode 100644 index 0000000..b7aaca8 Binary files /dev/null and b/assets/fonts/Inter-Regular.ttf differ diff --git a/assets/fonts/Inter-SemiBold.ttf b/assets/fonts/Inter-SemiBold.ttf new file mode 100644 index 0000000..47f8ab1 Binary files /dev/null and b/assets/fonts/Inter-SemiBold.ttf differ diff --git a/assets/fonts/JetBrainsMono-LICENSE.txt b/assets/fonts/JetBrainsMono-LICENSE.txt new file mode 100644 index 0000000..223ae0f --- /dev/null +++ b/assets/fonts/JetBrainsMono-LICENSE.txt @@ -0,0 +1,92 @@ +Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION AND CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/assets/fonts/JetBrainsMono-Regular.ttf b/assets/fonts/JetBrainsMono-Regular.ttf new file mode 100644 index 0000000..dff66cc Binary files /dev/null and b/assets/fonts/JetBrainsMono-Regular.ttf differ diff --git a/assets/target.png b/assets/target.png deleted file mode 100644 index b341847..0000000 Binary files a/assets/target.png and /dev/null differ diff --git a/assets/targets/Target1.jpg b/assets/targets/Target1.jpg deleted file mode 100644 index 30318f9..0000000 Binary files a/assets/targets/Target1.jpg and /dev/null differ diff --git a/assets/targets/Target10.jpg b/assets/targets/Target10.jpg deleted file mode 100644 index 1f680b4..0000000 Binary files a/assets/targets/Target10.jpg and /dev/null differ diff --git a/assets/targets/Target11.jpg b/assets/targets/Target11.jpg deleted file mode 100644 index 7335b34..0000000 Binary files a/assets/targets/Target11.jpg and /dev/null differ diff --git a/assets/targets/Target12.jpg b/assets/targets/Target12.jpg deleted file mode 100644 index ee83fd5..0000000 Binary files a/assets/targets/Target12.jpg and /dev/null differ diff --git a/assets/targets/Target14.jpg b/assets/targets/Target14.jpg deleted file mode 100644 index 88bb32e..0000000 Binary files a/assets/targets/Target14.jpg and /dev/null differ diff --git a/assets/targets/Target15.jpg b/assets/targets/Target15.jpg deleted file mode 100644 index 8fa6349..0000000 Binary files a/assets/targets/Target15.jpg and /dev/null differ diff --git a/assets/targets/Target16.jpg b/assets/targets/Target16.jpg deleted file mode 100644 index 3fd9803..0000000 Binary files a/assets/targets/Target16.jpg and /dev/null differ diff --git a/assets/targets/Target17.jpg b/assets/targets/Target17.jpg deleted file mode 100644 index a2d6ee3..0000000 Binary files a/assets/targets/Target17.jpg and /dev/null differ diff --git a/assets/targets/Target18.jpg b/assets/targets/Target18.jpg deleted file mode 100644 index cb05a45..0000000 Binary files a/assets/targets/Target18.jpg and /dev/null differ diff --git a/assets/targets/Target19.jpg b/assets/targets/Target19.jpg deleted file mode 100644 index cdcc65c..0000000 Binary files a/assets/targets/Target19.jpg and /dev/null differ diff --git a/assets/targets/Target2.jpg b/assets/targets/Target2.jpg deleted file mode 100644 index 2d85172..0000000 Binary files a/assets/targets/Target2.jpg and /dev/null differ diff --git a/assets/targets/Target20.jpg b/assets/targets/Target20.jpg deleted file mode 100644 index fd6805a..0000000 Binary files a/assets/targets/Target20.jpg and /dev/null differ diff --git a/assets/targets/Target22.jpg b/assets/targets/Target22.jpg deleted file mode 100644 index f6e5d85..0000000 Binary files a/assets/targets/Target22.jpg and /dev/null differ diff --git a/assets/targets/Target23.jpg b/assets/targets/Target23.jpg deleted file mode 100644 index 0edec6c..0000000 Binary files a/assets/targets/Target23.jpg and /dev/null differ diff --git a/assets/targets/Target24.jpg b/assets/targets/Target24.jpg deleted file mode 100644 index 0e9dca3..0000000 Binary files a/assets/targets/Target24.jpg and /dev/null differ diff --git a/assets/targets/Target25.jpg b/assets/targets/Target25.jpg deleted file mode 100644 index 4c42109..0000000 Binary files a/assets/targets/Target25.jpg and /dev/null differ diff --git a/assets/targets/Target26.jpg b/assets/targets/Target26.jpg deleted file mode 100644 index 8bb94f3..0000000 Binary files a/assets/targets/Target26.jpg and /dev/null differ diff --git a/assets/targets/Target27.jpg b/assets/targets/Target27.jpg deleted file mode 100644 index ec13a03..0000000 Binary files a/assets/targets/Target27.jpg and /dev/null differ diff --git a/assets/targets/Target28.jpg b/assets/targets/Target28.jpg deleted file mode 100644 index 65c693b..0000000 Binary files a/assets/targets/Target28.jpg and /dev/null differ diff --git a/assets/targets/Target29.jpg b/assets/targets/Target29.jpg deleted file mode 100644 index 9379857..0000000 Binary files a/assets/targets/Target29.jpg and /dev/null differ diff --git a/assets/targets/Target3.jpg b/assets/targets/Target3.jpg deleted file mode 100644 index 82aff72..0000000 Binary files a/assets/targets/Target3.jpg and /dev/null differ diff --git a/assets/targets/Target30.jpg b/assets/targets/Target30.jpg deleted file mode 100644 index fc77717..0000000 Binary files a/assets/targets/Target30.jpg and /dev/null differ diff --git a/assets/targets/Target35.jpg b/assets/targets/Target35.jpg deleted file mode 100644 index 486b9bf..0000000 Binary files a/assets/targets/Target35.jpg and /dev/null differ diff --git a/assets/targets/Target4.jpg b/assets/targets/Target4.jpg deleted file mode 100644 index 48e2962..0000000 Binary files a/assets/targets/Target4.jpg and /dev/null differ diff --git a/assets/targets/Target5.jpg b/assets/targets/Target5.jpg deleted file mode 100644 index fe9a919..0000000 Binary files a/assets/targets/Target5.jpg and /dev/null differ diff --git a/assets/targets/Target6.jpg b/assets/targets/Target6.jpg deleted file mode 100644 index 4ecf3a1..0000000 Binary files a/assets/targets/Target6.jpg and /dev/null differ diff --git a/assets/targets/Target7.jpg b/assets/targets/Target7.jpg deleted file mode 100644 index 1c911c7..0000000 Binary files a/assets/targets/Target7.jpg and /dev/null differ diff --git a/assets/targets/Target8.jpg b/assets/targets/Target8.jpg deleted file mode 100644 index 820abce..0000000 Binary files a/assets/targets/Target8.jpg and /dev/null differ diff --git a/assets/targets/Target9.jpg b/assets/targets/Target9.jpg deleted file mode 100644 index 59d7a3c..0000000 Binary files a/assets/targets/Target9.jpg and /dev/null differ diff --git a/assets/targets/v3/t01.webp b/assets/targets/v3/t01.webp new file mode 100644 index 0000000..f81edad Binary files /dev/null and b/assets/targets/v3/t01.webp differ diff --git a/assets/targets/v3/t05.webp b/assets/targets/v3/t05.webp new file mode 100644 index 0000000..741d0c9 Binary files /dev/null and b/assets/targets/v3/t05.webp differ diff --git a/assets/targets/v3/t07.webp b/assets/targets/v3/t07.webp new file mode 100644 index 0000000..93c8a04 Binary files /dev/null and b/assets/targets/v3/t07.webp differ diff --git a/assets/targets/v3/t08.webp b/assets/targets/v3/t08.webp new file mode 100644 index 0000000..57eeb67 Binary files /dev/null and b/assets/targets/v3/t08.webp differ diff --git a/assets/targets/v3/t42.webp b/assets/targets/v3/t42.webp new file mode 100644 index 0000000..7959125 Binary files /dev/null and b/assets/targets/v3/t42.webp differ diff --git a/assets/targets/v3/t70.webp b/assets/targets/v3/t70.webp new file mode 100644 index 0000000..5272596 Binary files /dev/null and b/assets/targets/v3/t70.webp differ diff --git a/assets/targets/v3/t71.webp b/assets/targets/v3/t71.webp new file mode 100644 index 0000000..d9be69d Binary files /dev/null and b/assets/targets/v3/t71.webp differ diff --git a/assets/targets/v3/t72.webp b/assets/targets/v3/t72.webp new file mode 100644 index 0000000..75b02a9 Binary files /dev/null and b/assets/targets/v3/t72.webp differ diff --git a/assets/targets/v3/t73.webp b/assets/targets/v3/t73.webp new file mode 100644 index 0000000..ec63ca7 Binary files /dev/null and b/assets/targets/v3/t73.webp differ diff --git a/assets/targets/v3/t74.webp b/assets/targets/v3/t74.webp new file mode 100644 index 0000000..3edfd86 Binary files /dev/null and b/assets/targets/v3/t74.webp differ diff --git a/assets/targets/v3/t75.webp b/assets/targets/v3/t75.webp new file mode 100644 index 0000000..878dd3a Binary files /dev/null and b/assets/targets/v3/t75.webp differ diff --git a/assets/targets/v3/t76.webp b/assets/targets/v3/t76.webp new file mode 100644 index 0000000..ca023b8 Binary files /dev/null and b/assets/targets/v3/t76.webp differ diff --git a/assets/targets/v3/t77.webp b/assets/targets/v3/t77.webp new file mode 100644 index 0000000..9e6f106 Binary files /dev/null and b/assets/targets/v3/t77.webp differ diff --git a/assets/targets/v3/t78.webp b/assets/targets/v3/t78.webp new file mode 100644 index 0000000..e047255 Binary files /dev/null and b/assets/targets/v3/t78.webp differ diff --git a/assets/targets/v3/t79.webp b/assets/targets/v3/t79.webp new file mode 100644 index 0000000..b92e517 Binary files /dev/null and b/assets/targets/v3/t79.webp differ diff --git a/lib/main.dart b/lib/main.dart index 1124852..2e948ba 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -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( + 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(), ); } } diff --git a/lib/models/contact.dart b/lib/models/contact.dart index 966ecb1..d94e38e 100644 --- a/lib/models/contact.dart +++ b/lib/models/contact.dart @@ -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'] ?? '', ); } diff --git a/lib/models/holiday_theme.dart b/lib/models/holiday_theme.dart new file mode 100644 index 0000000..c0c72b5 --- /dev/null +++ b/lib/models/holiday_theme.dart @@ -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 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); + } +} diff --git a/lib/models/target_style.dart b/lib/models/target_style.dart new file mode 100644 index 0000000..e675e7f --- /dev/null +++ b/lib/models/target_style.dart @@ -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.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 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 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)), + ]; +} diff --git a/lib/screens/book_screen.dart b/lib/screens/book_screen.dart index 4118775..cbde1fe 100644 --- a/lib/screens/book_screen.dart +++ b/lib/screens/book_screen.dart @@ -5,7 +5,9 @@ import 'package:shared_preferences/shared_preferences.dart'; import '../services/app_settings.dart'; import '../services/target_repository.dart'; import '../theme/app_theme.dart'; +import '../utils/format.dart'; import '../widgets/bar_tabs.dart'; +import '../widgets/ui.dart'; import '../widgets/help_sheet.dart'; import '../widgets/progress_chart.dart'; import '../widgets/section.dart'; @@ -54,6 +56,7 @@ class _BookScreenState extends State with WidgetsBindingObserver { void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); + TargetRepository.changed.addListener(_load); _restoreSettings().then((_) => _load()); } @@ -117,6 +120,7 @@ class _BookScreenState extends State with WidgetsBindingObserver { @override void dispose() { WidgetsBinding.instance.removeObserver(this); + TargetRepository.changed.removeListener(_load); super.dispose(); } @@ -197,37 +201,39 @@ class _BookScreenState extends State with WidgetsBindingObserver { }); } + // Dates a period covers, under its name in the sheet + String? _periodRange(_Period p) { + final s = AppSettings.instance; + final f = DateFormat('d. M. yyyy'); + final today = _today; + return switch (p) { + _Period.month => '${DateFormat('d. M.').format(DateTime(today.year, today.month))} – ${f.format(today)}', + _Period.threeMonths => '${DateFormat('d. M.').format(DateTime(today.year, today.month - 3, today.day))} – ${f.format(today)}', + _Period.year => '${today.year}', + _Period.all => s.t('since the first saved target'), + _Period.custom => _custom == null ? s.t('choose dates …') : _periodLabel(p), + }; + } + void _pickPeriod() { final s = AppSettings.instance; - showModalBottomSheet( - context: context, - builder: (sheet) => SafeArea( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Padding( - padding: const EdgeInsets.only(bottom: 12), - child: Text( - s.t('Period'), - style: const TextStyle( - color: Colors.white, - fontSize: 18, - fontWeight: FontWeight.bold), - ), + showAppSheet( + context, + title: s.t('Period'), + subtitle: s.t('Applies to Statistics and History'), + builder: (sheet) => Column( + children: [ + for (final p in _Period.values) + SheetOption( + label: p == _Period.custom ? s.t('Custom range') : _periodLabel(p), + subtitle: _periodRange(p), + selected: p == _period, + onTap: () { + Navigator.pop(sheet); + _setPeriod(p); + }, ), - for (final p in _Period.values) - SheetOption( - label: _periodLabel(p), - selected: p == _period, - selectedColor: s.bulletColor, - onTap: () { - Navigator.pop(sheet); - _setPeriod(p); - }, - ), - const SizedBox(height: 8), - ], - ), + ], ), ); } @@ -239,14 +245,20 @@ class _BookScreenState extends State with WidgetsBindingObserver { // Shots-per-target formats in the current tab, most used first List _formats(List sessions) { + final counts = _formatCounts(sessions); + return counts.keys.toList() + ..sort((a, b) => counts[b]!.compareTo(counts[a]!)); + } + + // Number of targets with each shot count + static Map _formatCounts(List sessions) { final counts = {}; for (final session in sessions) { for (final t in session.targets) { if (t.shots > 0) counts[t.shots] = (counts[t.shots] ?? 0) + 1; } } - return counts.keys.toList() - ..sort((a, b) => counts[b]!.compareTo(counts[a]!)); + return counts; } // The full session, not the copy limited to one format @@ -302,14 +314,14 @@ class _BookScreenState extends State with WidgetsBindingObserver { return Column( children: [ _buildTabs(), - _buildStatsBar(formats, shots), + _buildStatsBar(_formatCounts(typed.where(_inPeriod).toList()), shots), Expanded( child: _years.isEmpty ? _centered(_buildEmpty()) : stats.targets == 0 ? Column(children: [ Padding( - padding: const EdgeInsets.fromLTRB(16, 8, 16, 0), + padding: const EdgeInsets.fromLTRB(AppTheme.edge, 0, AppTheme.edge, 0), child: _periodRow()), Expanded(child: _centered(_noSessions())), ]) @@ -345,63 +357,46 @@ class _BookScreenState extends State with WidgetsBindingObserver { // Nothing in the chosen period or filter (there are sessions elsewhere) Widget _noSessions() { final s = AppSettings.instance; - final surf = Surfaces.current; return Padding( padding: const EdgeInsets.only(bottom: 48), // a little above the middle - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Icon(Icons.event_busy_rounded, size: 40, color: surf.textSecondary), - const SizedBox(height: 10), - Text(s.t('No sessions in this period'), - textAlign: TextAlign.center, - style: TextStyle(fontSize: 15, color: surf.textSecondary)), - ], - ), + child: EmptyState(icon: Icons.event_busy_rounded, title: s.t('No sessions in this period')), ); } - // Full-width "Obdobje … To leto ▾" button: says what it changes and that it - // can be tapped. Opens the period sheet; Statistika and Zgodovina share it. - Widget _periodRow() { + // "Obdobje … Ta mesec ▾": says what it changes and that it can be tapped. + // Opens the period sheet; Statistika and Zgodovina share it. + Widget _periodRow({bool compact = false}) { final s = AppSettings.instance; - final surf = Surfaces.current; - return Material( - color: surf.card, - borderRadius: BorderRadius.circular(14), - clipBehavior: Clip.antiAlias, - child: InkWell( - onTap: _pickPeriod, - child: Padding( - padding: const EdgeInsets.fromLTRB(14, 10, 8, 10), - child: Row( - children: [ - Icon(Icons.date_range_rounded, size: 20, color: s.bulletColor), - const SizedBox(width: 10), - Text(s.t('Period'), - style: TextStyle(fontSize: 13, color: surf.textSecondary)), - const SizedBox(width: 12), - Expanded( - child: Text( - _periodLabel(_period), - textAlign: TextAlign.right, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle( - fontSize: 14, - fontWeight: FontWeight.w700, - color: surf.textPrimary), - ), + final c = Palette.current; + return AppCard( + onTap: _pickPeriod, + radius: 14, + padding: const EdgeInsets.fromLTRB(14, 0, 10, 0), + child: SizedBox( + height: 46, + child: Row( + children: [ + Icon(Icons.calendar_today_outlined, size: 18, color: c.accent), + const SizedBox(width: 10), + Text(s.t('Period'), style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: c.ink)), + SizedBox(width: compact ? 8 : 12), + Expanded( + child: Text( + _periodLabel(_period), + textAlign: compact ? TextAlign.left : TextAlign.right, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 13, color: c.muted), ), - Icon(Icons.expand_more_rounded, color: surf.textSecondary), - ], - ), + ), + const SizedBox(width: 4), + Icon(Icons.expand_more_rounded, size: 20, color: c.muted), + ], ), ), ); } - // Zgodovina: every session of the chosen kind in the period, any shot count Widget _buildHistoryScreen() { if (_years.isEmpty) return _centered(_buildEmpty()); @@ -423,7 +418,7 @@ class _BookScreenState extends State with WidgetsBindingObserver { if (sessions.isEmpty) { return Column(children: [ Padding( - padding: const EdgeInsets.fromLTRB(16, 4, 16, 0), + padding: const EdgeInsets.fromLTRB(AppTheme.edge, 0, AppTheme.edge, 0), child: _historyHeader()), Expanded(child: _centered(_noSessions())), ]); @@ -431,26 +426,34 @@ class _BookScreenState extends State with WidgetsBindingObserver { return RefreshIndicator( onRefresh: _load, child: ListView( - padding: const EdgeInsets.fromLTRB(16, 4, 16, 32), + padding: const EdgeInsets.fromLTRB(AppTheme.edge, 0, AppTheme.edge, 24), children: _buildHistory(sessions, average), ), ); } - // The two screens; filters continue the dark app bar, like Koledar/Stiki + // Title, then the two screens Widget _buildTabs() { final s = AppSettings.instance; - return BarTabs( - tabs: [ - BarTab(s.t('Statistics'), Icons.insights_rounded), - BarTab(s.t('History'), Icons.history_rounded), + return Column( + children: [ + PageHeader( + title: s.t('Book'), + action: CircleButton(icon: Icons.info_outline_rounded, tooltip: s.t('Help'), onTap: () => showBookHelp(context)), + ), + BarTabs( + tabs: [ + BarTab(s.t('Statistics'), Icons.bar_chart_rounded), + BarTab(s.t('History'), Icons.history_rounded), + ], + selected: _view.index, + onSelect: (i) => _change(() => _view = _View.values[i]), + ), ], - selected: _view.index, - onSelect: (i) => _change(() => _view = _View.values[i]), ); } - // Zgodovina's dark row: which sessions to list + // Zgodovina: which sessions to list Widget _buildHistoryBar() { final s = AppSettings.instance; final labels = { @@ -458,18 +461,16 @@ class _BookScreenState extends State with WidgetsBindingObserver { _HistoryFilter.training: s.t('Trainings'), _HistoryFilter.tournament: s.t('Tournaments'), }; - return Container( - color: AppTheme.bar, - padding: const EdgeInsets.fromLTRB(12, 4, 12, 10), + return Padding( + padding: const EdgeInsets.fromLTRB(AppTheme.edge, 0, AppTheme.edge, 12), child: Row( children: [ for (final f in _HistoryFilter.values) ...[ - if (f.index > 0) const SizedBox(width: 6), + if (f.index > 0) const SizedBox(width: 8), Expanded( - child: _BarPill( + child: ChoicePill( label: labels[f]!, selected: f == _historyFilter, - empty: false, onTap: () => _change(() => _historyFilter = f), ), ), @@ -479,62 +480,91 @@ class _BookScreenState extends State with WidgetsBindingObserver { ); } - // Statistika's dark row: trainings or tournaments, then shots per target. - // Shots are always 1–5 (the capture limit); older saves above 5 keep their - // own pill. Formats with no targets yet are dimmed and can't be picked. - Widget _buildStatsBar(List formats, int? selected) { + // Statistika: trainings or tournaments, then the shots-per-target format as + // one chip with a menu. Shots are 1–5 (the capture limit); older saves above + // 5 keep their own entry. Formats with no targets yet can't be picked. + Widget _buildStatsBar(Map counts, int? selected) { final s = AppSettings.instance; + final c = Palette.current; final sorted = { for (int n = AppSettings.minBullets; n <= AppSettings.maxBullets; n++) n, - ...formats, + ...counts.keys, }.toList() - ..sort(); - Widget kind(_Filter f, String label) => Expanded( - flex: 5, - child: _BarPill( - label: s.t(label), - selected: f == _filter, - empty: false, - onTap: () => _change(() { - _filter = f; - _shots = null; - _chartAt = null; - }), - ), + ..sort((a, b) => b.compareTo(a)); + Widget kind(_Filter f, String label) => ChoicePill( + label: s.t(label), + selected: f == _filter, + onTap: () => _change(() { + _filter = f; + _shots = null; + _chartAt = null; + }), ); - return Container( - color: AppTheme.bar, - padding: const EdgeInsets.fromLTRB(12, 4, 12, 10), + return Padding( + padding: const EdgeInsets.fromLTRB(AppTheme.edge, 0, AppTheme.edge, 12), child: Row( children: [ - kind(_Filter.training, 'Trainings'), + Expanded(child: kind(_Filter.training, 'Trainings')), const SizedBox(width: 6), - kind(_Filter.tournament, 'Tournaments'), - // Divider between the two groups - Container( - width: 1, - height: 22, - margin: const EdgeInsets.symmetric(horizontal: 8), - color: Colors.white24), - for (final n in sorted) ...[ - if (n != sorted.first) const SizedBox(width: 4), - Expanded( - flex: 2, - child: _BarPill( - label: '$n', - selected: n == selected, - empty: !formats.contains(n), - onTap: formats.contains(n) - ? () => _change(() => _shots = n) - : null), + Expanded(child: kind(_Filter.tournament, 'Tournaments')), + const SizedBox(width: 6), + PopupMenuButton( + tooltip: s.t('Shots per target'), + initialValue: selected, + position: PopupMenuPosition.under, + offset: const Offset(0, 6), + color: c.isDark ? c.card2 : c.card, + surfaceTintColor: Colors.transparent, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(14), + side: BorderSide(color: c.line), ), - ], + onSelected: (n) => _change(() => _shots = n), + itemBuilder: (_) => [ + for (final n in sorted) + PopupMenuItem( + value: n, + enabled: (counts[n] ?? 0) > 0, + height: 44, + child: Row( + children: [ + SizedBox( + width: 22, + child: n == selected ? Icon(Icons.check_rounded, size: 18, color: c.accent) : null, + ), + const SizedBox(width: 6), + Text(shotCount(n), + style: TextStyle( + fontSize: 14, + fontWeight: n == selected ? FontWeight.w700 : FontWeight.w500, + color: (counts[n] ?? 0) > 0 ? c.ink : c.faint)), + const SizedBox(width: 16), + const Spacer(), + Text(targetCount(counts[n] ?? 0), + style: TextStyle(fontSize: 12, color: c.muted, fontFeatures: AppTheme.tnum)), + ], + ), + ), + ], + child: Container( + height: 32, + padding: const EdgeInsets.only(left: 12, right: 6), + decoration: BoxDecoration(color: c.tile, borderRadius: BorderRadius.circular(16)), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text(selected == null ? '–' : shotCount(selected), + style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: c.ink2)), + Icon(Icons.expand_more_rounded, size: 18, color: c.muted), + ], + ), + ), + ), ], ), ); } - // Monday–Sunday week of [date], cut to its month: "6.–12. 10.", "27.–31. 10." static String _weekLabel(DateTime date) { final day = DateTime(date.year, date.month, date.day); @@ -588,62 +618,36 @@ class _BookScreenState extends State with WidgetsBindingObserver { ); } - // Up = green, down = red; darker shades on light backgrounds - static Color _deltaColor(double delta) { - final light = AppSettings.instance.isLightBackground; - return delta >= 0 - ? (light ? Colors.green[800]! : Colors.greenAccent[400]!) - : (light ? Colors.red[800]! : Colors.redAccent[100]!); - } - - static String _signed(double v) => - '${v >= 0 ? '+' : '−'}${v.abs().toStringAsFixed(2)}'; - - // Tint of the bullet colour that still reads on the card: lighter on dark - // cards, darker on light ones - static Color _tint(double amount) { - final s = AppSettings.instance; - return Color.lerp(s.bulletColor, - s.isLightBackground ? Colors.black : Colors.white, amount)!; - } - - // Statistika as cards: one with the period's average per shot and its trend - // beside three counts; the graph; the best session. It fits - // the screen without scrolling, the graph taking the height that is left; - // on a screen too small for that it scrolls with a fixed-height graph. - // The graph gets every loaded session of the format, [all], and picks its - // own month or year. + // Statistika as cards: the period's average per shot and its trend beside + // three counts; the graph; the best session. It fits the screen without + // scrolling, the graph taking the height that is left; on a screen too + // small for that it scrolls with a fixed-height graph. The graph gets every + // loaded session of the format, [all], and picks its own month or year. Widget _buildStats(List all, ShooterStats stats) { final s = AppSettings.instance; + final c = Palette.current; final bestSession = stats.bestSession; final tournaments = _filter == _Filter.tournament; const gap = SizedBox(height: 12); - // One card: the average on the left, the three counts on the right - final surf = Surfaces.current; - final top = _BookCard( - padding: const EdgeInsets.symmetric(vertical: 14), + final top = AppCard( + padding: const EdgeInsets.symmetric(vertical: 16), child: IntrinsicHeight( child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - Expanded(flex: 11, child: _averageContent(stats)), - VerticalDivider(width: 1, thickness: 1, color: surf.divider), + Expanded(flex: 10, child: _averageContent(stats)), + VerticalDivider(width: 1, thickness: 1, color: c.line2), Expanded( - flex: 9, + flex: 10, child: Padding( - padding: const EdgeInsets.only(left: 14, right: 12), + padding: const EdgeInsets.only(left: 14, right: 10), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ - _CountLine( - value: '${stats.sessions}', - label: s.t(tournaments ? 'Tournaments' : 'Trainings')), - _CountLine( - value: '${stats.targets}', label: s.t('Targets')), - _CountLine( - value: stats.averageTarget!.toStringAsFixed(1), - label: s.t('Average target')), + _CountLine(value: '${stats.sessions}', label: s.t(tournaments ? 'Tournaments' : 'Trainings')), + _CountLine(value: '${stats.targets}', label: s.t('Targets')), + _CountLine(value: dec(stats.averageTarget!, 1), label: s.t('Average target')), ], ), ), @@ -656,25 +660,24 @@ class _BookScreenState extends State with WidgetsBindingObserver { final best = bestSession != null && stats.sessions > 1 ? _HeroRecord( label: s.t(tournaments ? 'Best tournament' : 'Best training'), - value: bestSession.averagePerShot!.toStringAsFixed(2), - caption: - '${DateFormat('d. M.').format(bestSession.date)} · ${bestSession.name}', + value: dec(bestSession.averagePerShot!), + caption: '${DateFormat('d. M.').format(bestSession.date)} · ${bestSession.name}', onTap: () => _openTargets(bestSession), ) : null; return LayoutBuilder(builder: (context, box) { // Room for the cards above plus a graph that is still worth reading - if (box.maxHeight >= 560) { + if (box.maxHeight >= 520) { return Padding( - padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), + padding: const EdgeInsets.fromLTRB(AppTheme.edge, 0, AppTheme.edge, 16), child: Column( children: [ _periodRow(), - const SizedBox(height: 8), + gap, top, gap, - Expanded(child: _BookCard(child: _buildChart(all, stats, fill: true))), + Expanded(child: AppCard(padding: EdgeInsets.zero, child: _buildChart(all, stats, fill: true))), if (best != null) ...[gap, best], ], ), @@ -683,13 +686,13 @@ class _BookScreenState extends State with WidgetsBindingObserver { return RefreshIndicator( onRefresh: _load, child: ListView( - padding: const EdgeInsets.fromLTRB(16, 8, 16, 32), + padding: const EdgeInsets.fromLTRB(AppTheme.edge, 0, AppTheme.edge, 24), children: [ _periodRow(), - const SizedBox(height: 8), + gap, top, gap, - _BookCard(child: _buildChart(all, stats)), + AppCard(padding: EdgeInsets.zero, child: _buildChart(all, stats)), if (best != null) ...[gap, best], ], ), @@ -699,7 +702,7 @@ class _BookScreenState extends State with WidgetsBindingObserver { Widget _averageContent(ShooterStats stats) { final s = AppSettings.instance; - final surf = Surfaces.current; + final c = Palette.current; final trend = stats.trend; return Padding( padding: const EdgeInsets.symmetric(horizontal: 16), @@ -707,35 +710,32 @@ class _BookScreenState extends State with WidgetsBindingObserver { crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ - Text(s.t('Average per shot').toUpperCase(), - maxLines: 2, - style: TextStyle( - fontSize: 11, - fontWeight: FontWeight.bold, - letterSpacing: 1.2, - color: surf.textSecondary)), + Text(s.t('Average per shot').toUpperCase(), maxLines: 2, style: AppTheme.kicker(c).copyWith(fontSize: 10.5)), FittedBox( fit: BoxFit.scaleDown, alignment: Alignment.centerLeft, child: Text( - stats.averagePerShot?.toStringAsFixed(2) ?? '–', + stats.averagePerShot == null ? '–' : dec(stats.averagePerShot!), style: TextStyle( - fontSize: 48, - fontWeight: FontWeight.w800, - color: surf.textPrimary, - height: 1.1), + fontSize: 46, fontWeight: FontWeight.w800, letterSpacing: -1, color: c.ink, height: 1.15, fontFeatures: AppTheme.tnum), ), ), - if (trend != null) - Text( - '${trend >= 0 ? '▲' : '▼'} ${trend.abs().toStringAsFixed(2)} ${s.t('vs earlier')}', - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle( - fontSize: 12, - fontWeight: FontWeight.w600, - color: _deltaColor(trend)), + if (trend != null) ...[ + const SizedBox(height: 4), + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + decoration: BoxDecoration( + color: trend >= 0 ? c.posSoft : c.redSoft, + borderRadius: BorderRadius.circular(20), + ), + child: Text( + '${trend >= 0 ? '▲' : '▼'} ${dec(trend.abs())} ${s.t('vs earlier')}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: c.delta(trend)), + ), ), + ], ], ), ); @@ -745,65 +745,54 @@ class _BookScreenState extends State with WidgetsBindingObserver { // [fill]: the graph takes all the height the card gets (inside an Expanded) Widget _buildChart(List all, ShooterStats stats, {bool fill = false}) { final s = AppSettings.instance; - final surf = Surfaces.current; + final c = Palette.current; final scored = all.where((x) => x.shots > 0).toList(); final today = _today; - final at = _chartAt ?? - (scored.isEmpty ? today : scored.first.date); // newest first + final at = _chartAt ?? (scored.isEmpty ? today : scored.first.date); // newest first final shown = [ for (final x in scored.reversed) // oldest first - if (x.date.year == at.year && - (_chartByYear || x.date.month == at.month)) - x + if (x.date.year == at.year && (_chartByYear || x.date.month == at.month)) x ]; final data = _chartData(shown); // One step back/forward; null when it would leave the years with sessions final first = DateTime(_years.isEmpty ? today.year : _years.last); - final prev = - _chartByYear ? DateTime(at.year - 1) : DateTime(at.year, at.month - 1); - final next = - _chartByYear ? DateTime(at.year + 1) : DateTime(at.year, at.month + 1); - // Short, fixed-width title so the arrows and the toggle never move - final title = _chartByYear - ? '${at.year}' - : toBeginningOfSentenceCase( - DateFormat('LLL yyyy', _locale).format(at).replaceAll('.', '')); + final prev = _chartByYear ? DateTime(at.year - 1) : DateTime(at.year, at.month - 1); + final next = _chartByYear ? DateTime(at.year + 1) : DateTime(at.year, at.month + 1); + final title = _chartByYear ? '${at.year}' : DateFormat('LLLL yyyy', _locale).format(at); - Widget arrow(IconData icon, DateTime? to) => IconButton( - visualDensity: VisualDensity.compact, - icon: - Icon(icon, color: to == null ? surf.divider : surf.textSecondary), - onPressed: to == null ? null : () => setState(() => _chartAt = to), + Widget arrow(IconData icon, DateTime? to) => GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: to == null ? null : () => setState(() => _chartAt = to), + child: Padding( + padding: const EdgeInsets.all(4), + child: Icon(icon, size: 20, color: to == null ? c.faint : c.ink2), + ), ); return Padding( - padding: const EdgeInsets.fromLTRB(12, 8, 12, 14), + padding: const EdgeInsets.fromLTRB(8, 10, 14, 14), child: Column( children: [ Row( children: [ - arrow(Icons.chevron_left_rounded, - prev.isBefore(first) ? null : prev), - SizedBox( - width: 76, - child: Text( - title, - textAlign: TextAlign.center, - maxLines: 1, - style: TextStyle( - fontSize: 15, - fontWeight: FontWeight.w700, - color: surf.textPrimary), + Expanded( + child: Row( + children: [ + arrow(Icons.chevron_left_rounded, prev.isBefore(first) ? null : prev), + Flexible( + child: FittedBox( + fit: BoxFit.scaleDown, + child: Text(title, maxLines: 1, style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: c.ink)), + ), + ), + arrow(Icons.chevron_right_rounded, next.isAfter(today) ? null : next), + ], ), ), - arrow(Icons.chevron_right_rounded, - next.isAfter(today) ? null : next), - const Spacer(), _Toggle( labels: [s.t('Month'), s.t('Year')], selected: _chartByYear ? 1 : 0, - color: s.bulletColor, onSelect: (i) => _change(() { _chartByYear = i == 1; _chartAt = at; @@ -816,27 +805,29 @@ class _BookScreenState extends State with WidgetsBindingObserver { fill, Padding( padding: const EdgeInsets.symmetric(vertical: 40), - child: Center( - child: Text(s.t('No sessions in this period'), - style: TextStyle(color: surf.textSecondary)), - ), + child: Center(child: Text(s.t('No sessions in this period'), style: TextStyle(color: c.muted))), ), ) else ...[ const SizedBox(height: 4), _fillIf( fill, - ProgressChart( - expand: fill, - labels: data.labels, - series: [ - ChartSeries(s.t('Shot average'), s.bulletColor, data.perShot, - axis: ChartAxis.left), - ChartSeries(s.t('Number of points'), _tint(0.55), data.total, - decimals: 0, axis: ChartAxis.right), - ], - textColor: surf.textSecondary, - gridColor: surf.divider, + Padding( + padding: const EdgeInsets.only(left: 6), + child: ProgressChart( + expand: fill, + labels: data.labels, + series: [ + ChartSeries(s.t('Shot average'), c.accent, data.perShot, axis: ChartAxis.left), + ChartSeries(s.t('Number of points'), c.isDark ? c.ink2 : c.muted, data.total, + decimals: 0, axis: ChartAxis.right), + ], + textColor: c.muted, + gridColor: c.line2, + surfaceColor: c.card, + tooltipColor: c.isDark ? c.ink : c.ink, + tooltipTextColor: c.isDark ? c.bg : Colors.white, + ), ), ), ], @@ -845,149 +836,117 @@ class _BookScreenState extends State with WidgetsBindingObserver { ); } - static Widget _fillIf(bool fill, Widget child) => - fill ? Expanded(child: child) : child; + static Widget _fillIf(bool fill, Widget child) => fill ? Expanded(child: child) : child; List _buildHistory(List sessions, double? average) { // Average per shot, so sessions with more targets don't win by volume final ordered = _sortByScore - ? ([...sessions]..sort( - (a, b) => (b.averagePerShot ?? 0).compareTo(a.averagePerShot ?? 0))) + ? ([...sessions]..sort((a, b) => (b.averagePerShot ?? 0).compareTo(a.averagePerShot ?? 0))) : sessions; + double? best; + for (final x in sessions) { + final avg = x.averagePerShot; + if (avg != null && (best == null || avg > best)) best = avg; + } return [ _historyHeader(), - for (final x in ordered) _sessionCard(x, average), + for (final x in ordered) _sessionCard(x, average, isBest: sessions.length > 1 && x.averagePerShot == best), ]; } - // Period selector (shared with Statistika) and the sort order, both labelled + // Period selector (shared with Statistika) and the sort order Widget _historyHeader() { final s = AppSettings.instance; - final surf = Surfaces.current; + final c = Palette.current; return Padding( - // With the list's 4 px this starts 8 px under the bar, like Statistika - padding: const EdgeInsets.only(top: 4, bottom: 8), - // Same height for both buttons - child: IntrinsicHeight( - child: Row( - crossAxisAlignment: CrossAxisAlignment.stretch, + padding: const EdgeInsets.only(bottom: 12), + child: Row( children: [ - Expanded(child: _periodRow()), + Expanded(child: _periodRow(compact: true)), const SizedBox(width: 8), // Each tap switches between date and score order - Material( - color: surf.card, - borderRadius: BorderRadius.circular(14), - clipBehavior: Clip.antiAlias, - child: InkWell( - onTap: () => _change(() => _sortByScore = !_sortByScore), - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), - child: Row( - children: [ - Icon( - _sortByScore - ? Icons.leaderboard_rounded - : Icons.event_rounded, - size: 20, - color: s.bulletColor), - const SizedBox(width: 6), - Text(s.t(_sortByScore ? 'Sort by Score' : 'Sort by Date'), - style: TextStyle( - fontSize: 13, - fontWeight: FontWeight.w600, - color: surf.textPrimary)), - ], - ), + AppCard( + radius: 14, + padding: const EdgeInsets.symmetric(horizontal: 12), + onTap: () => _change(() => _sortByScore = !_sortByScore), + child: SizedBox( + height: 46, + child: Row( + children: [ + Icon(_sortByScore ? Icons.leaderboard_outlined : Icons.calendar_today_outlined, size: 18, color: c.accent), + const SizedBox(width: 8), + Text(s.t(_sortByScore ? 'Sort by Score' : 'Sort by Date'), + style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: c.ink)), + ], ), ), ), ], - ), ), ); } // Date block left; points (Skupek) and average per shot right, the average - // with how far it is from [average]. - // Tap shows this session's targets on one target; long press opens details. - Widget _sessionCard(Session session, double? average) { + // with how far it is from [average]. Tap shows this session's targets on one + // target; long press or the dots open details. + Widget _sessionCard(Session session, double? average, {bool isBest = false}) { final s = AppSettings.instance; - final surf = Surfaces.current; + final c = Palette.current; final avg = session.averagePerShot; final delta = avg == null || average == null ? null : avg - average; return Padding( - padding: const EdgeInsets.only(bottom: 8), - child: Material( - color: surf.card, - borderRadius: BorderRadius.circular(12), - clipBehavior: Clip.antiAlias, - child: InkWell( - onTap: () => _openTargets(session), - onLongPress: () => _openDetails(session), - child: IntrinsicHeight( - child: Row( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - _DateBlock( - date: session.date, color: s.bulletColor, locale: _locale), - Expanded( - child: Padding( - padding: const EdgeInsets.fromLTRB(14, 10, 4, 10), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - if (session.isTournament) ...[ - Icon(Icons.emoji_events_rounded, - size: 16, color: s.bulletColor), - const SizedBox(width: 4), - ], - Flexible( - child: Text( - session.name, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle( - fontSize: 15, - fontWeight: FontWeight.w700, - color: surf.textPrimary), - ), - ), - ], - ), - const SizedBox(height: 3), - Text( - targetCount(session.targets.length), - style: TextStyle( - fontSize: 12, color: surf.textSecondary), - ), + padding: const EdgeInsets.only(bottom: 10), + child: AppCard( + padding: const EdgeInsets.fromLTRB(10, 10, 0, 10), + onTap: () => _openTargets(session), + onLongPress: () => _openDetails(session), + child: Row( + children: [ + _DateBlock(date: session.date, locale: _locale), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + if (session.isTournament) ...[ + Icon(Icons.emoji_events_outlined, size: 16, color: c.accent), + const SizedBox(width: 4), ], - ), + Flexible( + child: Text(session.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: c.ink)), + ), + ], ), - ), - _CardFigure( - label: s.t('Sum'), value: '${session.totalScore}'), - const SizedBox(width: 14), - _CardFigure( - label: s.t('Average'), - value: avg?.toStringAsFixed(2) ?? '–', - note: delta == null ? null : _signed(delta), - noteColor: delta == null ? null : _deltaColor(delta), - ), - IconButton( - tooltip: s.t('Details'), - visualDensity: VisualDensity.compact, - icon: - Icon(Icons.more_vert_rounded, color: surf.textSecondary), - onPressed: () => _openDetails(session), - ), - ], + const SizedBox(height: 3), + Text(targetCount(session.targets.length), style: TextStyle(fontSize: 12, color: c.muted)), + ], + ), ), - ), + _CardFigure(value: '${session.totalScore}', note: s.t('Sum'), noteColor: c.muted), + const SizedBox(width: 14), + _CardFigure( + value: avg == null ? '–' : dec(avg), + valueColor: isBest ? c.gold : null, + note: delta == null ? ' ' : signedDec(delta), + noteColor: delta == null ? null : c.delta(delta), + bold: true, + ), + SizedBox( + width: 40, + child: IconButton( + tooltip: s.t('Details'), + visualDensity: VisualDensity.compact, + icon: Icon(Icons.more_vert_rounded, size: 20, color: c.muted), + onPressed: () => _openDetails(session), + ), + ), + ], ), ), ); @@ -997,8 +956,7 @@ class _BookScreenState extends State with WidgetsBindingObserver { await Navigator.push( context, MaterialPageRoute( - builder: (_) => TargetViewScreen( - jsonFiles: files, refreshFolders: _load, isCombinedView: combined), + builder: (_) => TargetViewScreen(jsonFiles: files, refreshFolders: _load, isCombinedView: combined), ), ); _load(); @@ -1011,116 +969,39 @@ class _BookScreenState extends State with WidgetsBindingObserver { Widget _buildEmpty() { final s = AppSettings.instance; - final surf = Surfaces.current; - return Container( - width: double.infinity, - margin: const EdgeInsets.only(bottom: 48), // a little above the middle - padding: const EdgeInsets.symmetric(vertical: 36, horizontal: 24), - decoration: BoxDecoration( - color: surf.card, borderRadius: BorderRadius.circular(24)), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Container( - padding: const EdgeInsets.all(18), - decoration: BoxDecoration( - color: s.bulletColor.withValues(alpha: 0.15), - shape: BoxShape.circle, - ), - child: Icon(Icons.track_changes_rounded, - size: 44, color: s.bulletColor), - ), - const SizedBox(height: 16), - Text( - s.t('No saved target data found'), - textAlign: TextAlign.center, - style: TextStyle( - fontSize: 16, - fontWeight: FontWeight.w600, - color: surf.textPrimary), - ), - const SizedBox(height: 4), - Text( - s.t('Saved targets and your statistics will appear here'), - textAlign: TextAlign.center, - style: TextStyle(color: surf.textSecondary), - ), - ], + return Padding( + padding: const EdgeInsets.only(bottom: 48), // a little above the middle + child: EmptyState( + icon: Icons.track_changes_rounded, + title: s.t('No saved target data found'), + hint: s.t('Saved targets and your statistics will appear here'), ), ); } } -/// What Knjiga shows and where to tap; opened from the info button in the app bar. +/// What Knjiga shows and where to tap; opened from the info button. void showBookHelp(BuildContext context) { final s = AppSettings.instance; - showHelpSheet(context, accent: s.bulletColor, t: s.t, items: const [ - ( - Icons.insights_rounded, - 'Statistics / History: your form and progress graph, or the list of all your sessions.' - ), - ( - Icons.emoji_events_rounded, - 'Trainings / Tournaments: choose which sessions the statistics count.' - ), - ( - Icons.filter_5_rounded, - 'Shots 1–5: statistics only compare targets with the same number of shots. Grey numbers have no targets yet.' - ), - ( - Icons.trending_up_rounded, - 'Arrow under the average: your last 5 sessions compared with the 5 before them.' - ), - ( - Icons.show_chart_rounded, - 'Graph: shot average (left axis) and number of points (right axis). Month shows each session of a month, Year one point per month; the arrows go back through earlier months or years. Tap or drag on it to see the values.' - ), - ( - Icons.workspace_premium_rounded, - 'Best training / tournament in the top card: tap to open its targets.' - ), - ( - Icons.date_range_rounded, - 'Period: this month, last 3 months, this year, all or your own dates. Statistics and History both use it.' - ), - ( - Icons.filter_list_rounded, - 'History: All / Trainings / Tournaments chooses which sessions are listed, with any number of shots.' - ), - ( - Icons.sort_rounded, - 'Sort icon: tap to switch between date order and best average per shot. The coloured number shows how far a session is from your average.' - ), - ( - Icons.touch_app_rounded, - 'Tap a session to see all its targets on one target.' - ), - ( - Icons.more_vert_rounded, - 'Three dots on the right or long press: session details, single targets, rename and delete.' - ), + showHelpSheet(context, t: s.t, items: const [ + (Icons.bar_chart_rounded, 'Statistics / History: your form and progress graph, or the list of all your sessions.'), + (Icons.emoji_events_outlined, 'Trainings / Tournaments: choose which sessions the statistics count.'), + (Icons.grid_view_rounded, + 'Shots 1–5: statistics only compare targets with the same number of shots. Grey numbers have no targets yet.'), + (Icons.trending_up_rounded, 'Arrow under the average: your last 5 sessions compared with the 5 before them.'), + (Icons.show_chart_rounded, + 'Graph: shot average (left axis) and number of points (right axis). Month shows each session of a month, Year one point per month; the arrows go back through earlier months or years. Tap or drag on it to see the values.'), + (Icons.workspace_premium_outlined, 'Best training / tournament in the bottom card: tap to open its targets.'), + (Icons.calendar_today_outlined, + 'Period: this month, last 3 months, this year, all or your own dates. Statistics and History both use it.'), + (Icons.filter_list_rounded, 'History: All / Trainings / Tournaments chooses which sessions are listed, with any number of shots.'), + (Icons.sort_rounded, + 'Sort: tap to switch between date order and best average per shot. The coloured number shows how far a session is from your average.'), + (Icons.touch_app_outlined, 'Tap a session to see all its targets on one target.'), + (Icons.more_vert_rounded, 'Three dots on the right or long press: session details, single targets, rename and delete.'), ]); } -/// A rounded card on the page, the same surface as the history cards. -class _BookCard extends StatelessWidget { - final Widget child; - final EdgeInsetsGeometry padding; - - const _BookCard({required this.child, this.padding = EdgeInsets.zero}); - - @override - Widget build(BuildContext context) { - return Container( - padding: padding, - decoration: BoxDecoration( - color: Surfaces.current.card, - borderRadius: BorderRadius.circular(20)), - child: child, - ); - } -} - /// One count in the summary card: number, then its label, on one line. class _CountLine extends StatelessWidget { final String value; @@ -1130,183 +1011,126 @@ class _CountLine extends StatelessWidget { @override Widget build(BuildContext context) { - final surf = Surfaces.current; + final c = Palette.current; return Row( children: [ - Text(value, - style: TextStyle( - fontSize: 18, - fontWeight: FontWeight.w800, - color: surf.textPrimary)), - const SizedBox(width: 8), + Text(value, style: TextStyle(fontSize: 17, fontWeight: FontWeight.w800, color: c.ink, fontFeatures: AppTheme.tnum)), + const SizedBox(width: 6), Expanded( - child: Text(label, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle(fontSize: 12, color: surf.textSecondary)), + child: Text(label, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 12, color: c.muted)), ), ], ); } } -/// Best-session card: label and date left, value right. Tappable. +/// Best-session card: trophy, label and date left, value right. Tappable. class _HeroRecord extends StatelessWidget { final String label; final String value; final String caption; final VoidCallback onTap; - const _HeroRecord( - {required this.label, - required this.value, - required this.caption, - required this.onTap}); + const _HeroRecord({required this.label, required this.value, required this.caption, required this.onTap}); @override Widget build(BuildContext context) { - final surf = Surfaces.current; - return Material( - color: surf.card, - borderRadius: BorderRadius.circular(20), - clipBehavior: Clip.antiAlias, - child: InkWell( - onTap: onTap, - child: Padding( - padding: const EdgeInsets.fromLTRB(16, 14, 10, 14), - child: Row( - children: [ - Icon(Icons.emoji_events_rounded, - size: 20, color: AppSettings.instance.bulletColor), - const SizedBox(width: 10), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(label, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle( - fontSize: 12, - fontWeight: FontWeight.w600, - color: surf.textPrimary)), - Text(caption, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: - TextStyle(fontSize: 11, color: surf.textSecondary)), - ], - ), - ), - Text(value, - style: TextStyle( - fontSize: 20, - fontWeight: FontWeight.w800, - color: surf.textPrimary)), - Icon(Icons.chevron_right_rounded, - size: 20, color: surf.textSecondary), - ], - ), - ), - ), - ); - } -} - -/// Full-height date column on the card's left edge, like the calendar cards. -class _DateBlock extends StatelessWidget { - final DateTime date; - final Color color; - final String locale; - - const _DateBlock( - {required this.date, required this.color, required this.locale}); - - @override - Widget build(BuildContext context) { - final small = TextStyle( - fontSize: 10, - fontWeight: FontWeight.w700, - color: Colors.white.withValues(alpha: 0.9)); - return Container( - width: 56, - color: color, - padding: const EdgeInsets.symmetric(vertical: 8), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, + final c = Palette.current; + return AppCard( + onTap: onTap, + padding: const EdgeInsets.fromLTRB(14, 12, 10, 12), + child: Row( children: [ - Text(DateFormat('EEE', locale).format(date).toUpperCase(), - style: small), - Text( - DateFormat('d').format(date), - style: const TextStyle( - fontSize: 22, - fontWeight: FontWeight.bold, - color: Colors.white, - height: 1.15), + IconBadge(Icons.emoji_events_outlined, size: 40, color: c.gold), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: c.ink)), + Text(caption, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 12, color: c.muted)), + ], + ), ), - Text( - DateFormat('MMM', locale) - .format(date) - .toUpperCase() - .replaceAll('.', ''), - style: small), + Text(value, + style: TextStyle(fontSize: 21, fontWeight: FontWeight.w800, color: c.isDark ? c.gold : c.goldInk, fontFeatures: AppTheme.tnum)), + const SizedBox(width: 2), + Icon(Icons.chevron_right_rounded, size: 20, color: c.faint), ], ), ); } } -/// Two-option switch with fixed, equal segments, so it keeps its size and -/// place whichever option is selected or however long the labels are. -class _Toggle extends StatelessWidget { - static const double _segment = 58; +/// Date tile on the card's left: weekday, day, month. +class _DateBlock extends StatelessWidget { + final DateTime date; + final String locale; - final List labels; - final int selected; - final Color color; - final ValueChanged onSelect; - - const _Toggle( - {required this.labels, - required this.selected, - required this.color, - required this.onSelect}); + const _DateBlock({required this.date, required this.locale}); @override Widget build(BuildContext context) { - final surf = Surfaces.current; + final c = Palette.current; + final small = TextStyle(fontSize: 9, fontWeight: FontWeight.w700, letterSpacing: 0.4, color: c.accentInk); return Container( - padding: const EdgeInsets.all(2), - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(18), - border: Border.all(color: surf.divider), + width: 46, + padding: const EdgeInsets.symmetric(vertical: 6), + decoration: BoxDecoration(color: c.accentSoft, borderRadius: BorderRadius.circular(12)), + child: Column( + children: [ + Text(DateFormat('EEE', locale).format(date).toUpperCase().replaceAll('.', ''), style: small), + Text(DateFormat('d').format(date), + style: TextStyle(fontSize: 20, fontWeight: FontWeight.w800, height: 1.15, color: c.ink)), + Text(DateFormat('MMM', locale).format(date).toUpperCase().replaceAll('.', ''), style: small), + ], ), + ); + } +} + +/// Two-option switch (Mesec | Leto): a raised pill on a quiet track, each +/// segment as wide as its label. +class _Toggle extends StatelessWidget { + final List labels; + final int selected; + final ValueChanged onSelect; + + const _Toggle({required this.labels, required this.selected, required this.onSelect}); + + @override + Widget build(BuildContext context) { + final c = Palette.current; + return Container( + height: 30, + padding: const EdgeInsets.all(3), + decoration: BoxDecoration(color: c.isDark ? c.bg : c.tile, borderRadius: BorderRadius.circular(10)), child: Row( mainAxisSize: MainAxisSize.min, children: [ for (int i = 0; i < labels.length; i++) - Material( - color: i == selected ? color : Colors.transparent, - shape: const StadiumBorder(), - clipBehavior: Clip.antiAlias, - child: InkWell( - onTap: () => onSelect(i), - child: SizedBox( - width: _segment, - height: 28, - child: Center( - child: Text( - labels[i], - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle( - fontSize: 12, - fontWeight: FontWeight.w600, - color: i == selected - ? Colors.white - : surf.textSecondary), - ), + GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () => onSelect(i), + child: AnimatedContainer( + duration: const Duration(milliseconds: 150), + padding: const EdgeInsets.symmetric(horizontal: 10), + alignment: Alignment.center, + decoration: BoxDecoration( + color: i == selected ? (c.isDark ? c.tile : c.card) : Colors.transparent, + borderRadius: BorderRadius.circular(7), + boxShadow: i == selected && !c.isDark ? c.shadow : null, + ), + child: Text( + labels[i], + maxLines: 1, + style: TextStyle( + fontSize: 12, + fontWeight: i == selected ? FontWeight.w700 : FontWeight.w500, + color: i == selected ? c.ink : c.muted, ), ), ), @@ -1317,89 +1141,33 @@ class _Toggle extends StatelessWidget { } } -/// One figure on a history card: small uppercase label over a bold number, -/// with an optional coloured note underneath (its row is kept even when empty). +/// One figure on a history card: bold number with a small note under it. class _CardFigure extends StatelessWidget { - final String label; final String value; + final Color? valueColor; final String? note; final Color? noteColor; + final bool bold; - const _CardFigure( - {required this.label, required this.value, this.note, this.noteColor}); + const _CardFigure({required this.value, this.valueColor, this.note, this.noteColor, this.bold = false}); @override Widget build(BuildContext context) { - final surf = Surfaces.current; - return Padding( - padding: const EdgeInsets.symmetric(vertical: 10), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - Text(label.toUpperCase(), - style: TextStyle( - fontSize: 9, - fontWeight: FontWeight.bold, - letterSpacing: 1, - color: surf.textSecondary)), - Text(value, - style: TextStyle( - fontSize: 20, - fontWeight: FontWeight.w800, - fontFeatures: const [FontFeature.tabularFigures()], - color: surf.textPrimary)), - // The note row is always there (blank without a note), so label and - // number line up across figures whether or not they have a note. - Text(note ?? ' ', - style: TextStyle( - fontSize: 12, - fontWeight: FontWeight.w700, - fontFeatures: const [FontFeature.tabularFigures()], - color: noteColor)), - ], - ), - ); - } -} - -/// Small pill on the dark bar: white when selected, outlined otherwise. -class _BarPill extends StatelessWidget { - final String label; - final bool selected; - final bool empty; // no targets with this many shots - final VoidCallback? onTap; // null = not selectable - - const _BarPill( - {required this.label, - required this.selected, - this.empty = false, - required this.onTap}); - - @override - Widget build(BuildContext context) { - return Material( - color: selected ? Colors.white : Colors.transparent, - shape: StadiumBorder( - side: BorderSide(color: selected ? Colors.white : Colors.white30)), - child: InkWell( - customBorder: const StadiumBorder(), - onTap: onTap, - child: Padding( - padding: const EdgeInsets.symmetric(vertical: 6), - child: Text( - label, - textAlign: TextAlign.center, + final c = Palette.current; + return Column( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text(value, style: TextStyle( - fontSize: 12, - fontWeight: FontWeight.w600, - color: selected - ? Colors.black - : (empty ? Colors.white30 : Colors.white70), - ), - ), - ), - ), + fontSize: 17, fontWeight: FontWeight.w800, color: valueColor ?? c.ink, fontFeatures: AppTheme.tnum)), + // The note row is always there (blank without a note), so the numbers line up + Text(note ?? ' ', + style: TextStyle( + fontSize: bold ? 11 : 9.5, + fontWeight: bold ? FontWeight.w700 : FontWeight.w500, + color: noteColor, + fontFeatures: AppTheme.tnum)), + ], ); } } diff --git a/lib/screens/calendar_screen.dart b/lib/screens/calendar_screen.dart index dcd3a10..c120e88 100644 --- a/lib/screens/calendar_screen.dart +++ b/lib/screens/calendar_screen.dart @@ -1,7 +1,6 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:intl/intl.dart'; -import 'package:shared_preferences/shared_preferences.dart'; import 'package:url_launcher/url_launcher.dart'; import '../models/contact.dart'; import '../services/app_settings.dart'; @@ -9,15 +8,18 @@ import '../theme/app_theme.dart'; import '../widgets/bar_tabs.dart'; import '../services/google_calendar_service.dart'; import '../services/notification_service.dart'; -import '../utils/translations.dart'; -import '../utils/target_colors.dart'; +import '../widgets/section.dart'; +import '../widgets/ui.dart'; +import 'settings_screen.dart'; enum EventType { - regular, + regular, // dežurstvo competition, sestanek, } +/// Koledar (club events: today, the week, upcoming) and Kontakti (members). +/// Only shown to club members. class CalendarScreen extends StatefulWidget { const CalendarScreen({super.key}); @@ -30,38 +32,18 @@ class _CalendarScreenState extends State { bool _isLoading = false; List _events = []; String? _errorMessage; - String _bulletColor = 'Blue'; - String _selectedLanguage = 'English'; bool _showContacts = false; - late Color _backgroundColor; + String _query = ''; List get _contacts => AppSettings.instance.clubContacts; @override void initState() { super.initState(); - _backgroundColor = AppSettings.instance.backgroundColor; - _loadBulletColor(); - _loadLanguage(); - _loadSelectedTargetColor(); _loadEvents(); } - String _t(String key) => AppTranslations.translate(key, _selectedLanguage); - - Future _loadLanguage() async { - final prefs = await SharedPreferences.getInstance(); - setState( - () => _selectedLanguage = prefs.getString('language') ?? 'Slovenian'); - } - - Future _loadSelectedTargetColor() async { - final prefs = await SharedPreferences.getInstance(); - final selectedTarget = - prefs.getString('selectedTarget') ?? 'assets/target.png'; - setState(() => - _backgroundColor = TargetColors.getBackgroundColor(selectedTarget)); - } + String _t(String key) => AppSettings.instance.t(key); @override void dispose() { @@ -69,48 +51,6 @@ class _CalendarScreenState extends State { super.dispose(); } - Future _loadBulletColor() async { - final prefs = await SharedPreferences.getInstance(); - setState(() => _bulletColor = prefs.getString('bulletColor') ?? 'Blue'); - } - - Color _getAccentColor() { - switch (_bulletColor.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; - } - } - bool _isValidEvent(CalendarEvent event) { if (event.summary == null || event.summary!.trim().isEmpty) return false; return event.summary!.trim().length >= 2; @@ -119,9 +59,7 @@ class _CalendarScreenState extends State { EventType? _getEventType(CalendarEvent event) { if (event.summary == null) return null; final summary = event.summary!.toLowerCase(); - if (summary.contains('liga') || - summary.contains('tekmovanje') || - summary.contains('tekma')) { + if (summary.contains('liga') || summary.contains('tekmovanje') || summary.contains('tekma')) { return EventType.competition; } else if (summary.contains('sestanek')) { return EventType.sestanek; @@ -150,8 +88,7 @@ class _CalendarScreenState extends State { if (!_isValidEvent(event)) return false; if (_getEventType(event) == null) return false; if (event.startTime != null) { - final eventDate = DateTime(event.startTime!.year, - event.startTime!.month, event.startTime!.day); + final eventDate = DateTime(event.startTime!.year, event.startTime!.month, event.startTime!.day); return eventDate.isAtSameMomentAs(today) || eventDate.isAfter(today); } return false; @@ -163,30 +100,21 @@ class _CalendarScreenState extends State { return a.startTime!.compareTo(b.startTime!); }); - if (mounted) { - setState(() => _events = filteredEvents); - } + if (mounted) setState(() => _events = filteredEvents); NotificationService().scheduleEventNotifications(filteredEvents); } catch (e) { - if (mounted) { - setState(() => _errorMessage = 'Error loading events: $e'); - } + if (mounted) setState(() => _errorMessage = 'Error loading events: $e'); } finally { - if (mounted) { - setState(() => _isLoading = false); - } + if (mounted) setState(() => _isLoading = false); } } - Future _makePhoneCall(String phoneNumber) async { - final Uri launchUri = Uri(scheme: 'tel', path: phoneNumber); + Future _launch(Uri uri) async { try { - await launchUrl(launchUri); + await launchUrl(uri); } catch (e) { if (mounted) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text('${_t('Could not launch phone call: ')}$e')), - ); + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('${_t('Could not launch phone call: ')}$e'))); } } } @@ -201,688 +129,452 @@ class _CalendarScreenState extends State { void _copyToClipboard(String text, String label) { Clipboard.setData(ClipboardData(text: text)); ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text('$label ${_t('copied to clipboard')}'), - duration: const Duration(seconds: 2), - ), + SnackBar(content: Text('$label ${_t('copied to clipboard')}'), duration: const Duration(seconds: 2)), ); } - void _showContactPopup(BuildContext context, Contact contact) { - final accentColor = _getAccentColor(); - showModalBottomSheet( - context: context, - backgroundColor: Colors.grey[900], - shape: const RoundedRectangleBorder( - borderRadius: BorderRadius.vertical(top: Radius.circular(20)), - ), - builder: (context) { - // SafeArea keeps the buttons above Android's gesture bar (edge-to-edge) - return SafeArea( - child: RepaintBoundary( - child: Container( - padding: const EdgeInsets.all(20), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Padding( - padding: const EdgeInsets.only(bottom: 20), - child: Row( - children: [ - Container( - width: 50, - height: 50, - decoration: BoxDecoration( - color: accentColor, - borderRadius: BorderRadius.circular(10), - ), - child: Center( - child: Text( - contact.firstName[0].toUpperCase(), - style: const TextStyle( - color: Colors.white, - fontSize: 24, - fontWeight: FontWeight.bold), - ), - ), - ), - const SizedBox(width: 16), - Expanded( - child: Text( - _capitalize(contact.fullName), - style: const TextStyle( - color: Colors.white, - fontSize: 18, - fontWeight: FontWeight.bold), - ), - ), - ], - ), - ), - _buildContactDetailRow( - accentColor, Icons.phone, _t('Phone'), contact.phone, () { - _copyToClipboard(contact.phone, 'Phone number'); - Navigator.pop(context); - }), - const SizedBox(height: 12), - _buildContactDetailRow(accentColor, Icons.email, _t('Email'), - contact.email.toLowerCase(), () { - _copyToClipboard(contact.email, 'Email address'); - Navigator.pop(context); - }), - ], + // Avatar tint per member, from the design's six pairs (background, initials) + static (Color, Color) _avatar(Palette c, int i) { + const dark = [ + (Color(0x2634CF8E), Color(0xFF7EE6B9)), + (Color(0x266EA8FF), Color(0xFFA9CBFF)), + (Color(0x26F2706A), Color(0xFFF7A6A2)), + (Color(0x26B28CFF), Color(0xFFD2BCFF)), + (Color(0x26F2C12E), Color(0xFFF6D366)), + (Color(0x263CC8D6), Color(0xFF8FE3EC)), + ]; + const light = [ + (Color(0xFFE4F3EB), Color(0xFF0C6646)), + (Color(0xFFE7EEFB), Color(0xFF2D55A8)), + (Color(0xFFFBEAE4), Color(0xFFA3472B)), + (Color(0xFFF1EAFB), Color(0xFF6A43A8)), + (Color(0xFFFDF4D3), Color(0xFF7A5A00)), + (Color(0xFFE6F4F6), Color(0xFF1F6E7A)), + ]; + final list = c.isDark ? dark : light; + return list[i % list.length]; + } + + static String _initials(Contact contact) => + '${contact.firstName.isEmpty ? '' : contact.firstName[0]}${contact.lastName.isEmpty ? '' : contact.lastName[0]}'.toUpperCase(); + + void _showContactPopup(BuildContext context, Contact contact, int index) { + final c = Palette.current; + final (bg, fg) = _avatar(c, index); + showAppSheet( + context, + builder: (sheet) => Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + CircleAvatar( + radius: 26, + backgroundColor: bg, + child: Text(_initials(contact), style: TextStyle(color: fg, fontSize: 18, fontWeight: FontWeight.w700)), ), - ), + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(_capitalize(contact.fullName), style: TextStyle(color: c.ink, fontSize: 20, fontWeight: FontWeight.w700)), + if (contact.role.isNotEmpty) Text(contact.role, style: TextStyle(color: c.muted, fontSize: 13)), + ], + ), + ), + ], ), - ); - }, + const SizedBox(height: 18), + _contactDetailRow(Icons.phone_outlined, _t('Phone'), contact.phone, () { + _copyToClipboard(contact.phone, _t('Phone')); + Navigator.pop(sheet); + }), + const SizedBox(height: 10), + _contactDetailRow(Icons.mail_outline_rounded, _t('Email'), contact.email.toLowerCase(), () { + _copyToClipboard(contact.email, _t('Email')); + Navigator.pop(sheet); + }), + ], + ), ); } - Widget _buildContactDetailRow(Color accentColor, IconData icon, String label, - String value, VoidCallback onCopy) { - return Container( - padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 12), - decoration: BoxDecoration( - color: Colors.grey[850], borderRadius: BorderRadius.circular(10)), + Widget _contactDetailRow(IconData icon, String label, String value, VoidCallback onCopy) { + final c = Palette.current; + return AppCard( + color: c.isDark ? c.card2 : c.card, + padding: const EdgeInsets.fromLTRB(14, 10, 8, 10), child: Row( children: [ - Icon(icon, color: accentColor, size: 20), + IconBadge(icon, size: 36), const SizedBox(width: 12), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text(label, - style: const TextStyle(color: Colors.grey, fontSize: 11)), + Text(label, style: TextStyle(color: c.muted, fontSize: 11.5)), Text(value, - style: const TextStyle( - color: Colors.white, - fontSize: 14, - fontWeight: FontWeight.w600), + style: TextStyle(color: c.ink, fontSize: 14.5, fontWeight: FontWeight.w600), maxLines: 1, overflow: TextOverflow.ellipsis), ], ), ), - Container( - decoration: BoxDecoration( - color: accentColor, borderRadius: BorderRadius.circular(8)), - child: Material( - color: Colors.transparent, - child: InkWell( - onTap: onCopy, - borderRadius: BorderRadius.circular(8), - child: const Padding( - padding: EdgeInsets.all(8), - child: - Icon(Icons.content_copy, color: Colors.white, size: 18), - ), - ), - ), - ), + CircleButton(icon: Icons.copy_rounded, size: 38, iconSize: 18, onTap: onCopy), ], ), ); } Widget _buildContactsList() { - final accentColor = _getAccentColor(); - return ListView.builder( - itemCount: _contacts.length, - padding: const EdgeInsets.all(8), - itemBuilder: (context, index) { - final contact = _contacts[index]; - return GestureDetector( - // Card opens the info sheet (copy number/e-mail); the call strip on the right calls - onTap: () => _showContactPopup(context, contact), - child: Container( - margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 16), - decoration: BoxDecoration( - color: Surfaces.current.card, - borderRadius: BorderRadius.circular(12), - boxShadow: [ - BoxShadow( - color: Colors.black.withValues(alpha: 0.15), - blurRadius: 6, - offset: const Offset(0, 2)), - ], - ), - child: Stack( - children: [ - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Container( - width: double.infinity, - padding: const EdgeInsets.symmetric( - horizontal: 16, vertical: 12), - decoration: BoxDecoration( - color: accentColor.withValues(alpha: 0.6), - borderRadius: const BorderRadius.only( - topLeft: Radius.circular(12), - topRight: Radius.circular(12)), - ), - child: Row( - children: [ - Container( - width: 4, - height: 20, - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(2)), - ), - const SizedBox(width: 12), - Expanded( - child: Text( - _capitalize(contact.fullName), - style: const TextStyle( - fontSize: 16, - fontWeight: FontWeight.bold, - color: Colors.white), - ), - ), - ], - ), - ), - Padding( - padding: const EdgeInsets.symmetric( - horizontal: 14, vertical: 6), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row(children: [ - Icon(Icons.phone, size: 14, color: accentColor), - const SizedBox(width: 6), - Text(contact.phone, - style: TextStyle( - fontSize: 12, - color: Surfaces.current.textPrimary, - fontWeight: FontWeight.w500)), - ]), - const SizedBox(height: 4), - Row(children: [ - Icon(Icons.email, size: 14, color: accentColor), - const SizedBox(width: 6), - Expanded( - child: Text(contact.email.toLowerCase(), - style: TextStyle( - fontSize: 12, - color: Surfaces.current.textPrimary, - fontWeight: FontWeight.w500), - overflow: TextOverflow.ellipsis), - ), - ]), - ], - ), - ), - ], - ), - Positioned( - right: 0, - top: 0, - bottom: 0, - child: Container( - width: 80, - decoration: BoxDecoration( - color: accentColor, - borderRadius: const BorderRadius.only( - topRight: Radius.circular(10), - bottomRight: Radius.circular(10)), - ), - child: Material( - color: Colors.transparent, - child: InkWell( - onTap: () => _makePhoneCall(contact.phone), - borderRadius: const BorderRadius.only( - topRight: Radius.circular(10), - bottomRight: Radius.circular(10)), - child: const Center( - child: Icon(Icons.call, - color: Colors.white, size: 22)), - ), - ), - ), - ), - ], - ), + final c = Palette.current; + final q = _query.trim().toLowerCase(); + final all = _contacts; + final shown = [ + for (int i = 0; i < all.length; i++) + if (q.isEmpty || all[i].fullName.toLowerCase().contains(q) || all[i].role.toLowerCase().contains(q)) (i, all[i]), + ]; + return ListView( + padding: const EdgeInsets.fromLTRB(AppTheme.edge, 0, AppTheme.edge, 24), + children: [ + TextField( + onChanged: (v) => setState(() => _query = v), + style: TextStyle(color: c.ink, fontSize: 15), + decoration: InputDecoration( + hintText: _t('Search members …'), + prefixIcon: Icon(Icons.search_rounded, size: 20, color: c.muted), + fillColor: c.card, + border: OutlineInputBorder(borderRadius: BorderRadius.circular(14), borderSide: BorderSide(color: c.line2)), + enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(14), borderSide: BorderSide(color: c.line2)), ), - ); - }, - ); - } - - Color _eventColor(EventType type, Color accentColor) { - switch (type) { - case EventType.competition: - return Colors.orange; - case EventType.sestanek: - return const Color(0xFFE53935); - case EventType.regular: - return accentColor; - } - } - - IconData _eventIcon(EventType type) { - switch (type) { - case EventType.competition: - return Icons.emoji_events; - case EventType.sestanek: - return Icons.people; - case EventType.regular: - return Icons.calendar_today; - } - } - - String _eventBadgeLabel(EventType type) { - switch (type) { - case EventType.competition: - return _t('COMPETITION'); - case EventType.sestanek: - return _t('MEETING'); - case EventType.regular: - return _t('DUTY'); - } - } - - String _timeText(CalendarEvent event) { - final startTime = event.startTime; - if (event.isAllDay || startTime == null || event.endTime == null) { - return _t('All day'); - } - return '${DateFormat('HH:mm').format(startTime.toLocal())} – ${DateFormat('HH:mm').format(event.endTime!.toLocal())}'; - } - - // When [date] is given, the type stripe widens into a date block (upcoming list). - Widget _buildEventCard(CalendarEvent event, Color accentColor, - {bool highlight = false, DateTime? date, int daysFromToday = 0}) { - final eventType = _getEventType(event); - if (eventType == null) return const SizedBox(); - - final color = _eventColor(eventType, accentColor); - final hasLocation = event.location != null && event.location!.isNotEmpty; - - final surf = Surfaces.current; - return RepaintBoundary( - child: Container( - decoration: BoxDecoration( - color: surf.card, - borderRadius: BorderRadius.circular(12), - boxShadow: [ - BoxShadow( - color: Colors.black.withValues(alpha: 0.15), - blurRadius: 6, - offset: const Offset(0, 2)), - ], ), - clipBehavior: Clip.antiAlias, - child: IntrinsicHeight( - child: Row( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - // Type color stripe, or date block for upcoming events - date != null - ? _buildDateBlock(date, daysFromToday, color) - : Container(width: 5, color: color), - Expanded( + SectionHeader('${_t('Members')} · ${all.length}'), + if (shown.isNotEmpty) + GroupCard(children: [ + for (final (i, contact) in shown) + InkWell( + onTap: () => _showContactPopup(context, contact, i), child: Padding( - padding: EdgeInsets.fromLTRB( - 12, highlight ? 12 : 10, 12, highlight ? 12 : 10), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, + padding: const EdgeInsets.fromLTRB(14, 12, 12, 12), + child: Row( children: [ - Row( - children: [ - _buildTypeChip(_eventIcon(eventType), - _eventBadgeLabel(eventType), color), - const Spacer(), - Icon(Icons.access_time, - size: 13, color: surf.textSecondary), - const SizedBox(width: 4), - Text( - _timeText(event), - style: TextStyle( - fontSize: 12, - fontWeight: FontWeight.w600, - color: surf.textSecondary), - ), - ], + CircleAvatar( + radius: 19, + backgroundColor: _avatar(c, i).$1, + child: Text(_initials(contact), + style: TextStyle(color: _avatar(c, i).$2, fontSize: 13, fontWeight: FontWeight.w700)), ), - const SizedBox(height: 8), - Text( - event.summary ?? _t('Untitled Event'), - style: TextStyle( - fontSize: highlight ? 16 : 14, - fontWeight: FontWeight.w700, - color: surf.textPrimary, - ), - ), - if (hasLocation) ...[ - const SizedBox(height: 4), - Row( + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, children: [ - Icon(Icons.location_on, - size: 13, color: surf.textSecondary), - const SizedBox(width: 4), - Expanded( - child: Text( - event.location!, - style: TextStyle( - fontSize: 12, color: surf.textSecondary), + Text(_capitalize(contact.fullName), maxLines: 1, overflow: TextOverflow.ellipsis, - ), - ), + style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600, color: c.ink)), + Text(contact.role.isNotEmpty ? contact.role : contact.phone, + maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 12, color: c.muted)), ], ), - ], + ), + CircleButton( + icon: Icons.mail_outline_rounded, + size: 38, + iconSize: 18, + tooltip: _t('Email'), + onTap: () => _launch(Uri(scheme: 'mailto', path: contact.email)), + ), + const SizedBox(width: 8), + CircleButton( + icon: Icons.call_outlined, + size: 38, + iconSize: 18, + color: c.accent, + background: c.accentSoft, + tooltip: _t('Phone'), + onTap: () => _launch(Uri(scheme: 'tel', path: contact.phone)), + ), ], ), ), ), - ], - ), + ]), + ], + ); + } + + // Type colours: duty blue, competition gold, meeting purple + (Color stripe, Color chipBg, Color chipFg) _eventColors(EventType type) { + final c = Palette.current; + return switch (type) { + EventType.competition => (c.gold, c.goldSoft, c.isDark ? c.goldInk : c.goldInk), + EventType.sestanek => (c.purple, c.purple.withValues(alpha: 0.15), c.isDark ? const Color(0xFFD2BCFF) : c.purple), + EventType.regular => (c.blue, c.blue.withValues(alpha: 0.15), c.isDark ? const Color(0xFFA9CBFF) : c.blue), + }; + } + + String _eventBadgeLabel(EventType type) => switch (type) { + EventType.competition => _t('COMPETITION'), + EventType.sestanek => _t('MEETING'), + EventType.regular => _t('DUTY'), + }; + + String _timeText(CalendarEvent event) { + final startTime = event.startTime; + if (event.isAllDay || startTime == null || event.endTime == null) return _t('All day'); + return '${DateFormat('HH:mm').format(startTime.toLocal())} – ${DateFormat('HH:mm').format(event.endTime!.toLocal())}'; + } + + String _relative(int days) => + days == 1 ? _t('Tomorrow') : _t('in {n} days').replaceAll('{n}', '$days'); + + // Card with the type's colour as a stripe on the left + Widget _eventCard(CalendarEvent event, {bool today = false, int daysFromToday = 0}) { + final type = _getEventType(event); + if (type == null) return const SizedBox(); + final c = Palette.current; + final s = AppSettings.instance; + final (stripe, chipBg, chipFg) = _eventColors(type); + final hasLocation = event.location != null && event.location!.isNotEmpty; + final start = event.startTime?.toLocal(); + + return AppCard( + padding: EdgeInsets.zero, + child: IntrinsicHeight( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Container(width: 4, color: stripe), + Expanded( + child: Padding( + padding: EdgeInsets.fromLTRB(14, 12, 12, today ? 14 : 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + StatusChip(label: _eventBadgeLabel(type), color: chipFg, background: chipBg), + const Spacer(), + if (today) + StatusChip( + label: SettingsScreen.hoursBefore(s.reminderHours), + icon: Icons.notifications_none_rounded, + color: c.ink2, + background: c.tile, + ) + else + Text(_relative(daysFromToday), style: TextStyle(fontSize: 12, color: c.muted)), + ], + ), + const SizedBox(height: 8), + Text( + event.summary ?? _t('Untitled Event'), + style: TextStyle(fontSize: today ? 17 : 15.5, fontWeight: FontWeight.w700, color: c.ink), + ), + const SizedBox(height: 4), + if (today) + Wrap( + spacing: 16, + runSpacing: 4, + children: [ + _meta(Icons.schedule_rounded, _timeText(event)), + if (hasLocation) _meta(Icons.place_outlined, event.location!), + ], + ) + else + Text( + [ + if (start != null) DateFormat('EEE d. M.', s.dateLocale).format(start), + if (start != null && !event.isAllDay) DateFormat('H:mm').format(start), + if (hasLocation) event.location!, + ].join(' · '), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 12, color: c.muted), + ), + ], + ), + ), + ), + ], ), ), ); } - Widget _buildTypeChip(IconData icon, String label, Color color) { - return Container( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), - decoration: BoxDecoration( - color: color.withValues(alpha: 0.15), - borderRadius: BorderRadius.circular(20), - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Icon(icon, size: 11, color: color), - const SizedBox(width: 4), - Text(label, - style: TextStyle( - fontSize: 10, - fontWeight: FontWeight.bold, - color: color, - letterSpacing: 0.6)), - ], - ), + Widget _meta(IconData icon, String text) { + final c = Palette.current; + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 15, color: c.ink2), + const SizedBox(width: 5), + Flexible(child: Text(text, style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: c.ink2))), + ], ); } - Widget _buildSectionHeader(String label, Color dotColor, Color textColor, - {String? trailing, Color? trailingColor}) { + // Monday–Sunday of this week; today in the accent, a dot under days with events + Widget _weekStrip(DateTime today) { + final c = Palette.current; + final locale = AppSettings.instance.dateLocale; + final monday = today.subtract(Duration(days: today.weekday - 1)); + bool hasEvent(DateTime d) => _events.any((e) { + final s = e.startTime?.toLocal(); + return s != null && s.year == d.year && s.month == d.month && s.day == d.day; + }); return Row( children: [ - Container( - width: 8, - height: 8, - decoration: BoxDecoration(color: dotColor, shape: BoxShape.circle), - ), - const SizedBox(width: 8), - Text(label, - style: TextStyle( - fontSize: 12, - fontWeight: FontWeight.bold, - color: textColor, - letterSpacing: 1.4)), - if (trailing != null) ...[ - const SizedBox(width: 8), + for (int i = 0; i < 7; i++) ...[ + if (i > 0) const SizedBox(width: 6), Expanded( - child: Text( - '· $trailing', - style: TextStyle(fontSize: 12, color: trailingColor ?? textColor), - overflow: TextOverflow.ellipsis, - ), + child: Builder(builder: (_) { + final d = monday.add(Duration(days: i)); + final isToday = d == today; + final fg = isToday ? c.onAccent : c.ink; + return Container( + height: 62, + decoration: BoxDecoration( + color: isToday ? c.accent : c.card, + borderRadius: BorderRadius.circular(12), + border: isToday ? null : Border.all(color: c.line2), + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text(DateFormat('E', locale).format(d).substring(0, 1).toUpperCase(), + style: TextStyle(fontSize: 10, fontWeight: FontWeight.w600, color: isToday ? fg : c.muted)), + Text('${d.day}', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700, height: 1.2, color: fg, fontFeatures: AppTheme.tnum)), + Container( + width: 5, + height: 5, + decoration: BoxDecoration( + color: hasEvent(d) ? (isToday ? c.onAccent : c.accent) : Colors.transparent, + shape: BoxShape.circle, + ), + ), + ], + ), + ); + }), ), ], ], ); } - Widget _buildDateBlock(DateTime date, int daysFromToday, Color color) { - final locale = AppSettings.dateLocaleFor(_selectedLanguage); - final relative = daysFromToday == 1 - ? _t('Tomorrow') - : _t('in {n} days').replaceAll('{n}', '$daysFromToday'); + Widget _buildCalendarView() { + final c = Palette.current; + final now = DateTime.now(); + final today = DateTime(now.year, now.month, now.day); + final locale = AppSettings.instance.dateLocale; - return Container( - width: 56, - color: color, - padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 2), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, + DateTime dayOf(CalendarEvent e) => DateTime(e.startTime!.year, e.startTime!.month, e.startTime!.day); + + final todayEvents = _events.where((e) => e.startTime != null && dayOf(e).isAtSameMomentAs(today)).toList(); + final upcomingEvents = _events.where((e) => e.startTime != null && dayOf(e).isAfter(today)).toList(); + + return RefreshIndicator( + onRefresh: _loadEvents, + child: ListView( + physics: const AlwaysScrollableScrollPhysics(), + padding: const EdgeInsets.fromLTRB(AppTheme.edge, 0, AppTheme.edge, 24), children: [ - Text( - DateFormat('EEE', locale).format(date).toUpperCase(), - style: TextStyle( - fontSize: 10, - fontWeight: FontWeight.w700, - color: Colors.white.withValues(alpha: 0.9), - letterSpacing: 0.8), - ), - Text( - DateFormat('d').format(date), - style: const TextStyle( - fontSize: 22, - fontWeight: FontWeight.bold, - color: Colors.white, - height: 1.15), - ), - Text( - relative, - textAlign: TextAlign.center, - style: TextStyle( - fontSize: 9, - fontWeight: - daysFromToday == 1 ? FontWeight.bold : FontWeight.w500, - color: Colors.white.withValues(alpha: 0.9), - ), - ), + _weekStrip(today), + SectionHeader('${_t('TODAY')} · ${DateFormat('EEEE d. M.', locale).format(now)}'), + if (todayEvents.isEmpty) + AppCard( + padding: const EdgeInsets.all(14), + child: Row( + children: [ + Icon(Icons.event_busy_outlined, size: 18, color: c.muted), + const SizedBox(width: 10), + Text(_t('No events today'), style: TextStyle(fontSize: 13.5, color: c.muted)), + ], + ), + ) + else + for (final e in todayEvents) + Padding(padding: const EdgeInsets.only(bottom: 10), child: _eventCard(e, today: true)), + if (upcomingEvents.isNotEmpty) ...[ + SectionHeader(_t('UPCOMING')), + for (final e in upcomingEvents) + Padding( + padding: const EdgeInsets.only(bottom: 10), + child: _eventCard(e, daysFromToday: dayOf(e).difference(today).inDays), + ), + ], + if (_events.isEmpty) ...[ + const SizedBox(height: 32), + EmptyState(icon: Icons.event_available_outlined, title: _t('No upcoming events'), hint: _t('Pull down to refresh')), + ], ], ), ); } - bool _isLightBackground() { - return _backgroundColor.computeLuminance() > 0.4; - } - - Widget _buildCalendarView(Color accentColor) { - final now = DateTime.now(); - final today = DateTime(now.year, now.month, now.day); - final locale = AppSettings.dateLocaleFor(_selectedLanguage); - final isLight = _isLightBackground(); - final textPrimary = isLight ? Colors.black87 : Colors.white; - final textSecondary = isLight ? Colors.grey[700]! : Colors.grey[400]!; - final textMuted = isLight ? Colors.grey[600]! : Colors.grey[500]!; - - DateTime dayOf(CalendarEvent e) => - DateTime(e.startTime!.year, e.startTime!.month, e.startTime!.day); - - final todayEvents = _events - .where((e) => e.startTime != null && dayOf(e).isAtSameMomentAs(today)) - .toList(); - final upcomingEvents = _events - .where((e) => e.startTime != null && dayOf(e).isAfter(today)) - .toList(); - - // Build upcoming list grouped by month, each card carries its own date block - final upcomingWidgets = []; - DateTime? lastDay; - for (final e in upcomingEvents) { - final day = dayOf(e); - final isNewMonth = lastDay == null || - lastDay.month != day.month || - lastDay.year != day.year; - final isNewDay = lastDay == null || !lastDay.isAtSameMomentAs(day); - - if (isNewMonth) { - upcomingWidgets.add(Padding( - padding: EdgeInsets.fromLTRB(16, lastDay == null ? 4 : 18, 16, 8), - child: Text( - DateFormat('LLLL yyyy', locale).format(day).toUpperCase(), - style: TextStyle( - fontSize: 11, - fontWeight: FontWeight.bold, - color: textMuted, - letterSpacing: 1.5), - ), - )); - } - - upcomingWidgets.add(Padding( - padding: - EdgeInsets.fromLTRB(16, isNewDay && !isNewMonth ? 10 : 0, 16, 8), - child: _buildEventCard(e, accentColor, - date: day, daysFromToday: day.difference(today).inDays), - )); - lastDay = day; - } - - return RefreshIndicator( - onRefresh: _loadEvents, - color: accentColor, - child: ListView( - physics: const AlwaysScrollableScrollPhysics(), - children: [ - // TODAY section - Padding( - padding: const EdgeInsets.fromLTRB(16, 16, 16, 0), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - _buildSectionHeader( - _t('TODAY'), - accentColor, - textPrimary, - trailing: DateFormat('EEEE, d. MMMM', locale).format(now), - trailingColor: textSecondary, - ), - const SizedBox(height: 10), - if (todayEvents.isEmpty) - Container( - width: double.infinity, - padding: const EdgeInsets.symmetric( - vertical: 14, horizontal: 14), - decoration: BoxDecoration( - color: textMuted.withValues(alpha: 0.12), - borderRadius: BorderRadius.circular(12), - ), - child: Row( - children: [ - Icon(Icons.event_busy, size: 18, color: textMuted), - const SizedBox(width: 10), - Text(_t('No events today'), - style: - TextStyle(fontSize: 13, color: textSecondary)), - ], - ), - ) - else - ...todayEvents.map((e) => Padding( - padding: const EdgeInsets.only(bottom: 8), - child: _buildEventCard(e, accentColor, highlight: true), - )), - ], - ), - ), - - if (upcomingEvents.isNotEmpty) ...[ - Padding( - padding: const EdgeInsets.fromLTRB(16, 24, 16, 10), - child: - _buildSectionHeader(_t('UPCOMING'), textMuted, textPrimary), - ), - ...upcomingWidgets, - ], - - if (_events.isEmpty) ...[ - const SizedBox(height: 32), - Center( - child: Column( - children: [ - Icon(Icons.event_available, size: 56, color: textMuted), - const SizedBox(height: 12), - Text(_t('No upcoming events'), - style: TextStyle(fontSize: 15, color: textMuted)), - const SizedBox(height: 6), - Text(_t('Pull down to refresh'), - style: TextStyle(fontSize: 13, color: textSecondary)), - ], - ), - ), - ], - - const SizedBox(height: 24), - ], + void _showNotifications() { + final s = AppSettings.instance; + showAppSheet( + context, + title: s.t('Notifications'), + builder: (sheet) => ListenableBuilder( + listenable: s, + builder: (context, _) => GroupCard(children: SettingsScreen.notificationTiles(context)), ), ); } @override Widget build(BuildContext context) { - final accentColor = _getAccentColor(); - - if (_isLoading && _events.isEmpty) { - return Scaffold( - backgroundColor: _backgroundColor, - body: Center(child: CircularProgressIndicator(color: accentColor)), - ); - } - - if (_errorMessage != null && _events.isEmpty) { - return Scaffold( - backgroundColor: _backgroundColor, - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Icon(Icons.error_outline, size: 64, color: accentColor), - const SizedBox(height: 24), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 32), - child: Text(_errorMessage!, - textAlign: TextAlign.center, - style: TextStyle( - fontSize: 16, color: Surfaces.current.textSecondary)), + return ListenableBuilder( + listenable: AppSettings.instance, + builder: (context, _) { + Widget body; + if (_showContacts) { + body = _buildContactsList(); + } else if (_isLoading && _events.isEmpty) { + body = const Center(child: CircularProgressIndicator()); + } else if (_errorMessage != null && _events.isEmpty) { + body = Center( + child: Padding( + padding: const EdgeInsets.all(32), + child: EmptyState( + icon: Icons.cloud_off_rounded, + title: _t('Could not load the calendar'), + hint: _errorMessage, + action: SizedBox( + width: 180, + child: PrimaryButton(label: _t('Retry'), icon: Icons.refresh_rounded, height: 46, onTap: _loadEvents), + ), ), - const SizedBox(height: 16), - ElevatedButton.icon( - onPressed: _loadEvents, - icon: const Icon(Icons.refresh), - label: Text(_t('Retry')), - style: ElevatedButton.styleFrom( - backgroundColor: accentColor, - foregroundColor: Colors.white), - ), - ], - ), - ), - ); - } + ), + ); + } else { + body = _buildCalendarView(); + } - return Scaffold( - backgroundColor: _backgroundColor, - body: Column( - children: [ - BarTabs( - tabs: [ - BarTab(_t('Calendar'), Icons.calendar_month), - BarTab(_t('Contacts'), Icons.people), - ], - selected: _showContacts ? 1 : 0, - onSelect: (i) => setState(() => _showContacts = i == 1), - ), - // Body - Expanded( - child: _showContacts - ? _buildContactsList() - : _buildCalendarView(accentColor), - ), - ], - ), + return Column( + children: [ + PageHeader( + title: _t('Calendar'), + action: CircleButton(icon: Icons.notifications_none_rounded, tooltip: _t('Notifications'), onTap: _showNotifications), + ), + BarTabs( + tabs: [ + BarTab(_t('Calendar'), Icons.calendar_today_outlined), + BarTab(_t('Contacts'), Icons.person_add_alt_outlined), + ], + selected: _showContacts ? 1 : 0, + onSelect: (i) => setState(() => _showContacts = i == 1), + ), + Expanded(child: body), + ], + ); + }, ); } } diff --git a/lib/screens/camera_screen.dart b/lib/screens/camera_screen.dart index 98ba5b4..1189260 100644 --- a/lib/screens/camera_screen.dart +++ b/lib/screens/camera_screen.dart @@ -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 { Future? _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 { @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 { }); } - String _t(String key) { - return AppTranslations.translate(key, _selectedLanguage); - } - - Future _loadLanguage() async { - final prefs = await SharedPreferences.getInstance(); - setState(() { - _selectedLanguage = prefs.getString('language') ?? 'Slovenian'; - }); - } - - Future _loadSelectedTargetColor() async { - final prefs = await SharedPreferences.getInstance(); - final selectedTarget = - prefs.getString('selectedTarget') ?? 'assets/target.png'; - setState(() { - _backgroundColor = TargetColors.getBackgroundColor(selectedTarget); - }); - } - - Future _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 _loadBulletCount() async { final prefs = await SharedPreferences.getInstance(); @@ -191,6 +121,8 @@ class _CameraScreenState extends State { 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 { ), ), ); + AppSettings.instance.holdDark(); } catch (e) { debugPrint('Error taking picture: $e'); } finally { @@ -237,22 +170,25 @@ class _CameraScreenState extends State { 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 { } 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 _applyCamera(VoidCallback change, Future 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 apply( - VoidCallback change, Future Function() camera) async { - setState(change); + Future apply(VoidCallback change, Future 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 { ), 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 { @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; +} diff --git a/lib/screens/camera_settings_screen.dart b/lib/screens/camera_settings_screen.dart index 7a88b20..4cea4bf 100644 --- a/lib/screens/camera_settings_screen.dart +++ b/lib/screens/camera_settings_screen.dart @@ -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 _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'), diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dart index 22c640d..ad7d29d 100644 --- a/lib/screens/home_screen.dart +++ b/lib/screens/home_screen.dart @@ -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 { AppTab.settings: 'Settings', }; - static const Map _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 _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 { // 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 { 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]!)), ], ), ); diff --git a/lib/screens/preview_screen.dart b/lib/screens/preview_screen.dart index 9523783..6b7afc7 100644 --- a/lib/screens/preview_screen.dart +++ b/lib/screens/preview_screen.dart @@ -1,271 +1,148 @@ +import 'dart:convert'; import 'dart:io'; +import 'dart:math'; import 'dart:typed_data'; import 'dart:ui' as ui; import 'package:flutter/material.dart'; -import '../utils/target_colors.dart'; -import '../theme/app_theme.dart'; -import 'package:flutter/services.dart' show rootBundle, HapticFeedback; +import 'package:flutter/services.dart' show HapticFeedback; +import 'package:intl/intl.dart'; import 'package:path_provider/path_provider.dart'; -import 'yolo_detector.dart'; -import 'dart:convert'; // For JSON encoding -import 'dart:math'; -import 'package:shared_preferences/shared_preferences.dart'; -import '../utils/translations.dart'; +import '../services/app_settings.dart'; +import '../services/target_repository.dart'; +import '../theme/app_theme.dart'; import '../utils/target_scoring.dart'; +import '../widgets/help_sheet.dart'; +import '../widgets/section.dart'; +import '../widgets/target_face.dart'; +import '../widgets/ui.dart'; +import 'yolo_detector.dart'; +/// "Preveri zadetke": the detected hits on the chosen target design. Tap a +/// tile to pick a hit, then hold and drag on the target to move it; add or +/// remove hits; choose where to save; save. class PreviewScreen extends StatefulWidget { final String imagePath; final List detections; - final int bulletCount; // Add bulletCount parameter + final int bulletCount; - const PreviewScreen( - {super.key, - required this.imagePath, - required this.detections, - required this.bulletCount}); + const PreviewScreen({super.key, required this.imagePath, required this.detections, required this.bulletCount}); @override State createState() => _PreviewScreenState(); } -enum PreviewMode { cameraWithDetections, mappedTarget } +/// A folder to save into: an existing session or a new one. +class _SaveTarget { + final String name; + final bool isTournament; + final bool isNew; + final DateTime? date; + const _SaveTarget(this.name, this.isTournament, {this.isNew = false, this.date}); +} class _PreviewScreenState extends State { bool _isLoading = true; - PreviewMode _mode = PreviewMode.mappedTarget; + bool _showPhoto = false; // the photo with the raw detections instead of the target - List _mappedBullets = []; - late List _realImageDetections; + List _hits = []; // in target space (see TargetScoring) + int? _selected; + bool _dragging = false; + bool _saving = false; - Size? _realImageSize; // the photo; shown from its original bytes - Size? _targetImageSize; // the selected target skin - Future? _targetImageFuture; + Uint8List? _photo; + Size? _photoSize; - Uint8List? _cachedTargetImage; - Uint8List? _cachedRealImage; + // Size of the detected black (zones 7–10) on the target, for the mapping + static const Size _ringOnTarget = Size(355.94, 359.27); - late String targetAssetPath; + List _sessions = []; + bool _tournament = false; + _SaveTarget? _saveTo; - final Offset fixedRingTargetCenter = TargetScoring.center; - final Size fixedRingTargetSize = const Size(355.94, 359.27); - - // Scale factors for different target image dimensions - double _scaleFactorX = 1.0; - double _scaleFactorY = 1.0; - Size? _defaultTargetSize; // Default target for reference dimensions - - int? _highlightedBulletIndex; - - final List _manualBulletScores = []; - - Color _bulletColor = Colors.blue; // default fallback - double get _bulletOpacity => 0.8; - - bool _isEditMode = false; - int? _selectedBulletIndexInEdit; - - // Hold-and-drag on the edit controller: moves the selected bullet with the - // finger while a magnifier shows the area around it. - bool _isDragMovingBullet = false; - Offset _lastDragOffset = Offset.zero; - double _displayScaleX = 1; - double _displayScaleY = 1; - static const double _loupeSize = 130; - static const double _loupeZoom = 2.5; - - Color get _editColor => Colors.deepOrangeAccent; - Color get _activeColor => _isEditMode ? _editColor : _bulletColor; - Color get _activeColorWithOpacity => - _activeColor.withValues(alpha: _bulletOpacity); - - String _selectedLanguage = 'English'; - Color _backgroundColor = Colors.grey[900]!; - - String _currentFolderName = ''; - String _currentDate = ''; + String _t(String key) => AppSettings.instance.t(key); @override void initState() { super.initState(); - _realImageDetections = widget.detections; - targetAssetPath = 'assets/target.png'; // Default - _loadCurrentFolderInfo(); - _initializeScreen(); + _load(); } - Future _loadCurrentFolderInfo() async { + Future _load() async { + await Future.wait([_loadFolders(), _runDetectionAndMapping()]); + if (mounted) setState(() => _isLoading = false); + } + + // Default: the folder saved into last (most recently changed), like before + Future _loadFolders() async { + final sessions = await TargetRepository.loadSessions(); + final dir = Directory('${(await getApplicationDocumentsDirectory()).path}/saved_images'); + String? last; + if (await dir.exists()) { + final folders = dir.listSync().whereType().toList() + ..sort((a, b) => b.statSync().changed.compareTo(a.statSync().changed)); + if (folders.isNotEmpty) last = folders.first.path.split('/').last; + } + final lastSession = sessions.where((x) => x.name == last).firstOrNull; + _sessions = sessions; + _tournament = lastSession?.isTournament ?? false; + _saveTo = lastSession != null + ? _SaveTarget(lastSession.name, lastSession.isTournament, date: lastSession.date) + : _newFolder(_tournament); + } + + // Next "Trening 19" / "Tekmovanje 4"; numbering continues across languages + _SaveTarget _newFolder(bool tournament) { + var training = 1, tournaments = 1; + for (final x in _sessions) { + final tr = RegExp(r'^(?:Training|Trening) (\d+)$').firstMatch(x.name); + if (tr != null) training = max(training, int.parse(tr.group(1)!) + 1); + final to = RegExp(r'^(?:Tournament|Tekmovanje|Wettkampf) (\d+)$').firstMatch(x.name); + if (to != null) tournaments = max(tournaments, int.parse(to.group(1)!) + 1); + } + return tournament + ? _SaveTarget('${_t('Tournament')} $tournaments', true, isNew: true) + : _SaveTarget('${_t('Training')} $training', false, isNew: true); + } + + Future _runDetectionAndMapping() async { try { - final directory = await getApplicationDocumentsDirectory(); - final saveDirectory = Directory('${directory.path}/saved_images'); + final bytes = await File(widget.imagePath).readAsBytes(); + _photo = bytes; + _photoSize = await _imageSize(bytes); - if (await saveDirectory.exists()) { - final folders = - saveDirectory.listSync().whereType().toList(); - if (folders.isNotEmpty) { - // Sort by modification date to get the most recent folder - folders.sort( - (a, b) => b.statSync().changed.compareTo(a.statSync().changed)); - final lastFolder = folders.first.path.split('/').last; - final today = DateTime.now(); - final formattedDate = - "${today.day.toString().padLeft(2, '0')}-${today.month.toString().padLeft(2, '0')}-${today.year.toString().substring(2)}"; // DD-MM-YY format - - setState(() { - _currentFolderName = lastFolder; - _currentDate = formattedDate; - }); - } + final ring = _getRingCenterSize(widget.detections); + if (ring == null) { + debugPrint('⚠️ Ring (classId 2) not detected in real image.'); + return; } - } catch (e) { - debugPrint("Error loading current folder info: $e"); + final (ringCenter, ringSize) = ring; + + // Bullets (class 0) mapped from the photo onto the target, by the black's + // position and size + final scored = [ + for (final r in widget.detections.where((r) => r.classId == 0)) + _mapToTarget(Offset((r.x1 + r.x2) / 2, (r.y1 + r.y2) / 2), ringCenter, ringSize), + ]..sort((a, b) => TargetScoring.scoreAt(b).compareTo(TargetScoring.scoreAt(a))); + + // More found than shot: drop the highest-scoring ones (extra detections + // are usually holes counted twice in the centre) + while (scored.length > widget.bulletCount) { + scored.removeAt(0); + } + _hits = scored; + } catch (e, stack) { + debugPrint('❌ Error during detection mapping: $e'); + debugPrint(stack.toString()); + _hits = []; } } - Future _initializeScreen() async { - await Future.wait([ - _loadDefaultTarget(), // Load default target for scale reference - _loadSelectedTarget(), - _loadBulletColor(), - _loadLanguage(), - ]); - await _runDetectionAndMapping(); - } - - String _t(String key) { - return AppTranslations.translate(key, _selectedLanguage); - } - - Future _loadLanguage() async { - final prefs = await SharedPreferences.getInstance(); - setState(() { - _selectedLanguage = prefs.getString('language') ?? 'Slovenian'; - }); - } - - Future _loadDefaultTarget() async { - try { - final byteData = await rootBundle.load('assets/target.png'); - _defaultTargetSize = await _imageSize(byteData.buffer.asUint8List()); - } catch (e) { - debugPrint("❌ Error loading default target: $e"); - } - } - - Future _loadSelectedTarget() async { - final prefs = await SharedPreferences.getInstance(); - // Always load the selected/skin target for display - // This is used for background and for calculating scale factors - final selectedTarget = - prefs.getString('selectedTarget') ?? 'assets/target.png'; - - // Update the target path and trigger image load - targetAssetPath = selectedTarget; - _targetImageFuture = _loadAndDecodeTargetImage(); - _backgroundColor = _getBackgroundColorForTarget(selectedTarget); - - // Await the image decoding to ensure it's populated before rebuilding - _targetImageSize = await _targetImageFuture; - if (_targetImageSize != null) { - // Calculate scale factors based on target dimensions - _calculateScaleFactors(); - } - - setState(() { - // Trigger rebuild with the new target - }); - } - - void _calculateScaleFactors() { - if (_defaultTargetSize == null || _targetImageSize == null) { - _scaleFactorX = 1.0; - _scaleFactorY = 1.0; - return; - } - _scaleFactorX = _targetImageSize!.width / _defaultTargetSize!.width; - _scaleFactorY = _targetImageSize!.height / _defaultTargetSize!.height; - - debugPrint( - "📏 Scale factors calculated: X=$_scaleFactorX, Y=$_scaleFactorY"); - } - - // One source of truth for target colors (utils/target_colors.dart) - Color _getBackgroundColorForTarget(String targetPath) => - TargetColors.getBackgroundColor(targetPath); - - Future _loadBulletColor() async { - final prefs = await SharedPreferences.getInstance(); - final selectedColor = prefs.getString('bulletColor') ?? 'Blue'; - - setState(() { - _bulletColor = _getColorFromName(selectedColor); - }); - } - - 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 - } - } - - // Default-target position for a shot scored by hand. TargetScoring puts it - // where it scores exactly [score]; the angle spreads the hand-entered shots. - Offset _generatePositionForScore(int score) { - // Calculate angle based on which manual bullet this will be (add randomness for distribution) - final bulletIndex = _manualBulletScores.length; - final angleIncrement = 360.0 / widget.bulletCount; - final baseAngle = angleIncrement * bulletIndex; - // Add random offset within the angle increment to vary positioning - final randomOffset = (Random().nextDouble() - 0.5) * angleIncrement * 0.5; - final angle = baseAngle + randomOffset; - return TargetScoring.positionFor(score, angle * pi / 180); - } - - // Shown from the asset's own bytes; only its size is read - Future _loadAndDecodeTargetImage() async { - final byteData = await rootBundle.load(targetAssetPath); - final bytes = byteData.buffer.asUint8List(); - _cachedTargetImage = bytes; - return _imageSize(bytes); - } - // Width and height from the image header, without decoding the pixels static Future _imageSize(Uint8List bytes) async { try { final buffer = await ui.ImmutableBuffer.fromUint8List(bytes); final descriptor = await ui.ImageDescriptor.encoded(buffer); - final size = - Size(descriptor.width.toDouble(), descriptor.height.toDouble()); + final size = Size(descriptor.width.toDouble(), descriptor.height.toDouble()); descriptor.dispose(); buffer.dispose(); return size; @@ -274,1428 +151,544 @@ class _PreviewScreenState extends State { } } - Future _runDetectionAndMapping() async { - try { - // 1. Load target background image FIRST to calculate scale factors - _targetImageSize = await _targetImageFuture; - if (_targetImageSize != null) { - // Calculate scale factors based on target image dimensions - _calculateScaleFactors(); - } - - // 2. Read the real image file - final File realImageFile = File(widget.imagePath); - final realBytes = await realImageFile.readAsBytes(); - - // 3. Read its size (the header is enough; the pixels are shown as they are) - _realImageSize = await _imageSize(realBytes); - if (_realImageSize == null) { - debugPrint("❌ Failed to decode image from path: ${widget.imagePath}"); - setState(() => _isLoading = false); - return; - } - - // 4. Shown from the saved JPEG itself - _cachedRealImage = realBytes; - - // 5. Find the detected ring center and size - final ringCamData = _getRingCenterSize(_realImageDetections); - if (ringCamData == null) { - debugPrint("⚠️ Ring (classId 2) not detected in real image."); - setState(() => _isLoading = false); - return; - } - - final Offset ringCamCenter = ringCamData['center']; - final Size sizeCam = ringCamData['size']; - - // 6. Extract all bullet centers (classId 0) - final List bulletsCam = _realImageDetections - .where((r) => r.classId == 0) - .map((r) => Offset((r.x1 + r.x2) / 2, (r.y1 + r.y2) / 2)) - .toList(); - - // 7. Step 1: Map bullets to DEFAULT target coordinate system (1200x1200) - final List> scoredBullets = bulletsCam.map((bullet) { - final mappedToDefaultTarget = _mapToTargetNormalized( - bullet, - ringCamCenter, - fixedRingTargetCenter, - sizeCam, - fixedRingTargetSize, - ); - final score = _scoreForBullet(mappedToDefaultTarget); - return {'bullet': mappedToDefaultTarget, 'score': score}; - }).toList(); - - // 8. Trim to bullet limit by removing highest scoring ones - scoredBullets.sort((a, b) => b['score'].compareTo(a['score'])); - while (scoredBullets.length > widget.bulletCount) { - scoredBullets.removeAt(0); - } - - // 9. Step 2: Remap bullets from default target to actual display target - var mappedBullets = scoredBullets.map((bulletData) { - final defaultTargetBullet = bulletData['bullet'] as Offset; - // Scale bullet position based on actual target dimensions - final displayBullet = Offset( - defaultTargetBullet.dx * _scaleFactorX, - defaultTargetBullet.dy * _scaleFactorY, - ); - return displayBullet; - }).toList(); - - // 10. Update state with remapped bullets - setState(() { - _mappedBullets = mappedBullets; - _isLoading = false; - }); - } catch (e, stack) { - debugPrint("❌ Error during detection mapping: $e"); - debugPrint(stack.toString()); - setState(() { - _mappedBullets = []; - _isLoading = false; - }); - } + (Offset, Size)? _getRingCenterSize(List results) { + final ring = results.where((r) => r.classId == 2).firstOrNull; + if (ring == null) return null; + return (Offset((ring.x1 + ring.x2) / 2, (ring.y1 + ring.y2) / 2), Size(ring.x2 - ring.x1, ring.y2 - ring.y1)); } - void _showMissingBulletDialog(int bulletNum) { - showDialog( - context: context, - builder: (context) { - return Dialog( - backgroundColor: Colors.grey[900], - shape: - RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), - child: Padding( - padding: const EdgeInsets.all(24.0), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Text( - '${_t('Bullet')} $bulletNum - ${_t('Bullet Score')}', - style: const TextStyle( - color: Colors.white, - fontSize: 20, - fontWeight: FontWeight.bold, - ), - ), - const SizedBox(height: 24), - // Score buttons 1-9 in 3x3 grid - GridView.count( - crossAxisCount: 3, - shrinkWrap: true, - mainAxisSpacing: 12, - crossAxisSpacing: 12, - childAspectRatio: 1.0, - children: List.generate(9, (scoreIndex) { - final score = 9 - scoreIndex; - return ElevatedButton( - onPressed: () { - final bulletPosition = _generatePositionForScore(score); - // Scale position from default coordinate system to display target size - final scaledBulletPosition = Offset( - bulletPosition.dx * _scaleFactorX, - bulletPosition.dy * _scaleFactorY, - ); - - setState(() { - _mappedBullets.add(scaledBulletPosition); - _manualBulletScores.add(score); - _isEditMode = true; - _selectedBulletIndexInEdit = - _mappedBullets.length - 1; - }); - - Navigator.pop(context); - }, - style: ElevatedButton.styleFrom( - backgroundColor: _bulletColor, - foregroundColor: Colors.white, - padding: EdgeInsets.zero, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(12), - ), - ), - child: Text( - '$score', - style: const TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, - ), - ), - ); - }), - ), - const SizedBox(height: 12), - // Bottom row with 0 and 10 - Row( - children: [ - Expanded( - child: ElevatedButton( - onPressed: () { - final score = 0; - final bulletPosition = - _generatePositionForScore(score); - // Scale position from default coordinate system to display target size - final scaledBulletPosition = Offset( - bulletPosition.dx * _scaleFactorX, - bulletPosition.dy * _scaleFactorY, - ); - - setState(() { - _mappedBullets.add(scaledBulletPosition); - _manualBulletScores.add(score); - _isEditMode = true; - _selectedBulletIndexInEdit = - _mappedBullets.length - 1; - }); - - Navigator.pop(context); - }, - style: ElevatedButton.styleFrom( - backgroundColor: Colors.grey[600], - foregroundColor: Colors.white, - padding: const EdgeInsets.symmetric(vertical: 16), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(12), - ), - ), - child: const Text( - '0', - style: TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, - ), - ), - ), - ), - const SizedBox(width: 12), - Expanded( - child: ElevatedButton( - onPressed: () { - final score = 10; - final bulletPosition = - _generatePositionForScore(score); - // Scale position from default coordinate system to display target size - final scaledBulletPosition = Offset( - bulletPosition.dx * _scaleFactorX, - bulletPosition.dy * _scaleFactorY, - ); - - setState(() { - _mappedBullets.add(scaledBulletPosition); - _manualBulletScores.add(score); - _isEditMode = true; - _selectedBulletIndexInEdit = - _mappedBullets.length - 1; - }); - - Navigator.pop(context); - }, - style: ElevatedButton.styleFrom( - backgroundColor: Colors.grey[600], - foregroundColor: Colors.white, - padding: const EdgeInsets.symmetric(vertical: 16), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(12), - ), - ), - child: const Text( - '10', - style: TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, - ), - ), - ), - ), - ], - ), - ], - ), - ), - ); - }, + Offset _mapToTarget(Offset bulletCam, Offset ringCam, Size sizeCam) { + final scaleX = _ringOnTarget.width / sizeCam.width; + final scaleY = _ringOnTarget.height / sizeCam.height; + return Offset( + (bulletCam.dx - ringCam.dx) * scaleX + TargetScoring.center.dx, + (bulletCam.dy - ringCam.dy) * scaleY + TargetScoring.center.dy, ); } - Future _getLastFolder() async { - final directory = await getApplicationDocumentsDirectory(); - final saveDirectory = Directory('${directory.path}/saved_images'); + int _scoreAt(int i) => TargetScoring.scoreAt(_hits[i]); + int get _total => [for (int i = 0; i < _hits.length; i++) _scoreAt(i)].fold(0, (a, b) => a + b); - if (!await saveDirectory.exists()) { - return null; - } - - final folders = saveDirectory.listSync().whereType().toList(); - if (folders.isEmpty) { - return null; - } - - folders - .sort((a, b) => b.statSync().changed.compareTo(a.statSync().changed)); - return folders.first.path.split('/').last; + // A hand-entered shot goes where it scores exactly [score]; the angle spreads them + Offset _positionForScore(int score) { + final step = 360.0 / widget.bulletCount; + final angle = step * _hits.length + (Random().nextDouble() - 0.5) * step * 0.5; + return TargetScoring.positionFor(score, angle * pi / 180); } - Future _saveToLastFolder() async { - try { - final lastFolder = await _getLastFolder(); - if (lastFolder == null) { - // No last folder, show options dialog - _saveTargetDataWithDialog(); - return; - } - - await _performSave(lastFolder, false); - } catch (e) { - debugPrint("Error saving to last folder: $e"); - } + void _addHit() { + if (_hits.length >= widget.bulletCount) return; + final c = Palette.current; + showAppSheet( + context, + title: _t('Add hit'), + subtitle: _t('Its value; then drag it to where it hit.'), + builder: (sheet) => GridView.count( + crossAxisCount: 4, + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + mainAxisSpacing: 10, + crossAxisSpacing: 10, + childAspectRatio: 1.25, + children: [ + for (final score in [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) + Material( + color: score == 10 ? c.goldSoft : c.tile, + borderRadius: BorderRadius.circular(14), + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: () { + Navigator.pop(sheet); + setState(() { + _hits.add(_positionForScore(score)); + _selected = _hits.length - 1; + }); + }, + child: Center( + child: Text('$score', + style: TextStyle( + fontSize: 22, + fontWeight: FontWeight.w700, + color: score == 10 ? (c.isDark ? c.goldInk : c.goldInk) : c.ink, + fontFeatures: AppTheme.tnum)), + ), + ), + ), + ], + ), + ); } - Future _saveTargetDataWithDialog() async { - try { - // Show a dialog to let the user select between a new folder or an existing one - final result = await _showSaveOptionsDialog(); - - if (result == null) return; - - String? selectedFolder; - bool isTournament = false; - - try { - final decoded = jsonDecode(result); - selectedFolder = decoded['folder']; - isTournament = decoded['isTournament'] == true; - } catch (_) { - selectedFolder = - result; // Treat plain string as folder name (existing folder) - } - - if (selectedFolder == null) return; - - await _performSave(selectedFolder, isTournament); - } catch (e) { - debugPrint("Error saving target data: $e"); - } + void _removeHit() { + final i = _selected; + if (i == null) return; + setState(() { + _hits.removeAt(i); + _selected = null; + }); } - Future _performSave(String selectedFolder, bool isTournament) async { + void _moveSelected(Offset delta) { + final i = _selected; + if (i == null) return; + setState(() { + final p = _hits[i] + delta; + // Keep it on the canvas + _hits[i] = Offset(p.dx.clamp(0, TargetScoring.size), p.dy.clamp(0, TargetScoring.size)); + }); + } + + void _pickFolder() { + final c = Palette.current; + final kind = [for (final x in _sessions) if (x.isTournament == _tournament) x]; + final fresh = _newFolder(_tournament); + showAppSheet( + context, + title: _t('Save to folder'), + subtitle: _t(_tournament ? 'Tournaments' : 'Trainings'), + builder: (sheet) => Column( + children: [ + SheetOption( + label: fresh.name, + subtitle: _t('New folder'), + leading: IconBadge(Icons.create_new_folder_outlined, size: 34), + selected: _saveTo?.isNew == true && _saveTo?.name == fresh.name, + showDivider: false, + onTap: () { + Navigator.pop(sheet); + setState(() => _saveTo = fresh); + }, + ), + for (final x in kind.take(20)) + SheetOption( + label: x.name, + subtitle: '${DateFormat('d. M. yyyy').format(x.date)} · ${x.targets.length}', + leading: Icon(Icons.folder_outlined, color: c.muted), + selected: _saveTo?.name == x.name && _saveTo?.isNew != true, + onTap: () { + Navigator.pop(sheet); + setState(() => _saveTo = _SaveTarget(x.name, x.isTournament, date: x.date)); + }, + ), + ], + ), + ); + } + + void _setKind(bool tournament) { + if (tournament == _tournament) return; + setState(() { + _tournament = tournament; + // Latest folder of that kind, or a new one + final latest = _sessions.where((x) => x.isTournament == tournament).firstOrNull; + _saveTo = latest == null ? _newFolder(tournament) : _SaveTarget(latest.name, tournament, date: latest.date); + }); + } + + Future _save() async { + final to = _saveTo; + if (to == null || _saving) return; + setState(() => _saving = true); try { final directory = await getApplicationDocumentsDirectory(); - final saveDirectory = - Directory('${directory.path}/saved_images/$selectedFolder'); - - // Create folder if it doesn't exist + final saveDirectory = Directory('${directory.path}/saved_images/${to.name}'); if (!await saveDirectory.exists()) { await saveDirectory.create(recursive: true); - } - - // Save tournament metadata if applicable - if (isTournament) { - final metadataFile = File('${saveDirectory.path}/metadata.json'); - await metadataFile.writeAsString(jsonEncode({'isTournament': true})); + await File('${saveDirectory.path}/metadata.json').writeAsString(jsonEncode({ + 'isTournament': to.isTournament, + 'createdAt': DateTime.now().toIso8601String(), + })); } // Use timestamp for a unique file name final now = DateTime.now(); - final dateString = - "${now.day.toString().padLeft(2, '0')}/${now.month.toString().padLeft(2, '0')}/${now.year}"; - final dateStringFile = "${now.year}-${now.month}-${now.day}"; - final timeString = "${now.hour}-${now.minute}-${now.second}"; - final fileName = "target_${dateStringFile}_$timeString.json"; - final filePath = '${saveDirectory.path}/$fileName'; + final dateString = "${now.day.toString().padLeft(2, '0')}/${now.month.toString().padLeft(2, '0')}/${now.year}"; + final fileName = 'target_${now.year}-${now.month}-${now.day}_${now.hour}-${now.minute}-${now.second}.json'; + final scores = [for (int i = 0; i < _hits.length; i++) _scoreAt(i)]; - // Prepare target data to save - // Convert bullets from display coordinates back to default target coordinates (1200x1200) - final bulletsInDefaultCoordinates = _mappedBullets.map((b) { - return { - 'x': b.dx / _scaleFactorX, - 'y': b.dy / _scaleFactorY, - }; - }).toList(); - - // Score of every saved bullet, in the same order: hand-entered shots - // keep the score that was entered. The target view shows these as saved. - final scores = [for (int i = 0; i < _mappedBullets.length; i++) _scoreAt(i)]; - - final targetData = { + await File('${saveDirectory.path}/$fileName').writeAsString(jsonEncode({ 'date': dateString, 'totalScore': scores.fold(0, (a, b) => a + b), - 'bulletCount': widget - .bulletCount, // shots fired; missed ones are absent from 'bullets' - 'bullets': bulletsInDefaultCoordinates, + 'bulletCount': widget.bulletCount, // shots fired; missed ones are absent from 'bullets' + 'bullets': [for (final b in _hits) {'x': b.dx, 'y': b.dy}], 'scores': scores, - }; + })); + TargetRepository.notifyChanged(); - // Write file - final jsonFile = File(filePath); - await jsonFile.writeAsString(jsonEncode(targetData)); - - // Close preview and signal refresh if (!mounted) return; Navigator.pop(context, true); } catch (e) { - debugPrint("Error performing save: $e"); + debugPrint('Error performing save: $e'); + if (mounted) setState(() => _saving = false); } } - /// Score of the bullet at [index], live for manual and detected bullets. - int _scoreAt(int index) { - final manualStart = _mappedBullets.length - _manualBulletScores.length; - if (index >= manualStart) { - return _manualBulletScores[index - manualStart]; - } - final b = _mappedBullets[index]; - return _scoreForBullet(Offset(b.dx / _scaleFactorX, b.dy / _scaleFactorY)); - } - - Widget _buildEditController() { - final index = _selectedBulletIndexInEdit; - if (!_isEditMode || index == null || index >= _mappedBullets.length) { - return const SizedBox.shrink(); - } - - final s = Surfaces.current; - final accent = _bulletColor; - final dragging = _isDragMovingBullet; - const padSize = 156.0; - const step = 3.0; - - Widget arrow(IconData icon, Offset delta, Alignment align) { - return Align( - alignment: align, - child: Material( - color: Colors.transparent, - shape: const CircleBorder(), - clipBehavior: Clip.antiAlias, - child: InkWell( - onTap: () => _moveBullet(delta), - child: SizedBox( - width: 52, - height: 52, - child: Icon(icon, size: 34, color: s.textPrimary), - ), - ), - ), - ); - } - - return Positioned( - bottom: 20, - left: 0, - right: 0, - child: Center( - child: GestureDetector( - // Hold anywhere on the controller, then drag to move the bullet fast - onLongPressStart: (_) { - HapticFeedback.mediumImpact(); - setState(() { - _isDragMovingBullet = true; - _lastDragOffset = Offset.zero; - }); - }, - onLongPressMoveUpdate: (details) { - final delta = details.offsetFromOrigin - _lastDragOffset; - _lastDragOffset = details.offsetFromOrigin; - // Finger movement on screen = bullet movement on screen - _moveBullet(Offset( - delta.dx / _displayScaleX, - delta.dy / _displayScaleY, - )); - }, - onLongPressEnd: (_) => setState(() => _isDragMovingBullet = false), - onLongPressCancel: () => setState(() => _isDragMovingBullet = false), - child: AnimatedContainer( - duration: const Duration(milliseconds: 150), - width: 200, - decoration: BoxDecoration( - color: s.card, - borderRadius: BorderRadius.circular(20), - border: Border.all( - color: dragging ? accent : Colors.transparent, - width: 2, - ), - boxShadow: const [ - BoxShadow( - color: Colors.black38, - offset: Offset(0, 4), - blurRadius: 12, - ), - ], - ), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - // Header: which bullet, and its live score - Padding( - padding: const EdgeInsets.fromLTRB(16, 12, 12, 4), - child: Row( - children: [ - Text( - '${_t('Bullet')} ${index + 1}'.toUpperCase(), - style: TextStyle( - fontSize: 12, - fontWeight: FontWeight.bold, - letterSpacing: 1.4, - color: s.textSecondary, - ), - ), - const Spacer(), - Container( - constraints: const BoxConstraints(minWidth: 36), - padding: const EdgeInsets.symmetric( - horizontal: 10, vertical: 4), - decoration: BoxDecoration( - color: accent, - borderRadius: BorderRadius.circular(10), - ), - alignment: Alignment.center, - child: Text( - '${_scoreAt(index)}', - style: const TextStyle( - color: Colors.white, - fontSize: 16, - fontWeight: FontWeight.bold, - ), - ), - ), - ], - ), - ), - // Round d-pad with "done" in the middle - Padding( - padding: const EdgeInsets.symmetric(vertical: 8), - child: Container( - width: padSize, - height: padSize, - decoration: BoxDecoration( - shape: BoxShape.circle, - color: s.textPrimary.withValues(alpha: 0.06), - border: Border.all(color: s.divider), - ), - child: Stack( - children: [ - arrow(Icons.keyboard_arrow_up_rounded, - const Offset(0, -step), Alignment.topCenter), - arrow(Icons.keyboard_arrow_down_rounded, - const Offset(0, step), Alignment.bottomCenter), - arrow(Icons.keyboard_arrow_left_rounded, - const Offset(-step, 0), Alignment.centerLeft), - arrow(Icons.keyboard_arrow_right_rounded, - const Offset(step, 0), Alignment.centerRight), - Center( - child: Material( - color: accent, - shape: const CircleBorder(), - elevation: 2, - child: InkWell( - customBorder: const CircleBorder(), - onTap: () => setState( - () => _selectedBulletIndexInEdit = null), - child: SizedBox( - width: 52, - height: 52, - child: Icon( - dragging - ? Icons.open_with_rounded - : Icons.check_rounded, - color: Colors.white, - size: 28, - ), - ), - ), - ), - ), - ], - ), - ), - ), - Padding( - padding: const EdgeInsets.only(bottom: 12), - child: Text( - _t('Hold and drag to move'), - style: TextStyle(fontSize: 11, color: s.textSecondary), - ), - ), - ], - ), - ), - ), - ), - ); - } - - /// Magnifier shown above the selected bullet while it is being dragged. - Widget _buildBulletLoupe(Offset bullet, double scaleX, double scaleY, - double offsetX, double offsetY) { - final bx = bullet.dx * scaleX + offsetX; - final by = bullet.dy * scaleY + offsetY; - const gap = _loupeSize / 2 + 40; - // Put the loupe above the bullet, or below it when there is no room. - final cy = by - gap - _loupeSize / 2 >= 0 ? by - gap : by + gap; - return Positioned( - left: bx - _loupeSize / 2, - top: cy - _loupeSize / 2, - child: IgnorePointer( - child: RawMagnifier( - size: const Size(_loupeSize, _loupeSize), - magnificationScale: _loupeZoom, - focalPointOffset: Offset(0, by - cy), - decoration: const MagnifierDecoration( - shape: CircleBorder( - side: BorderSide(color: Colors.white, width: 3), - ), - shadows: [BoxShadow(color: Colors.black54, blurRadius: 8)], - ), - child: const Center( - child: Icon(Icons.add, color: Colors.red, size: 24), - ), - ), - ), - ); - } - - void _moveBullet(Offset offsetDelta) { - setState(() { - final index = _selectedBulletIndexInEdit!; - final current = _mappedBullets[index]; - final updated = current + offsetDelta; - - _mappedBullets[index] = updated; - - // If this is a manually added bullet, update its score live - final manualStartIndex = - _mappedBullets.length - _manualBulletScores.length; - if (index >= manualStartIndex) { - // Scale bullet back to default coordinate system for scoring - final defaultTargetBullet = Offset( - updated.dx / _scaleFactorX, - updated.dy / _scaleFactorY, - ); - final updatedScore = _scoreForBullet(defaultTargetBullet); - _manualBulletScores[index - manualStartIndex] = updatedScore; - } - }); - } - - Future _showSaveOptionsDialog() async { - final directory = await getApplicationDocumentsDirectory(); - final saveDirectory = Directory('${directory.path}/saved_images'); - - if (!await saveDirectory.exists()) { - await saveDirectory.create(recursive: true); - } - - final folders = saveDirectory.listSync().whereType().toList(); - - // Sort to get most recently modified - folders - .sort((a, b) => b.statSync().changed.compareTo(a.statSync().changed)); - - // Auto-generate next Training and Tournament folder names - int trainingCount = 1; - int tournamentCount = 1; - - // Get localized folder names - final trainingWord = _t('Training'); - final tournamentWord = _t('Tournament'); - - for (var folder in folders) { - final name = folder.path.split('/').last; - // Numbering continues across languages (English, Slovenian, German names) - final training = RegExp(r'^(?:Training|Trening) (\d+)$').firstMatch(name); - if (training != null) { - final num = int.parse(training.group(1)!); - if (num >= trainingCount) trainingCount = num + 1; - } - final tournament = RegExp(r'^(?:Tournament|Tekmovanje|Wettkampf) (\d+)$') - .firstMatch(name); - if (tournament != null) { - final num = int.parse(tournament.group(1)!); - if (num >= tournamentCount) tournamentCount = num + 1; - } - } - - final String nextTraining = '$trainingWord $trainingCount'; - final String nextTournament = '$tournamentWord $tournamentCount'; - - if (!mounted) return null; - return showDialog( - context: context, - builder: (context) { - return Dialog( - backgroundColor: Colors.grey[900], - shape: - RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), - child: Padding( - padding: const EdgeInsets.all(24), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Text( - _t('Save Target Data'), - style: const TextStyle( - color: Colors.white, - fontSize: 20, - fontWeight: FontWeight.bold, - ), - ), - const SizedBox(height: 24), - - // 🎯 Training Button (New folder) - SizedBox( - width: double.infinity, - child: ElevatedButton( - onPressed: () { - Navigator.pop( - context, - jsonEncode( - {'folder': nextTraining, 'isTournament': false}), - ); - }, - style: ElevatedButton.styleFrom( - backgroundColor: _bulletColor, - foregroundColor: Colors.white, - padding: const EdgeInsets.symmetric(vertical: 16), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(12), - ), - ), - child: Column( - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.center, - mainAxisSize: MainAxisSize.min, - children: [ - const Icon(Icons.track_changes, - size: 16, color: Colors.white), - const SizedBox(width: 8), - Text( - nextTraining, - style: const TextStyle( - fontWeight: FontWeight.bold, - fontSize: 16, - color: Colors.white), - ), - ], - ), - const SizedBox(height: 4), - Text( - _t('New folder'), - style: const TextStyle( - fontSize: 12, color: Colors.white70), - ), - ], - ), - ), - ), - const SizedBox(height: 12), - - // 🏆 Tournament Button (New folder) - SizedBox( - width: double.infinity, - child: ElevatedButton( - onPressed: () { - Navigator.pop( - context, - jsonEncode( - {'folder': nextTournament, 'isTournament': true}), - ); - }, - style: ElevatedButton.styleFrom( - backgroundColor: _bulletColor, - foregroundColor: Colors.white, - padding: const EdgeInsets.symmetric(vertical: 16), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(12), - ), - ), - child: Column( - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.center, - mainAxisSize: MainAxisSize.min, - children: [ - const Icon(Icons.emoji_events, - size: 16, color: Colors.white), - const SizedBox(width: 8), - Text( - nextTournament, - style: const TextStyle( - fontWeight: FontWeight.bold, - fontSize: 16, - color: Colors.white), - ), - ], - ), - const SizedBox(height: 4), - Text( - _t('New folder'), - style: const TextStyle( - fontSize: 12, color: Colors.white70), - ), - ], - ), - ), - ), - ], - ), - ), - ); - }, - ); - } - - Map? _getRingCenterSize(List results) { - try { - final ring = results.firstWhere((r) => r.classId == 2); - final cx = (ring.x1 + ring.x2) / 2; - final cy = (ring.y1 + ring.y2) / 2; - final width = ring.x2 - ring.x1; - final height = ring.y2 - ring.y1; - return { - 'center': Offset(cx, cy), - 'size': Size(width, height), - }; - } catch (_) { - return null; - } - } - - Offset _mapToTargetNormalized(Offset bulletCam, Offset ringCam, - Offset ringTarget, Size sizeCam, Size sizeTarget) { - // Calculate scale factor between detected ring and target ring - final scaleX = sizeTarget.width / sizeCam.width; - final scaleY = sizeTarget.height / sizeCam.height; - - // Translate bullet position relative to ring center - final relativeX = bulletCam.dx - ringCam.dx; - final relativeY = bulletCam.dy - ringCam.dy; - - // Scale the relative position and map to target - final mappedX = (relativeX * scaleX) + ringTarget.dx; - final mappedY = (relativeY * scaleY) + ringTarget.dy; - - return Offset(mappedX, mappedY); - } - - // Bullet in default target coordinates - int _scoreForBullet(Offset bullet) => TargetScoring.scoreAt(bullet); - - int get _totalScore { - // Score is based on the default target coordinate system (1200x1200) - // since bullets were mapped to that system and then scaled for display - // Manual bullets are appended after the detected ones and scored below, - // so take only the detected ones here (at most the remaining shot slots). - final detected = _mappedBullets.length - _manualBulletScores.length; - final autoScore = _mappedBullets - .take(min(detected, widget.bulletCount - _manualBulletScores.length)) - .map((b) { - // Scale bullet back to default coordinate system for scoring - final defaultTargetBullet = Offset( - b.dx / _scaleFactorX, - b.dy / _scaleFactorY, - ); - return _scoreForBullet(defaultTargetBullet); - }).fold(0, (sum, score) => sum + score); - - final manualScore = _manualBulletScores.fold(0, (a, b) => a + b); - - return autoScore + manualScore; - } - - Color _getBulletButtonColor(int index) { - final isSelected = _isEditMode - ? index == _selectedBulletIndexInEdit - : index == _highlightedBulletIndex; - - if (isSelected) return Colors.red; - - final manualStart = _mappedBullets.length - _manualBulletScores.length; - final isManual = index >= manualStart; - - if (isManual) return Colors.redAccent; // ⬅️ Light red for manual bullets - - if (_isEditMode) return _editColor; - - return _bulletColor; + void _showHelp() { + showHelpSheet(context, t: _t, items: const [ + (Icons.touch_app_outlined, 'Tap a value below to pick that hit; it gets a red border.'), + (Icons.open_with_rounded, 'Hold and drag on the target to move the picked hit; a magnifier shows where it is.'), + (Icons.add_rounded, 'Add hit: for a shot that was not found. Remove hit: deletes the picked one.'), + (Icons.folder_outlined, 'Save to: training or tournament, and which folder. The last one is chosen for you.'), + (Icons.photo_outlined, 'Photo icon: see the photo with what was detected.'), + ]); } @override Widget build(BuildContext context) { + final s = AppSettings.instance; + final c = Palette.current; + final found = widget.detections.where((r) => r.classId == 0).length; return Scaffold( - backgroundColor: _backgroundColor, - appBar: AppBar( - backgroundColor: Colors.grey[900], - iconTheme: const IconThemeData(color: Colors.white), - title: Text( - _t('Detection Preview'), - style: const TextStyle(color: Colors.white), - ), - actions: [ - IconButton( - icon: Icon( - _mode == PreviewMode.mappedTarget - ? Icons.camera_alt - : Icons.center_focus_strong, - color: Colors.white, - size: 24, - ), - onPressed: () async { - setState(() { - _mode = _mode == PreviewMode.mappedTarget - ? PreviewMode.cameraWithDetections - : PreviewMode.mappedTarget; - }); - await _loadSelectedTarget(); - }, - tooltip: _mode == PreviewMode.mappedTarget - ? _t("Show Camera Detections") - : _t("Show Mapped Target"), + body: Column( + children: [ + BackHeader( + title: _t('Check hits'), + subtitle: _t('{n} hits detected · correct them if needed').replaceAll('{n}', '${min(found, widget.bulletCount)}'), + actions: [CircleButton(icon: Icons.info_outline_rounded, onTap: _showHelp)], ), - const SizedBox(width: 8), + if (_isLoading) + const Expanded(child: Center(child: CircularProgressIndicator())) + else ...[ + Padding( + padding: const EdgeInsets.fromLTRB(AppTheme.edge, 4, AppTheme.edge, 0), + child: _saveCard(c), + ), + Expanded( + child: Stack( + children: [ + Positioned.fill(child: _showPhoto ? _photoView(c) : _targetView(s, c)), + // The photo with what the model saw, for checking + Positioned( + top: 8, + right: AppTheme.edge, + child: CircleButton( + icon: _showPhoto ? Icons.track_changes_rounded : Icons.photo_outlined, + size: 36, + iconSize: 18, + tooltip: _t(_showPhoto ? 'Show Mapped Target' : 'Show Camera Detections'), + onTap: () => setState(() => _showPhoto = !_showPhoto), + ), + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(AppTheme.edge, 0, AppTheme.edge, 0), + child: _tiles(c), + ), + Padding( + padding: const EdgeInsets.fromLTRB(AppTheme.edge, 12, AppTheme.edge, 0), + child: Row( + children: [ + Expanded( + child: SoftButton( + label: _t('Add hit'), + icon: Icons.add_rounded, + onTap: _hits.length < widget.bulletCount ? _addHit : null, + ), + ), + const SizedBox(width: 10), + Expanded( + child: SoftButton( + label: _t('Remove hit'), + icon: Icons.delete_outline_rounded, + destructive: _selected != null, + onTap: _selected == null ? null : _removeHit, + ), + ), + ], + ), + ), + Padding( + padding: EdgeInsets.fromLTRB(AppTheme.edge, 16, AppTheme.edge, 12 + MediaQuery.paddingOf(context).bottom), + child: PrimaryButton( + label: '${_t('Save target')} · $_total', + icon: Icons.check_rounded, + busy: _saving, + onTap: _save, + ), + ), + ], ], ), - body: _isLoading - ? const Center(child: CircularProgressIndicator()) - : Stack( - children: [ - Column( + ); + } + + Widget _saveCard(Palette c) { + final to = _saveTo; + final when = to == null + ? '' + : to.isNew + ? _t('new') + : DateUtils.isSameDay(to.date, DateTime.now()) + ? '${_t('today')} ${DateFormat('HH:mm').format(to.date!)}' + : DateFormat('d. M.').format(to.date ?? DateTime.now()); + return AppCard( + padding: const EdgeInsets.fromLTRB(12, 12, 12, 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Kicker(_t('Save to'), padding: const EdgeInsets.only(left: 2, bottom: 8)), + SegmentedTabs( + height: 40, + items: [SegmentItem(_t('Training')), SegmentItem(_t('Tournament'))], + selected: _tournament ? 1 : 0, + onSelect: (i) => _setKind(i == 1), + ), + const SizedBox(height: 8), + Material( + color: c.isDark ? c.card : c.card, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12), side: BorderSide(color: c.line)), + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: _pickFolder, + child: SizedBox( + height: 42, + child: Row( children: [ - // Training/Tournament Banner - Container( - color: Surfaces.current.card, - padding: const EdgeInsets.symmetric( - horizontal: 16, vertical: 10), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Expanded( - child: Text( - _currentFolderName.isNotEmpty - ? _currentFolderName - : _t('No training selected'), - style: TextStyle( - color: Surfaces.current.textPrimary, - fontSize: 13, - fontWeight: FontWeight.w600, - ), - overflow: TextOverflow.ellipsis, - ), - ), - if (_currentDate.isNotEmpty) - Text( - _currentDate, - style: TextStyle( - color: Surfaces.current.textPrimary, - fontSize: 11, - ), - ), - ], - ), + const SizedBox(width: 12), + Icon(Icons.folder_outlined, size: 18, color: c.accent), + const SizedBox(width: 10), + Flexible( + child: Text(to?.name ?? '', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: c.ink)), ), - Expanded( - child: LayoutBuilder( - builder: (context, constraints) { - final screenWidth = constraints.maxWidth; - final screenHeight = constraints.maxHeight; - - final displayImage = _mode == PreviewMode.mappedTarget - ? _cachedTargetImage - : _cachedRealImage; - - final imgData = _mode == PreviewMode.mappedTarget - ? _targetImageSize - : _realImageSize; - - if (displayImage == null || imgData == null) { - return const Center( - child: Text("Image not available")); - } - - final imgWidth = imgData.width.toDouble(); - final imgHeight = imgData.height.toDouble(); - final aspectRatio = imgWidth / imgHeight; - final screenAspect = screenWidth / screenHeight; - - double displayWidth, displayHeight, offsetX, offsetY; - - if (aspectRatio > screenAspect) { - displayWidth = screenWidth; - displayHeight = screenWidth / aspectRatio; - offsetX = 0; - offsetY = (screenHeight - displayHeight) / 2; - } else { - displayHeight = screenHeight; - displayWidth = screenHeight * aspectRatio; - offsetY = 0; - offsetX = (screenWidth - displayWidth) / 2; - } - - final scaleX = displayWidth / imgWidth; - final scaleY = displayHeight / imgHeight; - _displayScaleX = scaleX; - _displayScaleY = scaleY; - - final imageWidget = - Image.memory(displayImage, fit: BoxFit.fill); - - return Stack( - children: [ - Positioned( - left: offsetX, - top: offsetY, - width: displayWidth, - height: displayHeight, - child: imageWidget, - ), - if (_mode == PreviewMode.cameraWithDetections) - ..._realImageDetections.map((d) { - final left = d.x1 * scaleX + offsetX; - final top = d.y1 * scaleY + offsetY; - final width = (d.x2 - d.x1) * scaleX; - final height = (d.y2 - d.y1) * scaleY; - return Positioned( - left: left, - top: top, - width: width, - height: height, - child: Container( - decoration: BoxDecoration( - border: Border.all( - color: Colors.green, width: 2), - ), - child: Align( - alignment: Alignment.topLeft, - child: Container( - color: Colors.green - .withValues(alpha: 0.5), - padding: const EdgeInsets.symmetric( - horizontal: 4, vertical: 2), - child: Text( - "ID:${d.classId} ${(d.confidence * 100).toStringAsFixed(1)}%", - style: const TextStyle( - color: Colors.white, - fontSize: 12, - fontWeight: FontWeight.bold, - ), - ), - ), - ), - ), - ); - }), - if (_mode == PreviewMode.mappedTarget) - ..._mappedBullets - .asMap() - .entries - .take(widget.bulletCount) - .map((entry) { - final index = entry.key; - final b = entry.value; - final dx = b.dx * scaleX + offsetX; - final dy = b.dy * scaleY + offsetY; - // Scale bullet size by target scale factors and display scale factors - final double bulletSize = - (((_scaleFactorX + _scaleFactorY) / 2) * - 53) * - ((scaleX + scaleY) / 2); - - final isHighlighted = - index == _highlightedBulletIndex; - final isSelectedForEdit = - index == _selectedBulletIndexInEdit; - final manualStart = _mappedBullets.length - - _manualBulletScores.length; - final isManual = index >= manualStart; - - final Color bulletFillColor = - isSelectedForEdit || - (!_isEditMode && isHighlighted) - ? Colors.red.withValues( - alpha: _bulletOpacity) - : isManual - ? Colors.red.withValues( - alpha: _bulletOpacity) - : _activeColorWithOpacity; - - return Positioned( - left: dx - bulletSize / 2, - top: dy - bulletSize / 2, - child: Container( - width: bulletSize, - height: bulletSize, - decoration: BoxDecoration( - color: bulletFillColor, - shape: BoxShape.circle, - border: Border.all( - color: (isSelectedForEdit || - (!_isEditMode && - isHighlighted)) - ? Colors.red - : Colors.black, - width: (isSelectedForEdit || - (!_isEditMode && - isHighlighted)) - ? 3 - : 1, - ), - ), - ), - ); - }), - if (_mode == PreviewMode.mappedTarget && - _isDragMovingBullet && - _selectedBulletIndexInEdit != null && - _selectedBulletIndexInEdit! < - _mappedBullets.length) - _buildBulletLoupe( - _mappedBullets[_selectedBulletIndexInEdit!], - scaleX, - scaleY, - offsetX, - offsetY, - ), - ], - ); - }, - ), - ), - const SizedBox(height: 24), - // Shown even with no detections, so missed shots can be scored by hand - if (widget.bulletCount > 0) - Column( - children: [ - // Score buttons for detected and missing bullets - Padding( - padding: const EdgeInsets.symmetric( - horizontal: 12, vertical: 6), - child: AbsorbPointer( - absorbing: _isEditMode && - _selectedBulletIndexInEdit != null, - child: Row( - children: [ - // Detected bullets - ...List.generate( - _mappedBullets.length, - (index) { - final bullet = _mappedBullets[index]; - final isManual = index >= - (_mappedBullets.length - - _manualBulletScores.length); - final score = isManual - ? _manualBulletScores[index - - (_mappedBullets.length - - _manualBulletScores.length)] - // Convert bullet back to default coordinate system for scoring - : _scoreForBullet(Offset( - bullet.dx / _scaleFactorX, - bullet.dy / _scaleFactorY, - )); - - return Expanded( - child: Padding( - padding: const EdgeInsets.symmetric( - horizontal: 6), - child: GestureDetector( - onTap: () { - if (_isEditMode) { - setState(() => - _selectedBulletIndexInEdit = - index); - } - }, - onTapDown: (_) { - if (!_isEditMode) { - setState(() => - _highlightedBulletIndex = - index); - } - }, - onTapUp: (_) { - if (!_isEditMode) { - setState(() => - _highlightedBulletIndex = - null); - } - }, - onTapCancel: () { - if (!_isEditMode) { - setState(() => - _highlightedBulletIndex = - null); - } - }, - child: AnimatedContainer( - duration: const Duration( - milliseconds: 200), - height: 100, - decoration: BoxDecoration( - borderRadius: - BorderRadius.circular(16), - boxShadow: const [ - BoxShadow( - color: Colors.black26, - offset: Offset(0, 2), - blurRadius: 6, - ), - ], - ), - child: Column( - children: [ - Container( - height: 30, - decoration: BoxDecoration( - color: - Surfaces.current.card, - borderRadius: - const BorderRadius - .only( - topLeft: - Radius.circular(16), - topRight: - Radius.circular(16), - ), - ), - alignment: Alignment.center, - child: Text( - '${index + 1}', - style: TextStyle( - fontWeight: - FontWeight.bold, - fontSize: 14, - color: Surfaces.current - .textPrimary, - ), - ), - ), - Expanded( - child: Container( - decoration: BoxDecoration( - color: - _getBulletButtonColor( - index), - borderRadius: - const BorderRadius - .only( - bottomLeft: - Radius.circular( - 16), - bottomRight: - Radius.circular( - 16), - ), - ), - alignment: - Alignment.center, - child: Text( - '$score', - style: const TextStyle( - fontSize: 28, - fontWeight: - FontWeight.bold, - color: Colors.white, - ), - ), - ), - ), - ], - ), - ), - ), - ), - ); - }, - ), - // Missing bullets - ...List.generate( - widget.bulletCount - _mappedBullets.length, - (index) { - final bulletNum = - _mappedBullets.length + index + 1; - return Expanded( - child: Padding( - padding: const EdgeInsets.symmetric( - horizontal: 6), - child: GestureDetector( - onTap: () { - _showMissingBulletDialog( - bulletNum); - }, - child: Container( - height: 100, - decoration: BoxDecoration( - borderRadius: - BorderRadius.circular(16), - boxShadow: const [ - BoxShadow( - color: Colors.black26, - offset: Offset(0, 2), - blurRadius: 6, - ), - ], - ), - child: Column( - children: [ - Container( - height: 30, - decoration: BoxDecoration( - color: - Surfaces.current.card, - borderRadius: - const BorderRadius - .only( - topLeft: - Radius.circular(16), - topRight: - Radius.circular(16), - ), - ), - alignment: Alignment.center, - child: Text( - '$bulletNum', - style: TextStyle( - fontWeight: - FontWeight.bold, - fontSize: 14, - color: Surfaces.current - .textPrimary, - ), - ), - ), - Expanded( - child: Container( - decoration: BoxDecoration( - color: Colors.redAccent, - borderRadius: - const BorderRadius - .only( - bottomLeft: - Radius.circular( - 16), - bottomRight: - Radius.circular( - 16), - ), - ), - alignment: - Alignment.center, - child: const Text( - '?', - style: TextStyle( - fontSize: 32, - fontWeight: - FontWeight.bold, - color: Colors.white, - ), - ), - ), - ), - ], - ), - ), - ), - ), - ); - }, - ), - ], - ), - ), - ), - ], - ), - // Room for the save button, which sticks up out of the bottom bar - const SizedBox(height: 40), + Text(' · $when', style: TextStyle(fontSize: 12.5, color: c.muted)), + const Spacer(), + Icon(Icons.expand_more_rounded, size: 20, color: c.muted), + const SizedBox(width: 8), ], ), - _buildEditController(), - ], + ), ), - // Same layout as the camera screen: number on the left, round white - // main action docked in the notch, secondary icons on the right. - floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, - floatingActionButton: FloatingActionButton( - backgroundColor: Colors.white, - onPressed: _saveToLastFolder, - tooltip: _t("Save"), - child: const Icon(Icons.save, color: Colors.black), + ), + ], ), - bottomNavigationBar: BottomAppBar( - color: Colors.grey[900], - shape: const CircularNotchedRectangle(), - notchMargin: 8.0, - child: SizedBox( - height: 60, - child: Row( - children: [ - // Left - total score - Expanded( - child: Padding( - padding: const EdgeInsets.only(left: 16), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - _t('Total').toUpperCase(), - style: const TextStyle( - fontSize: 10, - fontWeight: FontWeight.bold, - letterSpacing: 1.2, - color: Colors.white54, - ), - ), - Text( - '$_totalScore', - style: const TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, - color: Colors.white, - height: 1.1, - ), - ), - ], + ); + } + + // The target with the hits; hold and drag moves the picked hit + Widget _targetView(AppSettings s, Palette c) { + return LayoutBuilder(builder: (context, box) { + final side = min(box.maxWidth, box.maxHeight) - 8; + if (side <= 0) return const SizedBox(); + final scale = side / TargetScoring.size; + final i = _selected; + final picked = i == null || i >= _hits.length ? null : _hits[i] * scale; + return Center( + child: SizedBox.square( + dimension: side, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTapUp: (d) => _pickAt(d.localPosition / scale), + onPanStart: (d) { + // Starting on another hit picks that one + final near = _nearest(d.localPosition / scale); + if (near != null) _selected = near; + if (_selected == null) return; + HapticFeedback.selectionClick(); + setState(() => _dragging = true); + }, + onPanUpdate: (d) => _moveSelected(d.delta / scale), + onPanEnd: (_) => setState(() => _dragging = false), + onPanCancel: () => setState(() => _dragging = false), + child: Stack( + clipBehavior: Clip.none, + children: [ + Positioned.fill( + child: TargetFace( + style: s.target, + hits: _hits, + hitColor: s.bulletColor, + highlighted: i == null ? const {} : {i}, ), ), - ), - // Center space for FAB - const SizedBox(width: 80), - // Right - save to another folder, edit mode - Expanded( - child: Row( - mainAxisAlignment: MainAxisAlignment.end, - children: [ - IconButton( - icon: const Icon(Icons.create_new_folder_outlined, - color: Colors.white, size: 24), - onPressed: _saveTargetDataWithDialog, - tooltip: _t("Save to folder"), - ), - IconButton( - icon: Icon( - _isEditMode ? Icons.check : Icons.edit, - color: _isEditMode ? Colors.red : Colors.white, - size: 24, + if (picked != null && !_dragging) + Positioned( + left: (picked.dx - 70).clamp(0, side - 140), + top: min(picked.dy + 26, side - 30), + child: IgnorePointer( + child: Container( + width: 140, + height: 30, + alignment: Alignment.center, + decoration: BoxDecoration( + color: c.isDark ? c.card : c.ink, + borderRadius: BorderRadius.circular(15), + border: c.isDark ? Border.all(color: c.line) : null, + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.open_with_rounded, size: 15, color: c.accent), + const SizedBox(width: 6), + Text(_t('Hold and drag'), + style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: c.isDark ? c.ink : Colors.white)), + ], + ), ), - onPressed: () { - setState(() { - _isEditMode = !_isEditMode; - _selectedBulletIndexInEdit = null; - }); - }, - tooltip: - _isEditMode ? _t("Done Editing") : _t("Edit Mode"), ), - const SizedBox(width: 4), - ], - ), - ), - ], + ), + if (picked != null && _dragging) _loupe(picked, side), + ], + ), ), ), + ); + }); + } + + int? _nearest(Offset p) { + int? best; + var bestD = 60.0; // target units: a little more than a hit's radius + for (int i = 0; i < _hits.length; i++) { + final d = (_hits[i] - p).distance; + if (d < bestD) { + bestD = d; + best = i; + } + } + return best; + } + + void _pickAt(Offset p) => setState(() => _selected = _nearest(p) ?? _selected); + + // Magnifier above the picked hit while it is dragged + Widget _loupe(Offset at, double side) { + const size = 120.0; + const gap = size / 2 + 36; + final cy = at.dy - gap - size / 2 >= -40 ? at.dy - gap : at.dy + gap; + return Positioned( + left: at.dx - size / 2, + top: cy - size / 2, + child: IgnorePointer( + child: RawMagnifier( + size: const Size(size, size), + magnificationScale: 2.5, + focalPointOffset: Offset(0, at.dy - cy), + decoration: const MagnifierDecoration( + shape: CircleBorder(side: BorderSide(color: Colors.white, width: 3)), + shadows: [BoxShadow(color: Colors.black54, blurRadius: 10)], + ), + child: const Center(child: Icon(Icons.add, color: Colors.red, size: 22)), + ), + ), + ); + } + + // The photo with every detection box, for checking what the model saw + Widget _photoView(Palette c) { + final photo = _photo; + final size = _photoSize; + if (photo == null || size == null) return Center(child: Text(_t('Image not available'), style: TextStyle(color: c.muted))); + return Padding( + padding: const EdgeInsets.all(12), + child: Center( + child: AspectRatio( + aspectRatio: size.width / size.height, + child: LayoutBuilder(builder: (context, box) { + final k = box.maxWidth / size.width; + return ClipRRect( + borderRadius: BorderRadius.circular(14), + child: Stack( + children: [ + Positioned.fill(child: Image.memory(photo, fit: BoxFit.fill)), + for (final d in widget.detections) + Positioned( + left: d.x1 * k, + top: d.y1 * k, + width: (d.x2 - d.x1) * k, + height: (d.y2 - d.y1) * k, + child: DecoratedBox( + decoration: BoxDecoration(border: Border.all(color: d.classId == 0 ? c.accent : c.pos, width: 2)), + child: Align( + alignment: Alignment.topLeft, + child: Container( + color: (d.classId == 0 ? c.accent : c.pos).withValues(alpha: 0.7), + padding: const EdgeInsets.symmetric(horizontal: 3), + child: Text('${d.classId} ${(d.confidence * 100).round()}%', + style: const TextStyle(color: Colors.black, fontSize: 9, fontWeight: FontWeight.w700)), + ), + ), + ), + ), + ], + ), + ); + }), + ), + ), + ); + } + + // One tile per shot (missing ones as +), then the total + Widget _tiles(Palette c) { + final missing = widget.bulletCount - _hits.length; + return Row( + children: [ + for (int i = 0; i < _hits.length; i++) ...[ + if (i > 0) const SizedBox(width: 8), + Expanded( + child: _HitTile( + value: '${_scoreAt(i)}', + selected: i == _selected, + gold: _scoreAt(i) == 10, + onTap: () => setState(() => _selected = i == _selected ? null : i), + ), + ), + ], + for (int k = 0; k < missing; k++) ...[ + if (_hits.isNotEmpty || k > 0) const SizedBox(width: 8), + Expanded(child: _HitTile(value: '+', missing: true, onTap: _addHit)), + ], + const SizedBox(width: 8), + Container( + width: 66, + height: 58, + decoration: BoxDecoration(color: c.ink, borderRadius: BorderRadius.circular(14)), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text(_t('Total').toUpperCase(), + style: TextStyle(fontSize: 8.5, fontWeight: FontWeight.w800, letterSpacing: 0.8, color: c.bg.withValues(alpha: 0.7))), + Text('$_total', + style: TextStyle(fontSize: 21, height: 1.15, fontWeight: FontWeight.w800, color: c.bg, fontFeatures: AppTheme.tnum)), + ], + ), + ), + ], + ); + } +} + +class _HitTile extends StatelessWidget { + final String value; + final bool selected; + final bool missing; + final bool gold; + final VoidCallback onTap; + + const _HitTile({required this.value, this.selected = false, this.missing = false, this.gold = false, required this.onTap}); + + @override + Widget build(BuildContext context) { + final c = Palette.current; + final Color bg = selected ? c.accent : (c.isDark ? c.tile : c.card); + final Color fg = selected ? c.onAccent : (missing ? c.faint : (gold ? (c.isDark ? c.goldInk : c.goldInk) : c.ink)); + return GestureDetector( + onTap: onTap, + child: AnimatedContainer( + duration: const Duration(milliseconds: 150), + height: 58, + alignment: Alignment.center, + decoration: BoxDecoration( + color: missing ? Colors.transparent : bg, + borderRadius: BorderRadius.circular(14), + border: missing ? Border.all(color: c.line, width: 1.5) : (c.isDark || selected ? null : Border.all(color: c.line2)), + ), + child: Text(value, style: TextStyle(fontSize: 21, fontWeight: FontWeight.w700, color: fg, fontFeatures: AppTheme.tnum)), ), ); } diff --git a/lib/screens/session_screen.dart b/lib/screens/session_screen.dart index c90312a..6cf8663 100644 --- a/lib/screens/session_screen.dart +++ b/lib/screens/session_screen.dart @@ -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 { late Session _session = widget.session; + Map _hits = {}; // file path -> hits, for the thumbnails + + @override + void initState() { + super.initState(); + _loadHits(); + } + + Future _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 _reload() async { final sessions = await TargetRepository.loadSessions(); @@ -27,6 +44,7 @@ class _SessionScreenState extends State { Navigator.pop(context); // session no longer exists } else { setState(() => _session = updated.first); + _loadHits(); } } @@ -59,14 +77,14 @@ class _SessionScreenState extends State { Future _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 _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 { 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 confirmDelete(BuildContext context, String message) { +/// "Potrdi brisanje" dialog. True when confirmed. +Future confirmDelete(BuildContext context, String message) { final s = AppSettings.instance; - return showDialog( - 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 showEditSessionDialog(BuildContext context, Session session) { final s = AppSettings.instance; final controller = TextEditingController(text: session.name); @@ -203,52 +240,39 @@ Future showEditSessionDialog(BuildContext context, Session session return showDialog( 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')), - ), - ], - ), + ); + }, ), ); } diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart index 2ca7c23..613ca41 100644 --- a/lib/screens/settings_screen.dart +++ b/lib/screens/settings_screen.dart @@ -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( - 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( + 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 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 _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 _confirmLock(BuildContext context) async { final s = AppSettings.instance; - final confirmed = await showDialog( - 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 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, ), ); } diff --git a/lib/screens/spectator_screen.dart b/lib/screens/spectator_screen.dart index 66c7a25..6c8cc93 100644 --- a/lib/screens/spectator_screen.dart +++ b/lib/screens/spectator_screen.dart @@ -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 createState() => _SpectatorScreenState(); } class _SpectatorScreenState extends State { - final List _selectedCameras = List.generate(6, (_) => true); // All selected by default - List _enabledCameras = List.generate(6, (_) => false); // Which cameras have IPs configured - List> _cameras = []; - Color _bulletColor = Colors.blue; // default/fallback bullet color + final Set _hidden = {}; // positions switched off in "Izberi kamere" late final Future _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 { 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 _loadCameras() async { - await _wifiReady; // streams must start after traffic is pinned to Wi-Fi - final prefs = await SharedPreferences.getInstance(); - List> cameras = []; - List 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 _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 = >[]; - 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), + ], + ), + ), + ], + ), ); } } diff --git a/lib/screens/stream_screen.dart b/lib/screens/stream_screen.dart index f20242d..011fd21 100644 --- a/lib/screens/stream_screen.dart +++ b/lib/screens/stream_screen.dart @@ -1,14 +1,14 @@ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; -import 'package:flutter/services.dart'; import 'package:flutter_mjpeg/flutter_mjpeg.dart'; import 'package:wakelock_plus/wakelock_plus.dart'; -import '../utils/translations.dart'; +import '../theme/app_theme.dart'; import '../services/app_settings.dart'; import '../widgets/camera_sheet.dart'; import '../widgets/help_sheet.dart'; import '../widgets/image_settings.dart'; +import '../widgets/ui.dart'; import '../services/wifi_binding.dart'; class CameraStreamScreen extends StatefulWidget { @@ -39,8 +39,7 @@ class _CameraStreamScreenState extends State int _numberOfBullets = 5; - Color _bulletColor = Colors.blue; - String _selectedLanguage = 'English'; + Color get _bulletColor => AppSettings.instance.bulletColor; // --- Timer state --- bool _timerEnabled = false; @@ -57,7 +56,7 @@ class _CameraStreamScreenState extends State Timer? _countdownTimer; // --- Manual bullet counter --- - bool _manualCounterEnabled = true; + bool _manualCounterEnabled = false; int _manualShotsLeft = 0; // --- Change target overlay --- @@ -76,9 +75,7 @@ class _CameraStreamScreenState extends State late AnimationController _reloadProgressController; late AnimationController _waitProgressController; - String _t(String key) { - return AppTranslations.translate(key, _selectedLanguage); - } + String _t(String key) => AppSettings.instance.t(key); // raw values always stored; null means "never configured" int? _reloadSecondsRaw; @@ -104,13 +101,10 @@ class _CameraStreamScreenState extends State final reloadOn = prefs.getBool('timerReloadEnabled') ?? false; final waitOn = prefs.getBool('timerWaitEnabled') ?? false; setState(() { - _selectedLanguage = prefs.getString('language') ?? 'Slovenian'; // Older versions allowed up to 10 _numberOfBullets = (prefs.getInt('bulletCount') ?? AppSettings.maxBullets) .clamp(AppSettings.minBullets, AppSettings.maxBullets); _image = image; - _bulletColor = - _getColorFromName(prefs.getString('bulletColor') ?? 'Blue'); _streamUrl = streamUrl; _isError = streamUrl == null; if (savedShoot != null) _shootSeconds = savedShoot; @@ -125,7 +119,7 @@ class _CameraStreamScreenState extends State _fullTarget = prefs.getBool('timerFullTarget') ?? false; _changeTargetOverlayEnabled = prefs.getBool('showChangeTargetOverlay') ?? true; - _manualCounterEnabled = prefs.getBool('manualCounterEnabled') ?? true; + _manualCounterEnabled = prefs.getBool('manualCounterEnabled') ?? false; // off until switched on _manualShotsLeft = _numberOfBullets; }); } @@ -152,8 +146,6 @@ class _CameraStreamScreenState extends State _wifiReady = WifiBinding.acquire(); _loadAllPrefs(); - _setSystemBarStyle(); - SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); _keepScreenAwake(); @@ -177,56 +169,6 @@ class _CameraStreamScreenState extends State }); } - 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 'sky': - 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 - } - } - - void _setSystemBarStyle() { - SystemChrome.setSystemUIOverlayStyle( - SystemUiOverlayStyle( - statusBarColor: Colors.grey[900], // ✅ match your AppBar - statusBarIconBrightness: Brightness.light, // white icons - systemNavigationBarColor: Colors.grey[900], - systemNavigationBarIconBrightness: Brightness.light, - // No grey scrim behind 3-button navigation; we paint the strip ourselves - systemNavigationBarContrastEnforced: false, - ), - ); - } - Future _keepScreenAwake() async { try { await WakelockPlus.enable(); @@ -253,8 +195,7 @@ class _CameraStreamScreenState extends State context, initial: _image, settingsId: widget.settingsId, - cameraLabel: "${_t('Camera')} ${widget.title}", - accent: _bulletColor, + cameraLabel: "${_t('Camera')} ${widget.cameraIndex}", t: _t, onChanged: (value) => setState(() => _image = value), ); @@ -279,14 +220,14 @@ class _CameraStreamScreenState extends State 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: setCount, ), const SizedBox(height: 8), @@ -298,25 +239,15 @@ class _CameraStreamScreenState extends State } void _showHelpDialog() { - showHelpSheet(context, accent: _bulletColor, t: _t, items: const [ - (Icons.pinch, 'Pinch to zoom on the camera stream'), - (Icons.filter_5_rounded, 'Number bottom left: shots per target (1–5).'), - ( - Icons.timer, - 'Timer icon: set shoot, reload and wait times. While the timer runs, tap it to stop.' - ), - ( - Icons.play_arrow, - 'Play / pause / stop in the middle: control the timer.' - ), - ( - Icons.circle_outlined, - 'Circle icon: shot counter. Tap + after each shot; when the target is full you get a "Change target!" warning.' - ), - ( - Icons.tune, - 'Settings icon: brightness, contrast, filters and rotation, saved for each camera.' - ), + showHelpSheet(context, t: _t, clearBarrier: true, items: const [ + (Icons.open_in_full_rounded, 'Pinch to zoom on the camera stream'), + (Icons.grid_view_rounded, 'Number bottom left: shots per target (1–5).'), + (Icons.timer_outlined, + '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.'), + (Icons.play_arrow_rounded, 'Play / pause: control the timer.'), + (Icons.add_rounded, + '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.'), + (Icons.tune_rounded, 'Picture icon: brightness, contrast, filters and rotation, saved for each camera.'), ]); } @@ -330,7 +261,6 @@ class _CameraStreamScreenState extends State _flashController.dispose(); WifiBinding.release(); _restoreScreenSettings(); - _setSystemBarStyle(); super.dispose(); } @@ -369,7 +299,7 @@ class _CameraStreamScreenState extends State _remaining = _reloadSeconds!; _shotsLeft = shots; _showFlash = true; - _flashColor = Colors.orange; + _flashColor = _reloadColor; }); _flashController.forward(from: 0.0); _startReloadProgress(_reloadSeconds!); @@ -381,7 +311,7 @@ class _CameraStreamScreenState extends State _remaining = _waitSeconds!; _shotsLeft = shots; _showFlash = true; - _flashColor = Colors.red; + _flashColor = _waitColor; }); _flashController.forward(from: 0.0); _startWaitProgress(_waitSeconds!); @@ -498,7 +428,7 @@ class _CameraStreamScreenState extends State if (hasWait) { setState(() { _showFlash = true; - _flashColor = Colors.red; + _flashColor = _waitColor; _isReloadPhase = false; _isWaitPhase = true; _remaining = _waitSeconds!; @@ -544,7 +474,7 @@ class _CameraStreamScreenState extends State if (hasReload) { setState(() { _showFlash = true; - _flashColor = Colors.orange; + _flashColor = _reloadColor; _isReloadPhase = true; _remaining = _reloadSeconds!; }); @@ -554,7 +484,7 @@ class _CameraStreamScreenState extends State } else if (hasWait) { setState(() { _showFlash = true; - _flashColor = Colors.red; + _flashColor = _waitColor; _isWaitPhase = true; _remaining = _waitSeconds!; }); @@ -597,346 +527,191 @@ class _CameraStreamScreenState extends State // --- Timer UI --- - Widget _buildTimerButton() { - return InkWell( - onTap: _timerEnabled && _isRunning ? _stopTimer : _showTimerDialog, - onLongPress: _timerEnabled ? _showTimerDialog : null, - borderRadius: BorderRadius.circular(8), - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4), - child: Icon( - _timerEnabled ? Icons.timer : Icons.timer_outlined, - color: Colors.white, - size: 26, - ), - ), - ); + // Phase colours: shoot in the accent, reload amber, wait blue + Color get _reloadColor => Palette.current.isDark ? const Color(0xFFF5B33B) : const Color(0xFFD18A00); + Color get _waitColor => Palette.current.blue; + + static String _clock(int seconds) => '${seconds ~/ 60}:${(seconds % 60).toString().padLeft(2, '0')}'; + + bool get _hasActiveTimer => _timerEnabled && (_shootEnabled || _reloadEnabled || _waitEnabled); + + // Length of the phase that is running (or the first one, before the start) + int get _phaseTotal { + if (_isRunning && _isWaitPhase) return _waitSeconds ?? 0; + if (_isRunning && _isReloadPhase) return _reloadSeconds ?? 0; + if (_shootEnabled) return _shootSeconds; + return _reloadSeconds ?? _waitSeconds ?? 0; } - Widget _buildCountdownOverlay() { - if (!_isRunning) return const SizedBox.shrink(); - if (_isWaitPhase) return _buildWaitOverlay(); - if (_isReloadPhase) return _buildReloadOverlay(); - return _buildShootOverlay(); + AnimationController get _phaseProgress => _isWaitPhase + ? _waitProgressController + : _isReloadPhase + ? _reloadProgressController + : _shootProgressController; + + String get _phaseName { + if (_isRunning && _isWaitPhase) return _t('Wait time'); + if (_isRunning && _isReloadPhase) return _t('Reload time'); + return _t('Shoot time'); } - // Bullet dots row: filled = remaining, hollow = shot - Widget _buildBulletDots(int total, int remaining, {double? size}) { - if (total <= 1) return const SizedBox.shrink(); - final dotSize = size ?? - (total <= 6 - ? 18.0 - : total <= 8 - ? 14.0 - : 11.0); - final hPad = total <= 6 - ? 4.0 - : total <= 8 - ? 3.0 - : 2.0; - return Container( - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), - decoration: BoxDecoration( - color: Colors.black.withValues(alpha: 0.55), - borderRadius: BorderRadius.circular(20), - border: Border.all(color: Colors.white24, width: 1), - ), - child: Wrap( - spacing: hPad * 2, - runSpacing: 4, - alignment: WrapAlignment.center, - children: List.generate(total, (i) { - final active = i < remaining; - return Container( - width: dotSize, - height: dotSize, + Color get _phaseColor => _isRunning && _isWaitPhase + ? _waitColor + : _isRunning && _isReloadPhase + ? _reloadColor + : _bulletColor; + + // Ring with the time left, the phase name and the three phase lengths + Widget _buildTimerCard(Palette c) { + final total = _phaseTotal; + final remaining = _isRunning ? _remaining : total; + final color = _phaseColor; + Widget chip(String label, int? seconds, bool active, bool enabled, Color tint) => Expanded( + child: Container( + height: 44, decoration: BoxDecoration( - shape: BoxShape.circle, - color: active ? Colors.white : Colors.transparent, - border: Border.all( - color: active ? Colors.white : Colors.white60, - width: 2, - ), + color: active ? tint.withValues(alpha: c.isDark ? 0.16 : 0.12) : c.tile, + borderRadius: BorderRadius.circular(10), ), - ); - }), - ), - ); - } + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text(label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 9.5, fontWeight: FontWeight.w600, color: active ? tint : c.muted)), + Text(enabled && seconds != null ? _clock(seconds) : '–', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w700, + color: active ? tint : (enabled ? c.ink : c.faint), + fontFeatures: AppTheme.tnum)), + ], + ), + ), + ); - // Shared top bar: progress bar + bullet dots centered + time pill on right - Widget _buildTopBar({ - required Animation progressAnim, - required Color barColor, - required String timeLabel, - required Color timeColor, - required IconData timeIcon, - }) { - final showDots = _fullTarget && _numberOfBullets > 1; - return Positioned( - top: 0, - left: 0, - right: 0, - child: IgnorePointer( - child: Column( - children: [ - AnimatedBuilder( - animation: progressAnim, - builder: (_, __) => LinearProgressIndicator( - value: (1.0 - progressAnim.value).clamp(0.0, 1.0), - minHeight: 5, - backgroundColor: Colors.white.withValues(alpha: 0.1), - valueColor: AlwaysStoppedAnimation(barColor), - ), - ), - const SizedBox(height: 8), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 12), - child: Row( - children: [ - // Left spacer = same width as pill to keep dots truly centered - const Expanded(child: SizedBox()), - // Bullet dots — centered - if (showDots) _buildBulletDots(_numberOfBullets, _shotsLeft), - // Right side: pill - Expanded( - child: Align( - alignment: Alignment.centerRight, - child: Container( - padding: const EdgeInsets.symmetric( - horizontal: 10, vertical: 4), - decoration: BoxDecoration( - color: Colors.black.withValues(alpha: 0.55), - borderRadius: BorderRadius.circular(20), - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Icon(timeIcon, color: timeColor, size: 13), - const SizedBox(width: 4), - Text( - timeLabel, - style: TextStyle( - color: timeColor, - fontSize: 13, - fontWeight: FontWeight.bold), - ), - ], - ), - ), + return AppCard( + padding: const EdgeInsets.fromLTRB(14, 14, 14, 14), + onTap: _isRunning ? null : _showTimerDialog, + child: Row( + children: [ + SizedBox.square( + dimension: 92, + child: Stack( + alignment: Alignment.center, + children: [ + SizedBox.expand( + child: AnimatedBuilder( + animation: _phaseProgress, + builder: (_, __) => CircularProgressIndicator( + value: _isRunning ? (1.0 - _phaseProgress.value).clamp(0.0, 1.0) : 1, + strokeWidth: 7, + strokeCap: StrokeCap.round, + color: color, + backgroundColor: c.tile, ), ), + ), + Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text(_clock(remaining.clamp(0, 5999)), + style: TextStyle(fontSize: 22, fontWeight: FontWeight.w800, color: c.ink, fontFeatures: AppTheme.tnum)), + Text('${_t('of')} ${_clock(total)}', style: TextStyle(fontSize: 10, color: c.muted)), + ], + ), + ], + ), + ), + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Expanded( + child: Text(_isPaused ? '$_phaseName · ${_t('paused')}' : _phaseName, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: c.ink)), + ), + if (_isRunning) + GestureDetector( + onTap: _stopTimer, + child: Container( + width: 28, + height: 28, + decoration: BoxDecoration(color: c.redSoft, shape: BoxShape.circle), + child: Icon(Icons.stop_rounded, size: 16, color: c.red), + ), + ), + ], + ), + if (_fullTarget && _isRunning) + Text('${_numberOfBullets - _shotsLeft} / $_numberOfBullets ${_t('shots')}', + style: TextStyle(fontSize: 11.5, color: c.muted)), + const SizedBox(height: 8), + Row( + children: [ + chip(_t('Wait'), _waitSecondsRaw ?? 30, _isRunning && _isWaitPhase, _waitEnabled, _waitColor), + const SizedBox(width: 6), + chip(_t('Shooting'), _shootSeconds, _isRunning && !_isWaitPhase && !_isReloadPhase, _shootEnabled, + _bulletColor), + const SizedBox(width: 6), + chip(_t('Reload phase'), _reloadSecondsRaw ?? 15, _isRunning && _isReloadPhase, _reloadEnabled, _reloadColor), + ], + ), + if (_changeTargetOverlayEnabled) ...[ + const SizedBox(height: 8), + Text('${_t('Signal at the end')}: »${_t('Change target!')}«', + maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 11, color: c.muted)), ], + ], + ), + ), + ], + ), + ); + } + + // Shots left of the counter, as dots on the image + Widget _buildBulletDots(Palette c) { + if (!_showManualCounter || _numberOfBullets <= 1) return const SizedBox.shrink(); + final left = _fullTarget && _isRunning ? _shotsLeft : _manualShotsLeft; + return Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), + decoration: BoxDecoration(color: Colors.black.withValues(alpha: 0.55), borderRadius: BorderRadius.circular(20)), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + for (int i = 0; i < _numberOfBullets; i++) ...[ + if (i > 0) const SizedBox(width: 6), + Container( + width: 10, + height: 10, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: i < left ? _bulletColor : Colors.transparent, + border: Border.all(color: i < left ? _bulletColor : Colors.white54, width: 1.5), ), ), ], - ), - ), - ); - } - - // Manual counter dots — shown at top when timer not running - Widget _buildManualDotsOverlay() { - if (!_showManualCounter || _numberOfBullets <= 1) { - return const SizedBox.shrink(); - } - return Positioned( - top: 8, - left: 0, - right: 0, - child: IgnorePointer( - child: Center( - child: _buildBulletDots(_numberOfBullets, _manualShotsLeft), - ), - ), - ); - } - - // Shoot phase: blue top bar - Widget _buildShootOverlay() { - return _buildTopBar( - progressAnim: _shootProgressController, - barColor: Colors.blue, - timeLabel: '$_remaining s', - timeColor: Colors.blue, - timeIcon: Icons.play_circle_outline, - ); - } - - // Reload phase: orange top bar + center circle - Widget _buildReloadOverlay() { - return Positioned.fill( - child: Stack( - children: [ - Positioned.fill( - child: IgnorePointer( - child: Center( - child: SizedBox( - width: 160, - height: 160, - child: Stack( - alignment: Alignment.center, - children: [ - SizedBox.expand( - child: CircularProgressIndicator( - value: 1.0, - strokeWidth: 10, - color: Colors.white.withValues(alpha: 0.1), - ), - ), - SizedBox.expand( - child: AnimatedBuilder( - animation: _reloadProgressController, - builder: (_, __) => CircularProgressIndicator( - value: (1.0 - _reloadProgressController.value) - .clamp(0.0, 1.0), - strokeWidth: 10, - color: Colors.orange, - strokeCap: StrokeCap.round, - ), - ), - ), - Container( - width: 130, - height: 130, - decoration: BoxDecoration( - shape: BoxShape.circle, - color: Colors.black.withValues(alpha: 0.6), - ), - ), - Column( - mainAxisSize: MainAxisSize.min, - children: [ - const Icon(Icons.refresh, - color: Colors.orange, size: 18), - const SizedBox(height: 2), - Text( - '$_remaining', - style: const TextStyle( - color: Colors.orange, - fontSize: 44, - fontWeight: FontWeight.bold, - height: 1.0, - ), - ), - Text('s', - style: TextStyle( - color: Colors.orange.withValues(alpha: 0.7), - fontSize: 13)), - ], - ), - ], - ), - ), - ), - ), - ), - _buildTopBar( - progressAnim: _reloadProgressController, - barColor: Colors.orange, - timeLabel: '$_remaining s', - timeColor: Colors.orange, - timeIcon: Icons.refresh, - ), ], ), ); } - // Wait phase: top bar (dots + time pill) + center circle - Widget _buildWaitOverlay() { - return Positioned.fill( - child: Stack( - children: [ - // Center wait circle - Positioned.fill( - child: IgnorePointer( - child: Center( - child: SizedBox( - width: 160, - height: 160, - child: Stack( - alignment: Alignment.center, - children: [ - SizedBox.expand( - child: CircularProgressIndicator( - value: 1.0, - strokeWidth: 10, - color: Colors.white.withValues(alpha: 0.1), - ), - ), - SizedBox.expand( - child: AnimatedBuilder( - animation: _waitProgressController, - builder: (_, __) => CircularProgressIndicator( - value: (1.0 - _waitProgressController.value) - .clamp(0.0, 1.0), - strokeWidth: 10, - color: Colors.red, - strokeCap: StrokeCap.round, - ), - ), - ), - Container( - width: 130, - height: 130, - decoration: BoxDecoration( - shape: BoxShape.circle, - color: Colors.black.withValues(alpha: 0.6), - ), - ), - Column( - mainAxisSize: MainAxisSize.min, - children: [ - const Icon(Icons.hourglass_empty, - color: Colors.red, size: 18), - const SizedBox(height: 2), - Text( - '$_remaining', - style: const TextStyle( - color: Colors.red, - fontSize: 44, - fontWeight: FontWeight.bold, - height: 1.0, - ), - ), - Text( - 's', - style: TextStyle( - color: Colors.red.withValues(alpha: 0.7), - fontSize: 13, - fontWeight: FontWeight.w500, - ), - ), - ], - ), - ], - ), - ), - ), - ), - ), - // Top bar: dots centered + time pill on right - _buildTopBar( - progressAnim: _waitProgressController, - barColor: Colors.red, - timeLabel: '$_remaining s', - timeColor: Colors.red, - timeIcon: Icons.hourglass_empty, - ), - ], - ), - ); - } - - bool get _showManualCounter => - _manualCounterEnabled && - (!_timerEnabled || (!_fullTarget && _timerEnabled)); + bool get _showManualCounter => _manualCounterEnabled && (!_timerEnabled || (!_fullTarget && _timerEnabled)); void _manualRegisterShot() { if (_manualShotsLeft <= 0) { // Already done — tap resets for next target - setState(() => _manualShotsLeft = _numberOfBullets); + setState(() { + _manualShotsLeft = _numberOfBullets; + _showChangeTarget = false; + }); return; } final newLeft = _manualShotsLeft - 1; @@ -947,156 +722,10 @@ class _CameraStreamScreenState extends State } } - Widget _buildBottomBarControls() { - final showCounter = _showManualCounter; - final hasActiveTimer = - _timerEnabled && (_shootEnabled || _reloadEnabled || _waitEnabled); - final showPlay = hasActiveTimer && !_isRunning; - - // Timer running: show stop/pause pill only - if (hasActiveTimer && _isRunning) { - // fall through to pill below - } else { - if (showCounter && showPlay) { - // Combined pill: + on left, play on right - return Container( - height: 48, - decoration: BoxDecoration( - color: Colors.grey[800], - borderRadius: BorderRadius.circular(24), - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - GestureDetector( - onTap: _manualRegisterShot, - child: Container( - width: 64, - height: 48, - decoration: BoxDecoration( - color: _manualShotsLeft <= 0 ? Colors.red : _bulletColor, - borderRadius: const BorderRadius.only( - topLeft: Radius.circular(24), - bottomLeft: Radius.circular(24), - ), - ), - child: Icon( - _manualShotsLeft <= 0 ? Icons.refresh : Icons.add, - color: Colors.white, - size: 26, - ), - ), - ), - Container(width: 1, height: 48, color: Colors.white24), - GestureDetector( - onTap: _startTimer, - child: Container( - width: 64, - height: 48, - decoration: const BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.only( - topRight: Radius.circular(24), - bottomRight: Radius.circular(24), - ), - ), - child: const Icon(Icons.play_arrow, - color: Colors.black, size: 26), - ), - ), - ], - ), - ); - } - if (showCounter) { - return GestureDetector( - onTap: _manualRegisterShot, - child: Container( - width: 48, - height: 48, - decoration: BoxDecoration( - color: _manualShotsLeft <= 0 ? Colors.red : _bulletColor, - shape: BoxShape.circle, - ), - child: Icon( - _manualShotsLeft <= 0 ? Icons.refresh : Icons.add, - color: Colors.white, - size: 30, - ), - ), - ); - } - if (showPlay) { - return GestureDetector( - onTap: _startTimer, - child: Container( - width: 48, - height: 48, - decoration: const BoxDecoration( - color: Colors.white, shape: BoxShape.circle), - child: const Icon(Icons.play_arrow, color: Colors.black, size: 28), - ), - ); - } - return const SizedBox.shrink(); - } - - if (!_isRunning) return const SizedBox.shrink(); - - // Running: pill with stop | pause/resume - return Container( - height: 44, - decoration: BoxDecoration( - color: Colors.grey[800], - borderRadius: BorderRadius.circular(22), - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - GestureDetector( - onTap: _stopTimer, - child: Container( - width: 60, - height: 44, - decoration: BoxDecoration( - color: Colors.red.shade700, - borderRadius: const BorderRadius.only( - topLeft: Radius.circular(22), - bottomLeft: Radius.circular(22), - ), - ), - child: const Icon(Icons.stop, color: Colors.white, size: 22), - ), - ), - Container(width: 1, height: 44, color: Colors.white24), - GestureDetector( - onTap: _isPaused ? _resumeTimer : _pauseTimer, - child: Container( - width: 60, - height: 44, - decoration: BoxDecoration( - color: _isPaused ? Colors.orange : Colors.white, - borderRadius: const BorderRadius.only( - topRight: Radius.circular(22), - bottomRight: Radius.circular(22), - ), - ), - child: Icon( - _isPaused ? Icons.play_arrow : Icons.pause, - color: _isPaused ? Colors.white : Colors.black, - size: 22, - ), - ), - ), - ], - ), - ); - } - void _showTimerDialog() { showCameraSheet( context, - builder: (ctx) => _TimerConfigDialog( + builder: (ctx) => _TimerSheet( shootSeconds: _shootSeconds, reloadSeconds: _reloadSecondsRaw, waitSeconds: _waitSecondsRaw, @@ -1104,10 +733,8 @@ class _CameraStreamScreenState extends State shootEnabled: _shootEnabled, reloadEnabled: _reloadEnabled, waitEnabled: _waitEnabled, - bulletColor: _bulletColor, fullTarget: _fullTarget, changeTargetEnabled: _changeTargetOverlayEnabled, - numberOfBullets: _numberOfBullets, onChangeTargetToggle: (v) async { setState(() => _changeTargetOverlayEnabled = v); final prefs = await SharedPreferences.getInstance(); @@ -1129,32 +756,57 @@ class _CameraStreamScreenState extends State }); _saveTimerPrefs(); }, + onStart: () { + Navigator.pop(ctx); + if (!_isRunning) _startTimer(); + }, translateFn: _t, ), ); } + Future _toggleCounter() async { + setState(() { + _manualCounterEnabled = !_manualCounterEnabled; + if (_manualCounterEnabled) _manualShotsLeft = _numberOfBullets; + }); + final prefs = await SharedPreferences.getInstance(); + await prefs.setBool('manualCounterEnabled', _manualCounterEnabled); + } + @override Widget build(BuildContext context) { - return Scaffold( - appBar: AppBar( - title: Text("${_t('Camera')} ${widget.title}"), - backgroundColor: Colors.grey[900], - foregroundColor: Colors.white, - leading: IconButton( - icon: const Icon(Icons.arrow_back, color: Colors.white), - onPressed: () => Navigator.pop(context), - ), - actions: [ - IconButton( - icon: const Icon(Icons.info_outline_rounded, color: Colors.white), - onPressed: _showHelpDialog, + return ListenableBuilder( + listenable: AppSettings.instance, + builder: (context, _) { + final c = Palette.current; + return Scaffold( + body: Column( + children: [ + BackHeader( + title: "${_t('Camera')} ${widget.cameraIndex}", + subtitle: widget.location, + actions: [CircleButton(icon: Icons.info_outline_rounded, onTap: _showHelpDialog)], + ), + Expanded(child: _buildVideo(c)), + if (_hasActiveTimer) + Padding( + padding: const EdgeInsets.fromLTRB(AppTheme.edge, 14, AppTheme.edge, 0), + child: _buildTimerCard(c), + ), + _buildBottomBar(c), + ], ), - const SizedBox(width: 16), - ], - ), - backgroundColor: Colors.black, - body: Stack( + ); + }, + ); + } + + Widget _buildVideo(Palette c) { + return Container( + margin: const EdgeInsets.only(top: 4), + color: c.isDark ? const Color(0xFF0A0B0D) : const Color(0xFF17191C), + child: Stack( children: [ LayoutBuilder( builder: (context, constraints) { @@ -1183,17 +835,10 @@ class _CameraStreamScreenState extends State fit: BoxFit.contain, error: (context, error, stackTrace) { // Mark as error so we can display error placeholder outside filters - WidgetsBinding.instance - .addPostFrameCallback((_) { - if (mounted) { - setState(() { - _isError = true; - }); - } + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) setState(() => _isError = true); }); - return SizedBox.expand( - child: Container(color: Colors.black), - ); + return const SizedBox.expand(child: ColoredBox(color: Colors.black)); }, ), ), @@ -1204,70 +849,54 @@ class _CameraStreamScreenState extends State ); }, ), - - _buildManualDotsOverlay(), - _buildCountdownOverlay(), + Positioned(top: 10, right: 12, child: IgnorePointer(child: _buildBulletDots(c))), // Phase-change flash overlay if (_showFlash) Positioned.fill( - child: FadeTransition( - opacity: _flashAnimation, - child: Container(color: _flashColor.withValues(alpha: 0.5)), + child: IgnorePointer( + child: FadeTransition( + opacity: _flashAnimation, + child: Container(color: _flashColor.withValues(alpha: 0.45)), + ), ), ), - // Change target overlay + // Change target overlay; tap it for a new target if (_showChangeTarget) Positioned.fill( - child: IgnorePointer( + child: GestureDetector( + onTap: () => setState(() { + _showChangeTarget = false; + _manualShotsLeft = _numberOfBullets; + }), child: Center( child: Container( - padding: const EdgeInsets.symmetric( - horizontal: 36, vertical: 28), + margin: const EdgeInsets.symmetric(horizontal: 32), + padding: const EdgeInsets.fromLTRB(24, 24, 24, 22), decoration: BoxDecoration( - color: Colors.black.withValues(alpha: 0.88), - borderRadius: BorderRadius.circular(24), - border: - Border.all(color: Colors.green.shade400, width: 2), - boxShadow: [ - BoxShadow( - color: Colors.green.withValues(alpha: 0.3), - blurRadius: 24, - spreadRadius: 2), - ], + color: _bulletColor, + borderRadius: BorderRadius.circular(22), + boxShadow: [BoxShadow(color: _bulletColor.withValues(alpha: 0.45), blurRadius: 30)], ), child: Column( mainAxisSize: MainAxisSize.min, children: [ - Stack( - alignment: Alignment.center, - children: [ - Icon(Icons.article_outlined, - color: Colors.green.shade300, size: 72), - Positioned( - bottom: 0, - right: 0, - child: Container( - padding: const EdgeInsets.all(4), - decoration: const BoxDecoration( - color: Colors.black, - shape: BoxShape.circle), - child: Icon(Icons.check_circle, - color: Colors.green.shade400, size: 24), - ), - ), - ], - ), - const SizedBox(height: 16), - Text( - _t('Change target!'), - textAlign: TextAlign.center, - style: TextStyle( - color: Colors.green.shade300, - fontSize: 26, - fontWeight: FontWeight.bold, - letterSpacing: 0.5, + Container( + width: 46, + height: 46, + decoration: BoxDecoration( + color: Palette.onColor(_bulletColor).withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(12), ), + child: Icon(Icons.description_outlined, color: Palette.onColor(_bulletColor), size: 24), ), + const SizedBox(height: 14), + Text(_t('Change target!'), + textAlign: TextAlign.center, + style: TextStyle(color: Palette.onColor(_bulletColor), fontSize: 24, fontWeight: FontWeight.w800)), + const SizedBox(height: 4), + Text('$_numberOfBullets / $_numberOfBullets ${_t('shots')} · ${_t('tap for a new target')}', + textAlign: TextAlign.center, + style: TextStyle(color: Palette.onColor(_bulletColor).withValues(alpha: 0.75), fontSize: 12.5)), ], ), ), @@ -1276,186 +905,102 @@ class _CameraStreamScreenState extends State ), ], ), - bottomNavigationBar: BottomAppBar( - color: Colors.grey[900], - child: SizedBox( - height: 64, - child: Row( - children: [ - // Left - Bullet count + Timer config - Expanded( - child: Row( - mainAxisAlignment: MainAxisAlignment.start, - children: [ - const SizedBox(width: 8), - InkWell( - onTap: _showBulletDialog, - borderRadius: BorderRadius.circular(8), - child: Padding( - padding: const EdgeInsets.symmetric( - horizontal: 8, vertical: 4), - child: Text( - '$_numberOfBullets', - style: const TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, - color: Colors.white, - ), - ), - ), - ), - _buildTimerButton(), - ], - ), - ), - // Center - Play/Stop/Pause controls - if (!_isError) _buildBottomBarControls(), - // Right - Counter toggle + Image settings - Expanded( - child: Row( - mainAxisAlignment: MainAxisAlignment.end, - children: [ - // Counter toggle — hidden when timer is full target - if (!(_timerEnabled && _fullTarget)) - InkWell( - onTap: () async { - setState(() { - _manualCounterEnabled = !_manualCounterEnabled; - if (_manualCounterEnabled) { - _manualShotsLeft = _numberOfBullets; - } - }); - final prefs = await SharedPreferences.getInstance(); - await prefs.setBool( - 'manualCounterEnabled', _manualCounterEnabled); - }, - borderRadius: BorderRadius.circular(8), - child: Padding( - padding: const EdgeInsets.symmetric( - horizontal: 4, vertical: 4), - child: Icon( - _manualCounterEnabled - ? Icons.circle - : Icons.circle_outlined, - color: Colors.white, - size: 24, - ), - ), - ), - IconButton( - icon: - const Icon(Icons.tune, color: Colors.white, size: 24), - onPressed: _showImageSettingsDialog, - ), - ], - ), - ), - ], + ); + } + + // Shots per target, timer, the big counter button, counter on/off, image settings + Widget _buildBottomBar(Palette c) { + final IconData timerIcon; + final VoidCallback timerAction; + if (!_hasActiveTimer) { + timerIcon = Icons.timer_outlined; + timerAction = _showTimerDialog; + } else if (!_isRunning) { + timerIcon = Icons.play_arrow_rounded; + timerAction = _startTimer; + } else if (_isPaused) { + timerIcon = Icons.play_arrow_rounded; + timerAction = _resumeTimer; + } else { + timerIcon = Icons.pause_rounded; + timerAction = _pauseTimer; + } + final full = _manualShotsLeft <= 0; + return Padding( + padding: EdgeInsets.fromLTRB(AppTheme.edge, 14, AppTheme.edge, 12 + MediaQuery.paddingOf(context).bottom), + child: Row( + children: [ + SquareButton( + size: 52, + tooltip: _t('Select the number of bullets'), + onTap: _showBulletDialog, + child: Text('$_numberOfBullets', + style: TextStyle(fontSize: 20, fontWeight: FontWeight.w800, color: c.ink, fontFeatures: AppTheme.tnum)), ), - ), + const SizedBox(width: 10), + GestureDetector( + onLongPress: _hasActiveTimer ? _showTimerDialog : null, + child: SquareButton(size: 52, icon: timerIcon, tooltip: _t('Shooting Timer'), onTap: _isError ? null : timerAction), + ), + const Spacer(), + if (_showManualCounter) + // Counted shot: a wide button in the accent, the same height as the tiles + Material( + color: full ? c.red : _bulletColor, + borderRadius: BorderRadius.circular(14), + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: _manualRegisterShot, + child: SizedBox( + width: 96, + height: 52, + child: Icon(full ? Icons.refresh_rounded : Icons.add_rounded, + size: 30, color: Palette.onColor(full ? c.red : _bulletColor)), + ), + ), + ), + const Spacer(), + if (!(_timerEnabled && _fullTarget)) + // Shot counter on/off: a tile like the others, tinted when on + SquareButton( + size: 52, + tooltip: _t('Shot counter'), + onTap: _toggleCounter, + icon: Icons.exposure_plus_1_rounded, + color: _manualCounterEnabled ? _bulletColor : c.ink, + background: _manualCounterEnabled ? c.accentSoft : null, + ), + const SizedBox(width: 10), + SquareButton(size: 52, icon: Icons.image_outlined, tooltip: _t('Image Settings'), onTap: _showImageSettingsDialog), + ], ), ); } Widget _buildErrorContent() { + final c = Palette.current; return Center( child: SingleChildScrollView( - child: Padding( - padding: const EdgeInsets.all(24), - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 32), - decoration: BoxDecoration( - color: Colors.grey[900], - borderRadius: BorderRadius.circular(16), - ), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Icon(Icons.error, color: _bulletColor, size: 100), - const SizedBox(height: 24), - Text( - _t("Unable to load camera stream"), - style: const TextStyle( - color: Colors.white, - fontSize: 18, - fontWeight: FontWeight.bold, - ), - ), - const SizedBox(height: 24), - Container( - padding: - const EdgeInsets.symmetric(horizontal: 16, vertical: 16), - decoration: BoxDecoration( - color: Colors.grey[800], - borderRadius: BorderRadius.circular(8), - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - _t("Please ensure:"), - style: const TextStyle( - color: Colors.white, - fontSize: 14, - fontWeight: FontWeight.w600, - ), - ), - const SizedBox(height: 12), - Row( - children: [ - const Icon(Icons.wifi, color: Colors.white, size: 18), - const SizedBox(width: 12), - Expanded( - child: Text( - _t("WiFi is enabled"), - style: const TextStyle( - color: Colors.white70, - fontSize: 14, - ), - ), - ), - ], - ), - const SizedBox(height: 12), - Row( - children: [ - // Mobile data can stay on: the app pins camera traffic to Wi-Fi - const Icon(Icons.videocam_outlined, - color: Colors.white, size: 18), - const SizedBox(width: 12), - Expanded( - child: Text( - _t("Cameras and PC are switched on"), - style: const TextStyle( - color: Colors.white70, - fontSize: 14, - ), - ), - ), - ], - ), - ], - ), - ), - const SizedBox(height: 24), - SizedBox( - width: double.infinity, - height: 48, - child: ElevatedButton.icon( - onPressed: _loadStreamUrl, - icon: const Icon(Icons.refresh, size: 20), - label: Text(_t("Reload")), - style: ElevatedButton.styleFrom( - backgroundColor: _bulletColor, - foregroundColor: Colors.white, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(8), - ), - ), - ), - ), - ], - ), + padding: const EdgeInsets.all(20), + child: AppCard( + padding: const EdgeInsets.fromLTRB(20, 24, 20, 20), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Center(child: IconBadge(Icons.videocam_off_outlined, size: 56, color: c.red)), + const SizedBox(height: 14), + Text(_t('Unable to load camera stream'), + textAlign: TextAlign.center, style: TextStyle(color: c.ink, fontSize: 17, fontWeight: FontWeight.w700)), + const SizedBox(height: 14), + Text(_t('Please ensure:'), style: TextStyle(color: c.muted, fontSize: 13, fontWeight: FontWeight.w600)), + const SizedBox(height: 8), + HelpRow(Icons.wifi_rounded, _t('WiFi is enabled')), + // Mobile data can stay on: the app pins camera traffic to Wi-Fi + HelpRow(Icons.videocam_outlined, _t('Cameras and PC are switched on')), + const SizedBox(height: 4), + PrimaryButton(label: _t('Reload'), icon: Icons.refresh_rounded, height: 46, onTap: _loadStreamUrl), + ], ), ), ), @@ -1463,7 +1008,9 @@ class _CameraStreamScreenState extends State } } -class _TimerConfigDialog extends StatefulWidget { +/// "Časovnik streljanja": single shot or full target, the three phase lengths, +/// the change-target sign, and start. +class _TimerSheet extends StatefulWidget { final int shootSeconds; final int? reloadSeconds; final int? waitSeconds; @@ -1472,15 +1019,13 @@ class _TimerConfigDialog extends StatefulWidget { final bool reloadEnabled; final bool waitEnabled; final bool fullTarget; - final Color bulletColor; - final int numberOfBullets; final bool changeTargetEnabled; - final void Function(int shoot, int? reload, bool reloadOn, int? wait, - bool waitOn, bool fullTarget) onConfirm; + final void Function(int shoot, int? reload, bool reloadOn, int? wait, bool waitOn, bool fullTarget) onConfirm; final void Function(bool) onChangeTargetToggle; + final VoidCallback onStart; final String Function(String) translateFn; - const _TimerConfigDialog({ + const _TimerSheet({ required this.shootSeconds, required this.reloadSeconds, required this.waitSeconds, @@ -1490,26 +1035,24 @@ class _TimerConfigDialog extends StatefulWidget { required this.waitEnabled, required this.fullTarget, required this.changeTargetEnabled, - required this.bulletColor, - required this.numberOfBullets, required this.onConfirm, required this.onChangeTargetToggle, + required this.onStart, required this.translateFn, }); @override - State<_TimerConfigDialog> createState() => _TimerConfigDialogState(); + State<_TimerSheet> createState() => _TimerSheetState(); } -class _TimerConfigDialogState extends State<_TimerConfigDialog> { +class _TimerSheetState extends State<_TimerSheet> { late int _shoot; late int _reload; late int _wait; - bool _shootEnabled = false; - bool _reloadEnabled = false; - bool _waitEnabled = false; + late bool _shootEnabled; + late bool _reloadEnabled; + late bool _waitEnabled; late bool _fullTarget; - bool _targetSelected = true; late bool _changeTargetEnabled; static const int _minSeconds = 5; @@ -1520,344 +1063,145 @@ class _TimerConfigDialogState extends State<_TimerConfigDialog> { void initState() { super.initState(); _shoot = _clamp(widget.shootSeconds > 0 ? widget.shootSeconds : 30); - _reload = _clamp(widget.reloadSeconds != null ? widget.reloadSeconds! : 15); - _wait = _clamp(widget.waitSeconds != null ? widget.waitSeconds! : 30); - _shootEnabled = widget.timerEnabled && widget.shootEnabled; + _reload = _clamp(widget.reloadSeconds ?? 15); + _wait = _clamp(widget.waitSeconds ?? 30); + // A fresh timer starts with the shoot time on + _shootEnabled = !widget.timerEnabled || widget.shootEnabled; _reloadEnabled = widget.timerEnabled && widget.reloadEnabled; _waitEnabled = widget.timerEnabled && widget.waitEnabled; _fullTarget = widget.fullTarget; - _targetSelected = widget.timerEnabled; _changeTargetEnabled = widget.changeTargetEnabled; } - int _clamp(int v) => - (((v / _step).round() * _step).clamp(_minSeconds, _maxSeconds)); + int _clamp(int v) => (((v / _step).round() * _step).clamp(_minSeconds, _maxSeconds)); String _t(String key) => widget.translateFn(key); - void _notify() { - widget.onConfirm( - _shootEnabled ? _shoot : 0, - _reload, - _reloadEnabled, - _wait, - _waitEnabled, - _targetSelected ? _fullTarget : false, - ); + void _notify() => widget.onConfirm( + _shootEnabled || _fullTarget ? _shoot : 0, + _reload, + _reloadEnabled, + _wait, + _waitEnabled, + _fullTarget, + ); + + static String _clock(int s) => '${s ~/ 60}:${(s % 60).toString().padLeft(2, '0')}'; + + void _change(VoidCallback f) { + setState(f); + _notify(); } - String _label(int s) { - if (s < 60) return '${s}s'; - final m = s ~/ 60; - final rem = s % 60; - return rem == 0 ? '${m}m' : '${m}m ${rem}s'; - } - - Widget _buildToggleRow( - String label, - IconData icon, - Color color, - bool enabled, - void Function(bool) onToggle, - int value, - VoidCallback onDec, - VoidCallback onInc) { - return Column( - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, + Widget _row({ + required String label, + IconData? icon, + bool? enabled, // null: always on (shoot time) + ValueChanged? onToggle, + required int value, + required ValueChanged onValue, + }) { + final c = Palette.current; + final on = enabled ?? true; + return AppCard( + color: c.isDark ? c.card2 : c.card, + padding: const EdgeInsets.fromLTRB(12, 8, 8, 8), + child: SizedBox( + height: 46, + child: Row( children: [ - Row( - children: [ - Icon(icon, color: enabled ? color : Colors.white38, size: 18), - const SizedBox(width: 8), - Text(label, - style: TextStyle( - color: enabled ? Colors.white : Colors.white38, - fontSize: 15)), - ], - ), - Switch( - value: enabled, - activeThumbColor: color, - onChanged: onToggle, - ), - ], - ), - if (enabled) ...[ - const SizedBox(height: 4), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - const SizedBox(width: 26), - _stepBtn(Icons.remove, onDec), - SizedBox( - width: 72, - child: Text( - _label(value), - textAlign: TextAlign.center, - style: TextStyle( - color: color, fontSize: 22, fontWeight: FontWeight.bold), - ), - ), - _stepBtn(Icons.add, onInc), - const SizedBox(width: 26), - ], - ), - const SizedBox(height: 8), - ], - ], - ); - } - - Widget _buildAlwaysOnRow(String label, IconData icon, Color color, int value, - VoidCallback onDec, VoidCallback onInc) { - return Column( - children: [ - Row( - children: [ - Icon(icon, color: color, size: 18), + if (enabled == null) + SizedBox(width: 44, child: Icon(icon, size: 22, color: c.accent)) + else + SizedBox(width: 52, child: FittedBox(child: Switch(value: on, onChanged: onToggle))), const SizedBox(width: 8), - Text(label, - style: const TextStyle(color: Colors.white, fontSize: 15)), - ], - ), - const SizedBox(height: 4), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - const SizedBox(width: 26), - _stepBtn(Icons.remove, onDec), - SizedBox( - width: 72, - child: Text( - _label(value), - textAlign: TextAlign.center, - style: TextStyle( - color: color, fontSize: 22, fontWeight: FontWeight.bold), - ), + Expanded( + child: Text(label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 14.5, fontWeight: FontWeight.w600, color: on ? c.ink : c.muted)), + ), + Stepper3( + value: _clock(value), + valueWidth: 54, + onMinus: on && value > _minSeconds ? () => onValue(value - _step) : null, + onPlus: on && value < _maxSeconds ? () => onValue(value + _step) : null, + style: TextStyle( + fontSize: 17, fontWeight: FontWeight.w700, color: on ? c.ink : c.faint, fontFeatures: AppTheme.tnum), ), - _stepBtn(Icons.add, onInc), - const SizedBox(width: 26), ], ), - const SizedBox(height: 8), - ], - ); - } - - Widget _stepBtn(IconData icon, VoidCallback onTap) { - return InkWell( - onTap: onTap, - borderRadius: BorderRadius.circular(8), - child: Container( - width: 40, - height: 40, - decoration: BoxDecoration( - color: Colors.white10, borderRadius: BorderRadius.circular(8)), - child: Icon(icon, color: Colors.white, size: 20), - ), - ); - } - - Widget _buildTargetPill(bool fullTarget) { - final c = widget.bulletColor; - final selected = _targetSelected && _fullTarget == fullTarget; - final label = fullTarget ? _t('Full target') : _t('Single shot'); - final icon = fullTarget ? Icons.filter_none : Icons.looks_one_outlined; - return Expanded( - child: GestureDetector( - onTap: () { - setState(() { - if (_targetSelected && _fullTarget == fullTarget) { - _targetSelected = false; - } else { - _targetSelected = true; - _fullTarget = fullTarget; - if (fullTarget) _shootEnabled = true; - } - }); - _notify(); - }, - child: AnimatedContainer( - duration: const Duration(milliseconds: 150), - padding: const EdgeInsets.symmetric(vertical: 10), - decoration: BoxDecoration( - color: selected ? c.withValues(alpha: 0.15) : Colors.white10, - borderRadius: BorderRadius.circular(10), - border: Border.all( - color: selected ? c : Colors.transparent, width: 1.5), - ), - child: Column( - children: [ - Icon(icon, color: selected ? c : Colors.white38, size: 20), - const SizedBox(height: 4), - Text(label, - style: TextStyle( - color: selected ? c : Colors.white38, - fontSize: 11, - fontWeight: selected ? FontWeight.bold : FontWeight.normal, - )), - ], - ), - ), ), ); } @override Widget build(BuildContext context) { - final c = widget.bulletColor; + final c = Palette.current; return Column( mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - CameraSheetHeader( - title: _t('Shooting Timer'), - icon: Icons.timer, - iconColor: c, - ), - - // Single / Full target - Row( - children: [ - _buildTargetPill(false), - const SizedBox(width: 8), - _buildTargetPill(true), + CameraSheetHeader(title: _t('Shooting Timer')), + SegmentedTabs( + items: [ + SegmentItem(_t('Single shot'), Icons.looks_one_outlined), + SegmentItem(_t('Full target'), Icons.layers_outlined), ], + selected: _fullTarget ? 1 : 0, + onSelect: (i) => _change(() { + _fullTarget = i == 1; + if (_fullTarget) _shootEnabled = true; + }), ), - const SizedBox(height: 12), - const Divider(color: Colors.white12, height: 4), - const SizedBox(height: 8), - - // Shoot time — always on in full target, toggleable in single shot - if (_targetSelected && _fullTarget) - _buildAlwaysOnRow( - _t('Shoot time'), - Icons.play_circle_outline, - Colors.blue, - _shoot, - () { - setState(() { - if (_shoot > _minSeconds) _shoot -= _step; - }); - _notify(); - }, - () { - setState(() { - if (_shoot < _maxSeconds) _shoot += _step; - }); - _notify(); - }, - ) - else - _buildToggleRow( - _t('Shoot time'), - Icons.play_circle_outline, - Colors.blue, - _shootEnabled, - (v) { - setState(() => _shootEnabled = v); - _notify(); - }, - _shoot, - () { - setState(() { - if (_shoot > _minSeconds) _shoot -= _step; - }); - _notify(); - }, - () { - setState(() { - if (_shoot < _maxSeconds) _shoot += _step; - }); - _notify(); - }, - ), - const Divider(color: Colors.white12, height: 4), - const SizedBox(height: 8), - - // Reload toggle + stepper - _buildToggleRow( - _t('Reload time'), - Icons.refresh, - Colors.orange, - _reloadEnabled, - (v) { - setState(() => _reloadEnabled = v); - _notify(); - }, - _reload, - () { - setState(() { - if (_reload > _minSeconds) _reload -= _step; - }); - _notify(); - }, - () { - setState(() { - if (_reload < _maxSeconds) _reload += _step; - }); - _notify(); + const SizedBox(height: 14), + _row( + label: _t('Shoot time'), + icon: Icons.play_arrow_outlined, + enabled: _fullTarget ? null : _shootEnabled, + onToggle: (v) => _change(() => _shootEnabled = v), + value: _shoot, + onValue: (v) => _change(() => _shoot = v), + ), + const SizedBox(height: 10), + _row( + label: _t('Reload time'), + enabled: _reloadEnabled, + onToggle: (v) => _change(() => _reloadEnabled = v), + value: _reload, + onValue: (v) => _change(() => _reload = v), + ), + const SizedBox(height: 10), + _row( + label: _t('Wait time'), + enabled: _waitEnabled, + onToggle: (v) => _change(() => _waitEnabled = v), + value: _wait, + onValue: (v) => _change(() => _wait = v), + ), + const SizedBox(height: 10), + ToggleRow( + icon: Icons.description_outlined, + label: _t('Change target sign'), + value: _changeTargetEnabled, + onChanged: (v) { + setState(() => _changeTargetEnabled = v); + widget.onChangeTargetToggle(v); }, ), - const Divider(color: Colors.white12, height: 4), - const SizedBox(height: 8), - - // Wait toggle + stepper - _buildToggleRow( - _t('Wait time'), - Icons.hourglass_empty, - Colors.red, - _waitEnabled, - (v) { - setState(() => _waitEnabled = v); - _notify(); - }, - _wait, - () { - setState(() { - if (_wait > _minSeconds) _wait -= _step; - }); - _notify(); - }, - () { - setState(() { - if (_wait < _maxSeconds) _wait += _step; - }); - _notify(); - }, - ), - const Divider(color: Colors.white12, height: 12), - const SizedBox(height: 4), - - // Change target overlay toggle - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Row( - children: [ - Icon(Icons.article_outlined, - color: _changeTargetEnabled ? Colors.green : Colors.white38, - size: 18), - const SizedBox(width: 8), - Text(_t('Change target sign'), - style: TextStyle( - color: _changeTargetEnabled - ? Colors.white - : Colors.white38, - fontSize: 15)), - ], - ), - Switch( - value: _changeTargetEnabled, - activeThumbColor: Colors.green, - onChanged: (v) { - setState(() => _changeTargetEnabled = v); - widget.onChangeTargetToggle(v); - }, - ), - ], + const SizedBox(height: 10), + Text(_t('Cycle: shot → reload → wait. On a full target »Change target!« is shown.'), + style: TextStyle(fontSize: 12, height: 1.35, color: c.muted)), + const SizedBox(height: 16), + PrimaryButton( + label: _t('Start timer'), + icon: Icons.play_arrow_rounded, + onTap: _shootEnabled || _reloadEnabled || _waitEnabled || _fullTarget + ? () { + _notify(); // what the sheet shows is what runs + widget.onStart(); + } + : null, ), ], ); diff --git a/lib/screens/target_screen.dart b/lib/screens/target_screen.dart index 4f70cf8..7697edb 100644 --- a/lib/screens/target_screen.dart +++ b/lib/screens/target_screen.dart @@ -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 createState() => _TargetScreenState(); +} + +class _TargetScreenState extends State { + 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 _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))), + ], + ), + ], + ), + ); + } } diff --git a/lib/screens/target_view.dart b/lib/screens/target_view.dart index c2e98ba..d9036a5 100644 --- a/lib/screens/target_view.dart +++ b/lib/screens/target_view.dart @@ -1,17 +1,20 @@ import 'dart:io'; -import 'dart:typed_data'; +import 'package:flutter/foundation.dart' show kDebugMode; import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; +import '../services/app_settings.dart'; +import '../services/target_repository.dart'; import '../theme/app_theme.dart'; -import 'package:flutter/services.dart' show rootBundle; -import 'dart:convert'; -import 'package:image/image.dart' as img; -import 'package:shared_preferences/shared_preferences.dart'; -import '../utils/translations.dart'; -import '../utils/target_scoring.dart'; -import '../utils/target_colors.dart'; +import '../utils/format.dart'; +import '../widgets/bar_list.dart'; import '../widgets/result_share.dart'; -import 'session_screen.dart' show targetCount, shotCount; +import '../widgets/target_face.dart'; +import '../widgets/ui.dart'; +import 'session_screen.dart' show targetCount, shotCount, confirmDelete; +/// The result of one target, or of a whole session on one target +/// ([isCombinedView]): the score, the target with every hit, the hits grouped +/// by value, sharing, and for a session a bar chart of its targets. class TargetViewScreen extends StatefulWidget { final List jsonFiles; final Function refreshFolders; @@ -29,1112 +32,379 @@ class TargetViewScreen extends StatefulWidget { } class _TargetViewScreenState extends State { - final int _currentIndex = 0; - List _bullets = []; - List _scores = []; // score of each bullet, same order as _bullets - List _scaledBullets = []; // Bullets scaled to display target size - int _totalScore = 0; - int _shotCount = 0; // shots fired, misses included (bulletCount) - Map _folderChartScores = {}; - Uint8List? _targetImageBytes; - img.Image? _targetImageDecoded; - String _date = ''; - int? _highlightedBulletIndex; - int? _pressedScoreGroup; - late String _targetFilePath; - late String targetAssetPath; - late String _selectedTargetPath; // For display - double _scaleFactorX = 1.0; // Scale factor for X coordinate - double _scaleFactorY = 1.0; // Scale factor for Y coordinate + List? _targets; // one per file, in the order given + TargetHits _all = TargetHits.empty; + int? _number; // 1-based number of a single target in its session + DateTime? _date; + int? _pressedValue; // tile held down: its hits are highlighted + bool _showChart = false; + bool _showScoring = false; // debug builds: long press the target + final _zoom = TransformationController(); - Color _bulletColor = Colors.blue; // default/fallback bullet color - String _selectedLanguage = 'English'; - Color _backgroundColor = Colors.white; - bool _showChartView = false; // Toggle between bullet view and chart view + String get _folder => widget.jsonFiles.first.parent.path.split('/').last; @override void initState() { super.initState(); - targetAssetPath = 'assets/target.png'; // Default - _initializeScreen(); + _load(); } - Future _initializeScreen() async { - await Future.wait([ - _loadBulletColor(), - _loadLanguage(), - _loadSelectedTarget(), - ]); - await _loadJsonAndImage(); + @override + void dispose() { + _zoom.dispose(); + super.dispose(); } - String _t(String key) { - return AppTranslations.translate(key, _selectedLanguage); - } - - Future _loadLanguage() async { - final prefs = await SharedPreferences.getInstance(); + Future _load() async { + final targets = await TargetRepository.readAllHits(widget.jsonFiles); + int? number; + DateTime? date; + final sessions = await TargetRepository.loadSessions(); + final session = sessions.where((x) => x.name == _folder).firstOrNull; + if (session != null) { + date = session.date; + if (!widget.isCombinedView) { + final i = session.targets + .indexWhere((t) => t.file.path == widget.jsonFiles.first.path); + if (i >= 0) { + number = i + 1; + date = session.targets[i].shotAt; + } + } + } + date ??= _parseDate(targets.isEmpty ? '' : targets.last.date); + if (!mounted) return; setState(() { - _selectedLanguage = prefs.getString('language') ?? 'Slovenian'; + _targets = targets; + _all = TargetHits.combine(targets); + _number = number; + _date = date; }); } - Future _loadSelectedTarget() async { - final prefs = await SharedPreferences.getInstance(); - final selectedTarget = - prefs.getString('selectedTarget') ?? 'assets/target.png'; - // Always use default target for bullet positioning - targetAssetPath = 'assets/target.png'; - // Store selected target for display - _selectedTargetPath = selectedTarget; - _backgroundColor = _getBackgroundColorForTarget(selectedTarget); - } - - // One source of truth for target colors (utils/target_colors.dart) - Color _getBackgroundColorForTarget(String targetPath) => - TargetColors.getBackgroundColor(targetPath); - - Future _loadBulletColor() async { - final prefs = await SharedPreferences.getInstance(); - final selectedColor = prefs.getString('bulletColor') ?? 'Blue'; - - setState(() { - _bulletColor = _getColorFromName(selectedColor); - }); - } - - 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 - } - } - - // Bullets, their scores and the total of one saved target. 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 as saving. - static ({List bullets, List scores, int total}) _readTarget( - Map 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 (bullets: bullets, scores: scores, total: total); - } - - Future _loadJsonAndImage() async { - try { - // Load default target for bullet positioning reference - final defaultByteData = await rootBundle.load(targetAssetPath); - final defaultBytes = defaultByteData.buffer.asUint8List(); - img.Image? defaultTargetDecoded = img.decodeImage(defaultBytes); - - if (defaultTargetDecoded == null) { - debugPrint("Failed to decode default target image."); - return; - } - - // Load selected target for display - final displayByteData = await rootBundle.load(_selectedTargetPath); - final displayBytes = displayByteData.buffer.asUint8List(); - _targetImageDecoded = img.decodeImage(displayBytes); - - if (_targetImageDecoded == null) { - debugPrint("Failed to decode display target image."); - return; - } - - _targetImageBytes = - Uint8List.fromList(img.encodePng(_targetImageDecoded!)); - - if (widget.isCombinedView) { - // In combined view, collect all bullets from all files - final allBullets = []; - final allScores = []; - final chartScores = {}; - var total = 0; - String latestDate = 'Unknown Date'; - - var shots = 0; - for (var file in widget.jsonFiles) { - final jsonString = await file.readAsString(); - final data = jsonDecode(jsonString) as Map; - final target = _readTarget(data); - - shots += (data['bulletCount'] as int?) ?? target.bullets.length; - allBullets.addAll(target.bullets); - allScores.addAll(target.scores); - total += target.total; - chartScores[chartScores.length + 1] = target.total; - - if (data['date'] != null) { - latestDate = data['date']; - } - } - - // Parse and convert date format from yyyy-m-d to dd/MM/yyyy - String rawDate = latestDate; - if (rawDate != 'Unknown Date' && rawDate.contains('-')) { - try { - final parts = rawDate.split('-'); - if (parts.length == 3) { - final year = parts[0]; - final month = parts[1].padLeft(2, '0'); - final day = parts[2].padLeft(2, '0'); - _date = '$day/$month/$year'; - } else { - _date = rawDate; - } - } catch (e) { - _date = rawDate; - } - } else { - _date = rawDate; - } - - _bullets = allBullets; - _scores = allScores; - _totalScore = total; - _folderChartScores = chartScores; - _shotCount = shots; - } else { - // Single file view - load from current file - final currentFile = widget.jsonFiles[_currentIndex]; - final jsonString = await currentFile.readAsString(); - final data = jsonDecode(jsonString); - - // Parse and convert date format from yyyy-m-d to dd/MM/yyyy - String rawDate = data['date'] ?? 'Unknown Date'; - if (rawDate != 'Unknown Date' && rawDate.contains('-')) { - try { - final parts = rawDate.split('-'); - if (parts.length == 3) { - final year = parts[0]; - final month = parts[1].padLeft(2, '0'); - final day = parts[2].padLeft(2, '0'); - _date = '$day/$month/$year'; - } else { - _date = rawDate; - } - } catch (e) { - _date = rawDate; - } - } else { - _date = rawDate; - } - final target = _readTarget(data as Map); - _bullets = target.bullets; - _scores = target.scores; - _totalScore = target.total; - _shotCount = (data['bulletCount'] as int?) ?? _bullets.length; - } - - _targetFilePath = widget.isCombinedView - ? widget.jsonFiles.first.path - : widget.jsonFiles[_currentIndex].path; - - // Calculate scale factors based on image dimensions - _scaleFactorX = _targetImageDecoded!.width / defaultTargetDecoded.width; - _scaleFactorY = _targetImageDecoded!.height / defaultTargetDecoded.height; - - // Scale bullets to match display target size - _scaledBullets = _bullets.map((bullet) { - return Offset( - bullet.dx * _scaleFactorX, - bullet.dy * _scaleFactorY, - ); - }).toList(); - - setState(() {}); - } catch (e) { - debugPrint("Error loading JSON or image: $e"); - } + // Saved targets store dd/MM/yyyy + static DateTime? _parseDate(String raw) { + final p = raw.split('/'); + if (p.length != 3) return null; + return DateTime.tryParse( + '${p[2]}-${p[1].padLeft(2, '0')}-${p[0].padLeft(2, '0')}'); } Future _deleteTarget() async { + final s = AppSettings.instance; + final ok = await confirmDelete(context, s.t('Are you sure you want to delete this target?')); + if (!ok) return; try { - final file = File(_targetFilePath); - await file.delete(); + await File(widget.jsonFiles.first.path).delete(); + TargetRepository.notifyChanged(); widget.refreshFolders(); - if (!mounted) return; - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Target deleted')), - ); - Navigator.pop(context); + if (mounted) Navigator.pop(context); } catch (e) { - debugPrint("Error deleting target: $e"); + debugPrint('Error deleting target: $e'); if (!mounted) return; ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Failed to delete target')), - ); + SnackBar(content: Text(s.t('Failed to delete target')))); } } - // What the screen shows, as one image: target and tiles left, chart right - void _share() { - final scores = _scores; - - final List<(String, String)> tiles; - final List> chart; - if (widget.isCombinedView) { - final groups = {}; - for (final s in scores) { - groups[s] = (groups[s] ?? 0) + 1; - } - final sorted = groups.entries.toList()..sort((a, b) => b.key.compareTo(a.key)); - tiles = [for (final e in sorted) ('${e.value}x', '${e.key}')]; - chart = _folderChartScores.entries.toList()..sort((a, b) => a.key.compareTo(b.key)); - } else { - final order = List.generate(scores.length, (i) => i) - ..sort((a, b) => scores[b].compareTo(scores[a])); - tiles = [for (final i in order) ('${i + 1}', '${scores[i]}')]; - chart = [for (int i = 0; i < scores.length; i++) MapEntry(i + 1, scores[i])]; + // Values shown as tiles: 10 down to 7 always (so a missing 10 shows as 0×), + // plus any lower value that was hit; at most 6 tiles. + List<(int value, int count)> _groups() { + final counts = {}; + for (final v in _all.scores) { + counts[v] = (counts[v] ?? 0) + 1; } + final values = {10, 9, 8, 7, ...counts.keys}.toList() + ..sort((a, b) => b.compareTo(a)); + return [for (final v in values.take(6)) (v, counts[v] ?? 0)]; + } - final folder = File(_targetFilePath).parent.path.split('/').last; + String get _title => widget.isCombinedView + ? _folder + : '${AppSettings.instance.t('Target')} ${_number ?? ''}'.trim(); + + String _subtitle(AppSettings s) { + final date = _date; + if (widget.isCombinedView) { + return [ + if (date != null) dayDate(date, year: true), + targetCount(widget.jsonFiles.length), + shotCount(_all.shots), + ].join(' · '); + } + return [_folder, if (date != null) DateFormat('d. M. yyyy').format(date)] + .join(' · '); + } + + void _share() { + final s = AppSettings.instance; + final targets = _targets; + if (targets == null) return; + final best = targets.isEmpty + ? 0 + : targets.map((t) => t.total).reduce((a, b) => a > b ? a : b); shareResult( context, ResultShareData( - title: folder, - date: _date.replaceAll('/', '.'), - countsLine: widget.isCombinedView - ? '${targetCount(widget.jsonFiles.length)} · ${shotCount(_shotCount)}' - : shotCount(_shotCount), - total: _totalScore, - averagePerShot: _shotCount == 0 ? null : _totalScore / _shotCount, - targetImage: _targetImageBytes!, - targetImageSize: Size(_targetImageDecoded!.width.toDouble(), - _targetImageDecoded!.height.toDouble()), - bullets: _scaledBullets, - bulletDiameter: ((_scaleFactorX + _scaleFactorY) / 2) * 53, - bulletColor: _bulletColor, - targetBackground: _backgroundColor, - tiles: tiles, - chart: chart, - chartPerShot: !widget.isCombinedView, - t: _t, + title: _title, + subtitle: _subtitle(s), + total: _all.total, + averagePerShot: _all.shots == 0 ? null : _all.total / _all.shots, + style: s.target, + hits: _all.bullets, + tiles: widget.isCombinedView + ? [for (final (v, n) in _groups()) ('$n×', '$v', n > 0)] + : [ + for (final v in [ + ..._all.scores + ]..sort((a, b) => b.compareTo(a))) + (null, '$v', true), + ], + chartTitle: + s.t(widget.isCombinedView ? 'Points per target' : 'Hits by value'), + bars: widget.isCombinedView + ? [ + for (int i = 0; i < targets.length; i++) + BarEntry('T${i + 1}', targets[i].total.toDouble(), + '${targets[i].total}', + highlight: targets[i].total == best), + ] + : [ + for (final v in [10, 9, 8, 7, 6]) + BarEntry( + '$v', + _all.scores.where((x) => x == v).length.toDouble(), + '${_all.scores.where((x) => x == v).length}×', + highlight: v == 10, + goldLabel: v == 10), + ], + barMax: widget.isCombinedView + ? _perTargetMax(targets) + : _all.shots.toDouble().clamp(1, 1000), + t: s.t, ), ); } + // Top of the per-target chart: the most a target of this session can score + double _perTargetMax(List targets) { + final shots = targets.isEmpty + ? 5 + : targets.map((t) => t.shots).reduce((a, b) => a > b ? a : b); + return (shots * 10).toDouble().clamp(10, 1000); + } + @override Widget build(BuildContext context) { - return Scaffold( - backgroundColor: _backgroundColor, - appBar: AppBar( - // Score on top, where it is read first; the date sits in the bottom bar - // Same look as the SKUPAJ total on the preview screen - title: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Text( - _t('Total score').replaceAll(':', '').toUpperCase(), - style: const TextStyle( - fontSize: 11, - letterSpacing: 1.5, - color: Colors.white54, - fontWeight: FontWeight.w600, + return ListenableBuilder( + listenable: AppSettings.instance, + builder: (context, _) { + final s = AppSettings.instance; + final c = Palette.current; + final loaded = _targets != null; + return Scaffold( + body: Column( + children: [ + BackHeader( + title: loaded ? _title : '', + subtitle: loaded ? _subtitle(s) : null, + centered: true), + if (!loaded) + const Expanded( + child: Center(child: CircularProgressIndicator())) + else ...[ + _scoreRow(s, c), + Expanded(child: _showChart ? _chart(s, c) : _target(s)), + if (!_showChart) _tiles(c), + _actions(s, c), + ], + ], + ), + ); + }, + ); + } + + Widget _scoreRow(AppSettings s, Palette c) { + final avg = _all.shots == 0 ? null : _all.total / _all.shots; + return Padding( + padding: const EdgeInsets.fromLTRB(AppTheme.edge, 12, AppTheme.edge, 0), + child: Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text('${_all.total}', + style: TextStyle( + fontSize: 56, + height: 1, + fontWeight: FontWeight.w800, + letterSpacing: -1.5, + color: c.ink, + fontFeatures: AppTheme.tnum)), + const SizedBox(width: 8), + Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Text( + widget.isCombinedView + ? s.t('total').toLowerCase() + : '/ ${_all.shots * 10}', + style: TextStyle( + fontSize: widget.isCombinedView ? 15 : 20, + fontWeight: FontWeight.w600, + color: c.muted), + ), + ), + const Spacer(), + if (avg != null) + Column( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text(dec(avg), + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.w700, + color: c.ink, + fontFeatures: AppTheme.tnum)), + Text(s.t('per shot'), + style: TextStyle(fontSize: 12, color: c.muted)), + ], + ), + ], + ), + ); + } + + // The target fills the free space; pinch to zoom in (the default target is + // vectors, so its lines stay sharp), double tap to zoom back out. + Widget _target(AppSettings s) { + final pressed = _pressedValue; + final scores = _all.scores; + return GestureDetector( + onDoubleTap: () => _zoom.value = Matrix4.identity(), + child: InteractiveViewer( + transformationController: _zoom, + minScale: 1, + maxScale: 6, + child: Center( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 8), + // Debug builds only: long press shows the scoring radii over the design + child: GestureDetector( + onLongPress: kDebugMode + ? () => setState(() => _showScoring = !_showScoring) + : null, + child: TargetFace( + style: s.target, + hits: _all.bullets, + hitColor: s.bulletColor, + showScoring: _showScoring, + highlighted: pressed == null + ? const {} + : { + for (int i = 0; i < scores.length; i++) + if (scores[i] == pressed) i + }, ), ), - Text( - "$_totalScore", - style: const TextStyle( - fontSize: 26, - height: 1.1, - fontWeight: FontWeight.bold, - color: Colors.white, + ), + ), + ), + ); + } + + Widget _tiles(Palette c) { + final groups = _groups(); + return Padding( + padding: const EdgeInsets.fromLTRB(AppTheme.edge, 8, AppTheme.edge, 0), + child: Row( + children: [ + for (int i = 0; i < groups.length; i++) ...[ + if (i > 0) const SizedBox(width: 10), + Expanded( + child: ScoreTile( + top: '${groups[i].$2}×', + value: '${groups[i].$1}', + filled: groups[i].$2 > 0, + height: 64, + onTapDown: groups[i].$2 == 0 + ? null + : (_) => setState(() => _pressedValue = groups[i].$1), + onTapEnd: () => setState(() => _pressedValue = null), ), ), ], - ), - backgroundColor: Colors.grey[900], - centerTitle: true, - iconTheme: const IconThemeData(color: Colors.white), - actions: [ - IconButton( - tooltip: _t('Share'), - icon: const Icon(Icons.share_rounded), - onPressed: _targetImageDecoded == null ? null : _share, - ), - // The combined view shows a whole session; deleting would remove an - // arbitrary one of its targets. Sessions are deleted from the Book list. - if (!widget.isCombinedView) - IconButton( - icon: const Icon(Icons.delete), - color: Colors.red, - onPressed: () { - showDialog( - context: context, - builder: (BuildContext context) { - return Dialog( - backgroundColor: Colors.grey[900], - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(16)), - child: Padding( - padding: const EdgeInsets.all(24.0), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Text( - _t('Delete Target'), - style: const TextStyle( - color: Colors.white, - fontSize: 20, - fontWeight: FontWeight.bold, - ), - textAlign: TextAlign.center, - ), - const SizedBox(height: 16), - Text( - _t("Are you sure you want to delete this target?"), - style: const TextStyle( - color: Colors.white70, fontSize: 16), - textAlign: TextAlign.center, - ), - const SizedBox(height: 24), - - // "Yes" Button - SizedBox( - width: double.infinity, - child: ElevatedButton( - onPressed: () { - Navigator.of(context).pop(); - _deleteTarget(); // call your delete function - }, - style: ElevatedButton.styleFrom( - backgroundColor: Colors.redAccent, - foregroundColor: Colors.white, - padding: - const EdgeInsets.symmetric(vertical: 14), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(12), - ), - ), - child: Text(_t("Yes, delete")), - ), - ), - const SizedBox(height: 12), - - // "Cancel" Button - SizedBox( - width: double.infinity, - child: ElevatedButton( - onPressed: () => Navigator.of(context).pop(), - style: ElevatedButton.styleFrom( - backgroundColor: Colors.grey[800], - foregroundColor: Colors.white, - padding: - const EdgeInsets.symmetric(vertical: 14), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(12), - ), - ), - child: const Text("Cancel"), - ), - ), - ], - ), - ), - ); - }, - ); - }, - ), ], ), - body: _targetImageDecoded == null - ? const Center(child: CircularProgressIndicator()) - : _showChartView - ? _buildChartView() - : Column( - children: [ - Expanded( - child: LayoutBuilder( - builder: (context, constraints) { - final imgWidth = _targetImageDecoded!.width.toDouble(); - final imgHeight = _targetImageDecoded!.height.toDouble(); - final screenWidth = constraints.maxWidth; - final screenHeight = constraints.maxHeight; - - final aspectRatio = imgWidth / imgHeight; - final screenAspect = screenWidth / screenHeight; - - double displayWidth, displayHeight, offsetX, offsetY; - - if (aspectRatio > screenAspect) { - displayWidth = screenWidth; - displayHeight = screenWidth / aspectRatio; - offsetX = 0; - offsetY = (screenHeight - displayHeight) / 2; - } else { - displayHeight = screenHeight; - displayWidth = screenHeight * aspectRatio; - offsetY = 0; - offsetX = (screenWidth - displayWidth) / 2; - } - - final scaleX = displayWidth / imgWidth; - final scaleY = displayHeight / imgHeight; - // Scale bullet size by target scale factors and display scale factors - final dynamicBulletSize = - (((_scaleFactorX + _scaleFactorY) / 2) * 53) * - ((scaleX + scaleY) / 2); - - return Stack( - children: [ - Positioned( - left: offsetX, - top: offsetY, - width: displayWidth, - height: displayHeight, - child: Image.memory(_targetImageBytes!, - fit: BoxFit.fill), - ), - ..._scaledBullets.asMap().entries.map((entry) { - final i = entry.key; - final scaledBullet = entry.value; - // Scaled bullets are already scaled to display target dimensions - final dx = scaledBullet.dx * scaleX + offsetX; - final dy = scaledBullet.dy * scaleY + offsetY; - final score = _scores[i]; - final isHighlighted = widget.isCombinedView - ? (_pressedScoreGroup == score) - : (i == _highlightedBulletIndex); - - return Positioned( - left: dx - dynamicBulletSize / 2, - top: dy - dynamicBulletSize / 2, - child: Container( - width: dynamicBulletSize, - height: dynamicBulletSize, - decoration: BoxDecoration( - color: _bulletColor.withValues(alpha: 0.8), - shape: BoxShape.circle, - border: Border.all( - color: isHighlighted - ? Colors.red - : Colors.black, - width: isHighlighted ? 3 : 1, - ), - ), - ), - ); - }), - ], - ); - }, - ), - ), - const SizedBox(height: 12), - Container( - color: _backgroundColor, - padding: - const EdgeInsets.symmetric(horizontal: 12, vertical: 6), - child: Row( - children: widget.isCombinedView - ? _buildGroupedScoreButtons() - : _buildIndividualScoreButtons(), - ), - ), - const SizedBox(height: 12), - ], - ), - bottomNavigationBar: BottomAppBar( - color: Colors.grey[900], - padding: EdgeInsets.zero, - child: SizedBox( - height: 60, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - // Date - Row( - children: [ - const Icon(Icons.calendar_today, - size: 20, color: Colors.white), - const SizedBox(width: 12), - Text( - // Saved targets store dd/MM/yyyy; show it the Slovenian way - _date.replaceAll('/', '.'), - style: const TextStyle( - fontSize: 16, - fontWeight: FontWeight.w600, - color: Colors.white, - ), - ), - ], - ), - // Chart toggle button - IconButton( - onPressed: () { - setState(() { - _showChartView = !_showChartView; - }); - }, - icon: Icon( - _showChartView ? Icons.bar_chart : Icons.image, - color: Colors.white, - size: 24, - ), - padding: EdgeInsets.zero, - constraints: const BoxConstraints(), - splashRadius: 24, - ), - ], - ), - ), - ), - ), ); } - Widget _buildChartView() { - if (widget.isCombinedView) { - // Folder view: each target position as a bar with combined scores - return _buildFolderChartView(); - } else { - // Single file view: each shot as a bar - return _buildSingleFileChartView(); - } - } - - Widget _buildFolderChartView() { - final Map targetScores = _folderChartScores; - - if (targetScores.isEmpty) { - return Center( - child: Text( - _t('No data available'), - style: const TextStyle(color: Colors.white70), - ), - ); - } - - final sortedTargets = targetScores.entries.toList() - ..sort((a, b) => a.key.compareTo(b.key)); - - final maxScore = sortedTargets.map((e) => e.value).reduce((a, b) => a > b ? a : b).toDouble(); - + Widget _chart(AppSettings s, Palette c) { + final targets = _targets!; + final best = targets.isEmpty + ? 0 + : targets.map((t) => t.total).reduce((a, b) => a > b ? a : b); + final max = _perTargetMax(targets); return Padding( - padding: const EdgeInsets.only(left: 16, right: 16, top: 16, bottom: 8), - child: Card( - color: Colors.white, - elevation: 2, - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), - child: Padding( - padding: const EdgeInsets.all(16), - child: CustomPaint( - painter: BarChartPainter( - data: sortedTargets, - maxScore: maxScore, - bulletColor: _bulletColor, - backgroundColor: Colors.white, - selectedLanguage: _selectedLanguage, - translateFunc: _t, + padding: const EdgeInsets.fromLTRB(AppTheme.edge, 16, AppTheme.edge, 0), + child: AppCard( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Kicker(s.t('Points per target'), + padding: const EdgeInsets.only(bottom: 14)), + Expanded( + child: BarList( + entries: [ + for (int i = 0; i < targets.length; i++) + BarEntry('T${i + 1}', targets[i].total.toDouble(), + '${targets[i].total}', + highlight: targets[i].total == best), + ], + max: max, + ticks: [0, max / 2, max], + ), ), - size: Size.infinite, - ), + const SizedBox(height: 8), + Text(s.t('Gold = best target of the session'), + style: TextStyle(fontSize: 11.5, color: c.muted)), + ], ), ), ); } - Widget _buildSingleFileChartView() { - // Single file view: each shot as a bar - final Map shotScores = {}; - for (int i = 0; i < _bullets.length; i++) { - shotScores[i + 1] = _scores[i]; // Shot number starts at 1 - } - - if (shotScores.isEmpty) { - return Center( - child: Text( - _t('No data available'), - style: const TextStyle(color: Colors.white70), - ), - ); - } - - final sortedShots = shotScores.entries.toList() - ..sort((a, b) => a.key.compareTo(b.key)); - - final maxScore = sortedShots.map((e) => e.value).reduce((a, b) => a > b ? a : b).toDouble(); - + Widget _actions(AppSettings s, Palette c) { return Padding( - padding: const EdgeInsets.only(left: 16, right: 16, top: 16, bottom: 8), - child: Card( - color: Colors.white, - elevation: 2, - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), - child: Padding( - padding: const EdgeInsets.all(16), - child: CustomPaint( - painter: BarChartPainter( - data: sortedShots, - maxScore: maxScore, - bulletColor: _bulletColor, - isShotView: true, - backgroundColor: Colors.white, - selectedLanguage: _selectedLanguage, - translateFunc: _t, - xAxisLabelKey: 'Points', + padding: EdgeInsets.fromLTRB(AppTheme.edge, 16, AppTheme.edge, + 12 + MediaQuery.paddingOf(context).bottom), + child: Row( + children: [ + Expanded( + child: PrimaryButton( + label: s.t('Share result'), + icon: Icons.share_outlined, + onTap: _share)), + const SizedBox(width: 10), + if (widget.isCombinedView) + SquareButton( + size: 52, + icon: _showChart ? Icons.image_outlined : Icons.bar_chart_rounded, + tooltip: s.t(_showChart ? 'Target' : 'Chart'), + onTap: () => setState(() => _showChart = !_showChart), + ) + else + // The combined view shows a whole session; deleting would remove an + // arbitrary one of its targets. Sessions are deleted from Knjiga. + SquareButton( + size: 52, + icon: Icons.delete_outline_rounded, + color: c.red, + background: c.redSoft, + tooltip: s.t('Delete'), + onTap: _deleteTarget, ), - size: Size.infinite, - ), - ), + ], ), ); } - - List _buildGroupedScoreButtons() { - final Map scoreGroups = {}; - for (final score in _scores) { - scoreGroups[score] = (scoreGroups[score] ?? 0) + 1; - } - - // Sort scores descending (10 → 0) - final sortedEntries = scoreGroups.entries.toList() - ..sort((a, b) => b.key.compareTo(a.key)); - - return sortedEntries.map((entry) { - final score = entry.key; - final count = entry.value; - - return Expanded( - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 6), - child: GestureDetector( - onTapDown: (_) => setState(() => _pressedScoreGroup = score), - onTapUp: (_) => setState(() => _pressedScoreGroup = null), - onTapCancel: () => setState(() => _pressedScoreGroup = null), - child: Container( - height: 100, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(16), - boxShadow: const [ - BoxShadow( - color: Colors.black26, - offset: Offset(0, 2), - blurRadius: 6, - ), - ], - ), - child: Column( - children: [ - Container( - height: 30, - decoration: BoxDecoration( - color: Surfaces.current.card, - borderRadius: const BorderRadius.only( - topLeft: Radius.circular(16), - topRight: Radius.circular(16), - ), - ), - alignment: Alignment.center, - child: FittedBox( - fit: BoxFit.scaleDown, - child: Text( - '${count}x', - style: TextStyle( - fontWeight: FontWeight.bold, - fontSize: 14, - color: Surfaces.current.textPrimary, - ), - ), - ), - ), - Expanded( - child: Container( - decoration: BoxDecoration( - color: _pressedScoreGroup == score - ? Colors.red[400] - : _bulletColor.withValues(alpha: 0.85), - borderRadius: const BorderRadius.only( - bottomLeft: Radius.circular(16), - bottomRight: Radius.circular(16), - ), - ), - alignment: Alignment.center, - child: FittedBox( - fit: BoxFit.scaleDown, - child: Text( - '$score', - style: const TextStyle( - fontSize: 28, - fontWeight: FontWeight.bold, - color: Colors.white, - ), - ), - ), - ), - ), - ], - ), - ), - ), - ), - ); - }).toList(); - } - - List _buildIndividualScoreButtons() { - final scoredBullets = _bullets.asMap().entries.map((entry) { - final index = entry.key; - final bullet = entry.value; - return {'index': index, 'score': _scores[index], 'bullet': bullet}; - }).toList(); - - // Sort descending by score - scoredBullets - .sort((a, b) => (b['score'] as int).compareTo(a['score'] as int)); - - return scoredBullets.map((entry) { - final int index = entry['index'] as int; - final int score = entry['score'] as int; - - return Expanded( - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 6), - child: GestureDetector( - onTapDown: (_) => setState(() => _highlightedBulletIndex = index), - onTapUp: (_) => setState(() => _highlightedBulletIndex = null), - onTapCancel: () => setState(() => _highlightedBulletIndex = null), - child: Container( - height: 100, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(16), - boxShadow: const [ - BoxShadow( - color: Colors.black26, - offset: Offset(0, 2), - blurRadius: 6, - ), - ], - ), - child: Column( - children: [ - Container( - height: 30, - decoration: BoxDecoration( - color: Surfaces.current.card, - borderRadius: const BorderRadius.only( - topLeft: Radius.circular(16), - topRight: Radius.circular(16), - ), - ), - alignment: Alignment.center, - child: Text( - '${index + 1}', - style: TextStyle( - fontWeight: FontWeight.bold, - fontSize: 14, - color: Surfaces.current.textPrimary, - ), - ), - ), - Expanded( - child: Container( - decoration: BoxDecoration( - color: _highlightedBulletIndex == index - ? Colors.red[400] - : _bulletColor.withValues(alpha: 0.85), - borderRadius: const BorderRadius.only( - bottomLeft: Radius.circular(16), - bottomRight: Radius.circular(16), - ), - ), - alignment: Alignment.center, - child: Text( - '$score', - style: const TextStyle( - fontSize: 28, - fontWeight: FontWeight.bold, - color: Colors.white, - ), - ), - ), - ), - ], - ), - ), - ), - ), - ); - }).toList(); - } -} - -class BarChartPainter extends CustomPainter { - final List> data; - final double maxScore; - final Color bulletColor; - final bool isShotView; - final Color backgroundColor; - final String selectedLanguage; - final Function(String) translateFunc; - final String? xAxisLabelKey; - - BarChartPainter({ - required this.data, - required this.maxScore, - required this.bulletColor, - this.isShotView = false, - this.backgroundColor = Colors.white, - this.selectedLanguage = 'English', - required this.translateFunc, - this.xAxisLabelKey, - }); - - @override - void paint(Canvas canvas, Size size) { - const leftLabelWidth = 50.0; - const padding = 24.0; - const bottomPadding = 35.0; - final chartWidth = size.width - leftLabelWidth - padding; - final chartHeight = size.height - padding - bottomPadding; - - // Determine if background is light or dark - final isLightBackground = _isLightColor(backgroundColor); - final axisColor = isLightBackground ? Colors.black54 : Colors.white54; - final gridColor = isLightBackground - ? Colors.black.withValues(alpha: 0.08) - : Colors.white.withValues(alpha: 0.08); - final labelColor = isLightBackground ? Colors.black87 : Colors.white70; - - // Draw Y axis (left) - thinner - canvas.drawLine( - Offset(leftLabelWidth, padding), - Offset(leftLabelWidth, size.height - bottomPadding), - Paint() - ..color = axisColor - ..strokeWidth = 1, - ); - - // Draw X axis (bottom) - thinner - canvas.drawLine( - Offset(leftLabelWidth, size.height - bottomPadding), - Offset(size.width - padding, size.height - bottomPadding), - Paint() - ..color = axisColor - ..strokeWidth = 1, - ); - - // Draw Y axis label (Score) - final yAxisLabel = TextPainter( - text: TextSpan( - text: translateFunc('Score'), - style: TextStyle(color: axisColor, fontSize: 10), - ), - textDirection: TextDirection.ltr, - ); - yAxisLabel.layout(); - yAxisLabel.paint( - canvas, - Offset(8, padding - 10), - ); - - // Draw X axis label (Targets, Shots, or Points) - late String xAxisLabelText; - if (xAxisLabelKey != null) { - xAxisLabelText = translateFunc(xAxisLabelKey!); - } else { - xAxisLabelText = isShotView ? translateFunc('Shots') : translateFunc('Targets'); - } - final xAxisLabel = TextPainter( - text: TextSpan( - text: xAxisLabelText, - style: TextStyle(color: axisColor, fontSize: 10), - ), - textDirection: TextDirection.ltr, - ); - xAxisLabel.layout(); - xAxisLabel.paint( - canvas, - Offset(size.width - padding - 40, size.height - 17), - ); - - // Draw grid lines and X axis labels (score values) - for (int i = 0; i <= 10; i++) { - final xValue = (maxScore / 10) * i; - final xPos = leftLabelWidth + (chartWidth * i / 10); - - // Grid line (lighter) - canvas.drawLine( - Offset(xPos, padding), - Offset(xPos, size.height - bottomPadding), - Paint() - ..color = gridColor - ..strokeWidth = 0.5, - ); - - // X axis label (score) - smaller and lighter - if (i % 2 == 0) { // Only show every 2nd label to avoid clutter - final textPainter = TextPainter( - text: TextSpan( - text: '${xValue.toInt()}', - style: TextStyle(color: labelColor.withValues(alpha: 0.6), fontSize: 10), - ), - textDirection: TextDirection.ltr, - ); - textPainter.layout(); - textPainter.paint( - canvas, - Offset(xPos - textPainter.width / 2, size.height - bottomPadding + 8), - ); - } - } - - // Draw horizontal bars - if (data.isNotEmpty) { - final barHeight = chartHeight / (data.length * 1.3); - final spacing = barHeight * 0.3; - - for (int i = 0; i < data.length; i++) { - final entry = data[i]; - final targetNum = entry.key; - final score = entry.value; - - final barWidth = (score / maxScore) * chartWidth; - final yPos = padding + (i * (barHeight + spacing)) + spacing; - final xStart = leftLabelWidth; - - // Draw bar with subtle shadow effect - final shadowPaint = Paint() - ..color = Colors.black.withValues(alpha: 0.1) - ..maskFilter = const MaskFilter.blur(BlurStyle.normal, 2); - - canvas.drawRRect( - RRect.fromRectAndRadius( - Rect.fromLTWH( - xStart + 1, - yPos + 1, - barWidth, - barHeight, - ), - const Radius.circular(6), - ), - shadowPaint, - ); - - // Draw main bar with rounded corners - canvas.drawRRect( - RRect.fromRectAndRadius( - Rect.fromLTWH( - xStart, - yPos, - barWidth, - barHeight, - ), - const Radius.circular(6), - ), - Paint()..color = bulletColor, - ); - - // Draw Y axis label (target name) - final label = isShotView ? 'S$targetNum' : 'T$targetNum'; - final labelPainter = TextPainter( - text: TextSpan( - text: label, - style: TextStyle( - color: labelColor, - fontSize: 12, - fontWeight: FontWeight.w600, - ), - ), - textDirection: TextDirection.ltr, - ); - labelPainter.layout(); - labelPainter.paint( - canvas, - Offset( - leftLabelWidth - labelPainter.width - 10, - yPos + barHeight / 2 - labelPainter.height / 2, - ), - ); - - // Draw score at end of bar (only if bar is wide enough) - if (barWidth > 20) { - final scorePainter = TextPainter( - text: TextSpan( - text: '${score.toInt()}', - style: TextStyle( - color: isLightBackground ? Colors.black87 : Colors.white, - fontSize: 10, - fontWeight: FontWeight.bold, - ), - ), - textDirection: TextDirection.ltr, - ); - scorePainter.layout(); - scorePainter.paint( - canvas, - Offset( - xStart + barWidth + 8, - yPos + barHeight / 2 - scorePainter.height / 2, - ), - ); - } - } - } - } - - @override - bool shouldRepaint(BarChartPainter oldDelegate) { - return oldDelegate.data != data || - oldDelegate.maxScore != maxScore || - oldDelegate.bulletColor != bulletColor || - oldDelegate.backgroundColor != backgroundColor || - oldDelegate.isShotView != isShotView || - oldDelegate.selectedLanguage != selectedLanguage || - oldDelegate.xAxisLabelKey != xAxisLabelKey; - } - - bool _isLightColor(Color color) { - // Calculate luminance to determine if background is light or dark - final r = (color.r * 255.0).round(); - final g = (color.g * 255.0).round(); - final b = (color.b * 255.0).round(); - final luminance = (r * 299 + g * 587 + b * 114) / 1000; - return luminance > 128; - } } diff --git a/lib/services/app_settings.dart b/lib/services/app_settings.dart index b5fb162..6b883cf 100644 --- a/lib/services/app_settings.dart +++ b/lib/services/app_settings.dart @@ -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 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 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 removedTargets = {13, 21, 31, 32, 33, 34}; - - static final List targets = [ - defaultTarget, - for (int i = 1; i <= 35; i++) - if (!removedTargets.contains(i)) 'assets/targets/Target$i.jpg', - ]; + static const List 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; + + // "-" 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 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 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.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 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 setTarget(String path) async { - _selectedTarget = path; + Future 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 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 setReminderHours(int hours) async { diff --git a/lib/services/target_repository.dart b/lib/services/target_repository.dart index 337746b..6b239e7 100644 --- a/lib/services/target_repository.dart +++ b/lib/services/target_repository.dart @@ -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 bullets; + final List 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 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 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? _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 changed = ValueNotifier(0); + static void notifyChanged() => changed.value++; + static Future _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 readHits(File file) async { + try { + return TargetHits.fromJson(jsonDecode(await file.readAsString()) as Map); + } catch (_) { + return TargetHits.empty; + } + } + + /// Hits of several targets, in the order given. + static Future> readAllHits(List files) => Future.wait(files.map(readHits)); + static Future deleteSession(Session session) async { final folder = Directory('${(await _root()).path}/${session.name}'); if (await folder.exists()) await folder.delete(recursive: true); + notifyChanged(); } static Future deleteTarget(TargetRecord target) async { if (await target.file.exists()) await target.file.delete(); + notifyChanged(); } } diff --git a/lib/theme/app_theme.dart b/lib/theme/app_theme.dart index 14106fc..3a4b840 100644 --- a/lib/theme/app_theme.dart +++ b/lib/theme/app_theme.dart @@ -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 shadow; // cards (light only) + final List 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 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(PageRoute route, BuildContext context, Animation animation, + Animation 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 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; } diff --git a/lib/utils/format.dart b/lib/utils/format.dart new file mode 100644 index 0000000..0a66886 --- /dev/null +++ b/lib/utils/format.dart @@ -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)}'; +} diff --git a/lib/utils/target_colors.dart b/lib/utils/target_colors.dart deleted file mode 100644 index 95beb4e..0000000 --- a/lib/utils/target_colors.dart +++ /dev/null @@ -1,40 +0,0 @@ -import 'package:flutter/material.dart'; - -class TargetColors { - static const Map 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]!; - } -} diff --git a/lib/utils/target_scoring.dart b/lib/utils/target_scoring.dart index c9fcdb8..46a3901 100644 --- a/lib/utils/target_scoring.dart +++ b/lib/utils/target_scoring.dart @@ -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 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). diff --git a/lib/utils/translations.dart b/lib/utils/translations.dart index 7dda510..732f61e 100644 --- a/lib/utils/translations.dart +++ b/lib/utils/translations.dart @@ -1,3 +1,5 @@ +import 'translations_v2.dart'; + class AppTranslations { static Map> 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]!; diff --git a/lib/utils/translations_v2.dart b/lib/utils/translations_v2.dart new file mode 100644 index 0000000..f44cae4 --- /dev/null +++ b/lib/utils/translations_v2.dart @@ -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> 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.', + }, +}; diff --git a/lib/widgets/bar_list.dart b/lib/widgets/bar_list.dart new file mode 100644 index 0000000..ea58c27 --- /dev/null +++ b/lib/widgets/bar_list.dart @@ -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 entries; + final double max; + final List 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)), + ), + ], + ), + ), + ), + ], + ); + }); + } +} diff --git a/lib/widgets/bar_tabs.dart b/lib/widgets/bar_tabs.dart index 2c2b483..ea39787 100644 --- a/lib/widgets/bar_tabs.dart +++ b/lib/widgets/bar_tabs.dart @@ -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 tabs; final int selected; final ValueChanged 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, ), ); } diff --git a/lib/widgets/bottom_nav.dart b/lib/widgets/bottom_nav.dart index 3cc2db5..1ac7448 100644 --- a/lib/widgets/bottom_nav.dart +++ b/lib/widgets/bottom_nav.dart @@ -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 onItemTapped; - final List items; + final List 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, + ), + ), + ], + ), + ); + } } diff --git a/lib/widgets/camera_sheet.dart b/lib/widgets/camera_sheet.dart index 2391e4f..9deb087 100644 --- a/lib/widgets/camera_sheet.dart +++ b/lib/widgets/camera_sheet.dart @@ -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 showCameraSheet(BuildContext context, - {required WidgetBuilder builder}) { - return showModalBottomSheet( - 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 showCameraSheet(BuildContext context, {required WidgetBuilder builder}) => + showAppSheet(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 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 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 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 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), + ], ], ); } diff --git a/lib/widgets/help_sheet.dart b/lib/widgets/help_sheet.dart index 4596314..1c9110f 100644 --- a/lib/widgets/help_sheet.dart +++ b/lib/widgets/help_sheet.dart @@ -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))], ), ); } diff --git a/lib/widgets/image_settings.dart b/lib/widgets/image_settings.dart index c8a7ac1..816006e 100644 --- a/lib/widgets/image_settings.dart +++ b/lib/widgets/image_settings.dart @@ -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 showImageSettingsSheet( required ImageAdjustments initial, required String settingsId, required String cameraLabel, - required Color accent, required String Function(String) t, required ValueChanged onChanged, }) { @@ -113,6 +115,7 @@ Future 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 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 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), ), ], ), diff --git a/lib/widgets/progress_chart.dart b/lib/widgets/progress_chart.dart index 39a667f..366f7d6 100644 --- a/lib/widgets/progress_chart.dart +++ b/lib/widgets/progress_chart.dart @@ -27,6 +27,9 @@ class ProgressChart extends StatefulWidget { final List 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 { 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 { 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 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; } diff --git a/lib/widgets/result_share.dart b/lib/widgets/result_share.dart index 87cbe21..73e4048 100644 --- a/lib/widgets/result_share.dart +++ b/lib/widgets/result_share.dart @@ -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 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> chart; // bar label number -> points - final bool chartPerShot; // bars are shots of one target, not targets of a session + final TargetStyle style; + final List hits; // in target space + final List<(String? top, String value, bool filled)> tiles; + final String chartTitle; + final List 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 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 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 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)), - ), - ), - ), - ], - ), - ); - } -} diff --git a/lib/widgets/section.dart b/lib/widgets/section.dart index ac2d0af..0e45120 100644 --- a/lib/widgets/section.dart +++ b/lib/widgets/section.dart @@ -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 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 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 tiles; @@ -225,24 +270,30 @@ class StatGrid extends StatelessWidget { @override Widget build(BuildContext context) { - final s = Surfaces.current; + final c = Palette.current; final rows = []; 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); } } diff --git a/lib/widgets/target_face.dart b/lib/widgets/target_face.dart new file mode 100644 index 0000000..f038364 --- /dev/null +++ b/lib/widgets/target_face.dart @@ -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 hits; // in target space (0–1200) + final Color hitColor; + final Set highlighted; // indexes of [hits] drawn with a ring + final Set 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 hits; + final Color color; + final Set highlighted; + final Set 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; +} diff --git a/lib/widgets/text_prompt.dart b/lib/widgets/text_prompt.dart index 5a0fbf1..af161cd 100644 --- a/lib/widgets/text_prompt.dart +++ b/lib/widgets/text_prompt.dart @@ -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 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 showTextPrompt( return showDialog( 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')), - ), - ], - ), + ); + }, ); } diff --git a/lib/widgets/ui.dart b/lib/widgets/ui.dart new file mode 100644 index 0000000..861a1ae --- /dev/null +++ b/lib/widgets/ui.dart @@ -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 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 items; + final int selected; + final ValueChanged 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 showAppSheet( + 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( + 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 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 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( + 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 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 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), + ], + ), + ), + ); + } +} diff --git a/pubspec.yaml b/pubspec.yaml index 3c8bfa7..d8ef6cd 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -44,6 +44,24 @@ flutter: uses-material-design: true assets: - assets/club.enc - - assets/target.png - assets/best_float32_nms.tflite - - assets/targets/ + - assets/targets/v3/ + - assets/backgrounds/ + + # Inter for the interface, JetBrains Mono for camera addresses (both SIL OFL 1.1) + fonts: + - family: Inter + fonts: + - asset: assets/fonts/Inter-Regular.ttf + weight: 400 + - asset: assets/fonts/Inter-Medium.ttf + weight: 500 + - asset: assets/fonts/Inter-SemiBold.ttf + weight: 600 + - asset: assets/fonts/Inter-Bold.ttf + weight: 700 + - asset: assets/fonts/Inter-ExtraBold.ttf + weight: 800 + - family: JetBrains Mono + fonts: + - asset: assets/fonts/JetBrainsMono-Regular.ttf diff --git a/test/holiday_theme_test.dart b/test/holiday_theme_test.dart new file mode 100644 index 0000000..0553109 --- /dev/null +++ b/test/holiday_theme_test.dart @@ -0,0 +1,54 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:sd_kovinar/models/holiday_theme.dart'; +import 'package:sd_kovinar/models/target_style.dart'; + +void main() { + String? on(int y, int m, int d) => HolidayTheme.on(DateTime(y, m, d))?.name; + + test('Easter Sunday', () { + expect(HolidayTheme.easterSunday(2024), DateTime(2024, 3, 31)); + expect(HolidayTheme.easterSunday(2025), DateTime(2025, 4, 20)); + expect(HolidayTheme.easterSunday(2026), DateTime(2026, 4, 5)); + expect(HolidayTheme.easterSunday(2027), DateTime(2027, 3, 28)); + }); + + test('windows, inclusive, across the new year', () { + expect(on(2026, 11, 30), isNull); + expect(on(2026, 12, 1), 'Božič'); + expect(on(2026, 12, 26), 'Božič'); + expect(on(2026, 12, 27), 'Novo leto'); + expect(on(2027, 1, 2), 'Novo leto'); + expect(on(2027, 1, 3), isNull); + expect(on(2026, 6, 23), 'Kresna noč'); + expect(on(2026, 6, 24), 'Dan državnosti'); + expect(on(2026, 10, 31), 'Noč čarovnic'); + expect(on(2026, 11, 11), 'Martinovo'); + expect(on(2026, 11, 27), isNull); + }); + + test('Easter-based holidays', () { + // 2026: Easter 5. 4., Shrove Tuesday 17. 2. + expect(on(2026, 2, 17), 'Pust'); + expect(on(2026, 2, 12), 'Valentinovo'); // first in the list wins over Pust (-52 = 12. 2.) + expect(on(2026, 3, 29), 'Velika noč'); + expect(on(2026, 4, 6), 'Velika noč'); + expect(on(2026, 4, 7), isNull); + }); + + test('Easter windows in calendar days, across the clock change', () { + final easter = HolidayTheme.all.firstWhere((h) => h.name == 'Velika noč'); + expect(easter.window(DateTime(2026, 4, 1)), (DateTime(2026, 3, 29), DateTime(2026, 4, 6))); + expect(on(2026, 3, 28), isNull); // the day before the window + final pust = HolidayTheme.all.firstWhere((h) => h.name == 'Pust'); + expect(pust.window(DateTime(2026, 2, 17)).$2, DateTime(2026, 2, 18)); + }); + + test('every holiday has its target and the window of a date around new year', () { + for (final h in HolidayTheme.all) { + expect(TargetStyle.byId(h.targetId).id, h.targetId); + } + final newYear = HolidayTheme.all.firstWhere((h) => h.name == 'Novo leto'); + expect(newYear.window(DateTime(2027, 1, 1)), (DateTime(2026, 12, 27), DateTime(2027, 1, 2))); + expect(newYear.window(DateTime(2026, 12, 30)), (DateTime(2026, 12, 27), DateTime(2027, 1, 2))); + }); +} diff --git a/test/target_scoring_test.dart b/test/target_scoring_test.dart index d19b2c6..28cbfc6 100644 --- a/test/target_scoring_test.dart +++ b/test/target_scoring_test.dart @@ -29,10 +29,16 @@ void main() { test('ring edges count the bullet radius', () { const c = TargetScoring.center; // Bullet edge exactly on the outer edge of ring 10 - expect(TargetScoring.scoreAt(c + const Offset(14 + 25, 0)), 10); - expect(TargetScoring.scoreAt(c + const Offset(14 + 25 + 0.5, 0)), 9); + expect(TargetScoring.scoreAt(c + const Offset(15 + 25, 0)), 10); + expect(TargetScoring.scoreAt(c + const Offset(15 + 25 + 0.5, 0)), 9); + // Touching a line counts the higher value: the edge is the line's outer edge + expect(TargetScoring.scoreAt(c + const Offset(70 + 2.5 + 25, 0)), 9); // 5 px line + expect(TargetScoring.scoreAt(c + const Offset(70 + 2.5 + 25 + 0.5, 0)), 8); + expect(TargetScoring.scoreAt(c + const Offset(235 + 1.5 + 25, 0)), 6); // 3 px line + expect(TargetScoring.scoreAt(c + const Offset(235 + 1.5 + 25 + 0.5, 0)), 5); // Outside the last ring - expect(TargetScoring.scoreAt(c + const Offset(510 + 25 + 0.5, 0)), 0); + expect(TargetScoring.scoreAt(c + const Offset(510 + 1.5 + 25, 0)), 1); + expect(TargetScoring.scoreAt(c + const Offset(510 + 1.5 + 25 + 0.5, 0)), 0); }); test('hand-entered shots stay on the 1200x1200 target', () { diff --git a/test/target_style_test.dart b/test/target_style_test.dart new file mode 100644 index 0000000..f82d31f --- /dev/null +++ b/test/target_style_test.dart @@ -0,0 +1,22 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:sd_kovinar/models/target_style.dart'; + +void main() { + test('every target design has its image, and ids are unique', () { + final ids = {}; + for (final style in [...TargetStyle.all, ...TargetStyle.holidays]) { + expect(ids.add(style.id), isTrue, reason: 'duplicate id ${style.id}'); + final asset = style.asset; + if (style.isDefault) { + expect(asset, isNull); // drawn as vectors + } else { + expect(File(asset!).existsSync(), isTrue, reason: '$asset missing'); + } + } + expect(TargetStyle.byId(13), TargetStyle.fallback); // removed skin falls back to the default + expect(TargetStyle.all.length, 6); // the default and five designs + expect(TargetStyle.byId(24), TargetStyle.fallback); // a design no longer shipped falls back too + }); +}