From 4af7385804510c07790b546cc69f3ae2e58adb2b Mon Sep 17 00:00:00 2001 From: Jurij Date: Sun, 11 Oct 2026 22:19:34 +0200 Subject: [PATCH] small bug fixes --- App.xaml.cs | 49 ++- AppShell.xaml | 13 +- Helpers/DateHelper.cs | 9 +- Helpers/TranslateExtension.cs | 21 ++ MauiProgram.cs | 5 +- .../Android/AndroidNotificationScheduler.cs | 8 +- ....png => store_vorstellung_wide_raster.png} | Bin ....svg => store_vorstellung_wide_vector.svg} | 0 Resources/Localization/AppStrings.en.resx | 230 +++++++++++++ Resources/Localization/AppStrings.resx | 230 +++++++++++++ Services/AppBootstrapService.cs | 3 +- Services/AppearanceService.cs | 31 +- Services/ExportUiHelper.cs | 28 +- Services/LocalizationService.cs | 269 +++++++++++++++ ViewModels/ActivityManageItemViewModel.cs | 5 +- ViewModels/DayEntryItemViewModel.cs | 10 +- ViewModels/DayViewModel.cs | 51 +-- ViewModels/LanguageOptionItemViewModel.cs | 8 + ViewModels/MonthSectionViewModel.cs | 29 +- ViewModels/MonthViewModel.cs | 2 +- .../NotificationScheduleItemViewModel.cs | 7 +- ViewModels/OptionsViewModel.cs | 306 +++++++++++++----- ViewModels/QuickEntryViewModel.cs | 41 ++- ViewModels/SymptomManageItemViewModel.cs | 5 +- ViewModels/WeekDaySummaryViewModel.cs | 7 +- ViewModels/WeekViewModel.cs | 15 +- ViewModels/YearViewModel.cs | 168 +++++++--- Views/DayPage.xaml | 21 +- Views/MonthPage.xaml | 21 +- Views/OptionsPage.xaml | 186 ++++++----- Views/OptionsPage.xaml.cs | 16 +- Views/QuickEntryPage.xaml | 70 ++-- Views/WeekPage.xaml | 48 +-- Views/YearPage.xaml | 37 ++- Views/YearPage.xaml.cs | 6 +- cfs-tracker.csproj | 2 +- 36 files changed, 1558 insertions(+), 399 deletions(-) create mode 100644 Helpers/TranslateExtension.cs rename Resources/Images/{store-vorstellung-1024x500.png => store_vorstellung_wide_raster.png} (100%) rename Resources/Images/{store-vorstellung-1024x500.svg => store_vorstellung_wide_vector.svg} (100%) create mode 100644 Resources/Localization/AppStrings.en.resx create mode 100644 Resources/Localization/AppStrings.resx create mode 100644 Services/LocalizationService.cs create mode 100644 ViewModels/LanguageOptionItemViewModel.cs diff --git a/App.xaml.cs b/App.xaml.cs index 80d03a7..7289516 100644 --- a/App.xaml.cs +++ b/App.xaml.cs @@ -1,4 +1,5 @@ using cfs_tracker.Services; +using cfs_tracker.ViewModels; using System.Diagnostics; namespace cfs_tracker; @@ -7,15 +8,22 @@ public partial class App : Application { private readonly IServiceProvider _serviceProvider; private readonly AppBootstrapService _bootstrapService; + private readonly LocalizationService _localizationService; private bool _startupTriggered; - public App(IServiceProvider serviceProvider, AppBootstrapService bootstrapService) + public App( + IServiceProvider serviceProvider, + AppBootstrapService bootstrapService, + LocalizationService localizationService) { - InitializeComponent(); - _serviceProvider = serviceProvider; _bootstrapService = bootstrapService; + _localizationService = localizationService; + + _localizationService.Initialize(); + + InitializeComponent(); UserAppTheme = AppTheme.Dark; } @@ -63,7 +71,7 @@ public partial class App : Application { return new ContentPage { - Title = "Laden", + Title = LocalizationService.Translate("App_Loading_Title"), BackgroundColor = Color.FromArgb("#0B1A2A"), Content = new Grid { @@ -86,7 +94,7 @@ public partial class App : Application }, new Label { - Text = "App wird geladen ...", + Text = LocalizationService.Translate("App_Loading_Message"), FontSize = 20, HorizontalTextAlignment = TextAlignment.Center, TextColor = Color.FromArgb("#DCE7F3") @@ -102,7 +110,7 @@ public partial class App : Application { return new ContentPage { - Title = "Startfehler", + Title = LocalizationService.Translate("App_Error_Title"), BackgroundColor = Color.FromArgb("#0B1A2A"), Content = new ScrollView { @@ -114,7 +122,7 @@ public partial class App : Application { new Label { - Text = "Fehler beim Starten der App", + Text = LocalizationService.Translate("App_Error_Header"), FontSize = 24, FontAttributes = FontAttributes.Bold, TextColor = Color.FromArgb("#FFB4B4") @@ -130,4 +138,29 @@ public partial class App : Application } }; } -} \ No newline at end of file + + public async Task ReloadShellAsync(string route = "//options", OptionsViewModel.OptionsTab? optionsTab = null) + { + var shell = _serviceProvider.GetRequiredService(); + + await MainThread.InvokeOnMainThreadAsync(async () => + { + var window = Windows.FirstOrDefault(); + if (window is null) + return; + + window.Page = shell; + + if (!string.IsNullOrWhiteSpace(route)) + await shell.GoToAsync(route); + + if (optionsTab.HasValue) + { + await Task.Delay(50); + + if (shell.CurrentPage is Views.OptionsPage optionsPage) + optionsPage.ViewModel.SelectedTab = optionsTab.Value; + } + }); + } +} diff --git a/AppShell.xaml b/AppShell.xaml index 5247de3..3e8d399 100644 --- a/AppShell.xaml +++ b/AppShell.xaml @@ -3,6 +3,7 @@ x:Class="cfs_tracker.AppShell" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" + xmlns:loc="clr-namespace:cfs_tracker.Helpers" xmlns:views="clr-namespace:cfs_tracker.Views" Shell.BackgroundColor="{DynamicResource ShellBackground}" Shell.ForegroundColor="{DynamicResource ShellForeground}" @@ -14,24 +15,24 @@ Shell.TabBarUnselectedColor="{DynamicResource TabBarUnselected}"> - - - - - - \ No newline at end of file + diff --git a/Helpers/DateHelper.cs b/Helpers/DateHelper.cs index 9589136..156fb3f 100644 --- a/Helpers/DateHelper.cs +++ b/Helpers/DateHelper.cs @@ -1,4 +1,5 @@ using System.Globalization; +using cfs_tracker.Services; namespace cfs_tracker.Helpers; @@ -14,14 +15,14 @@ public static class DateHelper } public static string ToGermanDateText(DateTime date) => - date.ToString("dddd, dd. MMMM yyyy", GermanCulture); + date.ToString(LocalizationService.Translate("Date_LongDateFormat"), LocalizationService.GetCurrentCulture()); public static string ToGermanShortDay(DateTime date) => - date.ToString("ddd dd.MM.", GermanCulture); + date.ToString(LocalizationService.Translate("Date_ShortDayFormat"), LocalizationService.GetCurrentCulture()); public static string ToGermanMonthYear(DateTime date) => - date.ToString("MMMM yyyy", GermanCulture); + date.ToString(LocalizationService.Translate("Date_MonthYearFormat"), LocalizationService.GetCurrentCulture()); public static string ToGermanYear(DateTime date) => - date.ToString("yyyy", GermanCulture); + date.ToString(LocalizationService.Translate("Date_YearFormat"), LocalizationService.GetCurrentCulture()); } diff --git a/Helpers/TranslateExtension.cs b/Helpers/TranslateExtension.cs new file mode 100644 index 0000000..d59313a --- /dev/null +++ b/Helpers/TranslateExtension.cs @@ -0,0 +1,21 @@ +using cfs_tracker.Services; +using Microsoft.Maui.Controls.Xaml; + +namespace cfs_tracker.Helpers; + +[ContentProperty(nameof(Key))] +[AcceptEmptyServiceProvider] +public sealed class TranslateExtension : IMarkupExtension +{ + public string Key { get; set; } = string.Empty; + + public string ProvideValue(IServiceProvider serviceProvider) + { + return LocalizationService.Translate(Key); + } + + object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider) + { + return ProvideValue(serviceProvider); + } +} diff --git a/MauiProgram.cs b/MauiProgram.cs index 3fff9a7..fc38009 100644 --- a/MauiProgram.cs +++ b/MauiProgram.cs @@ -40,6 +40,7 @@ public static class MauiProgram // Services builder.Services.AddSingleton(); + builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); #if ANDROID @@ -54,7 +55,7 @@ public static class MauiProgram builder.Services.AddSingleton(); // Shell / Pages - builder.Services.AddSingleton(); + builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); @@ -72,4 +73,4 @@ public static class MauiProgram return builder.Build(); } -} \ No newline at end of file +} diff --git a/Platforms/Android/AndroidNotificationScheduler.cs b/Platforms/Android/AndroidNotificationScheduler.cs index a15d922..1d3e83f 100644 --- a/Platforms/Android/AndroidNotificationScheduler.cs +++ b/Platforms/Android/AndroidNotificationScheduler.cs @@ -208,15 +208,19 @@ public sealed class AndroidNotificationScheduler : INotificationScheduler var redLabel = Preferences.Default.Get(PrefRedLabel, "Rot"); var grayLabel = Preferences.Default.Get(PrefGrayLabel, "Schwarz"); - var smallIcon = context.ApplicationInfo?.Icon ?? global::Android.Resource.Drawable.IcDialogInfo; + // A dedicated monochrome status icon is more reliable for Android system surfaces, + // including mirrored smartwatch notifications, than the adaptive launcher icon. + var smallIcon = global::Android.Resource.Drawable.IcDialogInfo; var builder = new NotificationCompat.Builder(context, channelId); builder.SetSmallIcon(smallIcon); builder.SetContentTitle(title); builder.SetContentText(message); + builder.SetStyle(new NotificationCompat.BigTextStyle().BigText(message)); + builder.SetCategory(NotificationCompat.CategoryReminder); + builder.SetVisibility((int)NotificationCompat.VisibilityPublic); builder.SetPriority((int)NotificationPriority.High); builder.SetAutoCancel(true); - builder.SetOnlyAlertOnce(true); if (openPendingIntent is not null) builder.SetContentIntent(openPendingIntent); diff --git a/Resources/Images/store-vorstellung-1024x500.png b/Resources/Images/store_vorstellung_wide_raster.png similarity index 100% rename from Resources/Images/store-vorstellung-1024x500.png rename to Resources/Images/store_vorstellung_wide_raster.png diff --git a/Resources/Images/store-vorstellung-1024x500.svg b/Resources/Images/store_vorstellung_wide_vector.svg similarity index 100% rename from Resources/Images/store-vorstellung-1024x500.svg rename to Resources/Images/store_vorstellung_wide_vector.svg diff --git a/Resources/Localization/AppStrings.en.resx b/Resources/Localization/AppStrings.en.resx new file mode 100644 index 0000000..450ee2f --- /dev/null +++ b/Resources/Localization/AppStrings.en.resx @@ -0,0 +1,230 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, ... + + + System.Resources.ResXResourceWriter, System.Windows.Forms, ... + + Loading + Loading app ... + Startup Error + Error while starting the app + Day + Week + Month + Year + Options + Today + Export + Edit + Delete + Cancel + Save + Reset + Active + Inactive + Yes + No + OK + Error + Morning + Afternoon + Default + Default value + Mon + Tue + Wed + Thu + Fri + Sat + Sun + {0} (inactive) + dddd, dd MMMM yyyy + ddd dd/MM + MMMM yyyy + yyyy + dd/MM/yyyy + No entries yet. + + Backfill + + Entry + Today you can set a quick status or create an entry with activity and symptoms. + For past days you can create a backfill for morning or afternoon. + No entries can be created for future days. + Delete entry + Do you really want to delete this entry? + Show details + Hide details + Activity: {0} + Duration: {0} + Symptoms: {0} + Week {0} - {1} + Show summary + Hide summary + Activities: {0} + Symptoms: {0} + Entry + Backfill + Part of day + Activity + Activity + Duration (HH:mm) + Symptoms + Save entry + Future days cannot be saved. + Selected status: {0} + Please choose a status + No activity + Green + Yellow + Red + Black + German + English + System ({0}) + Appearance + Notifications + Data management + Legal + Appearance + Edit status texts and language first. Color adjustments are shown below in the color dialog. + App language + Select language + Choose color + Automatically detected from the system language: {0} + Current app language: {0} + Appearance saved. + Appearance reset to defaults. + Already used, can only be deactivated. + Can be deleted as long as it is unused. + Current path: {0} + Add + Apply + From + To + Notifications + A time block can be active on multiple weekdays. + Vibration for notifications + On Android the matching notification channel is used automatically. + Add time + Save notification times + Export + Choose the date range and layout. After creating the export you can open or share it directly. + Filters (optional) + Multiple selection is possible. + Reset filters + Export mode + Day view + Week block + Day summary + Create export + Clear exports + 1 day selected: {0} + {0} days selected: {1} to {2} + Day view: each day is exported with all individual entries, activities, duration and symptoms. + Week block: each day shows morning and afternoon with status, activities, total duration and symptoms. + Day summary: each day appears compactly in a single line, similar to the month and year exports. + Activity: {0} + Symptoms: {0} + No filters active. + Hide symptoms + Hide symptoms ({0} selected) + Select symptoms + Select symptoms ({0} selected) + All activities + Do you really want to delete all locally saved exports? + {0} export file(s) were deleted. + There were no export files. + Export saved: {0} + Close + Open + Share + Open export + Share export + Activities + New activity + Activate/Deactivate + Symptoms + New symptom + Delete all entries + Type 'delete' to confirm. + delete + Delete everything + Database + Use external database + Folder or file path for external DB + For SQLite, an external file path can be useful. For real multi-user synchronization, a dedicated server or API layer would be the better long-term option. + Save database path + All entries were deleted. + Please enter an activity name first. + Activity added. + Activity saved. + Activity updated. + Activity was deactivated. + Activity was deleted. + Please enter a symptom name first. + Symptom added. + Symptom saved. + Symptom updated. + Symptom was deactivated. + Symptom was deleted. + Notification time added. + Notification time removed. + Please allow notifications, push messages and alarms, then save again. + Please allow notifications and push messages, then save again. + Please select at least one weekday for each notification time. + Notification times saved. Vibration is active. + Notification times saved. Vibration is off. + Database path saved. Please restart the app so the path becomes active. + Export created: {0} + App background + Card background + Secondary surface + Border + Primary text + Muted text + Green status color + Yellow status color + Red status color + Black / gray status color + Primary button background + Primary button text + Secondary button background + Secondary button text + App bar background + App bar foreground + App bar title + App bar inactive + Tab bar background + Tab bar active + Tab bar title + Tab bar inactive + Text for green + Text for yellow + Text for red + Text for black / gray + Privacy policy + As of: April 3, 2026 + This app processes your entries exclusively for use on your device. No user data is automatically transmitted to me or to third parties, sold, or shared for advertising purposes. + Saved data includes entries, selection lists, notification schedules, appearance settings and, when needed, locally created export files. The app does not offer cloud synchronization or automatic background uploads. + Data is stored locally in the internal app area or in a storage location chosen by you. The data is kept in technical app structures and is not intended for direct public display. However, direct technical access to the device or files may allow knowledgeable persons to infer the type and content of stored data. + If you intentionally share export files or use an external database path, you decide yourself about that storage or transfer path. + Disclaimer + Use of the app is at your own risk. To the extent permitted by law, I accept no warranty or liability for timeliness, accuracy, completeness, technical availability, data loss, or suitability for a specific purpose. + The app does not replace medical, therapeutic, nursing, legal, or technical professional advice. + Personal note + This app was not developed by a professional software engineer. I am personally affected by ME/CFS and created the application from my own perspective and experience. + That is exactly why the app is meant to help in everyday life, but it remains a personal project and not a professionally certified medical or software product. + Edit color + Red + Green + Blue + Brightness + Reset only loads the default value into the dialog. The change is saved only after Apply. Cancel discards everything from this dialog. + diff --git a/Resources/Localization/AppStrings.resx b/Resources/Localization/AppStrings.resx new file mode 100644 index 0000000..28e77c5 --- /dev/null +++ b/Resources/Localization/AppStrings.resx @@ -0,0 +1,230 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, ... + + + System.Resources.ResXResourceWriter, System.Windows.Forms, ... + + Laden + App wird geladen ... + Startfehler + Fehler beim Starten der App + Tag + Woche + Monat + Jahr + Optionen + Heute + Export + Bearbeiten + Löschen + Abbrechen + Speichern + Zurücksetzen + Aktiv + Inaktiv + Ja + Nein + OK + Fehler + Vormittag + Nachmittag + Standard + Standardwert + Mo + Di + Mi + Do + Fr + Sa + So + {0} (inaktiv) + dddd, dd. MMMM yyyy + ddd dd.MM. + MMMM yyyy + yyyy + dd.MM.yyyy + Noch keine Einträge vorhanden. + + Nachtrag + + Eintrag + Heute kannst du Schnellstatus oder einen Eintrag mit Tätigkeit und Symptomen setzen. + Für vergangene Tage legst du einen Nachtrag für Vormittag oder Nachmittag an. + Für zukünftige Tage sind keine Einträge möglich. + Eintrag löschen + Soll dieser Eintrag wirklich gelöscht werden? + Details anzeigen + Details ausblenden + Tätigkeit: {0} + Dauer: {0} + Symptome: {0} + Woche {0} - {1} + Zusammenfassung anzeigen + Zusammenfassung ausblenden + Tätigkeiten: {0} + Symptome: {0} + Eintrag + Nachtrag + Tageszeit + Tätigkeit + Tätigkeit + Dauer (HH:mm) + Symptome + Eintrag speichern + Zukünftige Tage können nicht gespeichert werden. + Gewählter Status: {0} + Bitte Status wählen + Keine Tätigkeit + Grün + Gelb + Rot + Schwarz + Deutsch + English + System ({0}) + Aussehen + Push-Nachrichten + Datenverwaltung + Rechtliches + Aussehen + Bearbeite zuerst Statustexte und Sprache. Die Farben werden darunter im Farbdialog angepasst. + App-Sprache + Sprache auswählen + Farbe wählen + Automatisch erkannt über die Systemsprache: {0} + Aktive App-Sprache: {0} + Aussehen gespeichert. + Aussehen auf Standard zurückgesetzt. + Bereits verwendet, kann nur deaktiviert werden. + Kann gelöscht werden, solange unbenutzt. + Aktiver Pfad: {0} + Hinzufügen + Übernehmen + Von + Bis + Push-Benachrichtigungen + Ein Zeitblock kann auf mehreren Wochentagen aktiv sein. + Vibration für Push-Nachrichten + Auf Android wird dafür automatisch der passende Benachrichtigungskanal verwendet. + Zeit hinzufügen + Benachrichtigungszeiten speichern + Export + Lege Zeitraum und Darstellung fest. Nach dem Erstellen kannst du den Export direkt öffnen oder teilen. + Filter (optional) + Mehrfachauswahl möglich. + Filter zurücksetzen + Exportmodus + Tagesansicht + Wochenblock + Tageszusammenfassung + Export erstellen + Export leeren + 1 Tag ausgewählt: {0} + {0} Tage ausgewählt: {1} bis {2} + Tagesansicht: Jeder Tag wird mit allen einzelnen Einträgen, Tätigkeiten, Dauer und Symptomen exportiert. + Wochenblock: Pro Tag werden Vormittag und Nachmittag mit Status, Tätigkeiten, Gesamtdauer und Symptomen dargestellt. + Tageszusammenfassung: Jeder Tag erscheint kompakt in einer Zeile, ähnlich wie bei Monats- und Jahresexporten. + Tätigkeit: {0} + Symptome: {0} + Keine Filter aktiv. + Symptome ausblenden + Symptome ausblenden ({0} ausgewählt) + Symptome auswählen + Symptome auswählen ({0} ausgewählt) + Alle Tätigkeiten + Möchtest du wirklich alle lokal gespeicherten Exporte löschen? + {0} Export-Datei(en) wurden gelöscht. + Es waren keine Export-Dateien vorhanden. + Export gespeichert: {0} + Schließen + Öffnen + Teilen + Export öffnen + Export teilen + Tätigkeiten + Neue Tätigkeit + Aktiv/Inaktiv + Symptome + Neues Symptom + Alle Einträge löschen + Zum Bestätigen 'löschen' eingeben. + löschen + Alles löschen + Datenbank + Externe Datenbank verwenden + Ordner oder Dateipfad für externe DB + Für SQLite ist ein externer Dateipfad sinnvoll. Für echte Mehrbenutzer-Synchronisierung ist später eher ein eigener Server oder eine API-Schicht besser geeignet. + Datenbankpfad speichern + Alle Einträge wurden gelöscht. + Bitte zuerst einen Tätigkeitsnamen eingeben. + Tätigkeit hinzugefügt. + Tätigkeit gespeichert. + Tätigkeit aktualisiert. + Tätigkeit wurde deaktiviert. + Tätigkeit wurde gelöscht. + Bitte zuerst einen Symptomnamen eingeben. + Symptom hinzugefügt. + Symptom gespeichert. + Symptom aktualisiert. + Symptom wurde deaktiviert. + Symptom wurde gelöscht. + Benachrichtigungszeit hinzugefügt. + Benachrichtigungszeit entfernt. + Bitte Benachrichtigungen, Push-Nachrichten und Alarme erlauben und danach erneut speichern. + Bitte Benachrichtigungen und Push-Nachrichten erlauben und danach erneut speichern. + Bitte pro Benachrichtigungszeit mindestens einen Wochentag auswählen. + Benachrichtigungszeiten gespeichert. Vibration ist aktiv. + Benachrichtigungszeiten gespeichert. Vibration ist aus. + Datenbankpfad gespeichert. Bitte App neu starten, damit der Pfad aktiv wird. + Export erstellt: {0} + App-Hintergrund + Karten-Hintergrund + Sekundäre Fläche + Rahmen + Haupttext + Nebentext + Statusfarbe Grün + Statusfarbe Gelb + Statusfarbe Rot + Statusfarbe Schwarz / Grau + Button Primär Hintergrund + Button Primär Text + Button Sekundär Hintergrund + Button Sekundär Text + App-Leiste Hintergrund + App-Leiste Vordergrund + App-Leiste Titel + App-Leiste Inaktiv + Tableiste Hintergrund + Tableiste Aktiv + Tableiste Titel + Tableiste Inaktiv + Text für Grün + Text für Gelb + Text für Rot + Text für Schwarz / Grau + Datenschutzerklärung + Stand: 03.04.2026 + Diese App verarbeitet deine Angaben ausschließlich für die Nutzung auf deinem Gerät. Es werden keine Nutzerdaten automatisch an mich oder an Dritte übermittelt, verkauft oder für Werbezwecke weitergegeben. + Gespeichert werden Einträge, Auswahllisten, Benachrichtigungszeiten, Darstellungseinstellungen und bei Bedarf lokal erzeugte Exportdateien. Eine Cloud-Synchronisierung oder ein automatischer Hintergrund-Upload findet durch diese App nicht statt. + Die Speicherung erfolgt lokal im internen App-Bereich beziehungsweise in einem von dir selbst gewählten Speicherort. Die Daten liegen dort in technischer App-Struktur und sind nicht für eine unmittelbar öffentliche Darstellung bestimmt. Bei direktem technischem Zugriff auf das Gerät oder auf Dateien kann jedoch nicht vollständig ausgeschlossen werden, dass fachkundige Personen Rückschlüsse auf Art und Inhalt der gespeicherten Daten ziehen können. + Wenn du Exportdateien bewusst teilst oder einen externen Datenbankpfad verwendest, entscheidest du selbst über diesen Speicher- oder Weitergabeweg. + Haftungshinweis + Die Nutzung der App erfolgt auf eigenes Risiko. Soweit gesetzlich zulässig, übernehme ich keine Gewähr oder Haftung für Aktualität, Richtigkeit, Vollständigkeit, technische Verfügbarkeit, Datenverlust oder dafür, dass die App für einen bestimmten Zweck geeignet ist. + Die App ersetzt keine medizinische, therapeutische, pflegerische, rechtliche oder technische Fachberatung. + Persönlicher Hinweis + Diese App wurde nicht von einem Fachinformatiker entwickelt. Ich bin selbst Betroffener mit ME/CFS und habe die Anwendung aus eigener Perspektive und Erfahrung heraus erstellt. + Gerade deshalb soll die App im Alltag helfen, sie ist aber ein persönliches Projekt und kein professionell zertifiziertes Medizin- oder Softwareprodukt. + Farbe bearbeiten + Rot + Grün + Blau + Hell + Zurücksetzen lädt nur den Standardwert in den Dialog. Erst Übernehmen speichert die Änderung. Abbrechen verwirft alles aus diesem Dialog wieder. + diff --git a/Services/AppBootstrapService.cs b/Services/AppBootstrapService.cs index 8a47228..e92dadc 100644 --- a/Services/AppBootstrapService.cs +++ b/Services/AppBootstrapService.cs @@ -38,6 +38,7 @@ public class AppBootstrapService await _activityRepository.EnsureDefaultsAsync(); await _symptomRepository.EnsureDefaultsAsync(); await _appearanceRepository.EnsureDefaultsAsync(); + await _appearanceService.SyncLocalizedStatusTextsAsync(); // Wichtig: gespeicherte Appearance-Werte direkt beim Start // auf die App-Ressourcen anwenden. @@ -47,4 +48,4 @@ public class AppBootstrapService _initialized = true; } -} \ No newline at end of file +} diff --git a/Services/AppearanceService.cs b/Services/AppearanceService.cs index c4e54d3..77be45f 100644 --- a/Services/AppearanceService.cs +++ b/Services/AppearanceService.cs @@ -65,6 +65,7 @@ public class AppearanceService public async Task ResetAsync() { await _appearanceRepository.ResetAsync(); + await SyncLocalizedStatusTextsAsync(); await _appearanceRepository.EnsureDefaultsAsync(); await ApplyAsync(); } @@ -96,6 +97,26 @@ public class AppearanceService return fallback; } + public async Task SyncLocalizedStatusTextsAsync() + { + var map = await _appearanceRepository.GetMapAsync(); + + foreach (var key in GetStatusTextKeys()) + { + var currentValue = map.TryGetValue(key, out var storedValue) + ? storedValue + : string.Empty; + + var normalized = LocalizationService.NormalizeStatusTextForCulture( + key, + currentValue, + LocalizationService.GetCurrentCulture()); + + if (!string.Equals((currentValue ?? string.Empty).Trim(), normalized, StringComparison.Ordinal)) + await _appearanceRepository.SaveAsync(key, normalized); + } + } + private static void ApplyValue(ResourceDictionary resources, string key, string value, string fallback) { if (IsColorKey(key)) @@ -138,4 +159,12 @@ public class AppearanceService _ => false }; -} \ No newline at end of file + + private static IEnumerable GetStatusTextKeys() + { + yield return AppearanceKeys.StatusGreenText; + yield return AppearanceKeys.StatusYellowText; + yield return AppearanceKeys.StatusRedText; + yield return AppearanceKeys.StatusGrayText; + } +} diff --git a/Services/ExportUiHelper.cs b/Services/ExportUiHelper.cs index af19bfa..f5bd7e7 100644 --- a/Services/ExportUiHelper.cs +++ b/Services/ExportUiHelper.cs @@ -1,29 +1,33 @@ -namespace cfs_tracker.Services; +namespace cfs_tracker.Services; public static class ExportUiHelper { public static async Task ShowExportSavedActionsAsync(ExportResult result) { - var action = await Shell.Current.DisplayActionSheetAsync( - $"Export gespeichert:\n{result.FileName}", - "Schließen", - null, - "Öffnen", - "Teilen"); + var closeText = LocalizationService.Translate("Options_Export_ActionClose"); + var openText = LocalizationService.Translate("Options_Export_ActionOpen"); + var shareText = LocalizationService.Translate("Options_Export_ActionShare"); - if (action == "Öffnen") + var action = await Shell.Current.DisplayActionSheetAsync( + LocalizationService.Format("Options_Export_ActionsTitle", result.FileName), + closeText, + null, + openText, + shareText); + + if (action == openText) { await Launcher.Default.OpenAsync(new OpenFileRequest( - "Export öffnen", + LocalizationService.Translate("Options_Export_OpenTitle"), new ReadOnlyFile(result.FilePath))); } - else if (action == "Teilen") + else if (action == shareText) { await Share.Default.RequestAsync(new ShareFileRequest { - Title = "Export teilen", + Title = LocalizationService.Translate("Options_Export_ShareTitle"), File = new ShareFile(result.FilePath) }); } } -} \ No newline at end of file +} diff --git a/Services/LocalizationService.cs b/Services/LocalizationService.cs new file mode 100644 index 0000000..82e9d0e --- /dev/null +++ b/Services/LocalizationService.cs @@ -0,0 +1,269 @@ +using cfs_tracker.Helpers; +using System.ComponentModel; +using System.Globalization; +using System.Resources; + +namespace cfs_tracker.Services; + +public sealed class LocalizationService : INotifyPropertyChanged +{ + public const string SystemLanguageCode = "system"; + public const string GermanLanguageCode = "de"; + public const string EnglishLanguageCode = "en"; + + private const string LanguagePreferenceKey = "app_language"; + + private static readonly ResourceManager ResourceManager = + new("cfs_tracker.Resources.Localization.AppStrings", typeof(LocalizationService).Assembly); + + private static readonly CultureInfo GermanCulture = new("de-DE"); + private static readonly CultureInfo EnglishCulture = new("en-GB"); + + private readonly CultureInfo _systemCulture; + + private string _selectedLanguageCode = SystemLanguageCode; + private CultureInfo _effectiveCulture; + + public static LocalizationService? Current { get; private set; } + + public event PropertyChangedEventHandler? PropertyChanged; + public event EventHandler? LanguageChanged; + + public LocalizationService() + { + Current ??= this; + _systemCulture = CaptureSystemCulture(); + _effectiveCulture = ResolveEffectiveCulture(SystemLanguageCode); + } + + public string SelectedLanguageCode => _selectedLanguageCode; + + public CultureInfo EffectiveCulture => _effectiveCulture; + + public string EffectiveLanguageCode => NormalizeLanguageCode(_effectiveCulture.TwoLetterISOLanguageName); + + public void Initialize() + { + ApplyLanguage(Preferences.Default.Get(LanguagePreferenceKey, SystemLanguageCode), persistSelection: false); + } + + public bool SetSelectedLanguage(string? languageCode) + { + var normalized = NormalizeLanguageCode(languageCode); + return ApplyLanguage(normalized, persistSelection: true); + } + + public CultureInfo GetCultureForSelection(string? languageCode) + { + return ResolveEffectiveCulture(NormalizeLanguageCode(languageCode)); + } + + public string GetString(string key) => GetString(key, _effectiveCulture); + + public string GetLanguageDisplayName(string? languageCode) + { + var normalized = NormalizeLanguageCode(languageCode); + + return normalized switch + { + GermanLanguageCode => GetString("Language_Name_German"), + EnglishLanguageCode => GetString("Language_Name_English"), + _ => string.Format( + _effectiveCulture, + GetString("Language_SystemOption"), + GetLanguageDisplayNameForCulture(ResolveEffectiveSystemCulture(), _effectiveCulture)) + }; + } + + public string GetSystemLanguageDisplayName() + { + return GetLanguageDisplayNameForCulture(ResolveEffectiveSystemCulture(), _effectiveCulture); + } + + public static string Translate(string key) + { + return Current?.GetString(key) ?? GetString(key, ResolveFallbackCulture()); + } + + public static string Format(string key, params object[] args) + { + var culture = GetCurrentCulture(); + return string.Format(culture, Translate(key), args); + } + + public static CultureInfo GetCurrentCulture() + { + return Current?.EffectiveCulture ?? ResolveFallbackCulture(); + } + + public static string GetString(string key, CultureInfo culture) + { + if (string.IsNullOrWhiteSpace(key)) + return string.Empty; + + return ResourceManager.GetString(key, culture) + ?? ResourceManager.GetString(key, GermanCulture) + ?? key; + } + + public static string NormalizeLanguageCode(string? languageCode) + { + var normalized = (languageCode ?? string.Empty).Trim().ToLowerInvariant(); + + return normalized switch + { + GermanLanguageCode => GermanLanguageCode, + EnglishLanguageCode => EnglishLanguageCode, + _ => SystemLanguageCode + }; + } + + public static string GetDefaultStatusText(string appearanceKey, CultureInfo? culture = null) + { + var resourceKey = appearanceKey switch + { + AppearanceKeys.StatusGreenText => "Status_Default_Green", + AppearanceKeys.StatusYellowText => "Status_Default_Yellow", + AppearanceKeys.StatusRedText => "Status_Default_Red", + AppearanceKeys.StatusGrayText => "Status_Default_Gray", + _ => string.Empty + }; + + if (string.IsNullOrWhiteSpace(resourceKey)) + return string.Empty; + + return GetString(resourceKey, culture ?? GetCurrentCulture()); + } + + public static string NormalizeStatusTextForCulture(string appearanceKey, string? currentValue, CultureInfo targetCulture) + { + if (IsKnownDefaultStatusText(appearanceKey, currentValue)) + return GetDefaultStatusText(appearanceKey, targetCulture); + + return (currentValue ?? string.Empty).Trim(); + } + + public static bool IsKnownDefaultStatusText(string appearanceKey, string? value) + { + if (string.IsNullOrWhiteSpace(value)) + return true; + + var trimmed = value.Trim(); + foreach (var culture in GetSupportedCultures()) + { + if (string.Equals(trimmed, GetDefaultStatusText(appearanceKey, culture), StringComparison.OrdinalIgnoreCase)) + return true; + } + + return false; + } + + public static bool IsKnownTranslation(string key, string? value) + { + if (string.IsNullOrWhiteSpace(value)) + return false; + + var trimmed = value.Trim(); + foreach (var culture in GetSupportedCultures()) + { + if (string.Equals(trimmed, GetString(key, culture), StringComparison.OrdinalIgnoreCase)) + return true; + } + + return false; + } + + public static bool IsNoActivityLabel(string? value) => IsKnownTranslation("Activity_None", value); + + private bool ApplyLanguage(string? languageCode, bool persistSelection) + { + var normalized = NormalizeLanguageCode(languageCode); + var nextCulture = ResolveEffectiveCulture(normalized); + + if (persistSelection) + Preferences.Default.Set(LanguagePreferenceKey, normalized); + + var selectionChanged = !string.Equals(_selectedLanguageCode, normalized, StringComparison.OrdinalIgnoreCase); + var cultureChanged = !string.Equals(_effectiveCulture.Name, nextCulture.Name, StringComparison.OrdinalIgnoreCase); + + _selectedLanguageCode = normalized; + _effectiveCulture = nextCulture; + ApplyCulture(nextCulture); + + if (selectionChanged) + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedLanguageCode))); + + if (selectionChanged || cultureChanged) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(EffectiveCulture))); + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(EffectiveLanguageCode))); + LanguageChanged?.Invoke(this, EventArgs.Empty); + } + + return cultureChanged; + } + + private CultureInfo ResolveEffectiveCulture(string normalizedLanguageCode) + { + return normalizedLanguageCode switch + { + GermanLanguageCode => GermanCulture, + EnglishLanguageCode => EnglishCulture, + _ => ResolveEffectiveSystemCulture() + }; + } + + private CultureInfo ResolveEffectiveSystemCulture() + { + return _systemCulture.TwoLetterISOLanguageName.ToLowerInvariant() switch + { + GermanLanguageCode => _systemCulture, + EnglishLanguageCode => _systemCulture, + _ => EnglishCulture + }; + } + + private static string GetLanguageDisplayNameForCulture(CultureInfo culture, CultureInfo uiCulture) + { + return culture.TwoLetterISOLanguageName.ToLowerInvariant() switch + { + GermanLanguageCode => GetString("Language_Name_German", uiCulture), + _ => GetString("Language_Name_English", uiCulture) + }; + } + + private static void ApplyCulture(CultureInfo culture) + { + CultureInfo.CurrentCulture = culture; + CultureInfo.CurrentUICulture = culture; + CultureInfo.DefaultThreadCurrentCulture = culture; + CultureInfo.DefaultThreadCurrentUICulture = culture; + } + + private static CultureInfo CaptureSystemCulture() + { + var current = CultureInfo.CurrentUICulture; + + return string.IsNullOrWhiteSpace(current.Name) + ? GermanCulture + : current; + } + + private static CultureInfo ResolveFallbackCulture() + { + var current = CultureInfo.CurrentUICulture; + + return current.TwoLetterISOLanguageName.ToLowerInvariant() switch + { + GermanLanguageCode => current, + EnglishLanguageCode => current, + _ => EnglishCulture + }; + } + + private static IEnumerable GetSupportedCultures() + { + yield return GermanCulture; + yield return EnglishCulture; + } +} diff --git a/ViewModels/ActivityManageItemViewModel.cs b/ViewModels/ActivityManageItemViewModel.cs index 2519839..77821b8 100644 --- a/ViewModels/ActivityManageItemViewModel.cs +++ b/ViewModels/ActivityManageItemViewModel.cs @@ -1,3 +1,4 @@ +using cfs_tracker.Services; using CommunityToolkit.Mvvm.ComponentModel; namespace cfs_tracker.ViewModels; @@ -15,6 +16,6 @@ public partial class ActivityManageItemViewModel : ObservableObject public bool IsUsed { get; init; } public string UsageHint => IsUsed - ? "Bereits verwendet – kann nur deaktiviert werden." - : "Kann gelöscht werden, solange unbenutzt."; + ? LocalizationService.Translate("Options_UsageHint_Used") + : LocalizationService.Translate("Options_UsageHint_Unused"); } diff --git a/ViewModels/DayEntryItemViewModel.cs b/ViewModels/DayEntryItemViewModel.cs index a5a22e0..39db2c2 100644 --- a/ViewModels/DayEntryItemViewModel.cs +++ b/ViewModels/DayEntryItemViewModel.cs @@ -1,3 +1,4 @@ +using cfs_tracker.Services; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; @@ -20,7 +21,12 @@ public partial class DayEntryItemViewModel : ObservableObject public bool HasDuration => !string.IsNullOrWhiteSpace(DurationText); public bool HasSymptoms => !string.IsNullOrWhiteSpace(SymptomsText); public bool HasDetails => HasActivity || HasDuration || HasSymptoms; - public string DetailsButtonText => IsExpanded ? "Details ausblenden" : "Details anzeigen"; + public string DetailsButtonText => IsExpanded + ? LocalizationService.Translate("DayPage_DetailsHide") + : LocalizationService.Translate("DayPage_DetailsShow"); + public string ActivitySummaryText => LocalizationService.Format("DayPage_ActivityFormat", ActivityText); + public string DurationSummaryText => LocalizationService.Format("DayPage_DurationFormat", DurationText); + public string SymptomsSummaryText => LocalizationService.Format("DayPage_SymptomsFormat", SymptomsText); [ObservableProperty] private bool isExpanded; @@ -44,4 +50,4 @@ public partial class DayEntryItemViewModel : ObservableObject IsExpanded = !IsExpanded; } -} \ No newline at end of file +} diff --git a/ViewModels/DayViewModel.cs b/ViewModels/DayViewModel.cs index f109981..069ac09 100644 --- a/ViewModels/DayViewModel.cs +++ b/ViewModels/DayViewModel.cs @@ -46,16 +46,16 @@ public partial class DayViewModel : ObservableObject private int grayCount; [ObservableProperty] - private string greenStatusText = "Grün"; + private string greenStatusText = "Green"; [ObservableProperty] - private string yellowStatusText = "Gelb"; + private string yellowStatusText = "Yellow"; [ObservableProperty] - private string redStatusText = "Rot"; + private string redStatusText = "Red"; [ObservableProperty] - private string grayStatusText = "Schwarz"; + private string grayStatusText = "Black"; [ObservableProperty] private Color greenStateColor = Color.FromArgb("#4E8B69"); @@ -82,15 +82,18 @@ public partial class DayViewModel : ObservableObject public string RedCounterText => BuildCounterText(RedStatusText, RedCount); public string GrayCounterText => BuildCounterText(GrayStatusText, GrayCount); - public string AddEntryButtonText => IsPastDate ? "+ Nachtrag" : "+ Eintrag"; + public string AddEntryButtonText => IsPastDate + ? LocalizationService.Translate("DayPage_AddBackfillButton") + : LocalizationService.Translate("DayPage_AddEntryButton"); + public bool CanAddEntry => !IsFutureDate; public bool HasNoEntries => !HasEntries; public string DayHintText => IsToday - ? "Heute kannst du Schnellstatus oder einen Eintrag mit Tätigkeit und Symptomen setzen." + ? LocalizationService.Translate("DayPage_HintToday") : IsPastDate - ? "Für vergangene Tage legst du einen Nachtrag für Vormittag oder Nachmittag an." - : "Für zukünftige Tage sind keine Einträge möglich."; + ? LocalizationService.Translate("DayPage_HintPast") + : LocalizationService.Translate("DayPage_HintFuture"); public IAsyncRelayCommand PreviousDayCommand { get; } public IAsyncRelayCommand NextDayCommand { get; } @@ -181,15 +184,15 @@ public partial class DayViewModel : ObservableObject { var slotText = entry.DayPart switch { - DayPart.Morning => "Vormittag", - DayPart.Afternoon => "Nachmittag", + DayPart.Morning => LocalizationService.Translate("Common_Morning"), + DayPart.Afternoon => LocalizationService.Translate("Common_Afternoon"), _ => entry.Timestamp.ToString("HH:mm", CultureInfo.InvariantCulture) }; var activityText = string.Empty; if (entry.ActivityId.HasValue && activityMap.TryGetValue(entry.ActivityId.Value, out var activityName) && - !string.Equals(activityName, "Keine Tätigkeit", StringComparison.OrdinalIgnoreCase)) + !LocalizationService.IsNoActivityLabel(activityName)) { activityText = activityName; } @@ -267,10 +270,10 @@ public partial class DayViewModel : ObservableObject return; var accepted = await Application.Current!.Windows[0].Page!.DisplayAlertAsync( - "Eintrag löschen", - "Soll dieser Eintrag wirklich gelöscht werden?", - "Ja", - "Nein"); + LocalizationService.Translate("DayPage_DeleteAlert_Title"), + LocalizationService.Translate("DayPage_DeleteAlert_Message"), + LocalizationService.Translate("Common_Yes"), + LocalizationService.Translate("Common_No")); if (!accepted) return; @@ -324,10 +327,18 @@ public partial class DayViewModel : ObservableObject private void LoadAppearance() { - GreenStatusText = _appearanceService.GetText(AppearanceKeys.StatusGreenText, "Grün"); - YellowStatusText = _appearanceService.GetText(AppearanceKeys.StatusYellowText, "Gelb"); - RedStatusText = _appearanceService.GetText(AppearanceKeys.StatusRedText, "Rot"); - GrayStatusText = _appearanceService.GetText(AppearanceKeys.StatusGrayText, "Schwarz"); + GreenStatusText = _appearanceService.GetText( + AppearanceKeys.StatusGreenText, + LocalizationService.GetDefaultStatusText(AppearanceKeys.StatusGreenText)); + YellowStatusText = _appearanceService.GetText( + AppearanceKeys.StatusYellowText, + LocalizationService.GetDefaultStatusText(AppearanceKeys.StatusYellowText)); + RedStatusText = _appearanceService.GetText( + AppearanceKeys.StatusRedText, + LocalizationService.GetDefaultStatusText(AppearanceKeys.StatusRedText)); + GrayStatusText = _appearanceService.GetText( + AppearanceKeys.StatusGrayText, + LocalizationService.GetDefaultStatusText(AppearanceKeys.StatusGrayText)); GreenStateColor = _appearanceService.GetColor(AppearanceKeys.StateGreen, "#4E8B69"); YellowStateColor = _appearanceService.GetColor(AppearanceKeys.StateYellow, "#B89A42"); @@ -352,4 +363,4 @@ public partial class DayViewModel : ObservableObject } private static string BuildCounterText(string label, int count) => $"{label}\n{count}"; -} \ No newline at end of file +} diff --git a/ViewModels/LanguageOptionItemViewModel.cs b/ViewModels/LanguageOptionItemViewModel.cs new file mode 100644 index 0000000..53253c3 --- /dev/null +++ b/ViewModels/LanguageOptionItemViewModel.cs @@ -0,0 +1,8 @@ +namespace cfs_tracker.ViewModels; + +public class LanguageOptionItemViewModel +{ + public string Code { get; init; } = string.Empty; + + public string DisplayName { get; init; } = string.Empty; +} diff --git a/ViewModels/MonthSectionViewModel.cs b/ViewModels/MonthSectionViewModel.cs index 8e068ad..5aac7a5 100644 --- a/ViewModels/MonthSectionViewModel.cs +++ b/ViewModels/MonthSectionViewModel.cs @@ -1,9 +1,34 @@ +using CommunityToolkit.Mvvm.ComponentModel; using System.Collections.ObjectModel; namespace cfs_tracker.ViewModels; -public class MonthSectionViewModel +public partial class MonthSectionViewModel : ObservableObject { - public string Title { get; init; } = string.Empty; + private string _title = string.Empty; + private bool _isLoading = true; + + public string Title + { + get => _title; + set => SetProperty(ref _title, value); + } + + public bool IsLoading + { + get => _isLoading; + set => SetProperty(ref _isLoading, value); + } + public ObservableCollection Cells { get; } = new(); + + public void ReplaceCells(IEnumerable cells) + { + Cells.Clear(); + + foreach (var cell in cells) + Cells.Add(cell); + + IsLoading = false; + } } diff --git a/ViewModels/MonthViewModel.cs b/ViewModels/MonthViewModel.cs index 4c8098d..46f4666 100644 --- a/ViewModels/MonthViewModel.cs +++ b/ViewModels/MonthViewModel.cs @@ -204,4 +204,4 @@ public partial class MonthViewModel : ObservableObject BorderColor = Colors.Transparent }; } -} \ No newline at end of file +} diff --git a/ViewModels/NotificationScheduleItemViewModel.cs b/ViewModels/NotificationScheduleItemViewModel.cs index 9c4236a..0bdbc0e 100644 --- a/ViewModels/NotificationScheduleItemViewModel.cs +++ b/ViewModels/NotificationScheduleItemViewModel.cs @@ -1,4 +1,5 @@ using cfs_tracker.Models; +using cfs_tracker.Services; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; @@ -35,7 +36,9 @@ public partial class NotificationScheduleItemViewModel : ObservableObject [ObservableProperty] private bool sunday; - public string IsEnabledButtonText => IsEnabled ? "Aktiv" : "Inaktiv"; + public string IsEnabledButtonText => IsEnabled + ? LocalizationService.Translate("Common_Active") + : LocalizationService.Translate("Common_Inactive"); public IRelayCommand ToggleIsEnabledCommand { get; } public IRelayCommand ToggleMondayCommand { get; } @@ -90,4 +93,4 @@ public partial class NotificationScheduleItemViewModel : ObservableObject Saturday = flags.HasFlag(NotificationWeekdays.Saturday); Sunday = flags.HasFlag(NotificationWeekdays.Sunday); } -} \ No newline at end of file +} diff --git a/ViewModels/OptionsViewModel.cs b/ViewModels/OptionsViewModel.cs index f8b3323..73887a6 100644 --- a/ViewModels/OptionsViewModel.cs +++ b/ViewModels/OptionsViewModel.cs @@ -6,6 +6,7 @@ using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using System.Collections.ObjectModel; using System.ComponentModel; +using System.Globalization; namespace cfs_tracker.ViewModels; @@ -14,6 +15,7 @@ public partial class OptionsViewModel : ObservableObject private readonly HealthEntryRepository _healthEntryRepository; private readonly AppearanceRepository _appearanceRepository; private readonly AppearanceService _appearanceService; + private readonly LocalizationService _localizationService; private readonly ActivityRepository _activityRepository; private readonly SymptomRepository _symptomRepository; private readonly NotificationScheduleRepository _notificationScheduleRepository; @@ -64,8 +66,15 @@ public partial class OptionsViewModel : ObservableObject [ObservableProperty] private bool isExportSymptomFilterExpanded; + [ObservableProperty] + private LanguageOptionItemViewModel? selectedLanguageOption; + + [ObservableProperty] + private bool requiresShellReload; + public ObservableCollection AppearanceColors { get; } = new(); public ObservableCollection StatusTexts { get; } = new(); + public ObservableCollection LanguageOptions { get; } = new(); public ObservableCollection Activities { get; } = new(); public ObservableCollection Symptoms { get; } = new(); public ObservableCollection NotificationSchedules { get; } = new(); @@ -78,7 +87,18 @@ public partial class OptionsViewModel : ObservableObject public bool IsExportTabSelected => SelectedTab == OptionsTab.Export; public bool IsLegalTabSelected => SelectedTab == OptionsTab.Legal; - public string NotificationVibrationButtonText => NotificationVibrationEnabled ? "Aktiv" : "Inaktiv"; + public string NotificationVibrationButtonText => NotificationVibrationEnabled + ? LocalizationService.Translate("Common_Active") + : LocalizationService.Translate("Common_Inactive"); + + public string CurrentDatabasePathText => LocalizationService.Format("Options_Database_CurrentPathFormat", CurrentDatabasePath); + + public string SelectedLanguageDescription => SelectedLanguageOption?.Code == LocalizationService.SystemLanguageCode + ? LocalizationService.Format("Options_Language_SystemHint", _localizationService.GetSystemLanguageDisplayName()) + : LocalizationService.Format( + "Options_Language_SelectedHint", + SelectedLanguageOption?.DisplayName ?? _localizationService.GetLanguageDisplayName(_localizationService.SelectedLanguageCode)); + public bool IsDayViewExportLayoutSelected => SelectedExportLayout == ExportLayout.DayView; public bool IsWeekBlockExportLayoutSelected => SelectedExportLayout == ExportLayout.WeekBlock; public bool IsDaySummaryExportLayoutSelected => SelectedExportLayout == ExportLayout.DaySummary; @@ -92,16 +112,16 @@ public partial class OptionsViewModel : ObservableObject var totalDays = (end - start).Days + 1; return totalDays == 1 - ? $"1 Tag ausgewählt: {start:dd.MM.yyyy}" - : $"{totalDays} Tage ausgewählt: {start:dd.MM.yyyy} bis {end:dd.MM.yyyy}"; + ? LocalizationService.Format("Options_Export_RangeSingleFormat", FormatShortDate(start)) + : LocalizationService.Format("Options_Export_RangeMultipleFormat", totalDays, FormatShortDate(start), FormatShortDate(end)); } } public string SelectedExportLayoutDescription => SelectedExportLayout switch { - ExportLayout.DayView => "Tagesansicht: Jeder Tag wird mit allen einzelnen Einträgen, Tätigkeiten, Dauer und Symptomen exportiert.", - ExportLayout.WeekBlock => "Wochenblock: Pro Tag werden Vormittag und Nachmittag mit Status, T\u00e4tigkeiten, Gesamtdauer und Symptomen dargestellt.", - _ => "Tageszusammenfassung: Jeder Tag erscheint kompakt in einer Zeile, ähnlich wie bei Monats- und Jahresexporten." + ExportLayout.DayView => LocalizationService.Translate("Options_Export_LayoutDescription_DayView"), + ExportLayout.WeekBlock => LocalizationService.Translate("Options_Export_LayoutDescription_WeekBlock"), + _ => LocalizationService.Translate("Options_Export_LayoutDescription_DaySummary") }; public string ExportFilterSummary @@ -111,7 +131,7 @@ public partial class OptionsViewModel : ObservableObject var parts = new List(); if (SelectedExportActivity?.Id is int) - parts.Add($"T\u00e4tigkeit: {SelectedExportActivity.Name}"); + parts.Add(LocalizationService.Format("Options_Export_Filter_ActivityFormat", SelectedExportActivity.Name)); var selectedSymptoms = ExportSymptoms .Where(x => x.IsSelected) @@ -120,11 +140,11 @@ public partial class OptionsViewModel : ObservableObject .ToList(); if (selectedSymptoms.Count > 0) - parts.Add($"Symptome: {string.Join(", ", selectedSymptoms)}"); + parts.Add(LocalizationService.Format("Options_Export_Filter_SymptomsFormat", string.Join(", ", selectedSymptoms))); return parts.Count > 0 ? string.Join(" | ", parts) - : "Keine Filter aktiv."; + : LocalizationService.Translate("Options_Export_Filter_None"); } } @@ -133,13 +153,14 @@ public partial class OptionsViewModel : ObservableObject get { var selectedCount = ExportSymptoms.Count(x => x.IsSelected); - var countSuffix = selectedCount > 0 - ? $" ({selectedCount} ausgewählt)" - : string.Empty; - return IsExportSymptomFilterExpanded - ? $"Symptome ausblenden{countSuffix}" - : $"Symptome auswählen{countSuffix}"; + return (IsExportSymptomFilterExpanded, selectedCount > 0) switch + { + (true, true) => LocalizationService.Format("Options_Export_SymptomsHideWithCount", selectedCount), + (true, false) => LocalizationService.Translate("Options_Export_SymptomsHide"), + (false, true) => LocalizationService.Format("Options_Export_SymptomsSelectWithCount", selectedCount), + _ => LocalizationService.Translate("Options_Export_SymptomsSelect") + }; } } @@ -176,6 +197,7 @@ public partial class OptionsViewModel : ObservableObject HealthEntryRepository healthEntryRepository, AppearanceRepository appearanceRepository, AppearanceService appearanceService, + LocalizationService localizationService, ActivityRepository activityRepository, SymptomRepository symptomRepository, NotificationScheduleRepository notificationScheduleRepository, @@ -187,6 +209,7 @@ public partial class OptionsViewModel : ObservableObject _healthEntryRepository = healthEntryRepository; _appearanceRepository = appearanceRepository; _appearanceService = appearanceService; + _localizationService = localizationService; _activityRepository = activityRepository; _symptomRepository = symptomRepository; _notificationScheduleRepository = notificationScheduleRepository; @@ -250,6 +273,16 @@ public partial class OptionsViewModel : ObservableObject OnPropertyChanged(nameof(NotificationVibrationButtonText)); } + partial void OnCurrentDatabasePathChanged(string value) + { + OnPropertyChanged(nameof(CurrentDatabasePathText)); + } + + partial void OnSelectedLanguageOptionChanged(LanguageOptionItemViewModel? value) + { + OnPropertyChanged(nameof(SelectedLanguageDescription)); + } + partial void OnExportStartDateChanged(DateTime value) { if (ExportEndDate.Date < value.Date) @@ -287,6 +320,7 @@ public partial class OptionsViewModel : ObservableObject public async Task LoadAsync() { await LoadAppearanceAsync(); + LoadLanguageOptions(); await LoadActivitiesAsync(); await LoadSymptomsAsync(); await LoadSchedulesAsync(); @@ -296,16 +330,22 @@ public partial class OptionsViewModel : ObservableObject ExternalDatabasePath = _databaseLocationService.ExternalDatabasePath; CurrentDatabasePath = _appDatabase.CurrentPath; StatusText = string.Empty; + RequiresShellReload = false; + } + + public void ClearShellReloadFlag() + { + RequiresShellReload = false; } private bool CanDeleteAllData() => - string.Equals(DeleteConfirmationText?.Trim(), "löschen", StringComparison.OrdinalIgnoreCase); + LocalizationService.IsKnownTranslation("Options_Data_DeleteConfirmationKeyword", DeleteConfirmationText); private async Task DeleteAllDataAsync() { await _healthEntryRepository.DeleteAllAsync(); DeleteConfirmationText = string.Empty; - StatusText = "Alle Einträge wurden gelöscht."; + StatusText = LocalizationService.Translate("Options_Status_AllDataDeleted"); } private async Task LoadAppearanceAsync() @@ -315,39 +355,39 @@ public partial class OptionsViewModel : ObservableObject var map = await _appearanceRepository.GetMapAsync(); - AddColor(AppearanceKeys.AppBackground, "App-Hintergrund"); - AddColor(AppearanceKeys.SurfaceBackground, "Karten-Hintergrund"); - AddColor(AppearanceKeys.SurfaceBackgroundAlt, "Sekundäre Fläche"); - AddColor(AppearanceKeys.Border, "Rahmen"); - AddColor(AppearanceKeys.TextPrimary, "Haupttext"); - AddColor(AppearanceKeys.TextMuted, "Nebentext"); + AddColor(AppearanceKeys.AppBackground); + AddColor(AppearanceKeys.SurfaceBackground); + AddColor(AppearanceKeys.SurfaceBackgroundAlt); + AddColor(AppearanceKeys.Border); + AddColor(AppearanceKeys.TextPrimary); + AddColor(AppearanceKeys.TextMuted); - AddColor(AppearanceKeys.StateGreen, "Statusfarbe Grün"); - AddColor(AppearanceKeys.StateYellow, "Statusfarbe Gelb"); - AddColor(AppearanceKeys.StateRed, "Statusfarbe Rot"); - AddColor(AppearanceKeys.StateGray, "Statusfarbe Schwarz / Grau"); + AddColor(AppearanceKeys.StateGreen); + AddColor(AppearanceKeys.StateYellow); + AddColor(AppearanceKeys.StateRed); + AddColor(AppearanceKeys.StateGray); - AddColor(AppearanceKeys.ButtonPrimaryBackground, "Button Primär Hintergrund"); - AddColor(AppearanceKeys.ButtonPrimaryText, "Button Primär Text"); - AddColor(AppearanceKeys.ButtonSecondaryBackground, "Button Sekundär Hintergrund"); - AddColor(AppearanceKeys.ButtonSecondaryText, "Button Sekundär Text"); + AddColor(AppearanceKeys.ButtonPrimaryBackground); + AddColor(AppearanceKeys.ButtonPrimaryText); + AddColor(AppearanceKeys.ButtonSecondaryBackground); + AddColor(AppearanceKeys.ButtonSecondaryText); - AddColor(AppearanceKeys.ShellBackground, "App-Leiste Hintergrund"); - AddColor(AppearanceKeys.ShellForeground, "App-Leiste Vordergrund"); - AddColor(AppearanceKeys.ShellTitle, "App-Leiste Titel"); - AddColor(AppearanceKeys.ShellUnselected, "App-Leiste Inaktiv"); + AddColor(AppearanceKeys.ShellBackground); + AddColor(AppearanceKeys.ShellForeground); + AddColor(AppearanceKeys.ShellTitle); + AddColor(AppearanceKeys.ShellUnselected); - AddColor(AppearanceKeys.TabBarBackground, "Tableiste Hintergrund"); - AddColor(AppearanceKeys.TabBarForeground, "Tableiste Aktiv"); - AddColor(AppearanceKeys.TabBarTitle, "Tableiste Titel"); - AddColor(AppearanceKeys.TabBarUnselected, "Tableiste Inaktiv"); + AddColor(AppearanceKeys.TabBarBackground); + AddColor(AppearanceKeys.TabBarForeground); + AddColor(AppearanceKeys.TabBarTitle); + AddColor(AppearanceKeys.TabBarUnselected); - AddText(AppearanceKeys.StatusGreenText, "Text für Grün"); - AddText(AppearanceKeys.StatusYellowText, "Text für Gelb"); - AddText(AppearanceKeys.StatusRedText, "Text für Rot"); - AddText(AppearanceKeys.StatusGrayText, "Text für Schwarz / Grau"); + AddText(AppearanceKeys.StatusGreenText); + AddText(AppearanceKeys.StatusYellowText); + AddText(AppearanceKeys.StatusRedText); + AddText(AppearanceKeys.StatusGrayText); - void AddColor(string key, string title) + void AddColor(string key) { var fallback = AppearanceDefaults.All[key]; var value = map.TryGetValue(key, out var stored) ? stored : fallback; @@ -356,27 +396,57 @@ public partial class OptionsViewModel : ObservableObject AppearanceColors.Add(new AppearanceColorItemViewModel { Key = key, - Title = title, + Title = GetAppearanceColorTitle(key), Fallback = fallback, Value = ToHex(preview), PreviewColor = preview }); } - void AddText(string key, string title) + void AddText(string key) { - var fallback = AppearanceDefaults.All[key]; + var fallback = LocalizationService.GetDefaultStatusText(key); + if (string.IsNullOrWhiteSpace(fallback)) + fallback = AppearanceDefaults.All[key]; + var value = map.TryGetValue(key, out var stored) ? stored : fallback; StatusTexts.Add(new AppearanceTextItemViewModel { Key = key, - Title = title, + Title = GetAppearanceTextTitle(key), Value = value }); } } + private void LoadLanguageOptions() + { + var currentCode = _localizationService.SelectedLanguageCode; + + LanguageOptions.Clear(); + LanguageOptions.Add(new LanguageOptionItemViewModel + { + Code = LocalizationService.SystemLanguageCode, + DisplayName = _localizationService.GetLanguageDisplayName(LocalizationService.SystemLanguageCode) + }); + LanguageOptions.Add(new LanguageOptionItemViewModel + { + Code = LocalizationService.GermanLanguageCode, + DisplayName = _localizationService.GetLanguageDisplayName(LocalizationService.GermanLanguageCode) + }); + LanguageOptions.Add(new LanguageOptionItemViewModel + { + Code = LocalizationService.EnglishLanguageCode, + DisplayName = _localizationService.GetLanguageDisplayName(LocalizationService.EnglishLanguageCode) + }); + + SelectedLanguageOption = LanguageOptions.FirstOrDefault(x => x.Code == currentCode) + ?? LanguageOptions.FirstOrDefault(); + + OnPropertyChanged(nameof(SelectedLanguageDescription)); + } + private async Task LoadActivitiesAsync() { var selectedExportActivityId = SelectedExportActivity?.Id; @@ -447,6 +517,14 @@ public partial class OptionsViewModel : ObservableObject private async Task SaveAppearanceAsync() { + RequiresShellReload = false; + + var targetLanguageCode = SelectedLanguageOption?.Code ?? _localizationService.SelectedLanguageCode; + var targetCulture = _localizationService.GetCultureForSelection(targetLanguageCode); + + foreach (var item in StatusTexts) + item.Value = LocalizationService.NormalizeStatusTextForCulture(item.Key, item.Value, targetCulture); + foreach (var item in AppearanceColors) { var normalized = ToHex(ColorUtility.ParseColor(item.Value, item.Fallback)); @@ -458,23 +536,30 @@ public partial class OptionsViewModel : ObservableObject foreach (var item in StatusTexts) await _appearanceService.SaveTextAsync(item.Key, item.Value); + var languageChanged = _localizationService.SetSelectedLanguage(targetLanguageCode); + await _appearanceService.ApplyAsync(); + await LoadAppearanceAsync(); + LoadLanguageOptions(); + await _notificationScheduler.SyncAsync(); - StatusText = "Aussehen gespeichert."; + RequiresShellReload = languageChanged; + StatusText = LocalizationService.Translate("Options_Status_AppearanceSaved"); } private async Task ResetAppearanceAsync() { await _appearanceService.ResetAsync(); await LoadAppearanceAsync(); + LoadLanguageOptions(); await _notificationScheduler.SyncAsync(); - StatusText = "Aussehen auf Standard zurückgesetzt."; + StatusText = LocalizationService.Translate("Options_Status_AppearanceReset"); } private async Task AddActivityAsync() { if (string.IsNullOrWhiteSpace(NewActivityName)) { - StatusText = "Bitte zuerst einen Tätigkeitsnamen eingeben."; + StatusText = LocalizationService.Translate("Options_Status_ActivityNameRequired"); return; } @@ -483,7 +568,7 @@ public partial class OptionsViewModel : ObservableObject await _activityRepository.AddAsync(NewActivityName); NewActivityName = string.Empty; await LoadActivitiesAsync(); - StatusText = "Tätigkeit hinzugefügt."; + StatusText = LocalizationService.Translate("Options_Status_ActivityAdded"); } catch (Exception ex) { @@ -500,7 +585,7 @@ public partial class OptionsViewModel : ObservableObject { await _activityRepository.RenameAsync(item.Id, item.Name); await LoadActivitiesAsync(); - StatusText = "Tätigkeit gespeichert."; + StatusText = LocalizationService.Translate("Options_Status_ActivitySaved"); } catch (Exception ex) { @@ -515,7 +600,7 @@ public partial class OptionsViewModel : ObservableObject await _activityRepository.SetActiveAsync(item.Id, !item.IsActive); await LoadActivitiesAsync(); - StatusText = "Tätigkeit aktualisiert."; + StatusText = LocalizationService.Translate("Options_Status_ActivityUpdated"); } private async Task DeleteActivityAsync(ActivityManageItemViewModel? item) @@ -525,14 +610,17 @@ public partial class OptionsViewModel : ObservableObject await _activityRepository.DeleteOrDeactivateAsync(item.Id); await LoadActivitiesAsync(); - StatusText = item.IsUsed ? "Tätigkeit wurde deaktiviert." : "Tätigkeit wurde gelöscht."; + StatusText = LocalizationService.Translate( + item.IsUsed + ? "Options_Status_ActivityDisabled" + : "Options_Status_ActivityDeleted"); } private async Task AddSymptomAsync() { if (string.IsNullOrWhiteSpace(NewSymptomName)) { - StatusText = "Bitte zuerst einen Symptomnamen eingeben."; + StatusText = LocalizationService.Translate("Options_Status_SymptomNameRequired"); return; } @@ -541,7 +629,7 @@ public partial class OptionsViewModel : ObservableObject await _symptomRepository.AddAsync(NewSymptomName); NewSymptomName = string.Empty; await LoadSymptomsAsync(); - StatusText = "Symptom hinzugefügt."; + StatusText = LocalizationService.Translate("Options_Status_SymptomAdded"); } catch (Exception ex) { @@ -558,7 +646,7 @@ public partial class OptionsViewModel : ObservableObject { await _symptomRepository.RenameAsync(item.Id, item.Name); await LoadSymptomsAsync(); - StatusText = "Symptom gespeichert."; + StatusText = LocalizationService.Translate("Options_Status_SymptomSaved"); } catch (Exception ex) { @@ -573,7 +661,7 @@ public partial class OptionsViewModel : ObservableObject await _symptomRepository.SetActiveAsync(item.Id, !item.IsActive); await LoadSymptomsAsync(); - StatusText = "Symptom aktualisiert."; + StatusText = LocalizationService.Translate("Options_Status_SymptomUpdated"); } private async Task DeleteSymptomAsync(SymptomManageItemViewModel? item) @@ -583,7 +671,10 @@ public partial class OptionsViewModel : ObservableObject await _symptomRepository.DeleteOrDeactivateAsync(item.Id); await LoadSymptomsAsync(); - StatusText = item.IsUsed ? "Symptom wurde deaktiviert." : "Symptom wurde gelöscht."; + StatusText = LocalizationService.Translate( + item.IsUsed + ? "Options_Status_SymptomDisabled" + : "Options_Status_SymptomDeleted"); } private Task AddScheduleAsync() @@ -599,7 +690,7 @@ public partial class OptionsViewModel : ObservableObject Friday = true }); - StatusText = "Benachrichtigungszeit hinzugefügt."; + StatusText = LocalizationService.Translate("Options_Status_NotificationAdded"); return Task.CompletedTask; } @@ -610,16 +701,17 @@ public partial class OptionsViewModel : ObservableObject var granted = await _notificationScheduler.EnsurePermissionAsync(); if (!granted) { - StatusText = OperatingSystem.IsAndroidVersionAtLeast(31) - ? "Bitte Benachrichtigungen, Push-Nachrichten und Alarme erlauben und danach erneut speichern." - : "Bitte Benachrichtigungen und Push-Nachrichten erlauben und danach erneut speichern."; + StatusText = LocalizationService.Translate( + OperatingSystem.IsAndroidVersionAtLeast(31) + ? "Options_Status_NotificationPermissionAndroid31" + : "Options_Status_NotificationPermissionLegacy"); return; } if (NotificationSchedules.Any(x => x.ToWeekdayMask() == 0)) { - StatusText = "Bitte pro Benachrichtigungszeit mindestens einen Wochentag auswählen."; + StatusText = LocalizationService.Translate("Options_Status_NotificationWeekdayRequired"); return; } @@ -636,9 +728,10 @@ public partial class OptionsViewModel : ObservableObject await _notificationScheduler.SyncAsync(); await LoadSchedulesAsync(); - StatusText = NotificationVibrationEnabled - ? "Benachrichtigungszeiten gespeichert. Vibration ist aktiv." - : "Benachrichtigungszeiten gespeichert. Vibration ist aus."; + StatusText = LocalizationService.Translate( + NotificationVibrationEnabled + ? "Options_Status_NotificationsSavedActive" + : "Options_Status_NotificationsSavedInactive"); } private Task DeleteScheduleAsync(NotificationScheduleItemViewModel? item) @@ -646,7 +739,7 @@ public partial class OptionsViewModel : ObservableObject if (item is not null) NotificationSchedules.Remove(item); - StatusText = "Benachrichtigungszeit entfernt."; + StatusText = LocalizationService.Translate("Options_Status_NotificationRemoved"); return Task.CompletedTask; } @@ -655,7 +748,7 @@ public partial class OptionsViewModel : ObservableObject _databaseLocationService.UseExternalDatabase = UseExternalDatabase; _databaseLocationService.ExternalDatabasePath = ExternalDatabasePath?.Trim() ?? string.Empty; CurrentDatabasePath = _databaseLocationService.ResolveDatabasePath(); - StatusText = "Datenbankpfad gespeichert. Bitte App neu starten, damit der Pfad aktiv wird."; + StatusText = LocalizationService.Translate("Options_Status_DatabaseSaved"); return Task.CompletedTask; } @@ -670,7 +763,7 @@ public partial class OptionsViewModel : ObservableObject SelectedExportActivity?.Id, ExportSymptoms.Where(x => x.IsSelected).Select(x => x.Id).ToList()); - StatusText = $"Export erstellt: {result.FileName}"; + StatusText = LocalizationService.Format("Options_Status_ExportCreated", result.FileName); await ExportUiHelper.ShowExportSavedActionsAsync(result); } catch (Exception ex) @@ -686,15 +779,17 @@ public partial class OptionsViewModel : ObservableObject ExportActivities.Add(new ActivityPickerItemViewModel { Id = null, - Name = "Alle T\u00e4tigkeiten" + Name = LocalizationService.Translate("Options_Export_AllActivities") }); - foreach (var item in activities.Where(x => !string.Equals(x.Name, "Keine T\u00e4tigkeit", StringComparison.OrdinalIgnoreCase))) + foreach (var item in activities.Where(x => !LocalizationService.IsNoActivityLabel(x.Name))) { ExportActivities.Add(new ActivityPickerItemViewModel { Id = item.Id, - Name = item.IsActive ? item.Name : $"{item.Name} (inaktiv)" + Name = item.IsActive + ? item.Name + : LocalizationService.Format("Common_InactiveSuffix", item.Name) }); } @@ -711,7 +806,9 @@ public partial class OptionsViewModel : ObservableObject var exportItem = new SelectableSymptomItemViewModel { Id = item.Id, - Name = item.IsActive ? item.Name : $"{item.Name} (inaktiv)", + Name = item.IsActive + ? item.Name + : LocalizationService.Format("Common_InactiveSuffix", item.Name), IsSelected = selectedSymptomIds.Contains(item.Id) }; @@ -747,10 +844,10 @@ public partial class OptionsViewModel : ObservableObject private async Task ClearExportsAsync() { var confirm = await Shell.Current.DisplayAlertAsync( - "Export entleeren", - "Möchtest du wirklich alle lokal gespeicherten Exporte löschen?", - "Ja", - "Nein"); + LocalizationService.Translate("Options_Export_Clear"), + LocalizationService.Translate("Options_Export_Clear_Confirm"), + LocalizationService.Translate("Common_Yes"), + LocalizationService.Translate("Common_No")); if (!confirm) return; @@ -758,11 +855,54 @@ public partial class OptionsViewModel : ObservableObject var deleted = await _pdfExportService.ClearExportsAsync(); await Shell.Current.DisplayAlertAsync( - "Export entleeren", + LocalizationService.Translate("Options_Export_Clear"), deleted > 0 - ? $"{deleted} Export-Datei(en) wurden gelöscht." - : "Es waren keine Export-Dateien vorhanden.", - "OK"); + ? LocalizationService.Format("Options_Export_Clear_ResultDeletedFormat", deleted) + : LocalizationService.Translate("Options_Export_Clear_ResultEmpty"), + LocalizationService.Translate("Common_OK")); + } + + private static string GetAppearanceColorTitle(string key) => LocalizationService.Translate(key switch + { + AppearanceKeys.AppBackground => "Options_Appearance_Color_AppBackground", + AppearanceKeys.SurfaceBackground => "Options_Appearance_Color_SurfaceBackground", + AppearanceKeys.SurfaceBackgroundAlt => "Options_Appearance_Color_SurfaceBackgroundAlt", + AppearanceKeys.Border => "Options_Appearance_Color_Border", + AppearanceKeys.TextPrimary => "Options_Appearance_Color_TextPrimary", + AppearanceKeys.TextMuted => "Options_Appearance_Color_TextMuted", + AppearanceKeys.StateGreen => "Options_Appearance_Color_StateGreen", + AppearanceKeys.StateYellow => "Options_Appearance_Color_StateYellow", + AppearanceKeys.StateRed => "Options_Appearance_Color_StateRed", + AppearanceKeys.StateGray => "Options_Appearance_Color_StateGray", + AppearanceKeys.ButtonPrimaryBackground => "Options_Appearance_Color_ButtonPrimaryBackground", + AppearanceKeys.ButtonPrimaryText => "Options_Appearance_Color_ButtonPrimaryText", + AppearanceKeys.ButtonSecondaryBackground => "Options_Appearance_Color_ButtonSecondaryBackground", + AppearanceKeys.ButtonSecondaryText => "Options_Appearance_Color_ButtonSecondaryText", + AppearanceKeys.ShellBackground => "Options_Appearance_Color_ShellBackground", + AppearanceKeys.ShellForeground => "Options_Appearance_Color_ShellForeground", + AppearanceKeys.ShellTitle => "Options_Appearance_Color_ShellTitle", + AppearanceKeys.ShellUnselected => "Options_Appearance_Color_ShellUnselected", + AppearanceKeys.TabBarBackground => "Options_Appearance_Color_TabBarBackground", + AppearanceKeys.TabBarForeground => "Options_Appearance_Color_TabBarForeground", + AppearanceKeys.TabBarTitle => "Options_Appearance_Color_TabBarTitle", + AppearanceKeys.TabBarUnselected => "Options_Appearance_Color_TabBarUnselected", + _ => key + }); + + private static string GetAppearanceTextTitle(string key) => LocalizationService.Translate(key switch + { + AppearanceKeys.StatusGreenText => "Options_Appearance_Text_Green", + AppearanceKeys.StatusYellowText => "Options_Appearance_Text_Yellow", + AppearanceKeys.StatusRedText => "Options_Appearance_Text_Red", + AppearanceKeys.StatusGrayText => "Options_Appearance_Text_Gray", + _ => key + }); + + private static string FormatShortDate(DateTime date) + { + var culture = LocalizationService.GetCurrentCulture(); + var format = LocalizationService.Translate("Date_ShortNumericFormat"); + return date.ToString(format, culture); } private static string ToHex(Color color) diff --git a/ViewModels/QuickEntryViewModel.cs b/ViewModels/QuickEntryViewModel.cs index 9ece5ef..ebda137 100644 --- a/ViewModels/QuickEntryViewModel.cs +++ b/ViewModels/QuickEntryViewModel.cs @@ -41,16 +41,16 @@ public partial class QuickEntryViewModel : ObservableObject private bool isEditing; [ObservableProperty] - private string greenStatusText = "Grün"; + private string greenStatusText = "Green"; [ObservableProperty] - private string yellowStatusText = "Gelb"; + private string yellowStatusText = "Yellow"; [ObservableProperty] - private string redStatusText = "Rot"; + private string redStatusText = "Red"; [ObservableProperty] - private string grayStatusText = "Schwarz"; + private string grayStatusText = "Black"; [ObservableProperty] private Color greenStateColor = Color.FromArgb("#4E8B69"); @@ -81,7 +81,7 @@ public partial class QuickEntryViewModel : ObservableObject public ObservableCollection Parts { get; } = new(); public string ModeText => IsFutureDate - ? "Zukünftige Tage können nicht gespeichert werden." + ? LocalizationService.Translate("QuickEntry_FutureDateMessage") : string.Empty; public bool CanSave => !IsFutureDate; @@ -89,8 +89,8 @@ public partial class QuickEntryViewModel : ObservableObject public bool CanExplicitSave => IsEditing && SelectedState.HasValue && !IsFutureDate; public string SelectedStateSummaryText => SelectedState.HasValue - ? $"Gewählter Status: {GetStateText(SelectedState.Value)}" - : "Bitte Status wählen"; + ? LocalizationService.Format("QuickEntry_SelectedStatusFormat", GetStateText(SelectedState.Value)) + : LocalizationService.Translate("QuickEntry_SelectStatusPrompt"); public IAsyncRelayCommand SaveGreenCommand { get; } public IAsyncRelayCommand SaveYellowCommand { get; } @@ -214,11 +214,11 @@ public partial class QuickEntryViewModel : ObservableObject Activities.Add(new ActivityPickerItemViewModel { Id = null, - Name = "Keine Tätigkeit" + Name = LocalizationService.Translate("Activity_None") }); var items = await _activityRepository.GetActiveAsync(); - foreach (var item in items.Where(x => !string.Equals(x.Name, "Keine Tätigkeit", StringComparison.OrdinalIgnoreCase))) + foreach (var item in items.Where(x => !LocalizationService.IsNoActivityLabel(x.Name))) { Activities.Add(new ActivityPickerItemViewModel { @@ -251,13 +251,13 @@ public partial class QuickEntryViewModel : ObservableObject Parts.Add(new DayPartOptionItemViewModel { Value = DayPart.Morning, - Name = "Vormittag" + Name = LocalizationService.Translate("Common_Morning") }); Parts.Add(new DayPartOptionItemViewModel { Value = DayPart.Afternoon, - Name = "Nachmittag" + Name = LocalizationService.Translate("Common_Afternoon") }); } @@ -366,10 +366,18 @@ public partial class QuickEntryViewModel : ObservableObject private void LoadAppearance() { - GreenStatusText = _appearanceService.GetText(AppearanceKeys.StatusGreenText, "Grün"); - YellowStatusText = _appearanceService.GetText(AppearanceKeys.StatusYellowText, "Gelb"); - RedStatusText = _appearanceService.GetText(AppearanceKeys.StatusRedText, "Rot"); - GrayStatusText = _appearanceService.GetText(AppearanceKeys.StatusGrayText, "Schwarz"); + GreenStatusText = _appearanceService.GetText( + AppearanceKeys.StatusGreenText, + LocalizationService.GetDefaultStatusText(AppearanceKeys.StatusGreenText)); + YellowStatusText = _appearanceService.GetText( + AppearanceKeys.StatusYellowText, + LocalizationService.GetDefaultStatusText(AppearanceKeys.StatusYellowText)); + RedStatusText = _appearanceService.GetText( + AppearanceKeys.StatusRedText, + LocalizationService.GetDefaultStatusText(AppearanceKeys.StatusRedText)); + GrayStatusText = _appearanceService.GetText( + AppearanceKeys.StatusGrayText, + LocalizationService.GetDefaultStatusText(AppearanceKeys.StatusGrayText)); GreenStateColor = _appearanceService.GetColor(AppearanceKeys.StateGreen, "#4E8B69"); YellowStateColor = _appearanceService.GetColor(AppearanceKeys.StateYellow, "#B89A42"); @@ -417,6 +425,7 @@ public partial class QuickEntryViewModel : ObservableObject case "gray": case "grey": + case "black": case "grau": case "schwarz": state = HealthState.Gray; @@ -441,4 +450,4 @@ public partial class QuickEntryViewModel : ObservableObject item.IsSelected = !item.IsSelected; } -} \ No newline at end of file +} diff --git a/ViewModels/SymptomManageItemViewModel.cs b/ViewModels/SymptomManageItemViewModel.cs index 2665ba4..9e1d13a 100644 --- a/ViewModels/SymptomManageItemViewModel.cs +++ b/ViewModels/SymptomManageItemViewModel.cs @@ -1,3 +1,4 @@ +using cfs_tracker.Services; using CommunityToolkit.Mvvm.ComponentModel; namespace cfs_tracker.ViewModels; @@ -15,6 +16,6 @@ public partial class SymptomManageItemViewModel : ObservableObject public bool IsUsed { get; init; } public string UsageHint => IsUsed - ? "Bereits verwendet – kann nur deaktiviert werden." - : "Kann gelöscht werden, solange unbenutzt."; + ? LocalizationService.Translate("Options_UsageHint_Used") + : LocalizationService.Translate("Options_UsageHint_Unused"); } diff --git a/ViewModels/WeekDaySummaryViewModel.cs b/ViewModels/WeekDaySummaryViewModel.cs index efd410b..f2ff4fd 100644 --- a/ViewModels/WeekDaySummaryViewModel.cs +++ b/ViewModels/WeekDaySummaryViewModel.cs @@ -1,3 +1,4 @@ +using cfs_tracker.Services; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; @@ -16,7 +17,11 @@ public partial class WeekDaySummaryViewModel : ObservableObject public bool HasDetails => !string.IsNullOrWhiteSpace(ActivitiesText) || !string.IsNullOrWhiteSpace(SymptomsText); public bool HasActivities => !string.IsNullOrWhiteSpace(ActivitiesText); public bool HasSymptoms => !string.IsNullOrWhiteSpace(SymptomsText); - public string DetailsButtonText => IsExpanded ? "Zusammenfassung ausblenden" : "Zusammenfassung anzeigen"; + public string DetailsButtonText => IsExpanded + ? LocalizationService.Translate("WeekPage_SummaryHide") + : LocalizationService.Translate("WeekPage_SummaryShow"); + public string ActivitiesSummaryText => LocalizationService.Format("WeekPage_ActivitiesFormat", ActivitiesText); + public string SymptomsSummaryText => LocalizationService.Format("WeekPage_SymptomsFormat", SymptomsText); [ObservableProperty] private bool isExpanded; diff --git a/ViewModels/WeekViewModel.cs b/ViewModels/WeekViewModel.cs index f8926a0..b6991d3 100644 --- a/ViewModels/WeekViewModel.cs +++ b/ViewModels/WeekViewModel.cs @@ -108,7 +108,10 @@ public partial class WeekViewModel : ObservableObject private void UpdateHeader() { WeekStart = DateHelper.StartOfWeekMonday(SelectedDate.Date); - HeaderText = $"Woche {WeekStart:dd.MM.yyyy} - {WeekStart.AddDays(6):dd.MM.yyyy}"; + HeaderText = LocalizationService.Format( + "WeekPage_HeaderFormat", + WeekStart.ToString(LocalizationService.Translate("Date_ShortNumericFormat"), LocalizationService.GetCurrentCulture()), + WeekStart.AddDays(6).ToString(LocalizationService.Translate("Date_ShortNumericFormat"), LocalizationService.GetCurrentCulture())); } private async Task OpenDayAsync(WeekDaySummaryViewModel? item) @@ -160,10 +163,10 @@ public partial class WeekViewModel : ObservableObject private string GetStateText(HealthState? state) => state switch { - HealthState.Green => _appearanceService.GetText(AppearanceKeys.StatusGreenText, "Grün"), - HealthState.Yellow => _appearanceService.GetText(AppearanceKeys.StatusYellowText, "Gelb"), - HealthState.Red => _appearanceService.GetText(AppearanceKeys.StatusRedText, "Rot"), - HealthState.Gray => _appearanceService.GetText(AppearanceKeys.StatusGrayText, "Schwarz"), + HealthState.Green => _appearanceService.GetText(AppearanceKeys.StatusGreenText, LocalizationService.GetDefaultStatusText(AppearanceKeys.StatusGreenText)), + HealthState.Yellow => _appearanceService.GetText(AppearanceKeys.StatusYellowText, LocalizationService.GetDefaultStatusText(AppearanceKeys.StatusYellowText)), + HealthState.Red => _appearanceService.GetText(AppearanceKeys.StatusRedText, LocalizationService.GetDefaultStatusText(AppearanceKeys.StatusRedText)), + HealthState.Gray => _appearanceService.GetText(AppearanceKeys.StatusGrayText, LocalizationService.GetDefaultStatusText(AppearanceKeys.StatusGrayText)), _ => "-" }; @@ -190,4 +193,4 @@ public partial class WeekViewModel : ObservableObject return HealthState.Green; } -} \ No newline at end of file +} diff --git a/ViewModels/YearViewModel.cs b/ViewModels/YearViewModel.cs index 0b75601..f9917d4 100644 --- a/ViewModels/YearViewModel.cs +++ b/ViewModels/YearViewModel.cs @@ -15,6 +15,7 @@ public partial class YearViewModel : ObservableObject private readonly AppearanceService _appearanceService; private readonly CalendarStateService _calendarStateService; private readonly IPdfExportService _pdfExportService; + private CancellationTokenSource? _refreshCancellationTokenSource; [ObservableProperty] private DateTime selectedDate; @@ -59,60 +60,44 @@ public partial class YearViewModel : ObservableObject public async Task RefreshAsync() { + var refreshCancellationTokenSource = BeginRefresh(); + var cancellationToken = refreshCancellationTokenSource.Token; + SelectedDate = _calendarStateService.SelectedDate.Date; UpdateHeader(); - var yearStart = new DateTime(SelectedDate.Year, 1, 1); - var yearEnd = yearStart.AddYears(1); - - var entries = await _healthEntryRepository.GetEntriesBetweenAsync(yearStart, yearEnd); - Months.Clear(); - - for (var monthNumber = 1; monthNumber <= 12; monthNumber++) + try { - var monthStart = new DateTime(SelectedDate.Year, monthNumber, 1); - var daysInMonth = DateTime.DaysInMonth(monthStart.Year, monthStart.Month); + var selectedYear = SelectedDate.Year; + var sections = CreateMonthSections(selectedYear); - var section = new MonthSectionViewModel + Months.Clear(); + foreach (var section in sections) + Months.Add(section); + + for (var monthNumber = 1; monthNumber <= sections.Count; monthNumber++) { - Title = monthStart.ToString("MMMM") - }; - - var leadingEmptyCells = GetMondayBasedColumnIndex(monthStart.DayOfWeek); - for (var i = 0; i < leadingEmptyCells; i++) - section.Cells.Add(CreatePlaceholderCell()); - - for (var day = 1; day <= daysInMonth; day++) - { - var date = new DateTime(monthStart.Year, monthStart.Month, day); - var dayEntries = entries.Where(x => x.EntryDate.Date == date.Date).ToList(); - var worstState = CalculateWorstState(dayEntries); - - section.Cells.Add(new MonthCellViewModel - { - Date = date, - DayNumberText = date.Day.ToString(), - IsCurrentMonth = true, - IsToday = date.Date == DateTime.Today, - HasEntries = dayEntries.Count > 0, - BackgroundColor = GetCellBackgroundColor(worstState), - TextColor = GetCellTextColor(worstState), - BorderColor = date.Date == DateTime.Today - ? _appearanceService.GetColor(AppearanceKeys.StateYellow, "#B89A42") - : _appearanceService.GetColor(AppearanceKeys.Border, "#2A3E55") - }); + cancellationToken.ThrowIfCancellationRequested(); + await LoadMonthSectionAsync( + sections[monthNumber - 1], + selectedYear, + monthNumber, + cancellationToken); } - - while (section.Cells.Count % 7 != 0) - section.Cells.Add(CreatePlaceholderCell()); - - Months.Add(section); + } + catch (OperationCanceledException) + { + // Ein neueres Refresh hat diese Aktualisierung ersetzt. + } + finally + { + EndRefresh(refreshCancellationTokenSource); } } private void UpdateHeader() { - HeaderText = SelectedDate.Year.ToString(); + HeaderText = DateHelper.ToGermanYear(SelectedDate); } private async Task OpenDayAsync(MonthCellViewModel? item) @@ -157,11 +142,108 @@ public partial class YearViewModel : ObservableObject { MainThread.BeginInvokeOnMainThread(async () => { + if (SelectedDate.Date == date.Date) + return; + SelectedDate = date.Date; await RefreshAsync(); }); } + private CancellationTokenSource BeginRefresh() + { + var refreshCancellationTokenSource = new CancellationTokenSource(); + var previousRefresh = Interlocked.Exchange(ref _refreshCancellationTokenSource, refreshCancellationTokenSource); + + previousRefresh?.Cancel(); + previousRefresh?.Dispose(); + + return refreshCancellationTokenSource; + } + + private void EndRefresh(CancellationTokenSource refreshCancellationTokenSource) + { + if (ReferenceEquals(_refreshCancellationTokenSource, refreshCancellationTokenSource)) + _refreshCancellationTokenSource = null; + + refreshCancellationTokenSource.Dispose(); + } + + private List CreateMonthSections(int year) + { + return Enumerable.Range(1, 12) + .Select(monthNumber => new MonthSectionViewModel + { + Title = new DateTime(year, monthNumber, 1).ToString("MMMM", LocalizationService.GetCurrentCulture()), + IsLoading = true + }) + .ToList(); + } + + private async Task LoadMonthSectionAsync( + MonthSectionViewModel section, + int year, + int monthNumber, + CancellationToken cancellationToken) + { + var monthStart = new DateTime(year, monthNumber, 1); + var monthEnd = monthStart.AddMonths(1); + var entries = await _healthEntryRepository.GetEntriesBetweenAsync(monthStart, monthEnd); + + cancellationToken.ThrowIfCancellationRequested(); + + var cells = BuildMonthCells(monthStart, entries); + + await MainThread.InvokeOnMainThreadAsync(() => + { + if (cancellationToken.IsCancellationRequested) + return; + + section.ReplaceCells(cells); + }); + } + + private List BuildMonthCells(DateTime monthStart, IReadOnlyList entries) + { + var cells = new List(); + var daysInMonth = DateTime.DaysInMonth(monthStart.Year, monthStart.Month); + var entriesByDay = entries + .GroupBy(x => x.EntryDate.Date) + .ToDictionary(group => group.Key, group => (IReadOnlyCollection)group.ToList()); + + var leadingEmptyCells = GetMondayBasedColumnIndex(monthStart.DayOfWeek); + for (var i = 0; i < leadingEmptyCells; i++) + cells.Add(CreatePlaceholderCell()); + + for (var day = 1; day <= daysInMonth; day++) + { + var date = new DateTime(monthStart.Year, monthStart.Month, day); + var dayEntries = entriesByDay.TryGetValue(date.Date, out var matches) + ? matches + : Array.Empty(); + var worstState = CalculateWorstState(dayEntries); + + cells.Add(new MonthCellViewModel + { + Date = date, + DayNumberText = date.Day.ToString(), + IsCurrentMonth = true, + IsToday = date.Date == DateTime.Today, + HasEntries = dayEntries.Count > 0, + BackgroundColor = GetCellBackgroundColor(worstState), + TextColor = GetCellTextColor(worstState), + BorderColor = date.Date == DateTime.Today + ? _appearanceService.GetColor(AppearanceKeys.StateYellow, "#B89A42") + : _appearanceService.GetColor(AppearanceKeys.Border, "#2A3E55") + }); + } + + while (cells.Count % 7 != 0) + cells.Add(CreatePlaceholderCell()); + + return cells; + } + private Color GetCellBackgroundColor(HealthState? state) => state switch { HealthState.Green => _appearanceService.GetColor(AppearanceKeys.StateGreen, "#4E8B69"), @@ -216,4 +298,4 @@ public partial class YearViewModel : ObservableObject BorderColor = Colors.Transparent }; } -} \ No newline at end of file +} diff --git a/Views/DayPage.xaml b/Views/DayPage.xaml index f7c15cb..3494f17 100644 --- a/Views/DayPage.xaml +++ b/Views/DayPage.xaml @@ -3,9 +3,10 @@ x:Name="RootPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" + xmlns:loc="clr-namespace:cfs_tracker.Helpers" xmlns:viewModels="clr-namespace:cfs_tracker.ViewModels" x:DataType="viewModels:DayViewModel" - Title="Tag" + Title="{loc:Translate Tab_Day}" BackgroundColor="{DynamicResource AppBackground}"> @@ -30,11 +31,11 @@ - - - - - - - -