calendar fix and update.

This commit is contained in:
2026-10-25 17:46:55 +01:00
parent cd3398df99
commit 9a65ff7ad4
10 changed files with 2596 additions and 1651 deletions
+2
View File
@@ -6,6 +6,8 @@
<uses-permission android:name="android.permission.WAKE_LOCK"/> <uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/> <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"/>
<application <application
+2
View File
@@ -8,6 +8,8 @@ void main() async {
try { try {
await NotificationService().initialize(); await NotificationService().initialize();
} catch (_) {} } catch (_) {}
// Refresh reminders in the background so they don't depend on opening the calendar
NotificationService().rescheduleFromCalendar();
// Lock orientation to portrait only // Lock orientation to portrait only
await SystemChrome.setPreferredOrientations([ await SystemChrome.setPreferredOrientations([
+7 -2
View File
@@ -19,6 +19,7 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
Map<String, List<File>> _groupedFiles = {}; // Files grouped by folder Map<String, List<File>> _groupedFiles = {}; // Files grouped by folder
Map<String, DateTime> _folderCreationDates = {}; // Folder creation dates Map<String, DateTime> _folderCreationDates = {}; // Folder creation dates
Map<String, int> _folderScores = {}; // Folder scores (sum of scores of all target files inside) Map<String, int> _folderScores = {}; // Folder scores (sum of scores of all target files inside)
Map<String, int> _fileScores = {}; // Per-file score cache to avoid sync reads in build
Color _bulletColor = Colors.blue; // default fallback Color _bulletColor = Colors.blue; // default fallback
Map<String, bool> _folderTypes = {}; // true = tournament, false = training Map<String, bool> _folderTypes = {}; // true = tournament, false = training
String _folderFilter = 'all'; String _folderFilter = 'all';
@@ -136,6 +137,7 @@ Color _getColorFromName(String colorName) {
Map<String, DateTime> folderDates = {}; Map<String, DateTime> folderDates = {};
Map<String, int> folderScores = {}; Map<String, int> folderScores = {};
Map<String, bool> folderTypes = {}; Map<String, bool> folderTypes = {};
Map<String, int> fileScores = {};
for (var folder in folders) { for (var folder in folders) {
String folderName = folder.path.split('/').last; String folderName = folder.path.split('/').last;
@@ -177,7 +179,9 @@ Color _getColorFromName(String colorName) {
for (var file in targetFiles) { for (var file in targetFiles) {
final jsonString = await file.readAsString(); final jsonString = await file.readAsString();
final data = jsonDecode(jsonString); final data = jsonDecode(jsonString);
totalScore += _getScoreFromJson(data); final score = _getScoreFromJson(data);
fileScores[file.path] = score;
totalScore += score;
} }
groupedFiles[folderName] = targetFiles; groupedFiles[folderName] = targetFiles;
@@ -201,6 +205,7 @@ Color _getColorFromName(String colorName) {
_folderTypes = { _folderTypes = {
for (var name in sortedFolderNames) name: folderTypes[name]! for (var name in sortedFolderNames) name: folderTypes[name]!
}; };
_fileScores = fileScores;
}); });
} catch (e) { } catch (e) {
debugPrint("Error loading target data files: $e"); debugPrint("Error loading target data files: $e");
@@ -782,7 +787,7 @@ Widget _buildTargetsList(String folderName) {
children: targetFiles.asMap().entries.map((entry) { children: targetFiles.asMap().entries.map((entry) {
final index = entry.key; final index = entry.key;
final file = entry.value; final file = entry.value;
final score = _getScoreFromJson(jsonDecode(file.readAsStringSync())); final score = _fileScores[file.path] ?? 0;
final fileName = "${_t('Target')} ${index + 1}"; final fileName = "${_t('Target')} ${index + 1}";
return Container( return Container(
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -133,7 +133,7 @@ class _HomeScreenState extends State<HomeScreen> {
padding: const EdgeInsets.only(right: 16.0), padding: const EdgeInsets.only(right: 16.0),
child: Center( child: Center(
child: Text( child: Text(
'V1.1', 'V1.2',
style: TextStyle( style: TextStyle(
color: Colors.grey[400], color: Colors.grey[400],
fontSize: 12, fontSize: 12,
+2 -1
View File
@@ -50,7 +50,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
bool _notifyDezuranje = true; bool _notifyDezuranje = true;
bool _notifySestanek = true; bool _notifySestanek = true;
bool _notifyTekma = true; bool _notifyTekma = true;
String _selectedLanguage = 'English'; String _selectedLanguage = 'English';
final List<Map<String, String>> _languages = [ final List<Map<String, String>> _languages = [
{'code': 'en', 'name': 'English', 'flag': '🇬🇧'}, {'code': 'en', 'name': 'English', 'flag': '🇬🇧'},
@@ -229,11 +228,13 @@ String _getTargetDisplayName(String targetPath) {
await prefs.setInt('notificationHours_single', hours); await prefs.setInt('notificationHours_single', hours);
await prefs.setStringList('notificationHours', [hours.toString()]); await prefs.setStringList('notificationHours', [hours.toString()]);
setState(() => _notificationHours = hours); setState(() => _notificationHours = hours);
NotificationService().rescheduleFromCalendar();
} }
Future<void> _saveNotifyType(String key, bool value) async { Future<void> _saveNotifyType(String key, bool value) async {
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
await prefs.setBool(key, value); await prefs.setBool(key, value);
NotificationService().rescheduleFromCalendar();
} }
Future<void> _loadCameraIPs() async { Future<void> _loadCameraIPs() async {
File diff suppressed because it is too large Load Diff
+17 -20
View File
@@ -29,6 +29,7 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
List<Offset> _bullets = []; List<Offset> _bullets = [];
List<Offset> _scaledBullets = []; // Bullets scaled to display target size List<Offset> _scaledBullets = []; // Bullets scaled to display target size
int _totalScore = 0; int _totalScore = 0;
Map<int, int> _folderChartScores = {};
Offset? _targetCenter; Offset? _targetCenter;
Uint8List? _targetImageBytes; Uint8List? _targetImageBytes;
img.Image? _targetImageDecoded; img.Image? _targetImageDecoded;
@@ -256,6 +257,21 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
.map((b) => _scoreForBullet(b, _targetCenter!)) .map((b) => _scoreForBullet(b, _targetCenter!))
.fold(0, (sum, score) => sum + score); .fold(0, (sum, score) => sum + score);
// Pre-compute folder chart scores to avoid sync file reads in build
if (widget.isCombinedView) {
final chartScores = <int, int>{};
for (int i = 0; i < widget.jsonFiles.length; i++) {
final data = jsonDecode(await widget.jsonFiles[i].readAsString());
final bullets = (data['bullets'] as List?) ?? [];
int s = 0;
for (final b in bullets) {
s += _scoreForBullet(Offset(b['x'].toDouble(), b['y'].toDouble()), _targetCenter!);
}
chartScores[i + 1] = s;
}
_folderChartScores = chartScores;
}
setState(() {}); setState(() {});
} catch (e) { } catch (e) {
print("Error loading JSON or image: $e"); print("Error loading JSON or image: $e");
@@ -565,26 +581,7 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
} }
Widget _buildFolderChartView() { Widget _buildFolderChartView() {
// Calculate target scores from all files final Map<int, int> targetScores = _folderChartScores;
// Each file represents one target at position (fileIndex + 1)
final Map<int, int> targetScores = {};
for (int fileIdx = 0; fileIdx < widget.jsonFiles.length; fileIdx++) {
final file = widget.jsonFiles[fileIdx];
final targetPosition = fileIdx + 1; // T1, T2, T3, etc.
final data = jsonDecode(file.readAsStringSync());
final bullets = (data['bullets'] as List?) ?? [];
// Sum scores for this target
int targetScore = 0;
for (int j = 0; j < bullets.length; j++) {
final bullet = Offset(bullets[j]['x'].toDouble(), bullets[j]['y'].toDouble());
final score = _scoreForBullet(bullet, _targetCenter ?? Offset.zero);
targetScore += score;
}
targetScores[targetPosition] = targetScore;
}
if (targetScores.isEmpty) { if (targetScores.isEmpty) {
return Center( return Center(
+51 -4
View File
@@ -62,9 +62,50 @@ class NotificationService {
AndroidFlutterLocalNotificationsPlugin>(); AndroidFlutterLocalNotificationsPlugin>();
await androidPlugin?.createNotificationChannel(_channel); await androidPlugin?.createNotificationChannel(_channel);
await requestPermissions(); await requestPermissions();
await _requestExactAlarmsOnce();
} catch (_) {} } catch (_) {}
} }
// Android 12+ needs "Alarms & reminders" access for on-time delivery.
// Ask once; without it we fall back to inexact alarms.
Future<void> _requestExactAlarmsOnce() async {
final android = _plugin.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>();
if (android == null) return;
if (await android.canScheduleExactNotifications() ?? true) return;
final prefs = await SharedPreferences.getInstance();
if (prefs.getBool('exactAlarmAsked') ?? false) return;
await prefs.setBool('exactAlarmAsked', true);
await android.requestExactAlarmsPermission();
}
Future<AndroidScheduleMode> _scheduleMode() async {
final android = _plugin.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>();
final canExact = await android?.canScheduleExactNotifications() ?? true;
return canExact
? AndroidScheduleMode.exactAllowWhileIdle
: AndroidScheduleMode.inexactAllowWhileIdle;
}
/// Fetches the calendar and reschedules all reminders. Call on app start
/// and whenever notification settings change.
Future<void> rescheduleFromCalendar() async {
final service = GoogleCalendarService();
try {
final now = DateTime.now();
final events = await service.getEvents(
startDate: now,
endDate: now.add(const Duration(days: 365)),
);
await scheduleEventNotifications(events);
} catch (_) {
} finally {
service.dispose();
}
}
Future<bool> requestPermissions() async { Future<bool> requestPermissions() async {
final android = _plugin.resolvePlatformSpecificImplementation< final android = _plugin.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>(); AndroidFlutterLocalNotificationsPlugin>();
@@ -96,6 +137,7 @@ class NotificationService {
final notifyTekma = prefs.getBool('notifyTekma') ?? true; final notifyTekma = prefs.getBool('notifyTekma') ?? true;
final isSlovenian = (prefs.getString('language') ?? 'English') == 'Slovenian'; final isSlovenian = (prefs.getString('language') ?? 'English') == 'Slovenian';
final now = DateTime.now(); final now = DateTime.now();
final mode = await _scheduleMode();
await _plugin.cancelAll(); await _plugin.cancelAll();
@@ -104,9 +146,11 @@ class NotificationService {
if (event.startTime == null) continue; if (event.startTime == null) continue;
final summary = (event.summary ?? '').toLowerCase(); final summary = (event.summary ?? '').toLowerCase();
final isCompetition = summary.contains('liga') || summary.contains('tekmovanje'); // Same classification as the calendar screen; skip anything else
final isSestanek = summary.contains('sestanek'); final isCompetition = summary.contains('liga') || summary.contains('tekmovanje') || summary.contains('tekma');
final isDezuranje = !isCompetition && !isSestanek; final isSestanek = !isCompetition && summary.contains('sestanek');
final isDezuranje = !isCompetition && !isSestanek && summary.contains('dežurstvo');
if (!isCompetition && !isSestanek && !isDezuranje) continue;
if (isCompetition && !notifyTekma) continue; if (isCompetition && !notifyTekma) continue;
if (isSestanek && !notifySestanek) continue; if (isSestanek && !notifySestanek) continue;
@@ -121,6 +165,7 @@ class NotificationService {
? (hours == 1 ? 'Začne se čez 1 uro' : 'Začne se čez $hours ur') ? (hours == 1 ? 'Začne se čez 1 uro' : 'Začne se čez $hours ur')
: (hours == 1 ? 'Starts in 1 hour' : 'Starts in $hours hours'), : (hours == 1 ? 'Starts in 1 hour' : 'Starts in $hours hours'),
scheduledDate: notifyAt, scheduledDate: notifyAt,
mode: mode,
); );
} }
} }
@@ -144,6 +189,7 @@ class NotificationService {
title: isSlovenian ? 'Načrtovano testno obvestilo' : 'Scheduled Test', title: isSlovenian ? 'Načrtovano testno obvestilo' : 'Scheduled Test',
body: isSlovenian ? 'Načrtovana obvestila delujejo!' : 'Scheduled notifications are working!', body: isSlovenian ? 'Načrtovana obvestila delujejo!' : 'Scheduled notifications are working!',
scheduledDate: in10s, scheduledDate: in10s,
mode: await _scheduleMode(),
); );
} catch (_) {} } catch (_) {}
} }
@@ -153,6 +199,7 @@ class NotificationService {
required String title, required String title,
required String body, required String body,
required DateTime scheduledDate, required DateTime scheduledDate,
required AndroidScheduleMode mode,
}) async { }) async {
final tzDate = tz.TZDateTime.from(scheduledDate, tz.local); final tzDate = tz.TZDateTime.from(scheduledDate, tz.local);
await _plugin.zonedSchedule( await _plugin.zonedSchedule(
@@ -161,7 +208,7 @@ class NotificationService {
body, body,
tzDate, tzDate,
_notifDetails, _notifDetails,
androidScheduleMode: AndroidScheduleMode.inexactAllowWhileIdle, androidScheduleMode: mode,
uiLocalNotificationDateInterpretation: uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime, UILocalNotificationDateInterpretation.absoluteTime,
); );
+82
View File
@@ -249,10 +249,26 @@ class AppTranslations {
'English': 'Today', 'English': 'Today',
'Slovenian': 'Danes', 'Slovenian': 'Danes',
}, },
'TODAY': {
'English': 'TODAY',
'Slovenian': 'DANES',
},
'UPCOMING': {
'English': 'UPCOMING',
'Slovenian': 'PRIHAJAJOČE',
},
'No events today': {
'English': 'No events today',
'Slovenian': 'Danes ni dogodkov',
},
'Tomorrow': { 'Tomorrow': {
'English': 'Tomorrow', 'English': 'Tomorrow',
'Slovenian': 'Jutri', 'Slovenian': 'Jutri',
}, },
'in {n} days': {
'English': 'in {n} days',
'Slovenian': 'čez {n} dni',
},
'NOW': { 'NOW': {
'English': 'NOW', 'English': 'NOW',
'Slovenian': 'ZDAJ', 'Slovenian': 'ZDAJ',
@@ -605,6 +621,10 @@ class AppTranslations {
'English': 'Tap camera button to capture and detect bullets', 'English': 'Tap camera button to capture and detect bullets',
'Slovenian': 'Tapnite gumb kamere za zajem in zaznavanje zadetkov', 'Slovenian': 'Tapnite gumb kamere za zajem in zaznavanje zadetkov',
}, },
'Timer icon: Configure shoot/wait timer and start session': {
'English': 'Timer icon: Configure shoot/wait timer and start session',
'Slovenian': 'Ikona časovnika: Nastavi časovnik strela/čakanja in začni serijo',
},
'Bottom left number: Set expected bullet count (1-5)': { 'Bottom left number: Set expected bullet count (1-5)': {
'English': 'Bottom left number: Set expected bullet count (1-5)', 'English': 'Bottom left number: Set expected bullet count (1-5)',
'Slovenian': 'Spodaj levo številka: Nastavite število zadetkov (1-5)', 'Slovenian': 'Spodaj levo številka: Nastavite število zadetkov (1-5)',
@@ -847,6 +867,68 @@ class AppTranslations {
'Slovenian': 'Točke', 'Slovenian': 'Točke',
}, },
// Timer Dialog
'Shooting Timer': {
'English': 'Shooting Timer',
'Slovenian': 'Časovnik streljanja',
},
'What do you want to time?': {
'English': 'What do you want to time?',
'Slovenian': 'Kaj želiš časovno meriti?',
},
'Shoot only': {
'English': 'Shoot only',
'Slovenian': 'Samo strel',
},
'Wait only': {
'English': 'Wait only',
'Slovenian': 'Samo čakanje',
},
'Both': {
'English': 'Both',
'Slovenian': 'Oboje',
},
'Shoot time': {
'English': 'Shoot time',
'Slovenian': 'Čas strela',
},
'Reload time': {
'English': 'Reload time',
'Slovenian': 'Čas polnjenja',
},
'Wait time': {
'English': 'Wait time',
'Slovenian': 'Čas čakanja',
},
'Single shot': {
'English': 'Single shot',
'Slovenian': 'En strel',
},
'Full target': {
'English': 'Full target',
'Slovenian': 'Polna tarča',
},
'Change target!': {
'English': 'Change target!',
'Slovenian': 'Zamenjaj tarčo!',
},
'Change target sign': {
'English': 'Change target sign',
'Slovenian': 'Znak zamenjave tarče',
},
'Bullet counter': {
'English': 'Bullet counter',
'Slovenian': 'Števec strelov',
},
'Disable': {
'English': 'Disable',
'Slovenian': 'Onemogoči',
},
'left': {
'English': 'left',
'Slovenian': 'ostalo',
},
// Notifications // Notifications
'Notifications': { 'Notifications': {
'English': 'Notifications', 'English': 'Notifications',