From 56a687169e339fad2e4385f23f5418c2edf12557 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Thu, 26 Nov 2026 15:20:08 +0100 Subject: [PATCH] Release v2.25.0 (#545) --- .forgejo/workflows/ci.yaml | 2 +- .gitea/actions/android-env/action.yml | 2 +- .gitignore | 1 + CHANGELOG.md | 1828 ++++------------- app/build.gradle.kts | 6 +- .../calendar/CalendarRepositorySmokeTest.kt | 1 + app/src/main/AndroidManifest.xml | 61 +- .../jeanlucmakiola/calendula/CalendulaApp.kt | 15 +- .../jeanlucmakiola/calendula/MainActivity.kt | 92 +- .../calendula/data/backup/AutoBackup.kt | 432 +++- .../calendula/data/backup/BackupChangeJob.kt | 87 + .../calendula/data/backup/SettingsBackup.kt | 265 +++ .../data/backup/SettingsBackupEngine.kt | 239 +++ .../data/backup/SettingsBackupSchema.kt | 135 ++ .../calendula/data/backup/SettingsImport.kt | 234 +++ .../data/calendar/AllDayReminderEncoding.kt | 12 + .../data/calendar/CalendarDataSource.kt | 272 ++- .../data/calendar/CalendarRepository.kt | 61 +- .../data/calendar/CalendarRepositoryImpl.kt | 254 ++- .../data/calendar/EventWriteMapper.kt | 38 +- .../data/calendar/IcsExportMapper.kt | 70 +- .../calendula/data/calendar/Projections.kt | 29 +- .../data/calendar/ReminderQueries.kt | 36 + .../calendula/data/calendar/SyncRequester.kt | 215 ++ .../calendula/data/di/DataModule.kt | 8 + .../calendula/data/ics/IcsExporter.kt | 43 +- .../calendula/data/prefs/CalendarPrefs.kt | 59 +- .../data/prefs/ReminderStatePrefs.kt | 27 +- .../calendula/data/prefs/SettingsPrefs.kt | 555 ++++- .../data/reminders/DailyDigestNotifier.kt | 155 ++ .../data/reminders/FullScreenAlerts.kt | 85 + .../data/reminders/ReminderActionReceiver.kt | 31 +- .../data/reminders/ReminderChannelPlan.kt | 211 ++ .../data/reminders/ReminderChannels.kt | 416 ++++ .../data/reminders/ReminderInstanceSource.kt | 32 +- .../data/reminders/ReminderNotifier.kt | 236 ++- .../data/reminders/ReminderRingService.kt | 354 ++++ .../data/reminders/ReminderScanner.kt | 104 +- .../data/reminders/ReminderTimeText.kt | 3 +- .../calendula/domain/EventForm.kt | 45 +- .../calendula/domain/InsertEventForm.kt | 9 +- .../jeanlucmakiola/calendula/domain/Models.kt | 4 + .../calendula/domain/NewEventCalendar.kt | 76 + .../calendula/domain/backup/BackupPlan.kt | 426 ++++ .../calendula/domain/ics/CalendarCopy.kt | 74 + .../calendula/domain/ics/CalendarRows.kt | 99 + .../calendula/domain/ics/IcsEvent.kt | 18 + .../calendula/domain/ics/IcsParser.kt | 29 +- .../calendula/domain/ics/IcsWriter.kt | 20 +- .../calendula/domain/ics/ParsedIcsForm.kt | 2 +- .../calendula/domain/reminders/DailyDigest.kt | 87 + .../domain/reminders/FixedTimeReminder.kt | 142 ++ .../domain/reminders/ReminderAlertStyle.kt | 43 + .../domain/reminders/ReminderMapQuery.kt | 18 + .../calendula/ui/CalendarHost.kt | 131 +- .../calendula/ui/ExternalRequests.kt | 15 +- .../calendula/ui/WidgetNavRequest.kt | 59 +- .../calendula/ui/agenda/AgendaRange.kt | 3 +- .../calendula/ui/agenda/AgendaRows.kt | 3 +- .../calendula/ui/agenda/AgendaViewModel.kt | 7 +- .../calendula/ui/calendars/BackupScreen.kt | 301 ++- .../calendula/ui/calendars/BackupUiState.kt | 42 +- .../calendula/ui/calendars/CalendarsScreen.kt | 162 +- .../ui/calendars/CalendarsViewModel.kt | 176 +- .../ui/calendars/CopyEventsScreen.kt | 386 ++++ .../ui/calendars/CopyEventsViewModel.kt | 150 ++ .../ui/calendars/SettingsBackupSection.kt | 224 ++ .../ui/calendars/SettingsBackupViewModel.kt | 108 + .../calendula/ui/common/AccountGroups.kt | 17 +- .../calendula/ui/common/CalendarDrawer.kt | 73 +- .../ui/common/CalendarPickerGroups.kt | 100 +- .../calendula/ui/common/CalendarTitle.kt | 3 +- .../calendula/ui/common/CalendarView.kt | 6 +- .../ui/common/EventActionsViewModel.kt | 5 +- .../calendula/ui/common/EventMoveHost.kt | 14 +- .../ui/common/FixedTimeReminderUi.kt | 220 ++ .../calendula/ui/common/Picker.kt | 111 +- .../calendula/ui/common/ReminderFormatting.kt | 48 +- .../ui/common/RescheduleViewModel.kt | 6 + .../calendula/ui/common/ResultSummary.kt | 135 ++ .../calendula/ui/common/SelectionTopBar.kt | 3 +- .../calendula/ui/common/SyncAccessPicker.kt | 153 ++ .../calendula/ui/common/SyncViewModel.kt | 107 + .../ui/common/ViewHiddenCalendars.kt | 63 + .../calendula/ui/detail/EventDetailScreen.kt | 20 +- .../calendula/ui/detail/EventDetailUiState.kt | 5 + .../ui/detail/EventDetailViewModel.kt | 18 +- .../calendula/ui/edit/EventEditScreen.kt | 119 +- .../calendula/ui/edit/EventEditUiState.kt | 2 +- .../calendula/ui/edit/EventEditViewModel.kt | 219 +- .../calendula/ui/filter/CalendarFilterList.kt | 126 +- .../calendula/ui/filter/FilterUiState.kt | 19 +- .../calendula/ui/filter/FilterViewModel.kt | 42 +- .../calendula/ui/filter/GroupVisibility.kt | 20 + .../ui/filter/ViewCalendarsPicker.kt | 67 + .../calendula/ui/imports/ImportScreen.kt | 201 +- .../calendula/ui/month/MonthScreen.kt | 4 +- .../calendula/ui/month/MonthViewModel.kt | 9 +- .../calendula/ui/onboarding/CalendarsStep.kt | 2 +- .../ui/onboarding/OnboardingViewModel.kt | 10 +- .../ui/reminders/ReminderAlertActivity.kt | 181 ++ .../ui/reminders/ReminderAlertScreen.kt | 195 ++ .../ui/reminders/ReminderAlertUiState.kt | 16 + .../calendula/ui/search/SearchScreen.kt | 2 + .../ui/settings/CalendarReminderSettings.kt | 486 +++++ .../ui/settings/EventFormSettings.kt | 67 + .../ui/settings/NotificationSettings.kt | 540 +++-- .../calendula/ui/settings/SettingsCommon.kt | 3 - .../calendula/ui/settings/SettingsScreen.kt | 20 +- .../calendula/ui/settings/SettingsUiState.kt | 32 +- .../ui/settings/SettingsViewModel.kt | 360 +++- .../ui/settings/SpecialDatesSettings.kt | 2 +- .../calendula/ui/settings/ViewsSettings.kt | 3 +- .../calendula/ui/settings/WeekStartPicker.kt | 3 +- .../calendula/ui/week/WeekScreen.kt | 3 +- .../calendula/ui/week/WeekViewModel.kt | 11 +- .../calendula/widget/WidgetConfig.kt | 4 - .../calendula/widget/WidgetData.kt | 1 + .../calendula/widget/WidgetParts.kt | 5 +- .../calendula/widget/agenda/AgendaWidget.kt | 9 +- .../widget/config/CountdownOptionsSection.kt | 3 +- .../widget/countdown/CountdownData.kt | 2 +- .../widget/countdown/CountdownWidget.kt | 7 +- .../calendula/widget/date/DateWidget.kt | 4 +- .../calendula/widget/month/MonthGridViews.kt | 3 +- .../calendula/widget/split/MonthDayWidget.kt | 5 +- .../calendula/widget/today/TodayWidget.kt | 5 +- .../widget/upcoming/UpcomingWidget.kt | 7 +- .../calendula/widget/week/WeekStripWidget.kt | 6 +- .../res/drawable/ic_notification_link.xml | 12 + .../main/res/drawable/ic_notification_map.xml | 12 + app/src/main/res/values/strings.xml | 208 +- app/src/main/res/xml/locales_config.xml | 1 + .../calendula/TestRepositories.kt | 58 +- .../data/backup/ChangeRunPolicyTest.kt | 30 + .../data/backup/SettingsBackupSchemaTest.kt | 45 + .../data/backup/SettingsBackupTest.kt | 441 ++++ .../calendar/AllDayReminderEncodingTest.kt | 20 +- .../calendar/CalendarRepositoryImplTest.kt | 149 +- .../data/calendar/EventWriteMapperTest.kt | 69 + .../data/calendar/FakeCalendarDataSource.kt | 29 +- .../data/calendar/IcsExportMapperTest.kt | 35 + .../data/calendar/ImportedEventValuesTest.kt | 18 + .../calendula/data/calendar/SyncNudgeTest.kt | 314 +++ .../calendula/data/prefs/CalendarPrefsTest.kt | 25 + .../calendula/data/prefs/SettingsPrefsTest.kt | 318 +++ .../data/reminders/ReminderChannelPlanTest.kt | 208 ++ .../calendula/domain/EventFormTest.kt | 11 +- .../domain/FixedTimeReminderFormTest.kt | 47 + .../calendula/domain/InsertEventFormTest.kt | 9 +- .../calendula/domain/NewEventCalendarTest.kt | 102 + .../calendula/domain/backup/BackupPlanTest.kt | 451 ++++ .../calendula/domain/ics/CalendarRowsTest.kt | 287 +++ .../domain/reminders/DailyDigestTest.kt | 89 + .../domain/reminders/FixedTimeReminderTest.kt | 100 + .../reminders/ReminderAlertStyleTest.kt | 38 + .../domain/reminders/ReminderMapQueryTest.kt | 51 + .../calendula/ui/WidgetNavRequestTest.kt | 48 + .../ui/calendars/BackupUiStateTest.kt | 66 +- .../ui/common/ReminderPresetsTest.kt | 67 + .../ui/common/RescheduleViewModelTest.kt | 5 +- .../calendula/ui/common/SyncViewModelTest.kt | 209 ++ .../calendula/ui/common/ViewBackStackTest.kt | 18 +- .../ui/common/ViewHiddenCalendarsTest.kt | 100 + .../ui/detail/EventDetailViewModelTest.kt | 5 +- .../ui/edit/EventEditViewModelTest.kt | 294 +++ .../calendula/ui/filter/FilterUiStateTest.kt | 31 + .../ui/filter/GroupVisibilityTest.kt | 49 + docs/ARCHITECTURE.md | 273 ++- docs/PRIVACY.md | 6 +- docs/RELEASING.md | 15 +- docs/SETTINGS_BACKUP.md | 148 ++ .../android/ar/changelogs/2250099.txt | 12 + .../android/be/changelogs/2250099.txt | 10 + .../android/cs-CZ/changelogs/2250099.txt | 10 + .../android/de-DE/changelogs/2250099.txt | 12 + .../android/en-US/changelogs/2250099.txt | 12 + .../android/es-ES/changelogs/2250099.txt | 10 + .../android/fr-FR/changelogs/2250099.txt | 10 + .../android/gl-ES/changelogs/2250099.txt | 10 + .../android/hu-HU/changelogs/2250099.txt | 10 + .../android/it-IT/changelogs/2250099.txt | 10 + .../android/iw-IL/changelogs/2250099.txt | 12 + .../android/ja-JP/changelogs/2250099.txt | 12 + .../android/nl-NL/changelogs/2250099.txt | 10 + .../android/pl-PL/changelogs/2250099.txt | 10 + .../android/pt-BR/changelogs/2250099.txt | 10 + .../android/pt-PT/changelogs/2250099.txt | 10 + .../android/ru-RU/changelogs/2250099.txt | 10 + .../android/sk/changelogs/2250099.txt | 10 + .../android/zh-CN/changelogs/2250099.txt | 12 + .../android/zh-TW/changelogs/2250099.txt | 12 + floret-kit | 2 +- scripts/release_notes.sh | 5 +- 194 files changed, 15612 insertions(+), 2617 deletions(-) create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/data/backup/BackupChangeJob.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/data/backup/SettingsBackup.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/data/backup/SettingsBackupEngine.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/data/backup/SettingsBackupSchema.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/data/backup/SettingsImport.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/ReminderQueries.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/DailyDigestNotifier.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlan.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/domain/NewEventCalendar.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/domain/backup/BackupPlan.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/domain/reminders/DailyDigest.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/domain/reminders/FixedTimeReminder.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderAlertStyle.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderMapQuery.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsScreen.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/SettingsBackupSection.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/SettingsBackupViewModel.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/ui/common/FixedTimeReminderUi.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/ui/common/ResultSummary.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/ui/common/ViewHiddenCalendars.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/GroupVisibility.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/ViewCalendarsPicker.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertActivity.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertScreen.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertUiState.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/CalendarReminderSettings.kt create mode 100644 app/src/main/res/drawable/ic_notification_link.xml create mode 100644 app/src/main/res/drawable/ic_notification_map.xml create mode 100644 app/src/test/java/de/jeanlucmakiola/calendula/data/backup/ChangeRunPolicyTest.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/calendula/data/backup/SettingsBackupSchemaTest.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/calendula/data/backup/SettingsBackupTest.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlanTest.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/calendula/domain/FixedTimeReminderFormTest.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/calendula/domain/NewEventCalendarTest.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/calendula/domain/backup/BackupPlanTest.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/calendula/domain/reminders/DailyDigestTest.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/calendula/domain/reminders/FixedTimeReminderTest.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderAlertStyleTest.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderMapQueryTest.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/calendula/ui/WidgetNavRequestTest.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/calendula/ui/common/ReminderPresetsTest.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/calendula/ui/common/ViewHiddenCalendarsTest.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/calendula/ui/filter/FilterUiStateTest.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/calendula/ui/filter/GroupVisibilityTest.kt create mode 100644 docs/SETTINGS_BACKUP.md create mode 100644 fastlane/metadata/android/ar/changelogs/2250099.txt create mode 100644 fastlane/metadata/android/be/changelogs/2250099.txt create mode 100644 fastlane/metadata/android/cs-CZ/changelogs/2250099.txt create mode 100644 fastlane/metadata/android/de-DE/changelogs/2250099.txt create mode 100644 fastlane/metadata/android/en-US/changelogs/2250099.txt create mode 100644 fastlane/metadata/android/es-ES/changelogs/2250099.txt create mode 100644 fastlane/metadata/android/fr-FR/changelogs/2250099.txt create mode 100644 fastlane/metadata/android/gl-ES/changelogs/2250099.txt create mode 100644 fastlane/metadata/android/hu-HU/changelogs/2250099.txt create mode 100644 fastlane/metadata/android/it-IT/changelogs/2250099.txt create mode 100644 fastlane/metadata/android/iw-IL/changelogs/2250099.txt create mode 100644 fastlane/metadata/android/ja-JP/changelogs/2250099.txt create mode 100644 fastlane/metadata/android/nl-NL/changelogs/2250099.txt create mode 100644 fastlane/metadata/android/pl-PL/changelogs/2250099.txt create mode 100644 fastlane/metadata/android/pt-BR/changelogs/2250099.txt create mode 100644 fastlane/metadata/android/pt-PT/changelogs/2250099.txt create mode 100644 fastlane/metadata/android/ru-RU/changelogs/2250099.txt create mode 100644 fastlane/metadata/android/sk/changelogs/2250099.txt create mode 100644 fastlane/metadata/android/zh-CN/changelogs/2250099.txt create mode 100644 fastlane/metadata/android/zh-TW/changelogs/2250099.txt diff --git a/.forgejo/workflows/ci.yaml b/.forgejo/workflows/ci.yaml index 0abfa276..dcdbdac0 100644 --- a/.forgejo/workflows/ci.yaml +++ b/.forgejo/workflows/ci.yaml @@ -120,7 +120,7 @@ jobs: - name: Setup Java if: steps.scope.outputs.code == 'true' - uses: actions/setup-java@v4 + uses: actions/setup-java@v5 with: distribution: 'zulu' java-version: '17' diff --git a/.gitea/actions/android-env/action.yml b/.gitea/actions/android-env/action.yml index c37e5aa1..fe7a674a 100644 --- a/.gitea/actions/android-env/action.yml +++ b/.gitea/actions/android-env/action.yml @@ -4,7 +4,7 @@ runs: using: composite steps: - name: Setup Java - uses: actions/setup-java@v4 + uses: actions/setup-java@v5 with: distribution: 'zulu' java-version: '17' diff --git a/.gitignore b/.gitignore index 06a7a2d0..c25ec7d9 100644 --- a/.gitignore +++ b/.gitignore @@ -74,3 +74,4 @@ Gemfile.lock # Claude Code /CLAUDE.md +.kotlin/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 70dd4456..42abdc2a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,1816 +7,760 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [2.25.0] — 2026-11-26 + +### Added +- Notifications per calendar: own switch, sound and channel ([#145], [#272], [#340]) +- Pick the reminder sound in the app, including Silent ([#518]) +- Full-screen reminders, optionally ringing like an alarm ([#171]) +- Reminders at a set time, e.g. "1 day before at 20:00" ([#459]) +- Daily summary notification of today's or tomorrow's events ([#459]) +- More reminder presets: 2–5 days and 2–3 weeks before ([#365]) +- Open link / Open in maps buttons on reminders ([#464]) +- Hide calendars in chosen views only ([#270], [#517]) +- Show or hide a whole account from the drawer ([#143]) +- Default calendar for new events ([#429]) +- Sync now from the drawer; synced edits reach the server sooner ([#240], [#303]) +- Copy events between calendars ([#325]) +- Back up synced calendars, one file each; backup after changes ([#147], [#411], [#516]) +- Back up and restore settings ([#481]) +- Hebrew, started on Weblate; most screens are still in English + +### Changed +- Back from a widget returns to the home screen ([#530]) +- All-day reminders show the day they fire on ([#514]) + +### Fixed +- Editing one occurrence no longer wipes the rest of some imported series ([#502]) +- `.ics` backups keep extra dates (RDATE) of repeating events ([#515]) +- Month and day names start with a capital letter in every language ([#543]) + ## [2.24.3] — 2026-11-20 ### Added -- **Galician**, a new community translation through [Calendula's Weblate](https://weblate.dev.jeanlucmakiola.de/projects/calendula/), complete from the start. Pick it under Settings → Language. Thanks to Jani Buni. +- Galician translation ### Changed -- Arabic, Italian and Spanish are now fully translated, with further updates to Belarusian, German and Slovak. Thanks to everyone translating on Weblate. +- Translation updates ## [2.24.2] — 2026-11-13 ### Fixed -- **Quick moves no longer get lost.** Dropping an event while an earlier move was still saving used to snap it back without a word. Drops now wait in line and are saved in order, and a moved event stays where you dropped it until the calendar shows it there. If an event changed before a drop could be saved, or the line is full, a message says so instead ([#494]). -- **Undo after a run of moves** keeps the first move's Undo, and each failed move gets its own message rather than replacing the last one ([#494]). +- Quick successive event moves are saved in order instead of snapping back ([#494]) +- Undo survives a run of moves, and each failed move gets its own message ([#494]) ### Changed -- **The day view's title names the month**, like the week and 3-day views. Weekday and date already sit in the column header below it ([#501]). -- Library updates (kotlinx-datetime, AppCompat). +- Day view title shows the month, like the week and 3-day views ([#501]) +- Library updates (kotlinx-datetime, AppCompat) ## [2.24.1] — 2026-11-12 ### Added -- **A classic style for the agenda widget.** Its settings now have a Style option: Cards keeps the new look, Classic brings back the 2.23 layout with a line per day and a colour stripe beside each event, under the current header. Dates in another year show the year. Classic has an Invert text colour switch, so its text stays readable on light and dark wallpapers ([#489]). -- **Widget opacity.** Every widget with a Solid or Tinted background has an Opacity slider from 20 to 100%. Below 50%, the card-style widgets back their content like a Transparent widget so it stays readable ([#489]). +- Classic style for the agenda widget, with an invert text colour switch ([#489]) +- Opacity slider for widgets with a Solid or Tinted background ([#489]) ### Fixed -- **Week numbers match your region.** With weeks starting on Sunday, the month and week views showed every week number one too low. Rows are now numbered by your region's rules, so ISO regions such as Germany are unchanged ([#493]). -- **The month widget shows events at every height.** At some sizes a week row had room for a little more than the date but not a full line of events, and drew none. It now fits a slimmer line there, and a row with a single line shows "+N" on days with more events than fit ([#491]). -- **Dimmed past events in dark widgets are readable again.** They used to turn pastel with white text on top ([#475]). -- **A widget set to Light or Dark matches the system colours.** With Material You, the + button and today's date could look different from a widget that follows the app ([#475]). +- Week numbers follow your region's rules, fixing Sunday-start weeks ([#493]) +- Month widget shows events at every height, with "+N" when more don't fit ([#491]) +- Dimmed past events in dark widgets are readable again ([#475]) +- Light or Dark widgets match the system colours with Material You ([#475]) ### Changed -- **Fewer permissions.** Calendula no longer asks for network state, wake lock or foreground service access, which a library added without the app needing them ([#448]). -- Translation updates from [Calendula's Weblate](https://weblate.dev.jeanlucmakiola.de/projects/calendula/). +- Fewer permissions: no network state, wake lock or foreground service ([#448]) +- Translation updates ## [2.24.0] — 2026-11-06 ### Added -- **Six new home-screen widgets.** Quick add (1×1) opens a new event on today with the same defaults as the app's + button ([#435]). Date (1×1) shows today's weekday and day number on a rounded shape and opens today ([#376]). Week strip (4×1) shows this week's days with a dot in each event's colour and today filled ([#436]). Upcoming (2×2) shows today's date over your next events, as many as fit ([#437]). Today lists today's events; once they're over it says "Nothing left today" and shows tomorrow's first one or two ([#438]). Countdown counts down to your next timed event, or to an event or series you pick, like a holiday in 12 days ([#439]). -- **A month and day widget.** A compact month grid sits beside the events of one day. Tap a day in the grid to see its events, and tap the list to open that day in the app ([#441]). -- **Each widget has its own settings.** Placing a widget, or long-pressing it and choosing Edit, opens a settings screen with a live preview. Pick a solid, tinted or transparent background, a light or dark theme or the app's, and which calendars it shows. Widgets that list events also have their time range, text size and how past events look. Settings → Widgets lists the widgets on your home screen so you can change them from there. These options used to be shared by all widgets; widgets you already placed keep what you had set ([#292]). -- **Turn off start times in the month view.** Settings → Views → Month → Start times hides the time in front of event titles, so narrow fonts keep more of the title. With it on, the time now only shows when the whole title, or at least its first 12 characters, still fits beside it ([#476]). -- **Drag all-day events.** In the day, 3-day and week views, long-press an event in the all-day strip and move it sideways to another day, or down into the grid to turn it into a timed event ([#296]). -- **Traditional Chinese**, started as a community translation through [Calendula's Weblate](https://weblate.dev.jeanlucmakiola.de/projects/calendula/). It covers only a few screens so far, so the rest still shows in English until it fills out. Pick it under Settings → Language. Thanks to AventineC. +- Quick add (1×1) widget ([#435]) +- Date (1×1) widget ([#376]) +- Week strip (4×1) widget ([#436]) +- Upcoming (2×2) widget ([#437]) +- Today widget, showing tomorrow's first events once today's are over ([#438]) +- Countdown widget to your next event or a picked event or series ([#439]) +- Month and day widget: a compact month grid beside one day's events ([#441]) +- Per-widget settings with live preview: background, theme, calendars and more ([#292]) +- Option to hide start times in the month view ([#476]) +- Drag all-day events to another day, or into the grid to make them timed ([#296]) +- Traditional Chinese translation (partial) ### Changed -- **The agenda and month widgets have a new look.** The agenda puts each day in its own card, with a round date pill beside the first event and today's pill filled. The month widget has rounded day cells, weekday pills, shaded days outside the month and a + for a new event. The agenda's refresh button is gone, since widgets now update on their own ([#71], [#90]). -- **Tapping a day in the month widget opens that day,** wherever in its cell you tap ([#386]). -- **The widget picker shows what each widget looks like.** On Android 15 and later the previews are the real widgets with sample events, in your language and colours; on older versions they are redrawn to match. -- **Widgets are listed by their name alone,** without "Calendula" in front, and each has a short description in the picker ([#71]). -- **Past events in widgets stay readable when dimmed.** Their background fades further and their text less ([#90]). -- **Events from midnight to midnight show as all-day events.** A timed event that starts and ends at midnight now sits in the all-day strip, shows as "All day" in the agenda and widgets, and its reminder names the day instead of 00:00 – 00:00. The event itself stays as it was saved ([#296]). -- **Cancelled and tentative events are marked.** Cancelled events are struck through and listed last, like declined invites, and tentative ones get the outline used for unanswered invites. Cancelled one-off events and series no longer disappear ([#388]). -- **One notification per event.** An event with several reminders now keeps a single notification, which each later reminder updates in place ([#463]). -- **Go further back and forward in time.** Every view and the date picker now reach from 1600 to 2399 ([#457]). -- **The split month agenda only lists days with events.** In other months it no longer starts with an empty 1st, and a month with nothing in it says so in one row ([#142]). +- New look for the agenda and month widgets; agenda refresh button removed ([#71], [#90]) +- Tapping a day in the month widget opens that day ([#386]) +- Widget picker shows real previews of each widget +- Widgets are listed by name alone, with a short description ([#71]) +- Dimmed past events in widgets stay readable ([#90]) +- Midnight-to-midnight events show as all-day ([#296]) +- Cancelled and tentative events are marked; cancelled ones no longer disappear ([#388]) +- One notification per event, updated by each later reminder ([#463]) +- Views and date picker reach from 1600 to 2399 ([#457]) +- Split month agenda only lists days with events ([#142]) ### Fixed -- **Widgets show your changes straight away.** After you added, edited or deleted an event, a widget could keep showing the old events until something else redrew it ([#420], [#229]). -- **Widgets follow the app's language.** After you picked a language in Settings, widgets kept the old one until something redrew them ([#90]). -- **The month widget handles busy months.** It could show "Can't show content", or only one or two events per day. Each day now shows as many events as its height fits, and the rest fold into +N ([#372]). -- **Short events late in the day are fully visible.** An event like 23:58–23:59 used to be cut down to a sliver at the bottom of the day, week and 3-day views. It now keeps its usual minimum height and sits flush against midnight ([#483]). -- **The month view no longer crashes after going before 1900** in the day or week view ([#457]). -- **Month pages keep updating.** After a small swipe that snapped back, a month page could stop showing new or edited events, and opening an event from the split view could show its old times ([#440], [#454]). -- **Smoother expand and collapse in the split month view.** The day cells morph cleanly between the two layouts, and week numbers now animate along with them ([#473]). -- **Back clears the selected day in the split month view.** With a day picked, the back gesture used to close the app; it now goes back to the whole month's agenda first ([#142]). +- Widgets update right after adding, editing or deleting events ([#420], [#229]) +- Widgets follow the app's language ([#90]) +- Month widget handles busy months, folding extras into +N ([#372]) +- Short late-evening events are fully visible in timeline views ([#483]) +- Month view no longer crashes after browsing before 1900 ([#457]) +- Month pages keep updating after a snapped-back swipe ([#440], [#454]) +- Smoother expand and collapse in the split month view ([#473]) +- Back clears the selected day in the split month view before closing the app ([#142]) ## [2.23.1] — 2026-10-28 ### Changed -- **The split month view fits more events.** With a day selected, its date is no longer shown twice: the filter chip now stands in for the day's header. Tapping the chip opens the day, and its ✕ clears the filter. The day headers in the month agenda below the grid take less room too ([#142]). +- Split month view fits more events; the filter chip replaces the day header ([#142]) ### Fixed -- **Event dots in the split month grid stay in place on busy days.** A day with a "+N" next to its dots used to push them further down the cell ([#142]). +- Event dots in the split month grid stay in place on busy days ([#142]) ## [2.23.0] — 2026-10-21 ### Added -- **Long press an event to select it.** In the day, 3-day and week views, a long press lifts the event and selects it. Keep your finger down and move to drag it straight away. A selected event has handles at its top and bottom: drag them to change when it starts or ends, in 15-minute steps and across midnight if you want. The bar at the top edits, duplicates, shares or deletes it, and tapping elsewhere or going back deselects it. The bar shows the new times while you move or resize. Read-only events can be selected but not moved or resized ([#141]). -- **Long press an empty slot to draft an event.** In the day, 3-day and week views, a long press on free time drops a block of your default event length there. Move it while still holding, or let go and drag it or its handles into place, then tap the tick to open a new event at that time. The ✕, a tap elsewhere or going back throws the draft away ([#153]). -- **Tap a phone number in an event to call it.** Phone numbers in an event's title, location and description are now links. Tapping one opens your phone app with the number filled in, ready to call. A conference dial-in like "+1 646 558 8656,,850123#" brings its meeting ID along. Meeting IDs and PINs on their own, dates, times and amounts stay plain text. Long-pressing a field copies it, even when you press on a link ([#339]). -- **Formatted event descriptions read properly.** Descriptions from Outlook, Exchange and Google Calendar are often stored as HTML, which used to show up as a wall of tags. The event view now shows them as formatted text: bold, italics, lists and links work, table rows sit on one line each, and the fonts and colours the sender picked are left out so the text matches the app. Search matches the text you see. The edit form still shows the original, so saving an event never changes its formatting ([#271]). -- **Scroll back to earlier days in the agenda.** Scroll up past today to see earlier days' events, loaded a month at a time. Past days follow the past-events setting: Dim fades them, and with Hide the agenda still starts at today ([#367]). -- **Create an event from shared or selected text.** Share text to Calendula, or select text in another app and pick Create event from the selection menu, and the new-event form opens with it filled in. A shared subject becomes the title, otherwise the first line does, and the rest goes into the description. The event starts at the next full hour with your default length; Calendula doesn't try to read a date out of the text. If Calendula was opened just for this, saving or closing the form takes you back to the app you came from ([#306]). -- **Tapping an event can open the edit form.** Settings → Views → Events → Tapping an event opens can now be set to Edit form instead of Details. Taps in the views and in search then go straight to the editor for events you can edit; read-only events, reminder notifications and widgets still open the details. The editor has Duplicate, Share and Delete in its menu, and going back with unsaved changes asks whether to save, discard or keep editing ([#178]). -- **A black theme for AMOLED screens.** Settings → Appearance → Theme now has Black next to System, Light and Dark. It's the dark theme with pure black backgrounds, which saves battery on AMOLED screens and makes event colours stand out more. Day cells and the hour grid stay a shade above black so the grid lines still show, and sheets and menus still stand out from the page. It works with Material You colours too. The home-screen widgets aren't affected ([#181]). -- **Donate through Liberapay.** Settings → Support development now offers Liberapay for recurring donations next to Ko-fi for one-off tips. -- **More haptic feedback.** Swiping between days in the split month pane ticks, and dropping a moved or resized event gives a short buzz ([#116]). +- Long-press an event to select, move or resize it ([#141]) +- Long-press an empty slot to draft a new event ([#153]) +- Tap a phone number in an event to call it ([#339]) +- HTML event descriptions show as formatted text ([#271]) +- Scroll back to earlier days in the agenda ([#367]) +- Create an event from shared or selected text ([#306]) +- Option to open the edit form when tapping an event ([#178]) +- Black theme for AMOLED screens ([#181]) +- Donate through Liberapay +- More haptic feedback ([#116]) ### Changed -- **The editor says Create for a new event.** New events, duplicates, shared text, imported .ics files and long-press drafts show Create instead of Save, so a duplicate no longer looks like you're editing the original ([#141]). +- The editor says Create for new events ([#141]) ### Fixed -- **Event colours follow the theme you picked in Calendula.** With the app set to Dark on a phone in light mode, or the other way round, events took their colours from the phone's setting, so they could come out too pale or too dark. They now match the app's theme. Starting the app with a theme set in Calendula also no longer flashes the phone's light or dark background first ([#181]). -- **Events on the day the clocks change show at their real time.** In the day, 3-day and week views, events later on the day of a daylight saving change were drawn an hour off, so a 14:45 event showed at 15:45. They now sit at their own time. When the clocks go back, 02:00 to 03:00 happens twice: an event in that hour now stays in the right one when you move, resize or edit it, and the editor and event details add the zone, like CEST or CET, so you can tell the two apart ([#387]). -- **The agenda always starts today.** Coming from the month or day view, the agenda used to start at the day you had open there, so "Next 30 days" could show the 1st to the 30th of the month. It now opens on today with your chosen range. Backing out of a day you opened from the agenda still returns you to where you were ([#367]). -- **Multi-day events dim on the days already behind you.** With past events dimmed, an event running over several days stayed at full strength on its earlier days until it ended. Those days now dim in the agenda, month, week and day views ([#367]). -- **Moving a recurring event to another calendar keeps the occurrences you changed.** Deleted occurrences used to come back after the move, and edited ones showed up twice. They now stay deleted or edited, and keep their colour. -- **Sharing an .ics file to Calendula opens the import,** even when the email app adds a subject line as text. -- **Rotating the phone no longer throws away an open import, duplicate or picker.** -- **The repeat-until date picker opens on today.** Near midnight it used to open on yesterday or tomorrow. -- **Tap ripples on week numbers, split-view day cells and the split-view handle stay inside their rounded shape** ([#413]). -- **The export calendar picker previews the back gesture** like the other full-screen pickers. +- Event colours follow the app's theme instead of the phone's ([#181]) +- Events on daylight saving change days show at their real time ([#387]) +- The agenda always opens on today ([#367]) +- Multi-day events dim on days already past ([#367]) +- Moving a recurring event to another calendar keeps its changed occurrences +- Sharing an .ics file opens the import even with a subject line attached +- Rotating no longer discards an open import, duplicate or picker +- Repeat-until date picker opens on today +- Tap ripples stay inside their rounded shapes ([#413]) +- Export calendar picker previews the back gesture ## [2.22.5] — 2026-10-07 ### Fixed -- **Reopening the app the next morning shows the right day.** The month view used to mark yesterday as today and keep the day you picked the evening before selected, so you had to tap today to see its events. Every view now moves on to the new day at midnight and when you come back to the app. A view you browsed to another date stays where it is ([#373]). +- Views move on to the new day at midnight and when you return to the app ([#373]) ## [2.22.4] — 2026-10-07 ### Fixed -- **Edits and deletions show up straight away on every phone.** On some phones, Samsung among them, an edited, moved or deleted event stayed where it was until the app was restarted, so a second edit could act on an event that had already changed. Calendula now refreshes its views itself after every change, and again when you come back to the app ([#364]). -- **The home-screen widgets do less work per update.** The month widget loads the months around the one it shows instead of more than two years of events, and the agenda widget only its chosen range. This should help widgets that stayed on "loading" on slower phones ([#363]). +- Edits and deletions show up straight away on every phone ([#364]) +- Widgets do less work per update, helping ones stuck on loading ([#363]) ## [2.22.3] — 2026-10-02 ### Fixed -- **The store listing is called "Calendula: Calendar" again,** with "Calendar" in each store language. Since 2.22.0 the Play listing comes from the repository, whose title was only "Calendula". The app is unchanged ([#361]). +- Store listing is called "Calendula: Calendar" again ([#361]) ## [2.22.2] — 2026-10-02 ### Fixed -- **2.22 reaches Google Play.** The Dutch store listing used the locale code `nl`, which Play rejects, so the Play uploads of 2.22.0 and 2.22.1 failed. It now uses `nl-NL`, and CI checks every store locale against the codes Play accepts. The app is unchanged from 2.22.1 ([#359]). +- 2.22 reaches Google Play again after a Dutch locale code fix ([#359]) ## [2.22.1] — 2026-10-02 ### Fixed -- **Tapping a link in an event's location opens it in the browser instead of a maps app.** Links are underlined, as in the description, and tapping the rest of the location still opens maps. A link with a capitalised `Https://`, or wrapped in `<…>` the way Outlook and Teams write them, opens correctly too. When no app can open a link, a short message says so instead of the tap doing nothing ([#357]). +- Links in an event's location open in the browser instead of maps ([#357]) ## [2.22.0] — 2026-10-01 ### Added -- **Day, Week, and Month all page with a swipeable pager that follows your finger** instead of cutting between dates ([#131], [#336]). -- **Pages can open the split agenda.** Swipe up from a full month to reveal the compact grid and month agenda; tap a day to filter it, then swipe down to return. The transition gives haptic feedback ([#111]). -- **A multi-day view shows a configurable number of days side by side,** with today in the first column. Set the day count in Settings ([#193]). -- **A "Visible hours" setting fits a chosen range of hours to the screen** when Day, Week, or the new multi-day view opens; earlier and later hours stay a scroll away ([#322]). -- **Timeline views mark events that run outside the visible hours** with a coloured edge at the top or bottom, and keep them tappable underneath it ([#188]). -- **Week numbers open their week.** Tap a week number in the month grid to open Week at that row; Back returns to Month ([#197]). +- Day, Week and Month page with a swipeable pager ([#131], [#336]) +- Swipe up from a full month to open the split agenda ([#111]) +- Multi-day view with a configurable number of days ([#193]) +- "Visible hours" setting fits a chosen hour range to the screen ([#322]) +- Timeline views mark events running outside the visible hours ([#188]) +- Tap a week number to open that week ([#197]) ### Changed -- **Day, multi-day, and Week share one timeline and morph into each other** when you switch views, instead of each view rebuilding its own ([#184]). -- **The back gesture previews the view you're returning to** and springs back to the current one if you cancel the gesture ([#185]). -- **Split view opens with the month's agenda.** It starts at today in the current month; tapping a day filters the list, and the filter chip restores the full month. Swiping the list moves by day when filtered and by month otherwise ([#142]). -- **Today stands out in the month grid.** Its whole cell has a distinct background; tapping Today briefly expands that cell and nudges its neighbours aside ([#241]). -- **All-day reminders due today or tomorrow say so** instead of spelling out the date ([#308]). -- **Store listing in every app language.** Google Play and F-Droid show the description in all 16 languages the app ships, and each release publishes the Play listing from the repository ([#285]). +- Day, multi-day and Week views morph into each other ([#184]) +- The back gesture previews the view you're returning to ([#185]) +- Split view opens with the month's agenda ([#142]) +- Today stands out in the month grid ([#241]) +- All-day reminders due today or tomorrow say so ([#308]) +- Store listing in every app language ([#285]) ### Fixed -- **Titles and locations stop growing at 255 characters.** Some CalDAV servers (Open-Xchange among them) silently truncate longer values on sync; Calendula now caps them first and shows a counter once you're close ([#331]). -- **The "Calendar" launcher alias is translatable.** The "App name" setting's alternate label was hard-coded to English regardless of the app's language ([#251]). -- **Multi-day events stay above shorter events.** Month and Week bars, Split day lists, and Agenda now place multi-day events before one-day all-day events, then timed events; declined events remain last ([#291]). -- **Editing one occurrence of a coloured Google series saves again.** Saving with "Only this event" kept you on the edit screen without saving anything ([#338]). +- Titles and locations are capped at 255 characters, with a counter ([#331]) +- The "Calendar" launcher alias is translatable ([#251]) +- Multi-day events sort above shorter events ([#291]) +- Editing one occurrence of a coloured Google series saves again ([#338]) ## [2.21.0] — 2026-09-23 ### Added -- **Setup makes sure you have a calendar to write to.** A fresh install could - finish onboarding and land on an empty grid with nothing saying why — either - because the device had no calendar at all, or because every calendar it had - was switched off. Setup now covers both: it offers to create a calendar on - this device or to add an account that syncs one, and it lists the calendars - that exist but are switched off so you can turn them back on ([#287]). +- Setup makes sure you have a calendar to write to ([#287]) ### Changed -- **The month grid gives its days more room.** Week numbers are set smaller and - their gutter is measured from the widest number it has to seat instead of - holding a fixed 40dp; event chips spend less of their width on padding; and - the labels in both are tracked more tightly, which is worth roughly a - character per chip ([#189], [#190], [#212], [#213]). -- **A month day shows as many events as it has height for.** The limit was a - flat three at every size, so a tall week row threw away space it could have - filled, while a cramped one drew a third chip its band could not hold and put - the "more" marker below the clip, where nothing showed the day held more at - all. It is measured per week row now, and a tablet or a landscape phone seats - more of them. -- **Split view no longer pads a short month out to six rows.** A five-row month - was handing the day pane a blank row and its gap — a sixth of the grid. The - grid now draws only the rows its month spans and the pane grows into the rest - ([#162]). +- The month grid gives its days more room ([#189], [#190], [#212], [#213]) +- A month day shows as many events as fit its height +- Split view no longer pads short months to six rows ([#162]) ### Fixed -- **Short events show their title in week and day view.** A block needed 20dp - of height before it drew any title at all, which at fit-the-whole-day put the - cutoff around the half hour. The padding now tapers as the block shrinks, so - a short event keeps its name ([#289]). -- **A fully zoomed-out timeline sits still.** Rounding its height up left it as - much as a pixel per hour taller than the viewport those hours are meant to - fill — some 24px of leftover scroll, enough to bounce off Android's - overscroll stretch ([#290]). -- **Backup & restore says what is going on instead of coming up blank.** It - built its rows straight from the calendar list, so loading, a provider error, - and a device with nothing to export all rendered as an empty page with no - buttons on it ([#304]). -- **An event with no title reads in your language.** It was labelled "(Ohne - Titel)" on every screen but the event's own, whatever language the phone was - set to: the German text was chosen before the translated one could be - ([#321]). -- **A calendar the system gives no name reads in your language.** The same - cause, in the calendar lists and pickers — and because the calendar editor - starts from that name, saving such a calendar wrote the German text into it - for real ([#329]). +- Short events show their title in week and day view ([#289]) +- A fully zoomed-out timeline no longer bounces ([#290]) +- Backup & restore shows loading, error and empty states instead of a blank page ([#304]) +- Untitled events read in your language ([#321]) +- Unnamed calendars read in your language ([#329]) ## [2.20.4] — 2026-09-20 ### Fixed -- **The app no longer reopens the event you last came in on.** Opening an event - from a reminder or a home-screen widget made the app return to that same - event on every later launch — and show an error screen once the event had - been deleted. Android hands an app the launch it was started with again each - time it is rebuilt, and Calendula was acting on it every time instead of - once ([#309]). -- **"Today" works in the agenda again.** Scrolling a few days ahead and tapping - today did nothing, because the agenda is browsed by scrolling rather than by - moving its date, and the button only moved the date. It now brings the list - back to today, and it stays offered while the list is scrolled away — before, - it was hidden in exactly the situation it is for ([#305]). -- **Calendula is filed under "Calendar & Agenda" in the self-hosted repo.** - Browsing by category in an F-Droid client set to prefer that repo listed the - app under "Time" instead ([#294]). +- The app no longer reopens the event you last launched it from ([#309]) +- "Today" works in the agenda again ([#305]) +- Listed under "Calendar & Agenda" in the self-hosted F-Droid repo ([#294]) ## [2.20.3] — 2026-09-12 ### Fixed -- **A custom agenda range crashed the app in French.** Choosing a custom range - for the agenda — or simply typing a number into that field — closed the app on - any phone set to French. The French translation of the "%d days" label was - missing the wording French uses for counts of two and above, and Android has - nothing to fall back on when that particular form is absent, so every value - except one day was affected ([#297], [#298]). +- A custom agenda range no longer crashes the app in French ([#297], [#298]) ## [2.20.2] — 2026-09-12 ### Fixed -- **Crash reports are filed in English.** Reporting a crash from a phone set to - another language prefilled the issue — title and body — in that language, so - a French crash arrived on Codeberg as a French issue ([#297], [#298]). The - text that is *posted* is now English for everyone; the dialog that asks you - to send it, and everything else you see in the app, is still translated. +- Crash reports are filed in English ([#297], [#298]) ## [2.20.1] — 2026-09-07 ### Fixed -- **An empty calendar now explains itself.** "No calendars configured" offered - an "Open system calendar settings" button that opened nothing — every screen - wired it to the same reload that had just produced the empty state. It now - opens the system's account chooser, filtered to the providers that sync - calendars ([#239]). -- **Calendars that are all switched off no longer look like an empty month.** - When every calendar on the device is hidden at system level there is nothing - to draw, but the app said nothing at all: it only ever checked whether the - device had *no* calendars, so a device that had them and hid them fell - through to a blank grid with no hint. That case now says so, and points at - Settings → Calendars — the one screen that can switch a calendar back on. The - navigation drawer's calendar list drew the same conflation and is fixed with - it ([#239]). +- The "no calendars" button now opens the system account chooser ([#239]) +- With every calendar switched off, the app says so instead of an empty month ([#239]) ## [2.20.0] — 2026-09-07 ### Added -- **Long-press to copy.** Holding down the title, the location or the - description on an event puts that whole field on the clipboard. Tapping still - does what it always did — the location opens maps, a link in the description - opens — and the times, calendar, repeat rule and guests stay uncopyable. Below - Android 13 a short confirmation appears; from Android 13 on the system shows - its own clipboard chip ([#195]). -- **The open-source projects Calendula ships** are now listed under Settings → - About, each with its copyright holder and licence, and each row tapping - through to that project's source ([#281]). +- Long-press an event's title, location or description to copy it ([#195]) +- Open-source licences listed under Settings → About ([#281]) ### Changed -- Event titles no longer end in an ellipsis. The "…" took the width of a couple - of characters and told you nothing you couldn't already see, so the title now - simply runs to the edge of its chip in the month, week and day views — a few - more letters per event, which is often the difference between two events you - can tell apart and two you can't. Right-to-left languages keep the ellipsis, - where clipping would cut the beginning of a title rather than its end - ([#164]). -- Month-view events now show their start time before the title, where the chip - is wide enough to keep the title readable — in landscape, on a foldable and on - a tablet, and never at the cost of a narrow phone column. All-day events show - no time, and neither does a bar carried in from the previous week, whose start - is not in that row. Event times across the month, week and day views are also - set in a regular weight against the title's, so a time reads as a time rather - than as part of the name next to it ([#219]). -- **The hour lines in week and day view are now an hour grid.** The setting - that drew a faint separator line at each hour now seats every hour in its own - rounded cell, so an hour boundary reads as the seam between two surfaces - rather than a line drawn across one — the same negative space that separates - the month grid's days and the week's columns. An event that starts on the hour - fills its cell instead of overhanging the seam, and one that runs past - midnight still meets the edge of its column ([#113]). -- **An invitation you haven't answered now reads as an outline.** An event still - waiting on your reply is drawn with the calendar's colour on its border and - its title and nothing behind it, so it stands apart from the ones you have - accepted — on the month chips, the all-day bars and the week and day blocks - alike. Declined events keep their filled, struck-through chip and now sort - last in the month view as well, so a day with more events than fit drops the - ones you said no to first ([#230]). -- The calendar titles now shorten instead of being cut off. When the full month - name doesn't fit the top bar, the month and week views fall back to its - three-letter form and the day view drops the weekday, rather than trailing off - mid-word at large font sizes. The view switcher, the title and the agenda's - range bar also line up with the grid underneath them ([#165]). -- The jump-to-today button in the toolbar now shows today's date. It drew a - generic calendar icon, which told you nothing you didn't already know from - tapping it; it now carries the current day number in an outlined box, so the - bar says what day it is as well as taking you there. It rolls over at midnight - on its own ([#220]). -- The quick-switch pill disappears when there is nothing left to switch between, - and you can now turn calendar views off all the way down to a single one — the - setting used to hold two open purely to keep the pill fed ([#150]). +- Event titles no longer end in an ellipsis ([#164]) +- Month-view events show their start time where there's room ([#219]) +- Hour lines in week and day view are now an hour grid ([#113]) +- Unanswered invitations show as an outline ([#230]) +- Calendar titles shorten instead of being cut off ([#165]) +- The today button shows today's date ([#220]) +- The quick-switch pill hides with one view; views can go down to one ([#150]) ### Fixed -- **A long location no longer runs off the edge of its field.** The location on - the edit screen sat on one line, so a full postal address or a long meeting - link scrolled sideways out of sight as you typed it. It now wraps and the card - grows to fit, with the pin and the contacts button staying level with the first - line at any font size. A multi-line address you paste in is joined with commas - — the way one picked from your contacts always has been — instead of running - together into a single word ([#273]). -- **The event form capitalizes sentences again.** The title, description and - guest fields had stopped starting a sentence with a capital letter; they - follow the keyboard's usual behaviour once more. The location is deliberately - left alone, since it is as often a URL as an address ([#146]). -- **A block you pick up no longer loses its second line.** Dragging an event - whose time or title wrapped to two lines clipped the floating copy to one line - for as long as you held it, and it snapped back on drop. The copy now measures - its text exactly as the block does ([#267]). +- Long locations wrap in the event editor ([#273]) +- The event form capitalises sentences again ([#146]) +- Dragged events keep their second line ([#267]) ## [2.19.4] — 2026-09-01 ### Fixed -- **A deleted occurrence no longer comes back when the series is re-timed.** - Delete a single occurrence of a repeating event, then change the time of the - whole series, and the occurrence you had removed reappeared. Doing it the - other way round — "This and all following events" — lost every removal in the - part of the series being changed. Removals now travel with the event: they - keep their place in the series across a time change, a move to a different - day, a timezone change and a switch to or from an all-day event, and they - carry over when a series is split. Repeating events on your device's own - calendars are affected, including the birthday and anniversary calendars - Calendula creates from your contacts ([#248]). -- **Home-screen widgets now turn the page at midnight.** Both the month and the - agenda widget kept highlighting yesterday as "today" — and the agenda kept - greying out the wrong events as already past — until you paged the month back - and forth or removed and re-added the widget. Calendula now wakes itself at the - day boundary and redraws, and re-arms after a reboot, a clock change or a - flight into another timezone. Paging the month widget forward and back also - stops quietly pinning it to that month, so it follows the date again instead of - being stranded on the month you happened to be looking at ([#228]). -- **"Only this event" now actually saves your edit.** On some calendars — - including Google ones that still show as on-device, and any local calendar — - editing a single occurrence of a repeating event did nothing at all: the scope - dialog closed, the edit screen stayed put, and saving again just repeated it. - Android can only attach a single-occurrence change to its series once the - calendar has been synced at least once, so on those calendars the change had - nowhere to go. Calendula now removes that one occurrence from the series and - saves the edit as its own event instead, which is what you see either way. A - save that does fail also says so for longer, rather than flashing past - ([#234]). -- **A failed import no longer costs you the whole file.** One event the calendar - refuses used to abort the entire import with nothing on screen but "couldn't - read this file". Events are now added one at a time: anything rejected is - counted and shown, and the rest still arrive. A faulty repeat rule in the file - is repaired instead of being handed on ([#225]). -- **All-day reminders survive a backup and an import.** They fire at the hour you - chose, not at midnight UTC — the same rule the app already applied to all-day - events you create yourself — and an export no longer leaves them out of the - file entirely. An imported yearly birthday fires at the right hour too, even - though the file dates it back to the year of birth ([#225]). -- **Birthdays and anniversaries imported from Fossify Calendar now show up.** - Fossify writes the ones it mirrors from your contacts as events that start and - end on the same day, which the calendar read as lasting no time at all: they - imported without complaint and then appeared nowhere. Any all-day event that - ends where it starts, or carries no end at all, is now a one-day event - ([#225]). -- **A backup no longer brings back occurrences you had deleted.** Remove a single - occurrence of a repeating event, back up, restore — and it was there again, - because the removals never made it into the file. They travel with the series - now, so a restored calendar looks the way you left it ([#225]). -- **A reminder left on your account's default no longer went off as the event - started.** An event whose reminder says "Default" is the account's to time, not - Calendula's — it was reading that setting as a lead time of its own and firing a - minute after the event began. It now leaves such a reminder alone, and says so - on the event. -- **"Only this event" on an event that doesn't repeat now edits or deletes it.** - Deleting used to write an exclusion onto a one-off event instead — which left - the event there and lost its end time — and editing filed the change away as an - exception to nothing, so it vanished. -- **An import that the calendar cuts short now tells you how far it got.** Losing - the calendar or the permission part way through a big file reported the whole - import as failed, so importing again added everything twice. -- **An event that runs past midnight can be dragged by either half.** Its second - half couldn't be picked up at all, and the first could only be moved later. Both - halves now move, and both are previewed while you hold either one, so the event - reads as moving rather than growing. The blocks are cut square at midnight - instead of rounded off, a month row draws an event crossing into the next week - as one bar, and a move across a daylight-saving change no longer lands an hour - out ([#253]). +- Deleted occurrences stay deleted when a repeating series is re-timed or split ([#248]) +- Widgets switch to the new day at midnight and follow the date again after paging ([#228]) +- "Only this event" saves edits on local and never-synced calendars ([#234]) +- Import keeps going past rejected events and reports how many were skipped ([#225]) +- All-day reminders keep their hour through backup and import ([#225]) +- Birthdays and anniversaries imported from Fossify Calendar now show up ([#225]) +- Restoring a backup no longer brings back deleted occurrences ([#225]) +- Reminders left on the account default no longer fire as the event starts +- "Only this event" on a non-repeating event now edits or deletes it +- An import cut short by the calendar reports how far it got +- Events crossing midnight can be dragged by either half ([#253]) ### Added -- **More of an imported `.ics` survives the trip**: tasks come across as events - rather than being dropped in silence, deleted occurrences of a repeating event - stay deleted, a calendar named like the one the file came from is preselected, - and event colours are carried over — matched to the closest colour your - calendar's account offers, so a migrated calendar still reads at a glance - ([#225]). -- **Belarusian, Hungarian and Slovak**, all three contributed as community - translations through - [Calendula's Weblate](https://weblate.dev.jeanlucmakiola.de/projects/calendula/). - Belarusian covers about nine tenths of the app, Slovak about a third and - Hungarian is just under way, so untranslated parts still show in English until - they fill out. Pick any of them under Settings → Language or in Android's - per-app language settings. Thanks to Dmitri Gabinski (Belarusian), Ábel Nagy - (Hungarian) and Julie (Slovak); help finishing them is very welcome. +- Imported `.ics` files keep tasks, deleted occurrences, colours and calendar choice ([#225]) +- Belarusian, Hungarian and Slovak translations ### Changed -- **Arabic, Polish and Simplified Chinese are now complete**, all three carried - the rest of the way this cycle — Simplified Chinese from a fifth of the app to - all of it. Czech and Russian grew too — Russian to about half — and still have - room. Thanks to Sup99999 (Arabic), Bazyli Cyran (Polish), JeanWenzel - (Simplified Chinese), James Trivette (Czech), and SpiritOTHawk and Artur - (Russian). +- Arabic, Polish and Simplified Chinese translations complete; Czech and Russian grew ## [2.19.3] — 2026-08-22 ### Added -- **Czech, Japanese and Russian**, all three contributed as community - translations through - [Calendula's Weblate](https://weblate.dev.jeanlucmakiola.de/projects/calendula/). - They are early — Czech covers about a third of the app, Russian a fifth, - Japanese has just started — so untranslated parts still show in English until - they fill out. Pick any of them under Settings → Language or in Android's - per-app language settings. Thanks to James Trivette (Czech), ame0011 - (Japanese), and chip and Pablo (Russian); help finishing them is very welcome. +- Czech, Japanese and Russian translations ### Changed -- **Brazilian Portuguese is now complete**, covering the whole app. Thanks to - bkrz for carrying it the rest of the way. +- Brazilian Portuguese translation complete ## [2.19.2] — 2026-08-17 ### Changed -- **A meeting you declined is now struck through** wherever it appears — month, - week, day, agenda, search and both widgets — and no longer schedules a - reminder. Declining an invitation in Google Calendar left the event looking - like any other in Calendula, and it still notified you about a meeting you had - said no to. It stays visible rather than disappearing: the organiser still - expects an answer from you, and the slot is still spoken for ([#180]). +- Declined meetings are struck through and no longer remind you ([#180]) ### Fixed -- **Tapping an event in month view opens the event**, not the day it sits on. - Every month style is affected — page, rolling, seamless weeks — and until now - the only way to reach an event from the month was to open its day first and - find it again there. Tapping anywhere else in the cell still opens the day - ([#187]). -- **An edit made to an event now shows the moment you re-open it.** Adding a - description to an event and opening it again showed the sheet as it was before - the save, because the detail was only re-read when a different occurrence was - opened ([#196]). -- **The month widget's arrows stopped working after a couple of taps.** The grid - was serialised as roughly 740 views, and one update ran to half a megabyte — - more than the launcher's buffer takes. The third update overran it, and Android - responded by dropping the whole widget host, which killed updates for *every* - widget on the home screen, ours and other apps', until the launcher rebound. - The grid now draws 192 views, and a resized widget reflows to its new size - instead of clipping ([#214]). -- Tapping a widget's refresh or month arrows redraws that widget by its own id - instead of asking Android to update all of them, which does nothing in a - process the tap has just woken from cold ([#18]). -- **Jump-to-today in seamless weeks lands on the current week** instead of - leaving a sliver of the previous row on screen ([#191]). -- Day and week view no longer run their events flush against the right edge - ([#192]). +- Tapping an event in month view opens the event, not its day ([#187]) +- Edits show immediately when re-opening an event ([#196]) +- Month widget arrows keep working and the widget reflows on resize ([#214]) +- Widget refresh and month arrows work when the app was not running ([#18]) +- Jump-to-today in seamless weeks lands on the current week ([#191]) +- Day and week view events no longer run flush against the right edge ([#192]) ## [2.19.1] — 2026-08-11 ### Added -- **Drag to reschedule can be turned off.** Settings → Views → *Drag to - reschedule*, on by default. Off, no event can be picked up in the month, week - or day view — for anyone who kept moving appointments by accident while - scrolling ([#173]). -- An early Brazilian Portuguese translation. Calendula has started speaking - Brazilian Portuguese, contributed as a community translation through - [Calendula's Weblate](https://weblate.dev.jeanlucmakiola.de/projects/calendula/). - About a third of the app is covered, so the rest still shows in English — you - can pick it under Settings → Language or in Android's per-app language - settings. Thanks to - [bkrz](https://weblate.dev.jeanlucmakiola.de/user/bkrz/) for getting it - started; help finishing it is very welcome. +- Setting to turn off drag to reschedule ([#173]) +- Early Brazilian Portuguese translation ### Fixed -- **The language picker forgot which language was picked.** Android hands the - applied language back with its script filled in — Simplified Chinese goes in - as `zh-CN` and comes out as `zh-Hans-CN` — so after a restart no entry in - Settings → Language showed as selected, and the row above it named the - language the long way round. Only languages that imply a script were - affected. +- Language picker remembers languages with an implied script, like Simplified Chinese ## [2.19.0] — 2026-08-10 ### Added -- **Drag an event to reschedule it.** Press and hold an event in the month, - week or day view and drop it on another time or day — the only way to move an - appointment used to be opening it and editing its start and end by hand. The - block follows your finger, the timeline scrolls when you carry it to an edge, - and the event's length is preserved: a 90-minute meeting dropped on 09:00 ends - at 10:30. In week and day view the drop snaps to 15-minute steps; in month - view it moves the event to the day you dropped it on and leaves the time - alone. A confirmation names the new slot and offers **Undo** wherever the move - can be taken back in one step. Events you can't edit — read-only calendars, and - birthdays and anniversaries mirrored from your contacts — can't be picked up. - Rescheduling isn't pointer-only: a screen reader gets a **Move…** action on - every event that can be moved ([#68]). -- Dragging a **recurring** event asks what it should apply to, the same *this - event / this and following / all events* choice a save does. Where moving the - whole series would change which weekday it falls on, the rule is rewritten to - match — a weekly Monday event dropped on a Wednesday becomes a weekly - Wednesday event. Where it can't be rewritten safely, the prompt says so and - offers to move just the one occurrence, rather than quietly leaving the - series behind ([#68]). -- **Delete several search results at once.** Long-press a hit in search to enter - selection mode, tap the rest (or **Select all**), and delete the lot in one - action — finding and removing, say, every leftover event with the same title - no longer means opening them one at a time. Recurring hits in the batch ask - once for the whole selection instead of once each, results on read-only - calendars can't be selected, and the deletion is confirmed before it runs - ([#80]). +- Drag an event to reschedule it in month, week and day view, with undo ([#68]) +- Dragging a recurring event asks which occurrences to move ([#68]) +- Delete several search results at once ([#80]) ### Changed -- **First launch is now a short wizard** instead of a single permission screen. - It counts its steps, each one can be stepped back out of, and beyond granting - calendar access it offers two things worth deciding once: turning on automatic - backup — chosen inline, folder picker and all, since events that live only on - the phone are lost with it — and choosing which view Calendula opens on, with - a live preview of the month, week, day and agenda layouts rather than four - names in a list. Both are skippable, everything chosen is changeable in - Settings afterwards, and the backup step is offered only where nothing - writable is being synced anywhere. Existing installs are not re-onboarded — - revoking and re-granting the calendar permission later does not restart the - wizard ([#163]). -- The one-time notice about calendars switched off for this device is now a step - in the flow rather than a dialog thrown over the app on first open. +- First launch is a short setup wizard with backup and start-view steps ([#163]) +- The notice about calendars switched off for this device is now a wizard step ### Fixed -- Removed the deprecated `statusBarColor` / `navigationBarColor` theme - attributes the Play Console flags on Android 15 and up, where they no longer - do anything. The launch backdrop now picks its status-bar icons from the - light/dark resource instead, so they stay legible over it either way - ([#123]). +- Removed deprecated system bar colour attributes flagged on Android 15+ ([#123]) ## [2.18.1] — 2026-08-06 ### Fixed -- Tapping an empty slot in week or day view creates the event at the hour you - tapped, after the timeline has been zoomed. Pinching the day taller or shorter - — or changing **Hour height** in Settings — left the tap still being measured - against the old spacing, so the new event landed at some other hour entirely - ([#148]). +- Tapping an empty slot after zooming creates the event at the tapped hour ([#148]) ## [2.18.0] — 2026-07-31 ### Added -- A new event no longer always lasts an hour. **Settings → New event form → - Default duration** sets how long one opens, and each calendar may keep its own - length underneath — 8 hours for the calendar you keep work shifts in, 30 - minutes for the one you book calls in. A calendar without its own length - follows the default, switching calendars mid-form re-stretches the event, and - setting an end time by hand keeps it. An event another app hands over with only - a start gets the default too; one that names its own end — an `.ics` file, a - duplicate — keeps that length. All-day events are unaffected ([#54]). -- Week and day view can be set to show more or less of the day at once, under - Settings → Views → Week & day → **Hour height**. **Fit whole day** sizes an - hour to your screen so all 24 hours are visible without scrolling — on a tall - phone the old fixed spacing showed only about half a day, so appointments - could sit below the fold all week. Compact and Comfortable are fixed steps - either side of the previous spacing, which stays the default. Both views share - the setting ([#56]). -- Week and day view can be **pinched** with two fingers to set the hour height - directly, anywhere between and beyond the named steps. The time under your - fingers stays put as it zooms, so you keep your place in the day. A pinched - height is remembered and appears as **Custom** in the Hour height setting, so - tapping a named step there takes you back to it ([#56]). +- Default event duration, globally and per calendar ([#54]) +- Hour height setting for week and day view, including Fit whole day ([#56]) +- Pinch to zoom the hour height in week and day view ([#56]) ### Changed -- The date in the top bar is now the way to jump: tapping the month, week or day - title opens the same date picker the sidebar's **Jump to date** offers, seeded - on whatever the bar is naming. A drop-down caret marks it as tappable. The - sidebar entry stays where it is ([#57]). -- A reminder in the status bar is now Calendula's own mark — the calendar with - the bloom — instead of the generic calendar glyph it shared with the system's - date surfaces and every other calendar app. The status bar draws that icon as - a plain silhouette, so its shape is the only thing that could tell them apart - ([#83]). -- Event blocks now only draw text they can draw whole. One too short for a full - line shows no title rather than a sliced one, a block that cannot fit both its - title and its time keeps the title, and a block too narrow to hold more than a - syllable stays on one ellipsised line instead of stacking letters down the - block. Tapping and the spoken description are unchanged ([#56]). -- Calendar colours are reworked so text on an event is always readable. They - were shaped by a brightness setting that does not match what the eye sees, so - whether a block got dark or light text depended on which hue you happened to - pick — an orange calendar took dark text while a red one beside it took light - — and colours landing in between were hard to read either way. Each colour now - keeps its hue and is moved clear of that middle: most become deep blocks with - light text, while naturally pale colours such as yellow stay pale and take - dark text, rather than being forced into a muddy brown. Dots, stripes and - icons are tuned separately from blocks, so they stay visible against the - background instead of sharing a colour meant to sit behind text. The setting - is now called **Harmonise calendar colours**; turning it off still shows the - raw colours from your calendar source ([#21], [#36]). +- Tap the top-bar date to jump to a date ([#57]) +- Reminder notifications use Calendula's own status-bar icon ([#83]) +- Event blocks only show text that fits whole ([#56]) +- Calendar colours reworked so event text is always readable ([#21], [#36]) ### Fixed -- The back gesture closes the sidebar instead of the app. With the drawer open, - swiping back left Calendula altogether rather than putting the sidebar away - ([#114]). -- The sidebar lines up. "Calendula", "View" and "Calendars" now share the left - edge of the rows under them, and the view, jump-to-date, Settings and calendar - rows sit on one vertical axis instead of each icon finding its own — the same - alignment the Settings screens use ([#114]). -- The status- and navigation-bar icons follow Calendula's own light/dark choice. - Setting the app dark while the system stayed light — or the other way round — - left the clock and battery drawn for the system's theme, so they could sit - near-invisible against the app's own bar ([#70]). +- Back gesture closes the sidebar instead of the app ([#114]) +- Sidebar headings and rows line up ([#114]) +- System bar icons follow the app's own light/dark setting ([#70]) ## [2.17.1] — 2026-07-30 ### Added -- Settings → Calendars now says what is different about a calendar instead of - leaving you to guess. Ones you can only view — a subscribed calendar, a - calendar shared with you read-only — are marked **Read-only** ([#76]). -- Calendars your device isn't syncing are marked **Not synced**, moved to the - bottom of their account and left without a switch. None of their events are on - the device, so the switch they used to have could not have shown you anything - — the calendar simply looked broken. They are no longer offered when you pick - a calendar for a new or an imported event either: an event saved there would - never reach the account. Whether an account syncs a calendar stays that - account's own app's decision ([#78]). -- The birthday and anniversary calendars Calendula fills from your contacts are - marked **Filled from your contacts**, which is why they can't be picked for a - new event: anything you put there would be removed again on the next sync. - Deleting one is held back while special dates are switched on — Calendula - would simply create it again — and the calendar's editor says so; turn the - feature off under Settings → Special dates and the delete works as usual - ([#76]). -- The calendar picker in the event form and in the .ics import screen now ends - with a **"Missing a calendar?"** row that opens Settings → Calendars, where - those marks then explain why a calendar isn't offered ([#76]). -- The agenda widget's text size is yours to set. **Settings → Widgets & tiles → - Agenda widget size** offers Small, Medium, Large and Extra large, replacing the guess - the widget used to make from its own measurements. Small is what it looks like - today, so nothing changes until you turn it up ([#51]). -- A repeating event now shows you its next few dates, not just a description of - the rule. Both the preset list and the custom recurrence picker carry a - **Next:** line — "Next: 30 Jul, 6 Aug, 13 Aug" — under the rule they would - save. A phrase like "monthly" on the 31st, or "every 2 weeks on Mon & Fri", - can mean something other than it sounds like, and only the dates say so. A - rule that can never fire says that instead ([#69]). -- The event visibility options now say who they affect. **Public**, **Private** - and **Confidential** each carry a line about what other people on a shared - calendar see — the part the four words on their own leave out ([#69]). +- Settings → Calendars marks read-only and contact-filled calendars ([#76]) +- Unsynced calendars are marked and no longer offered for new events ([#78]) +- "Missing a calendar?" row in calendar pickers ([#76]) +- Agenda widget text size setting ([#51]) +- Recurrence pickers show the next few dates ([#69]) +- Visibility options explain who they affect ([#69]) ### Changed -- **Settings has been reorganised so each setting sits where you would look for - it.** One long undifferentiated list is now three labelled groups — Look & - behaviour, Data, and App — whose rows open sub-screens and say what they do - rather than only naming themselves. Appearance, Views, New event form, - Notifications and the new Widgets & tiles are separate screens now, so the - settings for a calendar view are no longer mixed in with the ones for the - app's colours or for the home-screen widgets ([#69]). -- Settings that are hard to picture from their name now show you what they do. - The week-start picker rearranges a real month grid as you choose, the - past-events setting previews a sample agenda day for Show, Dim and Hide, the - font pickers set a specimen line in the face you are choosing, and the Agenda - range options carry the dates each one actually covers. Options that follow - the system additionally name which way they currently fall ([#69]). -- **Backup & restore** is now its own Settings entry instead of living inside - the calendar manager, where it was easy to miss — keeping a copy of your - calendars is a different question from which calendars you have. The calendar - manager keeps a row pointing to it, and nothing about how backup or automatic - backup works has changed ([#69]). -- Calendula's source code now lives on **Codeberg**, where its issues already - were. The **Source code** and **License** links in Settings → About point - there, so reporting a bug and reading the code no longer land on two different - sites. Nothing about the app itself changes, and the F-Droid repository is - unaffected. +- Settings reorganised into groups with sub-screens ([#69]) +- Settings show live previews of what they do ([#69]) +- Backup & restore is its own Settings entry ([#69]) +- Source code moved to Codeberg; About links updated ### Fixed -- A month-grid widget stays a month grid, and draws all seven days again. Since - 2.16.0 a placed month widget could redraw itself as the agenda widget a little - after any change to your events, and could draw only about four day columns - with the last one cut off part-way through. Both came from the release build - merging the two widgets into a single class, so Android could no longer tell - which of them a widget on your home screen was — and the month grid was handed - the wrong widget's measurements to lay its columns out against ([#89], [#103]). -- The back gesture on **Settings → Views** returns to Settings instead of - leaving Settings altogether and dropping you on the calendar. Special dates - did the same ([#81]). -- The dots standing in for the events that didn't fit a day in the month view - now dim with everything else when **Dim completed events** is on. A past day - with four or more events kept its last events at full strength while the rest - faded ([#79]). -- Two accounts that happen to share a name — a Google account and a DAVx5 - account for the same address, say — are no longer merged into one group. - They were listed together in Settings → Calendars and in the drawer's filter, - which also meant the group's source icon and its "manage in app" button could - send you to the wrong app, "toggle all" spanned both accounts at once, and - collapsing one collapsed the other. Where a name really is shared, each group - now names the app it comes from ([#77]). -- In the month view's **Split** style, the new-event button now starts on the - day you have selected. It always started on today, whichever day was selected - and listed below the grid ([#87]). -- Search results now show an all-day event's real date. West of UTC — anywhere in - the Americas, say — a search hit was dated one day early, disagreeing with the - day the month, week and agenda views file the same event under ([#82]). -- Reminders no longer depend on Android telling Calendula when they are due. - Calendula now works out each reminder's time itself and sets its own alarm for - it. On some phones — Samsung's among them — the system's calendar storage never - sends the signal a calendar app is meant to wake up on, and no amount of - battery or notification settings helps: the reminder is simply never announced. - None of that is visible from inside an app that waits to be told, which is why - it took a second pass to find ([#75]). - - Reminders also survive things that used to lose them quietly. After a restart - or an app update Calendula re-arms its alarms, and a reminder whose moment - passed while the phone was off still arrives, as long as the event has not - ended yet. - -- All-day reminders now arrive at the time you chose in **Settings → - Notifications**, on every occurrence. A yearly birthday could drift an hour - either way depending on daylight saving, and all-day reminders on calendars - from an account fired in the middle of the night instead of in the morning - ([#75]). - -- Reminders now arrive for every calendar you have switched on. A calendar that - was hidden at system level — switched off in another calendar app, or never - switched on after being added — still showed its events and listed their - reminders in Calendula, but never notified: Android only schedules reminder - alarms for calendars marked visible, and Calendula kept its own separate - on/off list that had no say in it. There is now one switch: **Settings → - Calendars** turns a calendar on or off for the whole device, so what you see - and what reminds you can no longer disagree ([#75]). - - Calendars you had switched off in Calendula are switched off here too on first - launch. Calendars that were already off — hidden in another calendar app, or - never switched on after being added — stay off, and Calendula says so once - rather than quietly switching them on for every app on your device; you can - turn any of them back on in Settings → Calendars. - - If you gave Calendula read-only access to your calendars, the switch still - works: your choice is kept in the app until it can be written. - - The drawer's filter is unchanged and still app-only: hiding a calendar there - tidies your view without silencing its reminders. +- Month widget no longer turns into the agenda widget or loses columns ([#89], [#103]) +- Back from Settings → Views returns to Settings ([#81]) +- Month view overflow dots dim with completed events ([#79]) +- Accounts sharing a name are no longer merged into one group ([#77]) +- Split month view's new-event button starts on the selected day ([#87]) +- Search shows the correct date for all-day events west of UTC ([#82]) +- Reminders fire reliably on all phones, including after restart or update ([#75]) +- All-day reminders arrive at the chosen time on every occurrence ([#75]) +- Reminders arrive for every calendar switched on in Settings → Calendars ([#75]) ## [2.16.0] — 2026-07-24 ### Added -- Choose how the month view is laid out. A new **Month view style** setting - (Settings → Views) offers three ways to read a month, each shown with a - preview of the layout it produces: - - **Pages** — what you have today: one month at a time, swiped sideways. - - **Continuous** — scroll up and down through the weeks without a break - between months. Because the weeks run on unbroken, no month is cut off and - no day appears twice, where paging repeats a boundary week at the end of one - month and the start of the next. The 1st of each month names itself so you - always know where you are, and the title bar keeps up as you scroll ([#38]). - - **Split** — a compact grid showing coloured dots for the days that have - something on them, with the day you tap listed in full underneath. Tap the - date above the list to open the whole day ([#53]). - - The Agenda view is untouched by this and stays available in all three styles — - the split layout lists a single day, while Agenda remains a rolling multi-day - window with its own range settings. -- Give an event its own time zone. A new **Time zone** field (under "more - fields" in the event form) pins an event to a specific zone, so a call set for - 8:00 AM in New York stays 8:00 AM in New York wherever you open it — and keeps - tracking that zone across daylight-saving changes instead of drifting an hour. - The form edits the event in its own zone and shows the local equivalent under - the times ("2:00 PM – 3:00 PM your time"); the event's details keep your local - time first and note the original beneath it, so both are always clear. Pick a - zone from a full-screen picker with your device zone and recent choices on top, - searching by city ("new york"), IANA id ("europe/berlin"), or abbreviation - ("CEST") to gather every matching zone at once. All-day events stay - date-anchored and carry no zone, as before ([#31]). -- Put the "jump to today" button in the toolbar. A new **Today button in - toolbar** setting (Settings → Appearance, off by default) swaps the floating - button that fades into the corner while you're away from today for a permanent - today icon in the top bar — always there, on today or not, matching the - familiar calendar-app pattern. Leave it off to keep the floating button as - before ([#60]). -- Choose what Calendula calls itself on your home screen. A new **App name** - setting (Settings → Appearance) switches the launcher label between - **Calendula** and **Calendar**, for launchers that can't rename apps - themselves. Pick from a full-screen chooser that previews both names as - launcher marks; the change applies at once ([#44]). -- Calendula now speaks **Arabic**, laid out right-to-left, and its French and - Italian translations have been brought up to date — thanks to the community - translators on Weblate. Pick a language under Settings → Language (or leave it - on the system default). +- Month view style setting: Pages, Continuous scrolling, or Split with day list ([#38], [#53]) +- Per-event time zone, with a searchable zone picker ([#31]) +- Option to show the Today button in the toolbar instead of floating ([#60]) +- App name setting: show Calendula or Calendar on the home screen ([#44]) +- Arabic translation, plus French and Italian updates ### Changed -- Dates in the Month, Week and Day title bars now follow your language and - region instead of one hardcoded layout. Every date was rendered in a fixed - German-style order with a trailing dot on the day number, whatever your - settings: US English showed "Fri, 17. Jul 2026" where it should read - "Fri, Jul 17". The Agenda view already formatted correctly, so the two - disagreed about the same date. All four views now share one formatter, and the - day/month order, the separators and the ordinal all come from your locale — - so English-in-Germany reads "Fri, 17 Jul" and English-in-the-US "Fri, Jul 17", - each correct for where you are ([#60]). -- The title bar drops the year while you're in the current one — "July" rather - than "July 2026". The year reappears the moment you page out of the current - year, which is when it tells you something you didn't already know. -- The Week view's title now names the month instead of spelling out the day range. - "24. Jun – 31. Jun" restated the day numbers already printed in the column - headers right below it, in the widest string in the bar. A week that straddles - two months keeps the outgoing month until it is fully gone ([#60]). -- The custom recurrence picker has been redesigned and tightened up. As you - build a rule — "every 2 weeks on Mon & Wed, until a date" — the live summary - now describes exactly what will be saved rather than a near-copy that could - drift from it, the amount fields accept being left blank (reading as their - shown default instead of greying out OK), and the read-out no longer jumps - around as you tap weekdays ([#42]). +- Title bar dates follow your language and region ([#60]) +- Title bar hides the year while you're in the current one +- Week view title shows the month instead of a day range ([#60]) +- Redesigned custom recurrence picker with an accurate live summary ([#42]) ### Fixed -- An all-day event no longer shows up again the day after it happened. In time - zones east of UTC, an all-day event — a birthday, say — set for one day also - appeared under the *next* day's heading in the Agenda (and the agenda widget), - because all-day events are anchored to UTC midnight and the following day's - window reached back across that boundary and pulled the event forward onto - "today". Each all-day event now lists only on the day it actually falls on - ([#65]). -- A multi-day event now shows under every day it spans in the Agenda, not just - its first day, so a trip or a multi-day booking appears on each day it covers. -- The "Upcoming" agenda widget now scales its text and rows to the size you give - it. Previously it was laid out once for the smallest size and simply stretched - when enlarged, so the text stayed small no matter how big you made the widget. - Now a bigger widget gets bigger, more readable type and roomier rows, while the - default size looks exactly as before — no new setting; it follows the size you - already chose ([#51]). -- Calendula now appears under other apps' "Add to calendar" / "Save to calendar" - actions. Some apps (e.g. DB Navigator) fire the widely-used "insert event" - intent with the singular `vnd.android.cursor.item/event` type, which Calendula - didn't advertise — so it was left out of the chooser, and if it was your only - calendar app the save silently did nothing. It now accepts that form, plus the - `INSERT_OR_EDIT` action, and opens the new event prefilled for review ([#74]). -- Opening a `.ics`/`.vcs` file now works even when another app hands it over - mislabelled as a generic download (`application/octet-stream`), as some mail - clients, browsers and file managers do — Calendula recognises it by its file - extension instead of relying on the declared type ([#74]). -- A recurrence end date no longer lands a day late. West of UTC, setting a rule - to end "until" a given day could save and show the day after the one picked; - the end date now reads back as chosen ([#42]). -- The status- and navigation-bar icons stay legible over full-screen pickers in - dark theme. They could render dark-on-dark — a near-invisible black clock - against the dark picker — instead of switching to light ([#70]). +- All-day events no longer repeat on the next day east of UTC ([#65]) +- Multi-day events show under every day they span in the Agenda +- Agenda widget text and rows scale with the widget size ([#51]) +- Calendula shows up in other apps' "Add to calendar" and opens mislabelled .ics files ([#74]) +- Recurrence end dates no longer land a day late west of UTC ([#42]) +- Status bar icons stay legible over full-screen pickers in dark theme ([#70]) ## [2.15.0] — 2026-07-15 ### Added -- Show raw calendar colours. Calendula normally softens each calendar and event - colour toward a theme-fitting pastel so harsh sync colours read well on both - light and dark; a new **Soften calendar colours** setting (Settings → Design, - on by default) lets you turn that off and paint the exact colours your calendar - source publishes — matching DAVx5/CalDAV and other calendar apps. Thanks to - @leonp5 for the report ([#36]). -- Readable titles on dark event colours. An event bar's title now shows in white - on a dark colour and near-black on a light one, chosen automatically from the - colour's brightness, so a deep blue or purple event is legible at a glance in - the busy Week and Month views instead of dark-on-dark. This applies whether or - not colours are softened. Thanks to @ptab for the suggestion ([#21]). -- A custom snooze duration. The **Snooze duration** setting (Settings → - Notifications) gains a **Custom…** option next to the minute presets: pick any - amount and switch between minutes and hours, so a snoozed reminder comes back - after exactly the delay you want instead of only a preset one ([#40]). -- Move an event to another calendar. When editing an existing event, the - calendar row is now tappable — pick a different calendar and saving moves the - event across, instead of having to delete it and recreate it elsewhere. - Recurring series move as a whole, keeping their individually-edited and - cancelled occurrences, and any reminders and guests come along too. A calendar - can't simply be reassigned underneath an event, so Calendula recreates it on - the target and removes the original — the same approach other calendar apps - take. Thanks to @prismplex for the suggestion ([#39]). -- Open an event straight into the edit form from another app. Calendula already - answered the "new event" and "open this event" hand-offs from other apps and - widgets; it now also answers the "edit this event" one, so an assistant, task - app, or widget can send an existing event to Calendula and land on its edit - screen rather than the read-only details. A hand-off with no event attached - opens the same prefilled create form as "new event". Calendula also recognises - a couple more file labels the same calendar data arrives under (`.vcs` - vCalendar files and the `application/ics` type), so opening or sharing those - into Calendula works too. -- Keep today at the top of the agenda. A new **Always show today** setting - (Settings → Agenda, on by default) anchors today as the first entry in both the - Agenda screen and its home-screen widget even once nothing is left today — - under today's header a "No more events today" note appears — so the first - events you see are clearly today's rather than a future day's. Turn it off to - keep the agenda purely upcoming. Thanks to @ptab for the suggestion ([#35]). -- Duplicate an event. The event details now carry a **Duplicate** action that - opens the editor pre-filled with a copy of the event as a new, unsaved one, so - a one-off like a shift or an appointment can be recreated by just changing the - day and time instead of re-typing every field. The copy keeps the original's - time, and its title, location, notes, colour, guests and reminders come along; - it's saved as its own single event (any repeat is left off — add one in the - editor if you want it). Duplicate works from read-only calendars too, dropping - the copy into a writable one. Thanks to @internet-rando for the suggestion - ([#52]). -- French and Polish, in early form. Calendula has started speaking French and - Polish, both contributed as community translations through - [Calendula's Weblate](https://weblate.dev.jeanlucmakiola.de/projects/calendula/). - They are partway there, so untranslated parts still show in English until they - fill out — you can already pick either under Settings → Language or in Android's - per-app language settings. Thanks to Thomas Tref (French) and Bazyli Cyran - (Polish) for getting them started; help finishing them is very welcome. +- Soften calendar colours setting, to show exact source colours ([#36]) +- Event titles switch to white or black for readability on any colour ([#21]) +- Custom snooze duration in minutes or hours ([#40]) +- Move an event to another calendar while editing ([#39]) +- Other apps can open an event straight into the editor; more .ics file types accepted +- Always show today setting keeps today at the top of the agenda ([#35]) +- Duplicate an event from its details ([#52]) +- Early French and Polish translations ### Fixed -- Reminders for events on another day no longer read as if they were today. A - reminder fired ahead of time — say, the day before — used to show only the - event's time, making it look like it was happening now. The notification now - says which day: **Tomorrow** or **Yesterday**, the weekday for another day this - week, or the date for anything further out. Thanks to @moonj for the report - ([#46]). -- Agenda dates now read in your locale's format. The agenda's range bar and its - day headers used a fixed day-month-year layout — and the range span even mixed - two orders (e.g. "15 Jul – Aug 13, 2026") — instead of following your language's - conventions. Dates across the agenda and its widget now use your locale's own - field order, matching the rest of the app. The range bar also no longer repeats - the range's name from the selector button beside it, showing just the dates. -- Calendar gutters line up with the menu button. The Month view's week-number - column, and the Week and Day views' hour labels, sat a few pixels left of the - hamburger menu above them; they now line up with it. In Month view the day - cells also sit squarely under their weekday letters. +- Reminders for other days say Tomorrow, the weekday or the date ([#46]) +- Agenda dates follow your locale's format +- Calendar gutters line up with the menu button ## [2.14.1] — 2026-07-13 ### Fixed -- Deleting one occurrence of a repeating event no longer breaks the series. - Choosing "This event" when deleting an occurrence of a recurring event could - wipe out every *other* occurrence while leaving the one you deleted behind as - a stale, still-tappable ghost — and deleting it again brought the series back. - A single-occurrence delete now removes exactly that occurrence and leaves the - rest of the series untouched, and the deleted occurrence disappears from the - grid straight away. This holds on every kind of calendar, including the - on-device ones Calendula keeps for contact birthdays and anniversaries, where - the series is a yearly repeat. Thanks to @moonj for the report ([#47]). -- Tapping an event in a third-party widget opens it in Calendula. v2.13.1 taught - Calendula to answer the "new event" hand-off from other apps and widgets; now - it also answers the "open this event" one, so tapping an existing event in a - widget such as Todo Agenda offers Calendula and lands on that event's details. - Thanks to @bushrang3r for the report ([#48]). -- Events created from other apps get your default reminder. An event handed over - by another app or widget — Google Maps' "add to calendar", the Todo Agenda - widget's "+" — opened with no reminder at all, ignoring the default set in - Settings. It now starts with your default reminder, the same as an event you - create in Calendula. An event opened from an `.ics` file is treated differently, - because the file has its own say: Calendula keeps whatever reminders it carries - (including none at all) and asks you once whether to apply your default instead - — it never quietly overrides the file. If you have no default set, it doesn't - ask ([#49]). -- A tidy colour picker on CalDAV calendars. For calendars synced by a CalDAV - app (such as DAVx5), the event colour picker showed every colour the account - publishes — nearly 150 swatches in alphabetical order, many of them - duplicates or near-identical shades. The picker now shows only visually - distinct colours, arranged as a rainbow; near-duplicate shades and the - washed-out neutrals are folded away so no two swatches look alike. Picked - colours still sync exactly as before, and calendars with hand-picked - palettes (like Google's) are unaffected. Thanks to @ptab for the report - ([#22]). +- Deleting one occurrence no longer breaks the rest of the series ([#47]) +- Tapping an event in third-party widgets opens it in Calendula ([#48]) +- Events created from other apps get your default reminder; .ics imports ask first ([#49]) +- CalDAV colour picker shows only distinct colours, as a rainbow ([#22]) ## [2.14.0] — 2026-07-06 ### Added -- Restore events from a backup file. The backup section of Settings can now read - events back **in** from an `.ics` file, not just write one out: pick a file, - choose which calendar to import into, and Calendula adds the events — skipping - any that are already there and telling you how many it skipped. Export gained a - per-calendar selector at the same time, so you can back up just the calendars - you pick instead of everything at once ([#32]). -- Week numbers in Month view. A new **Week numbers** setting (off by default) - adds a slim gutter down the left of the Month grid showing the calendar-week - number for each row, sized to match the day cells. Handy if you plan or refer - to dates by week number ([#25]). -- Tap a date header to open that day. In Week and Agenda view, tapping a date - header now opens that date in Day view — the same drill-in that Month view and - the agenda widget already offered, so every view behaves the same way. It makes - jumping to a specific day quicker: switch to Week, swipe to the week you want, - then tap the date to open it. Thanks to @ptab for the suggestion ([#37]). -- An early Simplified Chinese translation. Calendula has started speaking - Simplified Chinese, contributed as a community translation through - [Calendula's Weblate](https://weblate.dev.jeanlucmakiola.de/projects/calendula/). - It is still an early effort, so many parts of the app show in English until it - fills out — you can already pick it under Settings → Language or in Android's - per-app language settings. Thanks to - [zh-cn](https://weblate.dev.jeanlucmakiola.de/user/zh-cn/) for getting it - started; help finishing it is very welcome. +- Import events from an .ics backup, and export selected calendars only ([#32]) +- Optional week numbers in Month view ([#25]) +- Tap a date header in Week or Agenda to open that day ([#37]) +- Early Simplified Chinese translation ### Changed -- Long event titles wrap in the edit screen. When editing an event, a long title - now wraps onto multiple lines instead of being clipped to a single line, so you - can see and edit the whole thing ([#33]). +- Long event titles wrap in the editor ([#33]) ## [2.13.1] — 2026-07-06 ### Added -- Create events from other apps and widgets. Calendula now registers the - standard "insert event" intent (`ACTION_INSERT` on the calendar events type), - so other apps and home-screen widgets — such as the Todo Agenda widget — can - hand off to Calendula to create a new event. It opens the new-event form - prefilled with whatever they passed (title, start/end time, all-day, location, - description, recurrence), and picks your last-used or first writable calendar. - Thanks to @dschuermann for the suggestion ([#30]). +- Other apps and widgets can create events in Calendula ([#30]) ### Fixed -- Some recurring events could not be opened. Events in a series that started - before 1970 — for example yearly birthdays or anniversaries synced over CalDAV - — showed "Something went wrong" instead of opening, because their stored start - time is a negative value that was wrongly treated as invalid. They now open - normally and appear in search again. A related case (an event whose stored end - precedes its start) is now kept and openable instead of failing the same way. - Thanks to @dschuermann for the report ([#34]). -- The time picker now follows your 24-hour setting. With Calendula set to - 24-hour time, the clock dial for choosing an event's start and end time still - showed AM/PM instead of a 24-hour dial; it now matches your setting (and the - same fix applies to the all-day reminder time in Settings). Thanks to - @abrossimow for the report ([#27]). +- Recurring events that started before 1970 open again ([#34]) +- Time picker follows your 24-hour setting ([#27]) ## [2.13.0] — 2026-07-03 ### Added -- Calendula now speaks Spanish and Italian. Both arrived as community - translations through [Calendula's Weblate](https://weblate.dev.jeanlucmakiola.de/projects/calendula/) - — a **huge thank you** to - [kikerw](https://weblate.dev.jeanlucmakiola.de/user/kikerw/) for the Spanish - translation and to - [corrent](https://weblate.dev.jeanlucmakiola.de/user/corrent/) for the Italian - one! Pick your language under Settings → Language or in Android's per-app - language settings. Strings added in this very release may still show in - English until the translations catch up. Want Calendula in your language? - Translating happens entirely in the browser — every contribution is welcome. -- See your contacts' birthdays and anniversaries in your calendar. A new, - **optional** feature (Settings → Contact special dates) mirrors your contacts' - birthdays, anniversaries and other dates into local "Birthdays", - "Anniversaries" and "Other dates" calendars that stay in sync as your contacts - change. Each is a normal local calendar, so you set its colour, visibility and - reminders the usual way — new birthdays even start with a reminder a week before - *and* on the day. The title format is yours to customise (`{name}`, `{year}`). - This is the first feature to use the contacts permission: it is requested only - when you turn the feature on, everything stays on your device (Calendula has no - internet access), and your contacts are only ever read, never changed. Thanks - to @moonj for the suggestion ([#15]). -- Set more than one default reminder per calendar. A calendar's default - reminders — and the global defaults under Settings → Notifications — can now - hold several lead times instead of just one, so new events can start with, say, - a reminder a week before *and* one on the day. The reminder pickers are now - multi-select; per-calendar overrides can still inherit the global default or - turn reminders off entirely. Thanks to @moonj for the suggestion ([#14]). -- Widget headers now open the app. Tapping the month/year title on the month - widget opens the app on the month view, and tapping the "Upcoming" title on - the agenda widget opens it on your default view — so there's a one-tap way - back into the app that lands where you'd expect, instead of only through a day - or event. On the month widget, tapping anywhere on a day — not just the small - date number — now opens that day, and the "today" button snaps the grid back - to the current month in place. Thanks to @rgz46vic and @ptab for the - suggestions ([#18], [#20]). -- Make Calendula's text your own. Settings → Appearance gains **Headings font** - and **Body font** pickers: keep the system default, choose a bundled face - (Atkinson Hyperlegible, Lora, JetBrains Mono — each previewed in its own - face), or load any `.ttf`/`.otf` file from your device, independently per - role. Font size and colour stay with Android's accessibility scaling and the - app theme, as discussed on the issue. Thanks to @abrossimow for the - suggestion ([#19]). -- Choose what the view-switch button cycles through. Settings → Appearance now - lets you pick which views the top-right quick-switch button rotates between - and drag them into your preferred order; views you switch off stay reachable - from the navigation menu, which can be reordered the same way. Thanks to - @abrossimow for the suggestion ([#24]). +- Spanish and Italian translations +- Contact birthdays and anniversaries as local calendars (optional) ([#15]) +- Multiple default reminders per calendar ([#14]) +- Widget headers open the app; tap anywhere on a month widget day ([#18], [#20]) +- Custom headings and body fonts, bundled or from a file ([#19]) +- Choose and reorder the views the quick-switch button cycles through ([#24]) ### Fixed -- Month widget arrows and "today" button work again. On release builds the - prev/next-month arrows and the jump-to-today control on the month widget did - nothing when tapped — code shrinking had stripped the tap handlers behind - them. They respond again. Thanks to @rgz46vic for the report ([#18]). -- Disabled calendars no longer notify. Reminders for events in a calendar you - have disabled (Settings → Calendars) are now suppressed instead of still - popping up — matching how a disabled calendar's events already stay hidden - everywhere else in the app ([#17]). -- Editing a single occurrence of a recurring event works again. Choosing **Only - this event** and saving a change to one event in a repeating series silently - did nothing — the change was rejected and the edit form simply reappeared with - nothing applied. The edited occurrence is now stored correctly, so the change - lands on just that one event and leaves the rest of the series untouched - ([#16]). -- Every calendar can be picked when creating an event. The event editor's - calendar picker was a fixed-height dialog, so with many calendars anything - past the first nine or so was simply unreachable. It is now a full-screen, - scrollable list grouped by account, with each calendar's colour shown. - Thanks to @dschuermann for the report ([#29]). +- Month widget arrows and today button work again ([#18]) +- Disabled calendars no longer send reminders ([#17]) +- Editing a single occurrence of a recurring event works again ([#16]) +- Full-screen calendar picker, so every calendar can be chosen ([#29]) ## [2.12.0] — 2026-06-28 ### Added -- See past events your way. Two new settings change how events that have already - ended are shown. **Past events** (Settings → Appearance → Agenda) lets the - agenda — both in the app and the home-screen "Upcoming" widget — keep them as - usual, dim them, or hide them from the list entirely. **Dim completed events** - (Settings → Appearance) separately fades finished events in the month and week - views. Both are off by default, an event only counts as finished once it has - actually ended (events still in progress are never dimmed), and the lists - update on their own as the day goes on. Thanks to @ptab for the suggestion - ([#12]). +- Settings to dim or hide past events in the agenda and dim them in Month and Week ([#12]) ### Changed -- Readable titles on overlapping events. In the week and day views, events that - overlap split a day into slim columns where the title used to be clipped to a - character or two. The title now wraps across as many lines as the block can - fit, and the time is hidden on those narrow blocks so the name can fill the - space — so you can tell events apart without opening each one. Thanks to @ptab - for the suggestion ([#13]). +- Overlapping events wrap their titles in Week and Day views ([#13]) ## [2.11.2] — 2026-06-28 ### Added -- Jump straight to typing a title. When you start a new event, Calendula now puts - the cursor in the title field and opens the keyboard right away, so you can type - the name without an extra tap. It's on by default and only affects creating an - event — editing never grabs focus — and a new **Focus title on new event** - switch (Settings → New event form) turns it off. Thanks to @abrossimow for the - suggestion ([#10]). +- New events focus the title field right away, with a setting to turn it off ([#10]) ## [2.11.1] — 2026-06-28 ### Fixed -- Calendula can now be set as your default calendar app. It registers the - calendar-app intent filters the system uses, so it appears in the chooser when - you tap a date in a launcher or clock — and opening one takes you straight to - that day. Android has no way for an app to make itself the default, so you pick - it once from the system picker. Thanks to @abrossimow for the report ([#9]). +- Calendula can be set as the default calendar app ([#9]) ## [2.11.0] — 2026-06-27 ### Added -- Start the week on any day. The **Week starts on** setting (Settings → - Appearance) now offers every weekday — not just Monday or Sunday — alongside - the automatic, locale-based default. Thanks to @zmaherdev for the suggestion - ([#3]). -- Choose a 12- or 24-hour clock. A new **Time format** setting (Settings → - Appearance) lets you force a 12-hour (2:00 PM) or 24-hour (14:00) clock, or - follow the system setting automatically. It applies everywhere times appear — - the week and day timelines, agenda, event details, search and reminders — so - the format is now consistent across the whole app. Thanks to @zmaherdev for - the suggestion ([#6]). -- Optional hour lines in the timeline. A new **Hour lines** switch (Settings → - Appearance) draws a faint separator at each hour in the week and day views, - making it easier to see when events start and end. Off by default. Thanks to - @zmaherdev for the suggestion ([#5]). -- Limit how far ahead the agenda looks, and switch it on the fly. New **Agenda - range** and **Agenda widget range** settings (Settings → Appearance) let the - agenda screen and its home-screen widget each show just today, the rest of this - week, the rest of this month, a rolling 7 or 30 days, or a custom number of - days — "This week" follows your week-start. The agenda also gains a bar at the - top naming the exact dates in view, with a button to switch the range just for - the current session (it resets when you reopen the app); the bar can be turned - off. Thanks to @zmaherdev for the suggestion ([#4]). -- Automatic backup of local calendars. A new **Automatic backup** option - (Settings → Calendars → Backup) periodically exports your local calendars to an - `.ics` file in a folder you choose, on an interval you set (from 30 minutes up). - Useful for file-based syncing such as Syncthing, or simply as a safety net — it - is a one-way export and never touches your synced accounts. Thanks to @shield - for the discussion that inspired it ([#7], [#8]). -- Field icons in the event-form settings. Each optional-field toggle (Settings → - Event form) now shows the same icon the field uses in the new-event form, so - the list is easier to scan. -- Help translate Calendula. A **Help translate** link at the top of **Settings → - App language** opens the project's Weblate, where you can add or improve a - language in your browser — no coding needed. Contributions in any language are - welcome. +- Start the week on any day ([#3]) +- 12- or 24-hour time format setting ([#6]) +- Optional hour lines in Week and Day views ([#5]) +- Agenda and agenda widget range settings, with a quick range switcher ([#4]) +- Automatic backup of local calendars to an .ics file ([#7], [#8]) +- Field icons in the event form settings +- Help translate link in language settings ### Changed -- Tidied **Settings → Appearance** into clearer groups (theme & colour, calendar, - agenda), and the agenda's empty state now reads "You're all caught up". -- Reworked **Settings → Calendars**. Local and synced calendars are now grouped - into collapsible, source-branded cards — each account shows its app's icon — - with a per-account menu to enable or disable all of its calendars at once or - open the account in its source app. -- Reorganised **Settings → Notifications**: reliable-delivery and snooze settings - moved up with the other global reminder options, and the per-calendar reminder - overrides now fold into a single expandable section. -- Moved **Add Quick Settings tile** out of the event-form section to its own - top-level entry in Settings. +- Tidier Appearance, Calendars and Notifications settings +- Quick Settings tile entry moved to its own spot in Settings ## [2.10.0] — 2026-06-25 ### Added -- Turn a calendar off across the whole app. Settings → Calendars now has a - switch on every calendar — both your own and synced ones. Switching one off - removes it everywhere: its events disappear from all views and search, and it - drops out of the drawer's hide/show filter, the event-form calendar picker and - the import target picker. Unlike hiding (the quick per-view checkbox in the - drawer), a disabled calendar leaves the app entirely until you turn it back on. - Nothing is deleted and no other app is affected — it's a Calendula-only view - choice — so you can re-enable it any time from the same screen, where disabled - calendars stay listed but dimmed. -- An optional way to support development. Settings → About now has a "Support - development" button that opens Ko-fi in your browser. It's a plain donation - link with no perks attached, and it needs no new permissions — Calendula still - has no internet access of its own and just hands the link to your browser. +- Turn a calendar off app-wide from Settings → Calendars; nothing is deleted +- "Support development" Ko-fi link in Settings → About ## [2.9.0] — 2026-06-25 ### Added -- Choose the view Calendula opens on. A new **Default view** setting (Settings → - Appearance) lets you pick Month, Week, Day or Agenda as the view shown each - time you start the app, instead of always opening on Week. Thanks to - @devinside for the suggestion ([#1]). -- The month widget is now interactive: tap any day to open it, or tap an event to - open its details. Previously only the month's prev/next/today controls - responded. Thanks to @devinside for spotting this ([#2]). -- Predictive back. Swiping back from a screen — an event, the editor, search or - settings — now follows your finger, shrinking the screen to preview what's - behind so you can see where Back will take you before you let go; slide it back - to cancel. The preview needs Android 14 or newer; on older versions Back works - as before. -- Respect for "Remove animations". If you've turned animations off in your - device's Accessibility settings, Calendula now honours it everywhere: motion - collapses to a quick fade and the back preview is skipped. +- Default view setting: open on Month, Week, Day or Agenda ([#1]) +- Month widget days and events are tappable ([#2]) +- Predictive back gesture previews where Back goes (Android 14+) +- "Remove animations" accessibility setting is respected ### Changed -- Smoother, more consistent motion throughout. Expanding sections, list updates - in search and agenda, and the onboarding screens now animate the same way - across the app, instead of some places sliding or growing while others popped - in. Switching between Month, Week, Day and Agenda now cross-fades rather than - snapping, while paging within a view keeps its slide. +- Smoother, consistent motion; switching views cross-fades ### Fixed -- Home-screen widgets now back out the way you came in. A day or event opened - from the Agenda widget keeps you in the agenda context, and from the Month - widget in the month context — pressing Back returns there instead of dropping - you on the week view. More broadly, the app now keeps a real view history: - switching views and drilling into a day are retraced by Back one step at a - time, down to your default view before the app exits. Thanks to @devinside for - reporting ([#2]). +- Back from a widget returns to its view, and Back retraces your view history ([#2]) ## [2.8.0] — 2026-06-23 ### Added -- Find events fast. A search button in the top bar of every calendar view opens - a search box — type a couple of letters and matching events (by title, - location or description) appear, soonest first with past events below. Tap a - result to open it. Search covers your whole calendar, not just what's on - screen, and skips calendars you've hidden. A recurring event shows its next - occurrence rather than the date the series first started. -- A current-time line in the day and week views. A thin coloured line marks the - present moment across today's column, so you can see at a glance where you are - in the day. It updates every minute and only appears when today is in view. -- Add and remove event guests. The create/edit form now has a Guests section: - add people by email or pick them from your contacts, mark each as required or - optional, and remove them. Calendula never sends invitations itself (it has no - internet access) — it only records the guests; if the event lives on a synced - account, that account may email them when it syncs, and on a local calendar no - one is notified. The form tells you which applies. Picking a guest from - contacts needs no contacts permission. -- Pick a location from your contacts. A contacts button beside the location - field drops a contact's address straight into an event — handy for a meeting - at someone's home or office. Like the guest picker, it needs no contacts - permission. -- A "New event" Quick Settings tile. Add it to your quick settings to jump - straight into the new-event form from anywhere. Settings → New event has a - one-tap button to add the tile (Android 13+); on older versions you can add it - from the quick-settings editor. -- Snooze and dismiss buttons on reminder notifications. Dismiss clears the - reminder; snooze hides it and brings it back after a delay you pick in - Settings → Notifications (5 to 60 minutes, default 10). Android's calendar - system won't re-post a reminder on its own, so Calendula schedules an exact - alarm to bring a snoozed one back on time. +- Search events by title, location or description +- Current-time line in day and week views +- Add and remove event guests, including from contacts +- Pick an event location from your contacts +- "New event" Quick Settings tile +- Snooze and dismiss buttons on reminder notifications ### Changed -- Event details now show each guest's email beneath their name, instead of only - when no name is available. -- Crash and problem reports now open on the project's public Codeberg tracker, - where anyone can register and file an issue. Nothing is sent automatically — - you still review the report and submit it yourself in the browser. +- Event details show each guest's email under their name +- Crash and problem reports open on the public Codeberg tracker ## [2.7.5] — 2026-06-21 ### Changed -- Further build cleanup for the official F-Droid repository: stopped embedding - AGP's dependency-metadata block in the APK, which F-Droid's reproducible-build - scanner rejects as an extra signing block. No functional or visible changes — - the same app as 2.7.4, just without that Play-oriented metadata blob. +- Build cleanup for the official F-Droid repository, no visible changes ## [2.7.4] — 2026-06-21 ### Changed -- Build cleanup that lets Calendula ship in the official F-Droid repository: - removed an unused Gradle toolchain-resolver plugin, which F-Droid's offline, - reproducible build process disallows. No functional or visible changes — this - is the same app as 2.7.3. +- Build cleanup for the official F-Droid repository, no visible changes ## [2.7.3] — 2026-06-21 ### Fixed -- Home-screen widgets no longer get stuck on a loading spinner in the published - (F-Droid) release build. They render via Android's background-work system, and - release optimisation (R8) was stripping a helper class it loads by name, so the - render job never ran. Added the missing keep rule — widgets now load normally. +- Widgets no longer stuck loading in the F-Droid release build ## [2.7.2] — 2026-06-21 ### Added -- Crash reporting you control. If Calendula closes unexpectedly, it now captures - a technical report and, on the next launch, offers to send it as an issue on - the project's tracker. Nothing is uploaded automatically — the report stays on - your device until you choose to share it, it contains no personal data or - calendar content (only the app, Android and device versions plus the stack - trace), and you see the full text before sending. There's also a "Report a - problem" entry in Settings, and if the app ever fails to start repeatedly, a - minimal recovery screen still lets you send the report. +- Opt-in crash reporting: review and send a report after a crash, or from Settings ## [2.7.1] — 2026-06-21 ### Fixed -- Fixed the app crashing immediately on launch whenever calendar access hadn't - been granted yet (a fresh install, or after revoking the permission). The app - set up its live calendar-change listener before the permission screen could - appear, which newer Android versions reject outright — so the app died before - you could grant access. The listener now waits for the permission and attaches - itself the moment it's granted. +- App no longer crashes on launch before calendar access is granted ## [2.7.0] — 2026-06-18 ### Added -- Share a single event as an `.ics` file from the event detail screen — hands a - standard calendar file to any app via the system share sheet. -- Back up your local (device-only) calendars: Settings → Calendars → Export as - `.ics` file writes every event of your on-device calendars to a file you - choose. Local calendars aren't synced anywhere, so this is their only backup. -- Open or share an `.ics` file into Calendula: a single event opens the create - form prefilled for review, while a file with many events (e.g. a backup) opens - a bulk import — pick a calendar and import them all. Re-importing a backup - won't create duplicates (events are matched by their unique identifier), and - anything Calendula can't represent (changed recurring occurrences, guest - lists) is reported rather than silently dropped. +- Share a single event as an `.ics` file +- Export local calendars as an `.ics` backup +- Open or import `.ics` files, single events or bulk, without duplicates ### Fixed -- All-day events that cover a single day (e.g. a birthday) no longer show up on - the following day as well — in the day, week and month views or on the event - detail screen. The extra day came from interpreting the all-day date range in - the device's time zone instead of UTC. -- Fixed the app crashing immediately on every launch in the optimized release - build: release code-shrinking (R8) was stripping a database class the - home-screen widget framework needs, so the app died at startup before showing - anything. Added the missing keep rule. +- Single-day all-day events no longer spill onto the next day +- Release build no longer crashes on launch ## [2.6.0] — 2026-06-18 ### Added -- App language can now be set from Android's system per-app language settings - (Android 13+), in addition to the in-app picker in Settings — and the app is - set up so further languages can be added by community translators +- App language can be set from Android's per-app language settings (Android 13+) ### Fixed -- Changing the app language in Settings now takes effect immediately; the - picker previously had no effect +- Changing the app language in Settings takes effect immediately ## [2.5.0] — 2026-06-17 ### Added -- Home-screen widgets (two of them): an "Upcoming" agenda widget — a scrolling - list of the next month of events grouped under day headers, with refresh and - "New event" buttons — and a month-grid widget showing the full month with - today highlighted, connected multi-day event bars, and prev/next/today - navigation. Both reuse the in-app grouping and layout so they match the app - exactly, respect your hidden-calendar choices, and refresh automatically when - the calendar changes or the day rolls over. Tapping a day opens that day; - tapping an event opens its details -- App shortcut: long-press the Calendula icon for a "New event" action that - jumps straight into the create-event form -- Agenda view — a fourth top-level view alongside Month/Week/Day: a - forward-looking list of upcoming events grouped under "Today"/"Tomorrow"/date - headers, reachable from the view switcher -- Jump to date — a "Jump to date" row in the navigation drawer opens a date - picker and moves the active view (Month/Week/Day/Agenda) to the chosen day +- Home-screen widgets: upcoming agenda and month grid +- "New event" app shortcut on the launcher icon +- Agenda view listing upcoming events +- Jump to date from the navigation drawer ## [2.4.0] — 2026-06-17 ### Added -- Per-event colors: give a single event its own color, instead of always - inheriting its calendar's. Add the new "Color" field from "More fields" in - the event form. On calendars that publish their own color set — such as - Google — you pick from that calendar's palette, so the color is stored - with the event and shows correctly on every synced device. On local - calendars you pick from Calendula's palette. "Reset" returns an event to - its calendar's color -- A new "Allow colors on unsupported calendars" setting (New event form, - off by default) extends per-event colors to calendars that publish no - color set of their own (some CalDAV). Such a color is kept on the device - and may be dropped or overwritten on that calendar's next sync — a - limitation of those calendars, called out plainly in the setting and on - the color picker +- Per-event colors, using the calendar's palette where available +- Setting to allow event colors on calendars without a color set ## [2.3.0] — 2026-06-16 ### Changed -- Redesigned Settings around the Material 3 grouped-list pattern: a large - title that collapses into the toolbar as you scroll, category cards on the - main screen, and dedicated sub-pages for Appearance, the new-event form, and - Notifications. The theme, week-start and language pickers now use the app's - standard option-card dialogs instead of dropdown menus -- About moved to the top of Settings as a card — app icon, author, and quick - links to the source code and licence — with the version shown plainly at the - foot of the list -- The Calendars screen now uses the same grouped-card layout and collapsing - title, and each calendar shows a soft pastel-tinted calendar glyph rather - than a plain colour swatch -- Redesigned the navigation drawer to match: a branded header, the - Month / Week / Day switch and your calendars as grouped cards (with the - active view highlighted), and the whole drawer now scrolls as one +- Redesigned Settings with grouped cards and sub-pages +- About moved to the top of Settings as a card +- Calendars screen uses the new grouped-card layout +- Redesigned navigation drawer ## [2.2.0] — 2026-06-16 ### Added -- Tap an empty slot in the day or week view to create an event there: the - create form opens prefilled with that day and the tapped hour (snapped to - the hour, one hour long). Tapping an existing event still opens it -- Local calendars: create and manage device-only calendars that live - entirely on this phone — no account, no sync — from a new "Calendars" - screen in Settings. Give each a name, a colour, and an optional - description; rename, recolour, or delete them later. Useful when you want - a calendar without setting up an account -- The Calendars screen also lists your synced calendars (DAVx5, ICSx5, …) - grouped by account, each with a "Manage" button that opens the app the - calendar actually comes from, plus an "Add account" shortcut to the - system account settings. Calendula never touches a synced calendar's - server itself — that stays with its own app +- Tap an empty slot in day or week view to create an event there +- Create and manage local, device-only calendars +- Calendars screen lists synced calendars with a link to their app ### Changed -- Colour swatches in the calendar editor now preview the soft, pastel tone - a calendar is actually drawn with, instead of a bright raw colour -- The calendar editor reuses the event form's field and button styling for - a consistent look +- Calendar editor color swatches show the actual pastel tone +- Calendar editor matches the event form's styling ## [2.1.0] — 2026-06-15 ### Added -- The month view now shows real events in each day instead of coloured - dots: all-day and multi-day events render as continuous bars at the top - (a multi-day event is one connected bar across the days it spans, not a - chip per day), with single-day timed events as filled pills beneath. - Up to three rows show per day, then a "+N" dot indicator for the rest. - Each day keeps a rounded surface background, matching the week and day - views; today is marked with a filled circle on its number -- The slide-out panel now has a "View" section to switch between Month, - Week, and Day, mirroring the top-bar switcher pill — tapping a view - selects it and closes the drawer. The current view is highlighted +- Month view shows event bars and pills instead of dots +- Drawer has a View section to switch between Month, Week and Day ### Fixed -- Typing in the event title, location, and description fields no longer - makes the cursor jump around: the form state's round-trip to the UI was - hopping to a background dispatcher, so the text field saw a lagging value - while typing. Only the calendar/preferences reads stay off the main - thread now; the keystroke path is synchronous again +- Cursor no longer jumps while typing in the event form ## [2.0.0] — 2026-06-11 ### Added -- Conflict handling when saving an edit: if the event changed elsewhere - (sync, another device) while the form was open, saving now asks whether - to keep or discard your changes instead of silently overwriting the - edited fields — and tells you when the event was deleted in the meantime. - "Keep" still writes only the fields you touched; external changes to - untouched fields survive either way -- F-Droid store screenshots (German + English), captured with demo data +- Saving an edit warns when the event changed or was deleted elsewhere +- F-Droid store screenshots ### Changed -- F-Droid description and README no longer claim the app is read-only — - they now describe write support and reminder delivery +- F-Droid description and README describe write support and reminders ### Fixed -- `versionName`/`versionCode` bumped to 2.0.0 / 13 — closing out the - write-support milestone (v1.1 through v2.0) +- Version bumped to 2.0.0 ## [1.4.0] — 2026-06-11 ### Added -- Reminder notifications (v1.4): Calendula now delivers event reminders as - notifications itself — the system schedules them but posts nothing, so a - calendar app must (essential when Calendula is the only one installed). - Due reminders appear on a dedicated "Event reminders" channel; tapping one - opens the event's detail screen. Email reminders are never posted (the - provider only schedules alert-type reminders) -- A one-time onboarding step after the calendar grant introduces reminders, - requests the notification permission (Android 13+), and warns that a second - calendar app with notifications on will duplicate them. "Not now" leaves - the feature off -- Settings gained a "Notifications" section mirroring the choice: an event- - reminders toggle (default on) with the duplicate-reminders hint; turning it - on re-requests the notification permission when missing +- Calendula delivers event reminder notifications itself +- Onboarding step for reminders and the notification permission +- Event reminders toggle in Settings → Notifications ### Fixed -- `versionName`/`versionCode` bumped to 1.4.0 / 12 +- Version bumped to 1.4.0 ## [1.3.0] — 2026-06-11 ### Added -- Event editing: a pencil action on the detail screen (writable calendars - only) opens the event form prefilled with the event. Only fields you - actually changed are written back; saving an untouched form is a no-op. - Sections holding data are always shown, regardless of the form-field - defaults; the calendar itself can't be changed while editing -- Recurring events — scoped writes, chosen when saving (Google model): - "only this event" (a modified-occurrence exception), "this and all - following" (the series is split at the occurrence), or "all events in - the series". Changing the recurrence rule rules out "only this event" -- Deleting a recurring event gained the middle option too: "this and all - following events" ends the series just before the chosen occurrence -- Recurrence picker (create and edit): one-tap daily/weekly/monthly/yearly - presets plus a custom step with interval + unit, weekday toggles for - weekly rules ("every week on Mon and Fri"), and an end condition (never / - on a date / after a number of times). Rules the picker can't express - (e.g. "second Thursday monthly") are shown humanized and preserved - verbatim unless replaced. Recurrence also joined the optional form - fields and their settings defaults -- Validation: a repeat that would end before the event starts is flagged - (it would otherwise vanish from every view) +- Edit events from the detail screen +- Save recurring edits to this, this and following, or all events +- Delete "this and all following" occurrences of a recurring event +- Recurrence picker with presets, custom intervals, weekdays and end conditions +- Warning when a repeat ends before the event starts ### Changed -- Editing reminders reconciles against the provider's actual rows: - reminders you didn't touch keep their method (e.g. email reminders on - synced events survive unrelated edits) -- The contextual WRITE_CALENDAR upgrade for v1.0 installs covers the edit - action like delete +- Untouched reminders keep their method when editing +- Editing requests write permission like delete does ### Fixed -- Splitting a series ("this and following") sends the complete time-column - set in one update, so the provider regenerates its cached instances — an - RRULE-only update left a stale duplicate of the tapped occurrence on the - split day -- RRULE UNTIL values are written as the local end of day expressed in UTC - (instead of a flat `T235959Z`), so recurrences can't leak an extra day in - timezones ahead of UTC -- `versionName`/`versionCode` bumped to 1.3.0 / 11 +- Splitting a series no longer leaves a duplicate occurrence +- Recurrence end dates no longer leak an extra day east of UTC ## [1.2.1] — 2026-06-11 ### Added -- Optional event-form fields with user-controlled defaults: reminders, - availability (busy/free), and visibility (default/public/private/ - confidential) joined location and description as form sections. Settings - gained a "New event form" section choosing which show by default; the rest - unfold via a "More fields" picker -- Reminders editor: stacked rows with right-bound remove, full-width add - action; the picker offers one-tap presets and a custom amount + unit - (minutes/hours/days/weeks) step -- `OptionCard` — the app's standard selection-dialog row (full-width tonal - card, optional icon + supporting line, highlighted selection). All dialogs - (calendar, visibility, more-fields, reminder presets, recurring-delete) - now use it; radio-row dialogs are retired +- Optional event form fields for reminders, availability and visibility +- Reminders editor with presets and custom amounts +- Consistent card-style selection dialogs ### Changed -- Event form redesigned onto the detail screen's design system: tonal cards - with gutter icons (top-aligned on tall cards), borderless inline text - fields, calendar-coloured accent bar under the title, no dividers, no - top-bar title; placeholders render clearly fainter than input -- M3 Expressive motion: the theme now provides a MotionScheme - (`MaterialExpressiveTheme`, standard springs — expressive bounce reviewed - as overdone), the FAB stack and "more fields" reveals animate on theme - springs -- The jump-to-today slide is direction-aware (future → today slides in from - the left, past → from the right) -- `versionName`/`versionCode` bumped to 1.2.1 / 10 +- Redesigned event form +- Expressive motion for the FAB and form reveals +- Jump-to-today slide follows direction ### Fixed -- The keyboard no longer pans the whole event form; the screen stays - anchored and the focused field scrolls into view (`adjustResize` + - `imePadding`) +- Keyboard no longer pans the whole event form ## [1.2.0] — 2026-06-11 ### Added -- Create events (milestone 2, slice 2): - - A "+" FAB on the month, week, and day views opens a new full-screen event - form, prefilled with the visible day (today at the next full hour, or - 09:00 on other days) - - The form covers title, all-day toggle, start/end with Material 3 date and - time pickers (moving the start drags the end along, preserving duration), - target calendar, location, and description - - The calendar picker offers only writable calendars and preselects the one - you last created an event in - - Validation on save ("ends before it starts", no writable calendar), with - the same contextual write-permission upgrade as delete - - All-day events are stored provider-correctly (UTC midnights, exclusive - end), timed events in the device time zone +- Create events with a new event form from the "+" button ### Changed -- The jump-to-today pill now stacks above the new "+" FAB instead of being - the only floating action -- `versionName`/`versionCode` bumped to 1.2.0 / 9 +- Jump-to-today pill sits above the "+" button ## [1.1.0] — 2026-06-11 ### Added -- Write foundation (milestone 2, slice 1): Calendula can now **delete events**. - - Delete action on the event detail screen, with a confirmation dialog; - recurring events choose between "Only this event" (a cancelled exception, - so the rest of the series survives) and "All events in the series" - - `WRITE_CALENDAR` permission: onboarding asks for read+write in one system - dialog, but only read access is required — declining write keeps the app - fully usable read-only. Existing v1.0 installs are asked for the write - upgrade in place, on their first delete - - Read-only calendars (WebCal subscriptions, birthday calendars, …) are - detected via `CALENDAR_ACCESS_LEVEL` and show no edit/delete actions at all +- Delete events, including single occurrences of recurring ones ### Changed -- Onboarding copy no longer claims "read-only"; it now says your data stays on - the device (still no internet permission, still zero telemetry) -- The placeholder Edit button on the detail screen (a no-op since v0.4) is - removed until editing ships in a later slice -- `versionName`/`versionCode` bumped to 1.1.0 / 8 +- Onboarding no longer claims the app is read-only +- Removed the placeholder Edit button ## [1.0.0] — 2026-06-11 -First public release. Calendula is a read-only, Material 3 Expressive calendar -that lives entirely on top of Android's `CalendarContract` — every calendar -synced to the device (CalDAV via DAVx5, Google, local, WebCal, …) shows up -automatically, with zero telemetry and no internet permission. +First public release: a Material 3 Expressive calendar on top of Android's `CalendarContract`. ### Highlights (accumulated across v0.1 → v0.6) -- Month, week, and day views with a view switcher, swipe navigation, and - Loading / Failure / Success states on every screen -- Full-screen event detail surfacing every readable `CalendarContract` field — - times, recurrence (humanised), location, description (with tappable links), - attendees + roles + your own response, reminders, status, availability, - access level, and foreign time zones -- Per-calendar visibility filter (grouped by account, persisted) and a Settings - screen (theme, Material You dynamic colour, week start, app language) -- Material 3 Expressive first-run onboarding for calendar access -- German + English localization throughout +- Month, week and day views +- Full event detail screen +- Per-calendar visibility filter and Settings +- First-run onboarding for calendar access +- German and English translations ### Changed -- `versionName`/`versionCode` bumped to 1.0.0 / 7 +- Version bumped to 1.0.0 ## [0.6.0] — 2026-06-11 ### Added -- Full event read (v0.6): the detail screen now surfaces every readable - `CalendarContract` field that V1 had been dropping — - - **Reminders** — each configured lead time, humanised ("10 minutes before", - "1 day before", "At time of event"), read from `CalendarContract.Reminders` - - **Status** — Tentative / Cancelled chip under the title; a cancelled event - also strikes through its title (Confirmed shows no chip) - - **Availability** — a "Free" pill pinned top-right of the title when the - event doesn't block your time (`Events.AVAILABILITY`, the iCal TRANSP - field); the default "Busy" is left implicit to avoid noise on every event - - **Access level** — a Private / Confidential chip when the event isn't public - - **Attendee role** — organizer / optional / resource badge under each - attendee, plus the device user's own response ("Your response: …") from - `Events.SELF_ATTENDEE_STATUS` - - **Time zone** — shown only for timed events pinned to a zone other than the - device's, so cross-zone events read unambiguously - - **Linked URLs** — http(s) links in the description are now tappable -- Domain model rounded out with `Reminder`, `EventStatus`, `Availability`, - `AccessLevel`, `AttendeeRelationship`, `AttendeeType`, and the attendee/self - status fields; mappers + unit tests cover every new column's integer codes +- Event details show reminders, status, availability, access level, roles and time zone ### Changed -- Redesigned the first-run grant-access screen — the onboarding a new user - sees. Material 3 Expressive layout: branded launcher-mark hero, an app-name - eyebrow, a benefit-led headline, three trust rows (on-device, every calendar, - no tracking) with tonal icon chips, a full-width filled CTA with a trailing - arrow, and a "Read-only · no internet permission" footnote (the app declares - only `READ_CALENDAR`). The denied/recovery state shares the same shell with a - lock-badged hero and Open-settings / Try-again actions -- `versionName`/`versionCode` bumped to 0.6.0 / 6 +- Redesigned first-run onboarding screen ### Notes -- A dedicated event **URL** field was dropped from scope: `CalendarContract` - has no `Events.URL` column (only `CUSTOM_APP_URI`, an app deep-link), so URLs - are surfaced by linkifying the description instead +- Description links are tappable instead of a separate URL field ## [0.5.0] — 2026-06-10 ### Added -- Calendar filter (M3): the navigation drawer now hosts the calendar list - inline — every calendar grouped by account, each with a colour swatch and a - visibility switch. Hiding a calendar is persisted app-side (DataStore, - separate from the system VISIBLE flag) and applied centrally in the - repository, so month/week/day re-filter live the moment a switch flips. - The drawer was trimmed to just Today, the calendar filter, and Settings - (the stubbed jump-to-date entry was removed; jump-to-date was later cut - from scope entirely) -- Settings (M4): a full-screen destination with - - **Appearance** — theme (System / Light / Dark), Material You dynamic colour - (auto-disabled below Android 12), week start (Automatic / Monday / Sunday) - - **Language** — app language (System / Deutsch / English) via per-app - locales, persisted across cold starts down to Android 10 - - **About** — version, license, and a link to the source on Gitea -- Week-start preference now drives the month grid and week view; "Automatic" - follows the active locale (Monday in DE, Sunday in en-US) +- Hide or show calendars from the navigation drawer +- Settings screen for theme, dynamic color, week start, language and About +- Week start setting applies to month and week views ### Changed -- Theme is driven by one activity-scoped settings source, so a theme or - dynamic-colour change applies app-wide immediately -- `versionName`/`versionCode` bumped to 0.5.0 / 5 (the in-repo version had - lagged behind the release tags); the About screen reads it directly +- Theme changes apply app-wide immediately ## [0.4.0] — 2026-06-10 ### Added -- Event detail (S4): full-screen destination (MD3 list→detail, not a bottom - sheet) opened by tapping an event in the week/day timeline — title with a - calendar-colour accent line, a card per field (when, calendar, location, - description, attendees, recurrence) with leading icons, location tap opens a - maps intent, Loading/Failure/Success states, slide-in/out over the calendar -- Human-readable recurrence: RRULE rendered as e.g. "Every week on _Tue_ and - _Thu_ until 31 Dec 2026" (FREQ/INTERVAL/BYDAY/UNTIL/COUNT, abbreviated + - italicised day names, localized list formatting), with a generic fallback -- Month → day navigation: tapping a day cell opens the day view on that date +- Event detail screen +- Readable recurrence descriptions +- Tap a month day to open its day view ### Fixed -- Recurring events failed to open in the detail view: the series row stores - DURATION instead of DTEND, so the mapper dropped it (EventNotFound). The - detail now keeps such events and shows the tapped occurrence's own times - (from CalendarContract.Instances) instead of the series start +- Recurring events open in the detail view ## [0.3.0] — 2026-06-10 ### Added -- Month view (S1): Material 3 Expressive card-per-day grid (only the current - month's weeks; neighbouring days left blank), per-day event dots with "+N" - overflow, today emphasised via `primaryContainer`, spring-based press - feedback from the active motion scheme, swipe + drawer navigation, - Loading/Failure/Success states -- Week view (S2): vertical time schedule with overlap-resolved lanes, - separate all-day strip, midnight-spanning events clipped per day, swipe - navigation, Loading/Failure/Success states -- Day view (S3): single-column slice of the week schedule reusing its - overlap-lane layout, per-day swipe navigation, noon-centred scroll that - persists across swipes, animated all-day strip, compact top bar with the - full date, Loading/Failure/Success states -- Functional view-switcher (M1) cycling Month ↔ Week ↔ Day -- Shared calendar UI building blocks in `ui/common/` (navigation drawer, - failure screen, view-switcher pill, color pastelizer, observable locale) +- Month view +- Week view +- Day view +- View switcher for Month, Week and Day ### Removed -- Throwaway debug screen — superseded by the month view +- Debug screen ## [0.2.1] — 2026-06-09 ### Changed -- Regenerated the F-Droid catalog `icon.png` (512x512, both locales) so it - is pixel-faithful to the on-device adaptive launcher icon: same slate - background (`#5C6B7A`), off-white mark (`#FAF6F0`), and the foreground - group transform (`scale 0.5`, pivot `114,108`, translate `2,8`) baked in. -- Added `design/icon/calendula_launcher.svg` — the composed full-bleed - icon (background + transformed mark) as the single source of truth for - store/F-Droid renders. +- F-Droid icon matches the launcher icon ## [0.2.0] — 2026-06-08 ### Added -- Domain models for calendars, event instances, event detail, attendees -- `CalendarContract`-backed `CalendarRepository` with `ContentObserver`-driven live updates -- DataStore preference for app-side hidden-calendar visibility -- `READ_CALENDAR` permission flow (rationale + denied recovery + system-settings shortcut) -- Wegwerfbarer Debug-Screen: zeigt alle Kalender + die nächsten 50 Termine ab heute -- Hilt-Wiring für Data-Layer (Repository, DataSource, DataStore, IO-Dispatcher) -- Unit-Tests für Cursor-Mapping (alle §8-Defensiv-Cases), Repository-Flows mit Turbine, DataStore round-trip -- Instrumented smoke test against the real CalendarContract provider +- Calendar access and live calendar data +- Calendar permission flow ### Changed -- Redesigned launcher icon: line-art calendar with a stylized "1" inside - (kalendae reference) and a small calendula bloom badge in the - bottom-right corner. Replaces the simple "1"-only foreground from - v0.1.0. Source SVG checked in at `design/icon/calendula_mark.svg`, - also used to regenerate the F-Droid catalog `icon.png` (512x512) - per locale. +- Redesigned launcher icon ## [0.1.1] — 2026-06-08 ### Fixed -- F-Droid metadata format: renamed locale dirs from `de/` to `de-DE/`, - `short_description.txt` to `summary.txt`, `full_description.txt` to - `description.txt` (fastlane format that fdroidserver actually reads, - matching the working HouseHoldKeaper convention) -- Added `icon.png` (512x512) per locale; fdroidserver does NOT - auto-extract icons from APKs that only contain XML adaptive icons - (which is what minSdk-29 apps produce), so the app was rendered - blank-iconed in F-Droid clients +- App name, description and icon show correctly in F-Droid ### Changed -- CI pipeline cleanup: `lintDebug`/`testDebugUnitTest` instead of full - `lint`/`test` (cuts ~50% of lint work since release variant lint is - redundant for V1 single-variant build) -- Release workflow drops the lint step from its CI-sanity job since - the same lint already ran via `ci.yaml` when the underlying commit - hit main +- CI cleanup ## [0.1.0] — 2026-06-08 ### Added -- Initial project scaffold (Gradle Kotlin DSL, Version Catalog, Hilt, DataStore) -- Material 3 Expressive theme with Dynamic Color (API 31+) and slate-derived fallback -- Adaptive launcher icon — stylized "1" on slate squircle (references *kalendae*) -- German + English localization infrastructure -- Permission declaration for `READ_CALENDAR` (no UI flow yet — that's Plan 02) -- Gitea CI workflow: lint, unit tests, debug build, Trivy scan -- Gitea release workflow: signed release APK + F-Droid metadata sync to Hetzner -- F-Droid metadata stubs (DE + EN short/full descriptions) -- `.planning/` project-tracking documents +- Initial project setup with Material 3 Expressive theme +- Launcher icon +- German and English localization [#1]: https://codeberg.org/jlmakiola/calendula/issues/1 [#2]: https://codeberg.org/jlmakiola/calendula/issues/2 @@ -1993,3 +937,27 @@ automatically, with zero telemetry and no internet permission. [#493]: https://codeberg.org/jlmakiola/calendula/issues/493 [#494]: https://codeberg.org/jlmakiola/calendula/issues/494 [#501]: https://codeberg.org/jlmakiola/calendula/issues/501 +[#143]: https://codeberg.org/jlmakiola/calendula/issues/143 +[#145]: https://codeberg.org/jlmakiola/calendula/issues/145 +[#147]: https://codeberg.org/jlmakiola/calendula/issues/147 +[#171]: https://codeberg.org/jlmakiola/calendula/issues/171 +[#240]: https://codeberg.org/jlmakiola/calendula/issues/240 +[#270]: https://codeberg.org/jlmakiola/calendula/issues/270 +[#272]: https://codeberg.org/jlmakiola/calendula/issues/272 +[#303]: https://codeberg.org/jlmakiola/calendula/issues/303 +[#325]: https://codeberg.org/jlmakiola/calendula/issues/325 +[#340]: https://codeberg.org/jlmakiola/calendula/issues/340 +[#365]: https://codeberg.org/jlmakiola/calendula/issues/365 +[#411]: https://codeberg.org/jlmakiola/calendula/issues/411 +[#429]: https://codeberg.org/jlmakiola/calendula/issues/429 +[#459]: https://codeberg.org/jlmakiola/calendula/issues/459 +[#464]: https://codeberg.org/jlmakiola/calendula/issues/464 +[#481]: https://codeberg.org/jlmakiola/calendula/issues/481 +[#502]: https://codeberg.org/jlmakiola/calendula/issues/502 +[#543]: https://codeberg.org/jlmakiola/calendula/issues/543 +[#514]: https://codeberg.org/jlmakiola/calendula/issues/514 +[#515]: https://codeberg.org/jlmakiola/calendula/issues/515 +[#516]: https://codeberg.org/jlmakiola/calendula/issues/516 +[#517]: https://codeberg.org/jlmakiola/calendula/issues/517 +[#518]: https://codeberg.org/jlmakiola/calendula/issues/518 +[#530]: https://codeberg.org/jlmakiola/calendula/issues/530 diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 395e79a5..29082c9c 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -32,8 +32,8 @@ android { // (up to 2.22.3: 2.22.3 -> 22203; from 2.22.4: 2.23.0-beta.1 -> 2230001, // 2.22.4 -> 2220499), and CI fails if the committed one doesn't match. // See docs/RELEASING.md. - versionCode = 2240399 - versionName = "2.24.3" + versionCode = 2250099 + versionName = "2.25.0" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } @@ -177,11 +177,13 @@ dependencies { implementation("de.jeanlucmakiola.floret:core-crash") implementation("de.jeanlucmakiola.floret:core-di") implementation("de.jeanlucmakiola.floret:core-prefs") + implementation("de.jeanlucmakiola.floret:core-backup") implementation("de.jeanlucmakiola.floret:core-reminders") implementation("de.jeanlucmakiola.floret:core-android") implementation("de.jeanlucmakiola.floret:identity") implementation("de.jeanlucmakiola.floret:components") implementation("de.jeanlucmakiola.floret:glance") + implementation("de.jeanlucmakiola.floret:ring") implementation(libs.kotlinx.coroutines.core) debugImplementation(libs.androidx.ui.tooling) diff --git a/app/src/androidTest/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositorySmokeTest.kt b/app/src/androidTest/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositorySmokeTest.kt index d6eea3f1..308ca955 100644 --- a/app/src/androidTest/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositorySmokeTest.kt +++ b/app/src/androidTest/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositorySmokeTest.kt @@ -37,6 +37,7 @@ class CalendarRepositorySmokeTest { CalendarPrefs(store), SettingsPrefs(store), Dispatchers.IO, + AndroidSyncRequester(context), ) } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index b272d8e9..27cd8113 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -41,10 +41,18 @@ --> - + + + + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/CalendulaApp.kt b/app/src/main/java/de/jeanlucmakiola/calendula/CalendulaApp.kt index 2a5a2b36..0661c415 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/CalendulaApp.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/CalendulaApp.kt @@ -1,8 +1,10 @@ package de.jeanlucmakiola.calendula import android.app.Application +import androidx.work.Configuration import dagger.hilt.android.EntryPointAccessors import dagger.hilt.android.HiltAndroidApp +import de.jeanlucmakiola.calendula.data.backup.BackupChangeJob import de.jeanlucmakiola.calendula.data.backup.BackupScheduler import de.jeanlucmakiola.calendula.data.calendar.CalendarVisibilityReconciler import de.jeanlucmakiola.calendula.data.backup.BackupWorker @@ -27,7 +29,11 @@ import kotlinx.coroutines.launch * in AndroidManifest.xml. Hilt initializes its component graph here. */ @HiltAndroidApp -class CalendulaApp : Application() { +class CalendulaApp : Application(), Configuration.Provider { + + /** Keeps WorkManager's JobScheduler ids clear of [BackupChangeJob]'s. */ + override val workManagerConfiguration: Configuration = + Configuration.Builder().setJobSchedulerJobIdRange(0, BackupChangeJob.JOB_ID - 1).build() override fun onCreate() { super.onCreate() @@ -110,12 +116,7 @@ class CalendulaApp : Application() { val deps = EntryPointAccessors.fromApplication(this, BackupWorker.Deps::class.java) CoroutineScope(SupervisorJob() + Dispatchers.Default).launch { val prefs = deps.settingsPrefs() - BackupScheduler.apply( - context = this@CalendulaApp, - enabled = prefs.autoBackupEnabled.first(), - intervalMinutes = prefs.autoBackupIntervalMinutes.first(), - hasFolder = prefs.autoBackupFolderUri.first() != null, - ) + BackupScheduler.reconcile(this@CalendulaApp, prefs) } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/MainActivity.kt b/app/src/main/java/de/jeanlucmakiola/calendula/MainActivity.kt index 182a469d..346d4755 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/MainActivity.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/MainActivity.kt @@ -24,6 +24,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.core.content.IntentCompat import androidx.core.net.toUri +import androidx.core.os.BundleCompat import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.lifecycleScope @@ -39,6 +40,7 @@ import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.buildInsertEventForm import de.jeanlucmakiola.calendula.domain.sharedTextOrNull import de.jeanlucmakiola.calendula.ui.ExternalRequests +import de.jeanlucmakiola.calendula.ui.LeaveTarget import de.jeanlucmakiola.calendula.ui.InsertRequest import de.jeanlucmakiola.calendula.ui.RootScreen import de.jeanlucmakiola.calendula.ui.common.LocalShowHourGrid @@ -67,7 +69,10 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.launch import kotlinx.datetime.LocalDate +import kotlinx.datetime.LocalDateTime +import kotlinx.datetime.LocalTime import kotlinx.datetime.TimeZone +import kotlinx.datetime.toInstant import kotlinx.datetime.toLocalDateTime import kotlin.time.Clock import kotlin.time.Instant @@ -89,6 +94,10 @@ class MainActivity : AppCompatActivity() { insertFormOpen = false if (launchedForInsert) finish() }, + onLeave = { + homeOnReturn = moveTaskToBack(true) + homeOnReturn + }, ) // Whether such a form is still open. Only then does a recreation re-read the @@ -99,6 +108,9 @@ class MainActivity : AppCompatActivity() { // app that asked instead of leaving the calendar on top of it. private var launchedForInsert = false + // Back left a widget's day or event for the home screen; the next start shows the home view. + private var homeOnReturn = false + // A captured crash report awaiting the user's decision, surfaced as a dialog // over the calendar on the next launch (the single-crash path). A startup // crash-loop is handled out of band, before setContent — see below. @@ -147,7 +159,10 @@ class MainActivity : AppCompatActivity() { // specific event is what made a single reminder or widget tap re-open // that event on every later launch, an error screen once the event had // been deleted (#309); the user left it long ago, and the activity - // restores where they actually were along with its saved state. + // restores where they actually were along with its saved state. Every + // widget/shortcut navigation is held back the same way; one still pending + // at the recreation is restored from the saved state instead, so it's the + // request that actually arrived last, not the launch intent's (#530). // // Only those channels are held back. An .ics import or a prefilled // create form keeps no saved state of its own, so re-reading the intent @@ -159,8 +174,15 @@ class MainActivity : AppCompatActivity() { requests.detailKey = intent.detailKeyOrNull() ?: intent.viewEventKeyOrNull() requests.editKey = intent.editEventKeyOrNull() } - requests.nav = intent.navRequestOrNull() - ?.takeUnless { replaying && it is WidgetNavRequest.OpenEvent } + requests.nav = if (replaying) { + savedInstanceState?.let { BundleCompat.getSerializable(it, KEY_PENDING_NAV, WidgetNavRequest::class.java) } + } else { + intent.navRequestOrNull() + } + requests.leaveTarget = savedInstanceState?.let { + BundleCompat.getSerializable(it, KEY_LEAVE_TARGET, LeaveTarget::class.java) + } + homeOnReturn = savedInstanceState?.getBoolean(KEY_HOME_ON_RETURN) == true requests.importUri = intent.importUriOrNull() val insertOpenBefore = savedInstanceState?.getBoolean(KEY_INSERT_FORM_OPEN) == true requests.insert = intent.createRequestOrNull()?.takeIf { !replaying || insertOpenBefore } @@ -271,10 +293,22 @@ class MainActivity : AppCompatActivity() { override fun onStart() { super.onStart() + // Reset only now, so the screen doesn't change while the task animates away. + // A request arriving with this start (onNewIntent comes after) opens over it. + if (homeOnReturn) { + homeOnReturn = false + requests.resetToHome = true + } // Changes made while we were away may never have notified us (#364). calendarRepository.refresh() } + override fun onUserLeaveHint() { + super.onUserLeaveHint() + // Once the user has left, a later return is no longer the widget's day or event. + requests.leaveTarget = null + } + override fun onResume() { super.onResume() // Reaching a running UI means startup succeeded; reset the loop trail. @@ -286,6 +320,9 @@ class MainActivity : AppCompatActivity() { super.onSaveInstanceState(outState) outState.putBoolean(KEY_INSERT_FORM_OPEN, insertFormOpen) outState.putBoolean(KEY_LAUNCHED_FOR_INSERT, launchedForInsert) + outState.putSerializable(KEY_PENDING_NAV, requests.nav) + outState.putSerializable(KEY_LEAVE_TARGET, requests.leaveTarget) + outState.putBoolean(KEY_HOME_ON_RETURN, homeOnReturn) } override fun onNewIntent(intent: Intent) { @@ -365,6 +402,7 @@ class MainActivity : AppCompatActivity() { description = getStringExtra(CalendarContract.Events.DESCRIPTION), location = getStringExtra(CalendarContract.Events.EVENT_LOCATION), rrule = getStringExtra(CalendarContract.Events.RRULE), + calendarId = calendarIdExtraOrNull(), zone = TimeZone.currentSystemDefault(), now = Clock.System.now(), ) @@ -425,6 +463,15 @@ class MainActivity : AppCompatActivity() { private fun Intent.longExtraOrNull(key: String): Long? = if (hasExtra(key)) getLongExtra(key, 0L) else null + /** The calendar an insert intent names (#429); callers pass it as an int, a long or a string. */ + @Suppress("DEPRECATION") + private fun Intent.calendarIdExtraOrNull(): Long? = + when (val value = extras?.get(CalendarContract.Events.CALENDAR_ID)) { + is Number -> value.toLong() + is String -> value.trim().toLongOrNull() + else -> null + }?.takeIf { it > 0 } + /** * The date a launcher/clock date tap points at, parsed from the AOSP calendar * "view time" intent: ACTION_VIEW on `content://com.android.calendar/time/ @@ -443,9 +490,9 @@ class MainActivity : AppCompatActivity() { } private fun Intent.navRequestOrNull(): WidgetNavRequest? { - // An external date tap (launcher/clock) has no widget source, so it opens - // the day view rooted over the default home view (OpenDate source = null). - calendarTimeDateOrNull()?.let { return WidgetNavRequest.OpenDate(it.toString(), source = null) } + // An external date tap (launcher/clock) opens the day view over the default + // home view, and backs out to it. + calendarTimeDateOrNull()?.let { return WidgetNavRequest.OpenDate(it.toString(), fromWidget = false) } // A widget header tap: open a top-level view with no date drill-in. The // empty string carried by [openViewIntent] means "the default home view". if (hasExtra(EXTRA_OPEN_VIEW)) { @@ -468,8 +515,8 @@ class MainActivity : AppCompatActivity() { endMillis = getLongExtra(EXTRA_END_MILLIS, 0L), source = source, ) - source != null && getStringExtra(EXTRA_DATE_ISO) != null -> - WidgetNavRequest.OpenDate(getStringExtra(EXTRA_DATE_ISO)!!, source) + getStringExtra(EXTRA_DATE_ISO) != null -> + WidgetNavRequest.OpenDate(getStringExtra(EXTRA_DATE_ISO)!!, fromWidget = true) else -> null } } @@ -551,6 +598,9 @@ class MainActivity : AppCompatActivity() { private val CALENDAR_EXTENSIONS = listOf(".ics", ".vcs") private const val KEY_INSERT_FORM_OPEN = "insert_form_open" private const val KEY_LAUNCHED_FOR_INSERT = "launched_for_insert" + private const val KEY_PENDING_NAV = "pending_nav" + private const val KEY_LEAVE_TARGET = "leave_target" + private const val KEY_HOME_ON_RETURN = "home_on_return" private const val EXTRA_EVENT_ID = "de.jeanlucmakiola.calendula.extra.EVENT_ID" private const val EXTRA_BEGIN_MILLIS = "de.jeanlucmakiola.calendula.extra.BEGIN" @@ -589,17 +639,13 @@ class MainActivity : AppCompatActivity() { } /** - * Open the day view anchored on [date], drilled in over the launching - * widget's [source] view (home-screen widgets). Backing out of the day - * returns to [source], then to the default home view. + * Open the day view anchored on [date] from a home-screen widget; backing + * out of the day returns to the home screen (#530). */ - fun openDateIntent(context: Context, date: LocalDate, source: CalendarView): Intent = + fun openDateIntent(context: Context, date: LocalDate): Intent = Intent(context, MainActivity::class.java).apply { - // The source is part of the URI so widgets of different kinds - // tapping the same date don't share one PendingIntent. - data = "calendula://date/$date/${source.name}".toUri() + data = "calendula://date/$date".toUri() putExtra(EXTRA_DATE_ISO, date.toString()) - putExtra(EXTRA_SOURCE_VIEW, source.name) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } @@ -620,6 +666,20 @@ class MainActivity : AppCompatActivity() { putExtra(EXTRA_SOURCE_VIEW, source.name) } + /** + * Open the day view on [date] over the default home view — the daily + * summary's tap (#459). Spoken as the system's own "view time" intent, + * at the day's local noon, so it lands on the path a clock tap takes. + */ + fun openDayIntent(context: Context, date: LocalDate): Intent { + val noon = LocalDateTime(date, LocalTime(12, 0)) + .toInstant(TimeZone.currentSystemDefault()) + .toEpochMilliseconds() + return Intent(Intent.ACTION_VIEW, "content://$CALENDAR_PROVIDER_HOST/time/$noon".toUri()) + .setClass(context, MainActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + } + /** Open the create-event form prefilled for [date] (home-screen widgets). */ fun openCreateIntent(context: Context, date: LocalDate): Intent = Intent(context, MainActivity::class.java).apply { diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/backup/AutoBackup.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/backup/AutoBackup.kt index 8c504d93..2852e9b7 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/backup/AutoBackup.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/backup/AutoBackup.kt @@ -5,18 +5,23 @@ import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context +import android.net.Uri import android.os.Build import android.util.Log import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.net.toUri +import androidx.work.Constraints import androidx.work.CoroutineWorker import androidx.work.ExistingPeriodicWorkPolicy import androidx.work.ExistingWorkPolicy import androidx.work.OneTimeWorkRequestBuilder import androidx.work.PeriodicWorkRequestBuilder +import androidx.work.WorkInfo import androidx.work.WorkManager import androidx.work.WorkerParameters +import androidx.work.await +import androidx.work.workDataOf import dagger.hilt.EntryPoint import dagger.hilt.InstallIn import dagger.hilt.android.EntryPointAccessors @@ -25,50 +30,139 @@ import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository import de.jeanlucmakiola.calendula.data.ics.IcsExporter import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs +import de.jeanlucmakiola.calendula.domain.backup.BackupFilePlan +import de.jeanlucmakiola.calendula.domain.backup.BackupTarget +import de.jeanlucmakiola.calendula.domain.backup.backedUp +import de.jeanlucmakiola.calendula.domain.backup.backupFingerprint +import de.jeanlucmakiola.calendula.domain.backup.backupRunLatestOnly +import de.jeanlucmakiola.calendula.domain.backup.backupTargets +import de.jeanlucmakiola.calendula.domain.backup.inBackupOrder +import de.jeanlucmakiola.calendula.domain.backup.latestHeldElsewhere +import de.jeanlucmakiola.calendula.domain.backup.latestFileName +import de.jeanlucmakiola.calendula.domain.backup.latestLedgerKey +import de.jeanlucmakiola.calendula.domain.backup.needsRefresh +import de.jeanlucmakiola.calendula.domain.backup.planBackupFiles +import de.jeanlucmakiola.calendula.domain.backup.replacedLatestCopies +import de.jeanlucmakiola.calendula.domain.backup.withFingerprint +import de.jeanlucmakiola.calendula.domain.backup.withLedgerEntry import de.jeanlucmakiola.calendula.domain.ics.IcsWriter import de.jeanlucmakiola.floret.android.hasPermission +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.flow.first +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import java.time.LocalDateTime import java.util.concurrent.TimeUnit +import kotlin.coroutines.cancellation.CancellationException import kotlin.time.Clock /** - * Schedules and runs the automatic periodic `.ics` backup of local calendars - * (issue #8). One-way export only — it mirrors the manual "Back up" into a - * user-chosen folder on an interval; it is not a sync. Stays INTERNET-free: - * everything is local provider reads + a local file write. + * Schedules and runs the automatic periodic `.ics` backup (issue #8) of the + * calendars the user picked (#147). One-way export only — it mirrors the manual + * "Back up" into a user-chosen folder on an interval; it is not a sync. Stays + * INTERNET-free: everything is local provider reads + local file writes. */ object BackupScheduler { private const val WORK_NAME = "auto-backup" private const val WORK_NAME_NOW = "auto-backup-now" + private const val WORK_NAME_CHANGE = "auto-backup-change" + internal const val KEY_CHANGE_RUN = "change_run" + + private val reconcileLock = Mutex() + + /** A watch that fired while the option was off: still pending until it finishes, but not re-armed. */ + private var watchDropped = false /** - * Reconcile the scheduled work with the current settings: enqueue a unique - * periodic request when backup is on and a folder is set, otherwise cancel - * it. WorkManager persists the request across reboots on its own. + * Reconcile the scheduled work with the saved settings: enqueue a unique + * periodic request when backup is on, a folder is set and the interval + * isn't switched off (#516), otherwise cancel it. WorkManager persists the request across reboots on its own. * - * The first run is delayed by one interval so it never overlaps an immediate - * [runNow] (two simultaneous writes would race and leave a "(1)" duplicate). + * The first run is delayed by one interval so it doesn't follow an immediate + * [runNow] with a near-identical copy. With backing up after changes on + * (#516), the change watch ([BackupChangeJob]) is armed unless it already + * waits; it doesn't survive a reboot, and this runs on every process start. + * Serialised and not cancellable, so quick toggles settle on the last one. */ - fun apply(context: Context, enabled: Boolean, intervalMinutes: Long, hasFolder: Boolean) { + suspend fun reconcile(context: Context, prefs: SettingsPrefs) = withContext(NonCancellable + Dispatchers.IO) { + reconcileLock.withLock { + try { + apply(context, prefs) + } catch (e: Exception) { + Log.w(TAG, "Scheduling the automatic backup failed", e) + } + } + } + + private suspend fun apply(context: Context, prefs: SettingsPrefs) { val workManager = WorkManager.getInstance(context) - if (!enabled || !hasFolder) { + fun stopWatching() { + BackupChangeJob.cancel(context) + workManager.cancelUniqueWork(WORK_NAME_CHANGE) + } + if (!prefs.autoBackupEnabled.first() || prefs.autoBackupFolderUri.first() == null) { workManager.cancelUniqueWork(WORK_NAME) // Also cancel any pending immediate run — otherwise a failing run-now // keeps retrying after the user has turned backup off. workManager.cancelUniqueWork(WORK_NAME_NOW) + stopWatching() return } - // WorkManager's own floor is 15 min; the UI floors the user choice at 30. - val interval = intervalMinutes.coerceAtLeast(15L) - val request = PeriodicWorkRequestBuilder(interval, TimeUnit.MINUTES) - .setInitialDelay(interval, TimeUnit.MINUTES) + if (prefs.autoBackupScheduled.first()) { + // WorkManager's own floor is 15 min; the UI floors the user choice at 30. + val interval = prefs.autoBackupIntervalMinutes.first().coerceAtLeast(15L) + val request = PeriodicWorkRequestBuilder(interval, TimeUnit.MINUTES) + .setInitialDelay(interval, TimeUnit.MINUTES) + .build() + workManager.enqueueUniquePeriodicWork( + WORK_NAME, + ExistingPeriodicWorkPolicy.UPDATE, + request, + ) + } else { + workManager.cancelUniqueWork(WORK_NAME) + } + if (!prefs.autoBackupOnChange.first()) { + stopWatching() + } else if (watchDropped || !BackupChangeJob.isPending(context)) { + // Replacing a waiting watch would drop the changes it has seen. + BackupChangeJob.schedule(context) + watchDropped = false + } + } + + /** + * The watch fired: queue a change run and arm the next watch, unless the + * option went off meanwhile. Under [reconcileLock], so it can't re-arm + * after a switch-off. + */ + internal suspend fun changed(context: Context, prefs: SettingsPrefs) = withContext(NonCancellable) { + reconcileLock.withLock { + // Re-armed even when queueing the run fails: a trigger fires only once. + var wanted = true + try { + wanted = prefs.autoBackupEnabled.first() && prefs.autoBackupFolderUri.first() != null && + prefs.autoBackupOnChange.first() + if (wanted) queueChangeRun(context) + } finally { + if (wanted) BackupChangeJob.schedule(context) + watchDropped = !wanted + } + } + } + + private suspend fun queueChangeRun(context: Context) { + val workManager = WorkManager.getInstance(context) + val states = workManager.getWorkInfosForUniqueWorkFlow(WORK_NAME_CHANGE).first().map { it.state } + val policy = changeRunPolicy(states) ?: return + val run = OneTimeWorkRequestBuilder() + .setConstraints(Constraints.Builder().setRequiresBatteryNotLow(true).build()) + .setInputData(workDataOf(KEY_CHANGE_RUN to true)) .build() - workManager.enqueueUniquePeriodicWork( - WORK_NAME, - ExistingPeriodicWorkPolicy.UPDATE, - request, - ) + workManager.enqueueUniqueWork(WORK_NAME_CHANGE, policy, run).await() } /** @@ -83,11 +177,25 @@ object BackupScheduler { OneTimeWorkRequestBuilder().build(), ) } + + private const val TAG = "BackupScheduler" } /** - * Exports the local calendars to `calendula-backup.ics` in the configured folder, - * overwriting the previous file. Pulls its collaborators through a Hilt + * How a fired change watch queues its run (#516), from the change runs' work + * [states]: a run that hasn't started yet will see the change anyway (null); + * one already going may have read too early, so the new one queues behind it. + */ +internal fun changeRunPolicy(states: List): ExistingWorkPolicy? = when { + states.any { it == WorkInfo.State.ENQUEUED || it == WorkInfo.State.BLOCKED } -> null + WorkInfo.State.RUNNING in states -> ExistingWorkPolicy.APPEND_OR_REPLACE + else -> ExistingWorkPolicy.REPLACE +} + +/** + * Exports the selected calendars into the configured folder — one dated file + * per calendar, or one combined file (#411) — then prunes each series down to + * the retention count. Pulls its collaborators through a Hilt * [EntryPoint] so it works under WorkManager's default (no-arg) worker factory — * no custom factory / Application wiring needed. Records the outcome for the * settings status line, and notifies after repeated failures. @@ -107,27 +215,267 @@ class BackupWorker( override suspend fun doWork(): Result { val deps = EntryPointAccessors.fromApplication(applicationContext, Deps::class.java) - val prefs = deps.settingsPrefs() - // Respect the toggle even for already-queued work: if backup was turned - // off, no-op (and don't retry) so a lingering run can't revive itself. - if (!prefs.autoBackupEnabled.first()) return Result.success() - val folder = prefs.autoBackupFolderUri.first() - ?: return Result.failure() // nothing to write to — leave scheduling to settings - val now = System.currentTimeMillis() - return try { - val events = deps.repository().exportEvents() - val content = IcsWriter().writeCalendar(events, Clock.System.now()) - deps.exporter().writeToFolder(folder.toUri(), BACKUP_FILE_NAME, content) - prefs.recordAutoBackupRun(success = true, atMillis = now) - Result.success() + val changeRun = inputData.getBoolean(BackupScheduler.KEY_CHANGE_RUN, false) + if (!changeRun) return backUp(deps, deps.settingsPrefs(), changeRun = false) + // A failed change run would fail the one queued behind it too. + try { + backUp(deps, deps.settingsPrefs(), changeRun = true) + } catch (e: CancellationException) { + throw e } catch (e: Exception) { - prefs.recordAutoBackupRun(success = false, atMillis = now) - if (prefs.autoBackupStatus.first().consecutiveFailures >= FAILURE_NOTIFY_THRESHOLD) { - notifyFailure(applicationContext) - } - Log.w(TAG, "Automatic backup failed", e) - Result.retry() + Log.w(TAG, "Backup after a change failed", e) } + return Result.success() + } + + /** + * One run under the shared lock, recorded for the status line. A change + * run (#516) refreshes only the stable copies and never retries. The + * failure notification comes once per failure streak, when it reaches + * [FAILURE_NOTIFY_THRESHOLD], and goes with the next success of any run. + */ + private suspend fun backUp(deps: Deps, prefs: SettingsPrefs, changeRun: Boolean): Result { + // One run at a time, or each would overwrite the other's ledger. + val outcome = runLock.withLock { + val now = System.currentTimeMillis() + // Respect the toggles even for already-queued work, so a lingering + // run can't revive itself. + if (!prefs.autoBackupEnabled.first()) return Result.success() + if (changeRun && !prefs.autoBackupOnChange.first()) return Result.success() + val folder = prefs.autoBackupFolderUri.first() ?: return Result.failure() + val outcome = try { + runBackup(deps, prefs, folder.toUri(), changeRun, prefs.autoBackupScheduled.first()) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Automatic backup failed", e) + RunOutcome.Failed + } + if (outcome != RunOutcome.NothingToDo) { + withContext(NonCancellable) { + prefs.recordAutoBackupRun(success = outcome == RunOutcome.Written, atMillis = now) + when { + outcome == RunOutcome.Written -> clearFailureNotification(applicationContext) + prefs.autoBackupStatus.first().consecutiveFailures == FAILURE_NOTIFY_THRESHOLD -> + notifyFailure(applicationContext) + } + } + } + outcome + } + // Only a run that wrote nothing retries: a retry rewrites every series. + return if (outcome == RunOutcome.Failed && !changeRun) Result.retry() else Result.success() + } + + /** [Blocked]: failed only on series no retry can back up, so it isn't retried. */ + private enum class RunOutcome { Written, PartlyFailed, Failed, Blocked, NothingToDo } + + /** How a stable copy's write went: under its own name, under one the provider picked, or not at all. */ + private enum class LatestWrite { Landed, Renamed, Failed } + + /** + * Writes each series and prunes it only once its new file has landed. A + * change run (#516) leaves the dated files and their retention to the + * schedule and rewrites only the stable copies whose calendars changed. + * With the interval off, no run writes dated files, so a series whose + * stable name a file of the user's holds counts as failed (a change run + * only when its content changed). + */ + private suspend fun runBackup( + deps: Deps, + prefs: SettingsPrefs, + folder: Uri, + changeRun: Boolean, + intervalOn: Boolean, + ): RunOutcome { + val latestOnly = backupRunLatestOnly(changeRun, intervalOn) + val repository = deps.repository() + val exporter = deps.exporter() + if (!applicationContext.hasPermission(Manifest.permission.READ_CALENDAR)) return RunOutcome.Failed + val all = repository.calendars().first() + val selection = prefs.autoBackupSelection.first() + val combined = prefs.autoBackupCombined.first() + if (all.none(selection::selects)) return RunOutcome.NothingToDo + prefs.adoptLegacyBackupFile() + val listing = exporter.listFolder(folder) + val ledger = prefs.autoBackupLedger.first() + // A listing still loading can't tell a gone file from a late one. + val existing = if (listing.complete) listing.files.keys else listing.files.keys + ledger.values.flatten() + val targets = backupTargets(all.filter(selection::selects), combined, ledger, existing) + if (targets.isEmpty()) return RunOutcome.NothingToDo + val stamp = Clock.System.now() + val fingerprints = prefs.autoBackupFingerprints.first() + suspend fun export(target: BackupTarget): String? = try { + val events = repository.exportEvents(target.calendarIds).inBackupOrder() + IcsWriter().writeCalendar(events, stamp, target.calendarName) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Reading one series failed", e) + null + } + fun fingerprintOf(target: BackupTarget, text: String) = + backupFingerprint(text, latestFileName(target.baseName)) + // Hashes only serve change runs; without them a stale one could pass later. + val trackHashes = prefs.autoBackupOnChange.first() + if (!trackHashes && fingerprints.isNotEmpty()) prefs.updateAutoBackupFingerprints(folder.toString()) { emptyMap() } + // A change run hashes first (null: unreadable) and leaves the folder alone when nothing moved. + val preHashes: Map = if (changeRun) { + targets.associate { target -> target.key to export(target)?.let { fingerprintOf(target, it) } } + } else { + emptyMap() + } + // With the interval off, unless a stable copy went missing: no scheduled run would restore it. + fun copyListed(target: BackupTarget) = latestFileName(target.baseName) in listing.files || + ledger[latestLedgerKey(target.key)].orEmpty().any { it in listing.files } + if (changeRun && + targets.all { preHashes[it.key].let { hash -> hash != null && hash == fingerprints[it.key] } } && + (intervalOn || !listing.complete || targets.all(::copyListed)) + ) { + return RunOutcome.NothingToDo + } + val plans = planBackupFiles( + targets = targets, + ledger = ledger, + existing = existing, + at = LocalDateTime.now(), + keep = prefs.autoBackupKeep.first(), + ) + val liveKeys = all.map { it.id.toString() }.toSet() + suspend fun record(key: String, files: List) = + prefs.updateAutoBackupLedger(folder.toString()) { withLedgerEntry(it, key, files, liveKeys) } + + suspend fun writeDated(plan: BackupFilePlan, bytes: ByteArray): Boolean = try { + val name = exporter.writeToFolder(folder, listing, plan.fileName, bytes) + record(plan.target.key, plan.prune + plan.keep + name) + val undeleted = exporter.deleteFromFolder(listing, plan.prune) + record(plan.target.key, plan.prune.filter { it in undeleted } + plan.keep + name) + true + } catch (e: Exception) { + Log.w(TAG, "Backup of one series failed", e) + false + } + + // An old copy goes only once the new one has landed. + suspend fun writeLatest(plan: BackupFilePlan, bytes: ByteArray, fingerprint: String): LatestWrite { + val target = plan.target + val latest = checkNotNull(plan.latestName) + var landed: String? = null + try { + val latestKey = latestLedgerKey(target.key) + if (trackHashes && target.key in fingerprints) { + prefs.updateAutoBackupFingerprints(folder.toString()) { it - target.key } + } + landed = exporter.writeToFolder(folder, listing, latest, bytes) + // A provider that renamed it leaves a copy to clean up next + // run; the intended name stays ours only if it already was. + val ownsLatest = landed == latest || latest in ledger[latestKey].orEmpty() + val current = listOfNotNull(landed, latest.takeIf { ownsLatest }) + // A hand-off stays on record only until its new owner claimed it. + suspend fun recordLatest(stale: List, landedFingerprint: String? = null) = + prefs.updateAutoBackupLedger( + folder.toString(), + fingerprints = landedFingerprint?.let { hash -> + { old -> withFingerprint(old, target.key, hash, liveKeys) } + }, + ) { + val pending = plan.handOff - it.latestHeldElsewhere(target.key) + withLedgerEntry(it, latestKey, stale + pending + current, liveKeys) + } + recordLatest(plan.staleLatest, fingerprint.takeIf { trackHashes }) + val staleLeft = exporter.deleteFromFolder(listing, plan.staleLatest) + recordLatest(plan.staleLatest.filter { it in staleLeft }) + } catch (e: Exception) { + Log.w(TAG, "Stable copy of one series failed", e) + } + return when (landed) { + null -> LatestWrite.Failed + latest -> LatestWrite.Landed + else -> LatestWrite.Renamed + } + } + + // A copy blocked by a file of the user's keeps its hash, so a later change run can stop early. + suspend fun rememberBlocked(plan: BackupFilePlan, hash: String) { + val key = plan.target.key + if (plan.latestName == null && trackHashes && fingerprints[key] != hash) { + prefs.updateAutoBackupFingerprints(folder.toString()) { withFingerprint(it, key, hash, liveKeys) } + } + } + + var written = 0 + var failed = 0 + var blocked = 0 + var stillBlocked = 0 + val landedLatest = mutableSetOf() + for (plan in plans) { + val target = plan.target + val hash = if (changeRun) { + preHashes[target.key] ?: run { + failed++ + continue + } + } else { + null + } + if (!plan.backedUp(intervalOn)) { + // Its hash still goes on record, so a later change run can stop early. + val blockedHash = hash ?: if (trackHashes) export(target)?.let { fingerprintOf(target, it) } else null + blockedHash?.let { rememberBlocked(plan, it) } + // A change run doesn't fail again on one that didn't change, nor report the run a success. + if (changeRun && hash == fingerprints[target.key]) { + stillBlocked++ + continue + } + failed++ + blocked++ + continue + } + if (hash != null) rememberBlocked(plan, hash) + if (hash != null && !plan.needsRefresh(hash, fingerprints, listing.files.keys, listing.complete)) { + if (plan.latestName in listing.files) landedLatest += target.key + continue + } + // Read again rather than held since the pre-pass: one series' text in memory at a time. + val text = export(target) ?: run { + failed++ + continue + } + val fingerprint = fingerprintOf(target, text) + if (!changeRun) rememberBlocked(plan, fingerprint) + val bytes = text.toByteArray(Charsets.UTF_8) + // Not cancellable once a file exists: it must reach the ledger. + withContext(NonCancellable) { + val dated = if (latestOnly) null else writeDated(plan, bytes) + val latest = plan.latestName?.let { writeLatest(plan, bytes, fingerprint) } + if (latest == LatestWrite.Landed) landedLatest += target.key + // A full run's status follows its dated file; the stable copy is best-effort there. + val ok = dated ?: (latest != LatestWrite.Failed) + if (ok) written++ else failed++ + } + } + // A layout switch retires the other layout's copies once every new one is there. + if (landedLatest.size == plans.size) { + replacedLatestCopies(targets, prefs.autoBackupLedger.first(), existing).forEach { (key, names) -> + withContext(NonCancellable) { + val left = exporter.deleteFromFolder(listing, names) + record(latestLedgerKey(key), names.filter { it in left }) + // Its copy is gone, so its hash mustn't let a change run stop early. + prefs.updateAutoBackupFingerprints(folder.toString()) { it - key } + } + } + } + return when { + failed == 0 && (written == 0 || stillBlocked > 0) -> RunOutcome.NothingToDo + failed == 0 -> RunOutcome.Written + written == 0 && failed == blocked -> RunOutcome.Blocked + written == 0 -> RunOutcome.Failed + else -> RunOutcome.PartlyFailed + } + } + + private fun clearFailureNotification(context: Context) { + NotificationManagerCompat.from(context).cancel(NOTIFICATION_ID) } private fun notifyFailure(context: Context) { @@ -165,10 +513,10 @@ class BackupWorker( } companion object { - const val BACKUP_FILE_NAME = "calendula-backup.ics" private const val FAILURE_NOTIFY_THRESHOLD = 2 private const val CHANNEL_ID = "backup" private const val NOTIFICATION_ID = 2 private const val TAG = "BackupWorker" + private val runLock = Mutex() } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/backup/BackupChangeJob.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/backup/BackupChangeJob.kt new file mode 100644 index 00000000..3b56b30d --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/backup/BackupChangeJob.kt @@ -0,0 +1,87 @@ +package de.jeanlucmakiola.calendula.data.backup + +import android.app.job.JobInfo +import android.app.job.JobParameters +import android.app.job.JobScheduler +import android.app.job.JobService +import android.content.ComponentName +import android.content.Context +import android.provider.CalendarContract +import android.util.Log +import dagger.hilt.android.EntryPointAccessors +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.launch +import java.util.concurrent.TimeUnit + +/** + * The watch behind "Also back up after changes" (#516): a JobScheduler job + * with a content trigger on the provider's root URI, where it reports every + * change, whoever made it (this app, a sync adapter or another app). It waits + * for [SETTLE_MINUTES] of quiet, at most [MAX_WAIT_MINUTES], so a burst makes + * one run. A trigger fires once; each firing queues a change run and schedules + * the next watch under the same id before finishing, which hands over the + * changes seen meanwhile, so exactly one watch exists and none are lost. + */ +class BackupChangeJob : JobService() { + + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + override fun onStartJob(params: JobParameters): Boolean { + scope.launch { + // Retried when it failed early, so the watch isn't lost; once re-armed, the retry is moot. + val failed = try { + val deps = EntryPointAccessors.fromApplication(applicationContext, BackupWorker.Deps::class.java) + BackupScheduler.changed(applicationContext, deps.settingsPrefs()) + false + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Queueing a backup after a change failed", e) + true + } + jobFinished(params, failed) + } + return true + } + + /** Stopped before it could re-arm: run again rather than leave the provider unwatched. */ + override fun onStopJob(params: JobParameters): Boolean = true + + override fun onDestroy() { + scope.cancel() + super.onDestroy() + } + + companion object { + /** Above the range WorkManager is given (see CalendulaApp). */ + const val JOB_ID = 0x0516_0001 + private const val SETTLE_MINUTES = 2L + private const val MAX_WAIT_MINUTES = 15L + private const val TAG = "BackupChangeJob" + + fun schedule(context: Context) { + val job = JobInfo.Builder(JOB_ID, ComponentName(context, BackupChangeJob::class.java)) + .addTriggerContentUri( + JobInfo.TriggerContentUri( + CalendarContract.CONTENT_URI, + JobInfo.TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS, + ), + ) + .setTriggerContentUpdateDelay(TimeUnit.MINUTES.toMillis(SETTLE_MINUTES)) + .setTriggerContentMaxDelay(TimeUnit.MINUTES.toMillis(MAX_WAIT_MINUTES)) + .build() + if (context.getSystemService(JobScheduler::class.java).schedule(job) != JobScheduler.RESULT_SUCCESS) { + Log.w(TAG, "The change watch could not be scheduled") + } + } + + fun isPending(context: Context): Boolean = + context.getSystemService(JobScheduler::class.java).getPendingJob(JOB_ID) != null + + fun cancel(context: Context) = context.getSystemService(JobScheduler::class.java).cancel(JOB_ID) + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/backup/SettingsBackup.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/backup/SettingsBackup.kt new file mode 100644 index 00000000..a13f519f --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/backup/SettingsBackup.kt @@ -0,0 +1,265 @@ +package de.jeanlucmakiola.calendula.data.backup + +import androidx.datastore.preferences.core.Preferences +import de.jeanlucmakiola.calendula.data.appname.LauncherName +import de.jeanlucmakiola.calendula.data.calendar.ManagedCalendarRow +import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefKeys +import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride +import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys +import de.jeanlucmakiola.calendula.data.prefs.fixedTimeOverrideFor +import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType +import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder +import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle +import de.jeanlucmakiola.calendula.ui.common.CalendarView +import de.jeanlucmakiola.floret.backup.BackupDocument +import de.jeanlucmakiola.floret.backup.BackupResult +import de.jeanlucmakiola.floret.backup.PrefsSection +import de.jeanlucmakiola.floret.backup.invalidBackup +import de.jeanlucmakiola.floret.backup.optBoolean +import de.jeanlucmakiola.floret.backup.optIntList +import de.jeanlucmakiola.floret.backup.optObject +import de.jeanlucmakiola.floret.backup.optObjectList +import de.jeanlucmakiola.floret.backup.optInt +import de.jeanlucmakiola.floret.backup.optString +import de.jeanlucmakiola.floret.backup.optStringList +import de.jeanlucmakiola.floret.backup.readBackup +import de.jeanlucmakiola.floret.backup.requireString +import de.jeanlucmakiola.floret.prefs.Pref +import de.jeanlucmakiola.floret.prefs.get +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject + +/** + * A calendar as another device can find it again: provider ids are per + * device, so a calendar is named by its account and display name, and a + * special-dates mirror by the date type it mirrors. + */ +data class CalendarIdentity( + val accountName: String, + val accountType: String, + val displayName: String, + val specialDates: SpecialDateType? = null, +) + +/** The per-calendar settings of one calendar; null fields inherit the global default. */ +data class CalendarSettings( + val calendar: CalendarIdentity, + val hidden: Boolean = false, + val lastUsed: Boolean = false, + val eventDurationMinutes: Int? = null, + /** Timed reminder override; an empty list is "no reminder". */ + val reminders: List? = null, + val allDayReminders: List? = null, + /** The views it is hidden in only (#270). */ + val hiddenInViews: Set = emptySet(), + /** False when Calendula posts none of its reminders (#272). */ + val notifications: Boolean = true, + /** Its alert style (#171); null is a plain notification. */ + val alertStyle: ReminderAlertStyle? = null, + /** Its set-time reminder override (#459). */ + val fixedTimeReminder: FixedTimeOverride = FixedTimeOverride.Inherit, + /** False when the daily summary leaves it out (#459). */ + val inDailyDigest: Boolean = true, + /** The automatic backup's choice for it (#147); null follows the default for its kind. */ + val autoBackup: Boolean? = null, +) + +/** The app language a file carries; [tag] null follows the system. */ +data class LanguageChoice(val tag: String?) + +/** Everything a settings backup holds. Null [language]/[launcherName]: the file didn't say. */ +data class SettingsBackup( + val prefs: Map, Any>, + val calendars: List, + val language: LanguageChoice? = null, + val launcherName: LauncherName? = null, +) + +internal val plainSection = PrefsSection(SettingsBackupSchema.plain) + +/** + * The backup of [snapshot]. Per-calendar entries are named through + * [calendars] and [managed]; an id neither knows (a deleted calendar's + * leftover) is dropped. + */ +fun buildSettingsBackup( + snapshot: Preferences, + calendars: List, + managed: List, + language: LanguageChoice?, + launcherName: LauncherName?, +): SettingsBackup { + val hidden = snapshot[CalendarPrefKeys.hiddenCalendarIds] + val lastUsed = snapshot[CalendarPrefKeys.lastUsedCalendarId] + val durations = snapshot[SettingsKeys.perCalendarEventDuration] + val reminders = snapshot[SettingsKeys.perCalendarReminderOverride] + val allDay = snapshot[SettingsKeys.perCalendarAllDayReminderOverride] + val hiddenViews = snapshot[SettingsKeys.perCalendarHiddenViews] + val muted = snapshot[SettingsKeys.mutedReminderCalendarIds] + val alertStyles = snapshot[SettingsKeys.reminderAlertStyles] + val fixedTime = snapshot[SettingsKeys.perCalendarFixedTimeReminderOverride] + val notInDigest = snapshot[SettingsKeys.digestExcludedCalendarIds] + val backupIncluded = snapshot[SettingsKeys.autoBackupIncluded] + val backupExcluded = snapshot[SettingsKeys.autoBackupExcluded] + val ids = hidden + listOfNotNull(lastUsed) + durations.keys + reminders.keys + allDay.keys + + hiddenViews.keys + muted + alertStyles.keys + fixedTime.keys + notInDigest + backupIncluded + backupExcluded + val byId = calendars.associateBy { it.id } + val managedType = managed.associate { it.id to it.type } + val entries = ids.sorted().mapNotNull { id -> + val calendar = byId[id] ?: return@mapNotNull null + CalendarSettings( + calendar = CalendarIdentity( + accountName = calendar.accountName, + accountType = calendar.accountType, + displayName = calendar.displayName, + specialDates = managedType[id], + ), + hidden = id in hidden, + lastUsed = id == lastUsed, + eventDurationMinutes = durations[id], + reminders = reminders[id], + allDayReminders = allDay[id], + hiddenInViews = hiddenViews[id].orEmpty(), + notifications = id !in muted, + alertStyle = alertStyles[id]?.takeUnless { it == ReminderAlertStyle.Notification }, + fixedTimeReminder = fixedTime.fixedTimeOverrideFor(id), + inDailyDigest = id !in notInDigest, + autoBackup = when (id) { + in backupIncluded -> true + in backupExcluded -> false + else -> null + }, + ) + } + return SettingsBackup( + prefs = plainSection.snapshot(snapshot), + calendars = entries, + language = language, + launcherName = launcherName, + ) +} + +fun encodeSettingsBackup(backup: SettingsBackup, exportedAtMillis: Long, appVersion: String?): String { + val body = buildJsonObject { + put(KEY_SETTINGS, plainSection.encode(backup.prefs)) + put(KEY_CALENDARS, JsonArray(backup.calendars.map { it.toJson() })) + put( + KEY_APP, + buildJsonObject { + backup.language?.let { put(KEY_LANGUAGE, it.tag?.let(::JsonPrimitive) ?: JsonNull) } + backup.launcherName?.let { put(KEY_LAUNCHER_NAME, JsonPrimitive(it.name)) } + }, + ) + } + val document = BackupDocument( + version = SettingsBackupSchema.format.version, + exportedAtMillis = exportedAtMillis, + appVersion = appVersion, + body = body, + ) + return SettingsBackupSchema.format.encode(document) +} + +/** Validates the whole file before anything is applied; see docs/SETTINGS_BACKUP.md. */ +fun decodeSettingsBackup(text: String): BackupResult { + val document = when (val decoded = SettingsBackupSchema.format.decode(text)) { + is BackupResult.Failure -> return decoded + is BackupResult.Success -> decoded.value + } + return readBackup { + val body = document.body + val app = body.optObject(KEY_APP) + SettingsBackup( + prefs = plainSection.read(body.optObject(KEY_SETTINGS) ?: invalidBackup("$KEY_SETTINGS: missing")), + calendars = body.optObjectList(KEY_CALENDARS).orEmpty().map { it.toCalendarSettings() }, + language = app?.takeIf { KEY_LANGUAGE in it }?.let { LanguageChoice(it.optString(KEY_LANGUAGE)) }, + launcherName = app?.optString(KEY_LAUNCHER_NAME) + ?.let { name -> LauncherName.entries.firstOrNull { it.name == name } }, + ) + } +} + +private fun CalendarSettings.toJson(): JsonObject = buildJsonObject { + put(KEY_ACCOUNT_NAME, JsonPrimitive(calendar.accountName)) + put(KEY_ACCOUNT_TYPE, JsonPrimitive(calendar.accountType)) + put(KEY_DISPLAY_NAME, JsonPrimitive(calendar.displayName)) + calendar.specialDates?.let { put(KEY_SPECIAL_DATES, JsonPrimitive(it.name)) } + if (hidden) put(KEY_HIDDEN, JsonPrimitive(true)) + if (lastUsed) put(KEY_LAST_USED, JsonPrimitive(true)) + eventDurationMinutes?.let { put(KEY_EVENT_DURATION, JsonPrimitive(it)) } + reminders?.let { put(KEY_REMINDERS, JsonArray(it.map(::JsonPrimitive))) } + allDayReminders?.let { put(KEY_ALL_DAY_REMINDERS, JsonArray(it.map(::JsonPrimitive))) } + if (hiddenInViews.isNotEmpty()) { + put(KEY_HIDDEN_IN_VIEWS, JsonArray(hiddenInViews.sortedBy { it.ordinal }.map { JsonPrimitive(it.name) })) + } + if (!notifications) put(KEY_NOTIFICATIONS, JsonPrimitive(false)) + alertStyle?.let { put(KEY_ALERT_STYLE, JsonPrimitive(it.storageValue)) } + when (val fixed = fixedTimeReminder) { + FixedTimeOverride.Inherit -> Unit + FixedTimeOverride.Off -> put(KEY_FIXED_TIME_REMINDER, JsonPrimitive(FIXED_TIME_OFF)) + is FixedTimeOverride.At -> put(KEY_FIXED_TIME_REMINDER, JsonPrimitive(fixed.reminder.toToken())) + } + if (!inDailyDigest) put(KEY_IN_DAILY_DIGEST, JsonPrimitive(false)) + autoBackup?.let { put(KEY_AUTO_BACKUP, JsonPrimitive(it)) } +} + +/** + * Strict about what it reads. A special-dates type this build doesn't know + * reads as an ordinary calendar, which then simply finds no match. + */ +private fun JsonObject.toCalendarSettings(): CalendarSettings { + return CalendarSettings( + calendar = CalendarIdentity( + accountName = requireString(KEY_ACCOUNT_NAME), + accountType = requireString(KEY_ACCOUNT_TYPE), + displayName = requireString(KEY_DISPLAY_NAME), + specialDates = optString(KEY_SPECIAL_DATES)?.let { name -> SpecialDateType.entries.firstOrNull { it.name == name } }, + ), + hidden = optBoolean(KEY_HIDDEN) ?: false, + lastUsed = optBoolean(KEY_LAST_USED) ?: false, + eventDurationMinutes = optInt(KEY_EVENT_DURATION), + reminders = optIntList(KEY_REMINDERS)?.cleanReminders(), + allDayReminders = optIntList(KEY_ALL_DAY_REMINDERS)?.cleanReminders(), + hiddenInViews = optStringList(KEY_HIDDEN_IN_VIEWS).orEmpty() + .mapNotNullTo(mutableSetOf()) { name -> CalendarView.entries.firstOrNull { it.name == name } }, + notifications = optBoolean(KEY_NOTIFICATIONS) ?: true, + alertStyle = optString(KEY_ALERT_STYLE)?.let(ReminderAlertStyle::fromStorage) + ?.takeUnless { it == ReminderAlertStyle.Notification }, + fixedTimeReminder = when (val token = optString(KEY_FIXED_TIME_REMINDER)) { + null -> FixedTimeOverride.Inherit + FIXED_TIME_OFF -> FixedTimeOverride.Off + else -> FixedTimeReminder.parse(token)?.let(FixedTimeOverride::At) ?: FixedTimeOverride.Inherit + }, + inDailyDigest = optBoolean(KEY_IN_DAILY_DIGEST) ?: true, + autoBackup = optBoolean(KEY_AUTO_BACKUP), + ) +} + +/** As the reminder setters store them: no negative leads, each once, ascending. */ +private fun List.cleanReminders(): List = filter { it >= 0 }.distinct().sorted() + +private const val KEY_SETTINGS = "settings" +private const val KEY_CALENDARS = "calendars" +private const val KEY_APP = "app" +private const val KEY_LANGUAGE = "language" +private const val KEY_LAUNCHER_NAME = "launcher_name" +private const val KEY_ACCOUNT_NAME = "account_name" +private const val KEY_ACCOUNT_TYPE = "account_type" +private const val KEY_DISPLAY_NAME = "display_name" +private const val KEY_SPECIAL_DATES = "special_dates" +private const val KEY_HIDDEN = "hidden" +private const val KEY_LAST_USED = "last_used" +private const val KEY_EVENT_DURATION = "event_duration_minutes" +private const val KEY_REMINDERS = "reminders" +private const val KEY_ALL_DAY_REMINDERS = "all_day_reminders" +private const val KEY_HIDDEN_IN_VIEWS = "hidden_in_views" +private const val KEY_NOTIFICATIONS = "notifications" +private const val KEY_ALERT_STYLE = "alert_style" +private const val KEY_FIXED_TIME_REMINDER = "fixed_time_reminder" +private const val FIXED_TIME_OFF = "off" +private const val KEY_IN_DAILY_DIGEST = "in_daily_digest" +private const val KEY_AUTO_BACKUP = "auto_backup" diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/backup/SettingsBackupEngine.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/backup/SettingsBackupEngine.kt new file mode 100644 index 00000000..9cb30cc8 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/backup/SettingsBackupEngine.kt @@ -0,0 +1,239 @@ +package de.jeanlucmakiola.calendula.data.backup + +import android.content.Context +import android.util.Log +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.edit +import dagger.hilt.android.qualifiers.ApplicationContext +import de.jeanlucmakiola.calendula.BuildConfig +import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.data.appname.LauncherNameManager +import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource +import de.jeanlucmakiola.calendula.data.contacts.ContactSpecialDatesDataSource +import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesScheduler +import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesSyncEngine +import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesSyncResult +import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs +import de.jeanlucmakiola.calendula.data.prefs.SpecialDatesStalledReason +import de.jeanlucmakiola.calendula.data.fonts.CustomFontStore +import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys +import de.jeanlucmakiola.calendula.data.prefs.autoBackupScheduled +import de.jeanlucmakiola.calendula.data.reminders.ReminderScanner +import de.jeanlucmakiola.calendula.domain.FontRole +import de.jeanlucmakiola.calendula.widget.requestWidgetRedraw +import de.jeanlucmakiola.floret.backup.BackupProblem +import de.jeanlucmakiola.floret.backup.BackupResult +import de.jeanlucmakiola.floret.di.IoDispatcher +import de.jeanlucmakiola.floret.locale.AppLanguage +import de.jeanlucmakiola.floret.prefs.get +import de.jeanlucmakiola.floret.prefs.rawValue +import de.jeanlucmakiola.floret.reminders.reminderOverrideFor +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.withContext +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Exports and imports Calendula's settings (#481). The file format and what + * it holds are [SettingsBackupSchema]'s; the import is planned purely by + * [planSettingsImport], written in one DataStore edit, and then followed by + * the side effects the settings screens would have run themselves. + */ +@Singleton +class SettingsBackupEngine @Inject constructor( + private val store: DataStore, + private val calendars: CalendarDataSource, + private val contacts: ContactSpecialDatesDataSource, + private val specialDates: SpecialDatesSyncEngine, + private val settingsPrefs: SettingsPrefs, + private val reminderScanner: ReminderScanner, + private val launcherNames: LauncherNameManager, + @ApplicationContext private val context: Context, + @IoDispatcher private val io: CoroutineDispatcher, +) { + + suspend fun export(): String = withContext(io) { + val supported = supportedLanguages() + val snapshot = store.data.first() + // Without the list the per-calendar settings would silently drop out of the file. + val list = if (snapshot.hasCalendarSettings()) calendars.calendars() else emptyList() + val backup = buildSettingsBackup( + snapshot = snapshot, + calendars = list, + managed = if (list.any { it.isManaged }) calendars.findManagedCalendars() else emptyList(), + language = LanguageChoice(AppLanguage.currentTag(context, supported)), + launcherName = launcherNames.current(), + ) + encodeSettingsBackup(backup, System.currentTimeMillis(), BuildConfig.VERSION_NAME) + } + + /** Validates [text] in full, then replaces the settings; nothing is written for an invalid file. */ + suspend fun import(text: String): BackupResult = withContext(io) { + val backup = when (val decoded = decodeSettingsBackup(text)) { + is BackupResult.Failure -> return@withContext decoded + is BackupResult.Success -> decoded.value + } + val current = store.data.first() + val supported = supportedLanguages() + val environment = environment(current, backup, supported) + val plan = planSettingsImport(backup, current, environment) + val existingMirrors = environment.managed.map { it.id }.toSet() + // Once the write starts, the side effects have to follow it, whoever cancels. + withContext(NonCancellable) { + try { + store.edit { plan.applyTo(it) } + } catch (e: Exception) { + Log.w(TAG, "Settings import could not be written", e) + return@withContext BackupResult.Failure(BackupProblem.NOT_APPLIED, e.message.orEmpty()) + } + val lateSkips = afterImport(plan, current, supported, existingMirrors) + BackupResult.Success(plan.summary(plan.calendars.orEmpty().size + lateSkips.matched, lateSkips.skipped)) + } + } + + private class LateMatches(val matched: Int, val skipped: List) + + /** + * Brings what reads the settings outside DataStore in line: the mirror, + * reminder alarms, scheduled backups, the launcher alias and the language. + * Each step stands alone, so one failing never undoes the import. + */ + private suspend fun afterImport( + plan: SettingsImportPlan, + before: Preferences, + supported: List, + existingMirrors: Set, + ): LateMatches { + val after = store.data.first() + val wasMirroring = before[SettingsKeys.specialDatesEnabled] + val mirroring = after[SettingsKeys.specialDatesEnabled] + var late = LateMatches(0, plan.pendingSpecialDates.map { it.calendar.skipped() }) + step("special dates") { + if (mirroring) { + SpecialDatesScheduler.apply(context, enabled = true) + val result = specialDates.sync() + if (result != SpecialDatesSyncResult.Disabled) { + val stalled = SpecialDatesStalledReason.PermissionRevoked + .takeIf { result == SpecialDatesSyncResult.PermissionMissing } + settingsPrefs.recordSpecialDatesRun(System.currentTimeMillis(), stalled) + } + late = matchSpecialDates(plan, before, existingMirrors, synced = result == SpecialDatesSyncResult.Success) + } else if (wasMirroring) { + SpecialDatesScheduler.apply(context, enabled = false) + specialDates.teardown() + } + } + step("reminders") { reminderScanner.scan() } + step("auto backup") { + BackupScheduler.reconcile(context, settingsPrefs) + // Like the settings screen, an import that switches the interval (#516) backs up right away. + val active = after[SettingsKeys.autoBackupEnabled] && after[SettingsKeys.autoBackupFolderUri] != null + if (active && before.autoBackupScheduled != after.autoBackupScheduled) BackupScheduler.runNow(context) + } + plan.launcherName?.let { name -> + step("launcher name") { if (launcherNames.current() != name) launcherNames.set(name) } + } + plan.language?.let { choice -> + step("language") { + if (AppLanguage.currentTag(context, supported) != choice.tag) { + withContext(Dispatchers.Main) { AppLanguage.apply(context, choice.tag) } + requestWidgetRedraw(context) + } + } + } + return late + } + + /** + * Gives late-created mirror calendars their entries (only after a + * successful [synced] run), then rewrites each mirror whose all-day + * reminders differ from what its events carry: the pre-import override for + * a calendar that already existed, the sync's seed for a new one. A mirror + * the file doesn't override inherits again. + */ + private suspend fun matchSpecialDates( + plan: SettingsImportPlan, + before: Preferences, + existingMirrors: Set, + synced: Boolean, + ): LateMatches { + val managed = calendars.findManagedCalendars() + val skipped = mutableListOf() + var matched = 0 + val resolved = if (!synced) { + skipped += plan.pendingSpecialDates.map { it.calendar.skipped() } + emptyList() + } else { + plan.pendingSpecialDates.mapNotNull { entry -> + val id = managed.firstOrNull { it.type == entry.calendar.specialDates }?.id + if (id == null) skipped += entry.calendar.skipped() else matched++ + id?.let { it to entry } + } + } + if (resolved.isNotEmpty()) { + store.edit { prefs -> + resolved.forEach { (id, entry) -> prefs.addCalendarSettings(id, entry.copy(allDayReminders = null)) } + } + } + if (plan.calendars != null) { + val wanted = (plan.calendars.values + resolved.map { it.second }) + .mapNotNull { entry -> entry.calendar.specialDates?.let { it to entry.allDayReminders } } + .toMap() + val carried = before[SettingsKeys.perCalendarAllDayReminderOverride] + val seeded = store.data.first()[SettingsKeys.perCalendarAllDayReminderOverride] + managed.distinctBy { it.type }.forEach { (id, type) -> + val minutes = wanted[type] + val onEvents = if (id in existingMirrors) carried[id] else seeded[id] + if (onEvents == minutes) return@forEach + val desired = minutes?.let { mapOf(id to it) }.orEmpty() + specialDates.applyReminders(type, desired.reminderOverrideFor(id)) + } + } + return LateMatches(matched, skipped) + } + + /** The highest byte count [import] is worth reading. */ + val maxImportBytes: Int get() = SettingsBackupSchema.format.maxChars + + private fun environment( + current: Preferences, + backup: SettingsBackup, + supported: List, + ): ImportEnvironment = ImportEnvironment( + // An empty list here is a failed read as far as the import can tell, never "wipe them all". + calendars = if (backup.calendars.isEmpty()) { + emptyList() + } else { + runCatching { calendars.calendars() }.getOrNull()?.takeIf { it.isNotEmpty() } + }, + managed = runCatching { calendars.findManagedCalendars() }.getOrDefault(emptyList()), + contactsPermission = contacts.hasPermission(), + customFonts = FontRole.entries.filter { CustomFontStore.exists(context, it) }.toSet(), + hasBackupFolder = current[SettingsKeys.autoBackupFolderUri] != null, + supportedLanguages = supported, + ) + + private fun Preferences.hasCalendarSettings(): Boolean = + SettingsBackupSchema.perCalendar.any { rawValue(it) != null } + + private fun supportedLanguages(): List = AppLanguage.supportedTags(context, R.xml.locales_config) + + private suspend fun step(name: String, block: suspend () -> Unit) { + try { + block() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Settings import: $name could not be refreshed", e) + } + } + + private companion object { + const val TAG = "SettingsBackup" + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/backup/SettingsBackupSchema.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/backup/SettingsBackupSchema.kt new file mode 100644 index 00000000..f4d7bf3d --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/backup/SettingsBackupSchema.kt @@ -0,0 +1,135 @@ +package de.jeanlucmakiola.calendula.data.backup + +import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefKeys +import de.jeanlucmakiola.calendula.data.prefs.ReminderStateKeys +import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys +import de.jeanlucmakiola.floret.backup.BackupFormat +import de.jeanlucmakiola.floret.prefs.Pref + +/** + * Which stored keys a settings backup carries (#481), and how. Every key of + * the settings store is in exactly one of the three lists; a test holds that, + * so a new setting cannot ship without deciding. See docs/SETTINGS_BACKUP.md. + */ +internal object SettingsBackupSchema { + + val format = BackupFormat(name = "calendula-settings", version = 1) + + /** Carried as stored and restored over the current value; an absent key restores the default. */ + val plain: List> = listOf( + SettingsKeys.themeMode, + SettingsKeys.dynamicColor, + SettingsKeys.weekStart, + SettingsKeys.softenCalendarColors, + SettingsKeys.brandFont, + SettingsKeys.plainFont, + SettingsKeys.timeFormat, + SettingsKeys.showHourGrid, + SettingsKeys.pastEventDisplay, + SettingsKeys.dimCompletedEvents, + SettingsKeys.showWeekNumbers, + SettingsKeys.monthShowStartTimes, + SettingsKeys.monthViewStyle, + SettingsKeys.timelineScale, + SettingsKeys.multiDayCount, + SettingsKeys.timelineHoursEnabled, + SettingsKeys.timelineHoursStart, + SettingsKeys.timelineHoursEnd, + SettingsKeys.todayButtonInToolbar, + SettingsKeys.dragToReschedule, + SettingsKeys.tapOpensEditor, + SettingsKeys.agendaScreenRange, + SettingsKeys.agendaShowRangeBar, + SettingsKeys.agendaShowToday, + SettingsKeys.defaultView, + SettingsKeys.quickSwitchConfig, + SettingsKeys.drawerViewOrder, + SettingsKeys.defaultFormFields, + SettingsKeys.autofocusEventTitle, + // Names its calendar by account and display name, so it finds it again on another device. + SettingsKeys.defaultNewEventCalendar, + SettingsKeys.defaultEventDurationMinutes, + SettingsKeys.remindersEnabled, + SettingsKeys.allowColorOnUnsupportedCalendars, + SettingsKeys.defaultReminderMinutes, + SettingsKeys.defaultAllDayReminderMinutes, + SettingsKeys.allDayReminderTimeMinutes, + SettingsKeys.snoozeMinutes, + SettingsKeys.defaultFixedTimeReminder, + SettingsKeys.dailyDigestEnabled, + SettingsKeys.dailyDigestTimeMinutes, + SettingsKeys.dailyDigestDay, + SettingsKeys.autoBackupEnabled, + SettingsKeys.autoBackupIntervalMinutes, + SettingsKeys.autoBackupCombinedStored, + SettingsKeys.autoBackupKeep, + SettingsKeys.autoBackupOnChange, + SettingsKeys.autoBackupScheduledStored, + SettingsKeys.specialDatesEnabled, + SettingsKeys.specialDatesShowYear, + ) + SettingsKeys.specialDateTypeEnabled.values + SettingsKeys.specialDatesTitleTemplate.values + + /** + * Keyed by calendar id on disk, so carried per calendar under a portable + * identity instead ([CalendarSettings]) and re-keyed to this device's ids. + */ + val perCalendar: List> = listOf( + CalendarPrefKeys.hiddenCalendarIds, + CalendarPrefKeys.lastUsedCalendarId, + SettingsKeys.perCalendarEventDuration, + SettingsKeys.perCalendarReminderOverride, + SettingsKeys.perCalendarAllDayReminderOverride, + SettingsKeys.perCalendarHiddenViews, + SettingsKeys.mutedReminderCalendarIds, + SettingsKeys.reminderAlertStyles, + SettingsKeys.perCalendarFixedTimeReminderOverride, + SettingsKeys.digestExcludedCalendarIds, + SettingsKeys.autoBackupIncluded, + SettingsKeys.autoBackupExcluded, + ) + + /** Never exported: this install's own state, bookkeeping, or meaningless on another device. */ + val excluded: List> = ( + listOf( + // Cache-busting counters for the locally imported font file. + SettingsKeys.brandFontStamp, + SettingsKeys.plainFontStamp, + // Legacy defaults for unconfigured widgets; widget configuration stays out. + SettingsKeys.agendaWidgetRange, + SettingsKeys.widgetSize, + // Usage history, not a setting. + SettingsKeys.recentTimeZones, + SettingsKeys.recentFixedTimeReminders, + // A dismissed hint of this install. + SettingsKeys.notificationCategoryHintDismissed, + // This device's notification channels. + SettingsKeys.reminderChannelVersions, + // Sync-request grants of this device's accounts. + CalendarPrefKeys.syncAccessDismissed, + // First-run wizard progress of this install. + SettingsKeys.onboardingWizardArmed, + CalendarPrefKeys.visibilityNoticePending, + // A SAF grant, which does not survive a reinstall or another device. + SettingsKeys.autoBackupFolderUri, + // Run status. + SettingsKeys.autoBackupLastRun, + SettingsKeys.autoBackupLastSuccess, + SettingsKeys.autoBackupFailures, + SettingsKeys.specialDatesLastRun, + SettingsKeys.specialDatesStalled, + SettingsKeys.specialDatesLastForegroundSync, + SettingsKeys.dailyDigestArmedAt, + ReminderStateKeys.lastDigestDay, + // What the automatic backup wrote to this install's folder. + SettingsKeys.autoBackupLedger, + SettingsKeys.autoBackupFingerprints, + // Switch-offs still owed to the provider on this device. + CalendarPrefKeys.pendingDisabledCalendarIds, + // The reminder delivery watermark. + ReminderStateKeys.lastScanMillis, + ) + + SettingsKeys.onboardingDone.values + + // The mirror re-adopts its calendars by their provider marker. + SettingsKeys.specialDatesCalendarId.values + ).distinct() +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/backup/SettingsImport.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/backup/SettingsImport.kt new file mode 100644 index 00000000..e4b6ef0d --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/backup/SettingsImport.kt @@ -0,0 +1,234 @@ +package de.jeanlucmakiola.calendula.data.backup + +import androidx.datastore.preferences.core.MutablePreferences +import androidx.datastore.preferences.core.Preferences +import de.jeanlucmakiola.calendula.data.appname.LauncherName +import de.jeanlucmakiola.calendula.data.calendar.ManagedCalendarRow +import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefKeys +import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride +import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys +import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs +import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.domain.FontRole +import de.jeanlucmakiola.calendula.ui.theme.FONT_CUSTOM_TOKEN +import de.jeanlucmakiola.floret.locale.AppLanguage +import de.jeanlucmakiola.floret.prefs.Pref +import de.jeanlucmakiola.floret.prefs.get +import de.jeanlucmakiola.floret.prefs.rawValue +import de.jeanlucmakiola.floret.prefs.set +import de.jeanlucmakiola.floret.prefs.setRawValue + +/** What this device can take of a backup, read before planning. */ +data class ImportEnvironment( + /** Null when the calendar list can't be read: the per-calendar settings are then left alone. */ + val calendars: List?, + val managed: List, + val contactsPermission: Boolean, + val customFonts: Set, + val hasBackupFolder: Boolean, + val supportedLanguages: List, +) + +/** Something in the file this device could not take, for the import summary. */ +sealed interface SkippedSetting { + /** No calendar on this device matches the file's, or [ambiguous]ly more than one does. */ + data class Calendar( + val displayName: String, + val accountName: String, + val ambiguous: Boolean = false, + ) : SkippedSetting + + /** The calendars couldn't be read, so the per-calendar settings were left as they are. */ + data object CalendarsUnavailable : SkippedSetting + + /** A custom font: the font file itself is not part of the backup. */ + data class CustomFont(val role: FontRole) : SkippedSetting + + /** Contact special dates were on, but this device hasn't granted the contacts permission. */ + data object SpecialDates : SkippedSetting + + /** Automatic backup was on, but its folder has to be chosen again here. */ + data object AutoBackupFolder : SkippedSetting + + /** The file's app language isn't one this build ships. */ + data class Language(val tag: String) : SkippedSetting +} + +data class SettingsImportSummary( + val calendarsMatched: Int, + val skipped: List, +) + +/** + * A validated backup laid onto this device: the stored values to write in one + * edit, the side effects the engine runs after it, and the summary. + * [calendars] null leaves the per-calendar keys untouched. + * [pendingSpecialDates] are mirror calendars that don't exist yet; the engine + * matches them once the mirror's sync has created them. + */ +data class SettingsImportPlan( + val prefs: Map, Any?>, + val calendars: Map?, + val pendingSpecialDates: List, + val language: LanguageChoice?, + val launcherName: LauncherName?, + val skipped: List, +) + +/** Plans an import that replaces every backed-up setting; see docs/SETTINGS_BACKUP.md. */ +fun planSettingsImport( + backup: SettingsBackup, + current: Preferences, + environment: ImportEnvironment, +): SettingsImportPlan { + val skipped = mutableListOf() + val prefs = backup.prefs.toMutableMap, Any?>() + + fun keepCurrent(pref: Pref<*>) { + prefs[pref] = current.rawValue(pref) + } + + FontRole.entries.forEach { role -> + val pref = role.fontPref() + if (prefs[pref] == FONT_CUSTOM_TOKEN && role !in environment.customFonts) { + keepCurrent(pref) + skipped += SkippedSetting.CustomFont(role) + } + } + if (prefs[SettingsKeys.specialDatesEnabled] == true && !environment.contactsPermission) { + keepCurrent(SettingsKeys.specialDatesEnabled) + skipped += SkippedSetting.SpecialDates + } + if (prefs[SettingsKeys.autoBackupEnabled] == true && !environment.hasBackupFolder) { + keepCurrent(SettingsKeys.autoBackupEnabled) + skipped += SkippedSetting.AutoBackupFolder + } + + val language = backup.language?.let { choice -> + val tag = choice.tag ?: return@let choice + val resolved = AppLanguage.resolveTag(tag, environment.supportedLanguages) + if (resolved in environment.supportedLanguages) { + LanguageChoice(resolved) + } else { + skipped += SkippedSetting.Language(tag) + null + } + } + + // The mirror's calendars are torn down when the imported settings leave it off. + val mirroring = prefs[SettingsKeys.specialDatesEnabled] == true + val available = environment.calendars + val calendars = linkedMapOf() + val pending = mutableListOf() + if (available == null) { + if (backup.calendars.isNotEmpty()) skipped += SkippedSetting.CalendarsUnavailable + } else { + val repeated = backup.calendars.groupingBy { it.calendar }.eachCount().filterValues { it > 1 }.keys + backup.calendars.forEach { entry -> + val type = entry.calendar.specialDates + if (type != null) { + // The mirror only keeps calendars for the types the imported settings switch on. + val typeOn = prefs[SettingsKeys.specialDateTypeEnabled.getValue(type)] != false + if (!mirroring || !typeOn) return@forEach + val id = environment.managed.firstOrNull { it.type == type }?.id + if (id != null) calendars[id] = entry else pending += entry + return@forEach + } + if (entry.calendar in repeated) { + // Two calendars on the exporting phone that this one can't tell apart. + val reported = SkippedSetting.Calendar(entry.calendar.displayName, entry.calendar.accountName, ambiguous = true) + if (reported !in skipped) skipped += reported + return@forEach + } + val candidates = available.filter { !it.isManaged && it.matches(entry.calendar) } + when (candidates.size) { + 1 -> calendars[candidates.single().id] = entry + else -> skipped += entry.calendar.skipped(ambiguous = candidates.size > 1) + } + } + } + + return SettingsImportPlan( + prefs = prefs, + calendars = calendars.takeIf { available != null }, + pendingSpecialDates = pending, + language = language, + launcherName = backup.launcherName, + skipped = skipped, + ) +} + +/** Writes the plan's stored values, replacing every backed-up setting and all per-calendar ones. */ +fun SettingsImportPlan.applyTo(target: MutablePreferences) { + plainSection.apply(target, prefs) + calendars?.let(target::writeCalendarSettings) +} + +/** + * Replaces the per-calendar keys with [calendars], by this device's ids. A + * last-used calendar only counts from the first entry claiming it. + */ +fun MutablePreferences.writeCalendarSettings(calendars: Map) { + SettingsBackupSchema.perCalendar.forEach { setRawValue(it, null) } + calendars.forEach { (id, entry) -> addCalendarSettings(id, entry) } +} + +/** Adds one late-matched calendar's settings to what [writeCalendarSettings] stored. */ +fun MutablePreferences.addCalendarSettings(id: Long, entry: CalendarSettings) { + if (entry.hidden) this[CalendarPrefKeys.hiddenCalendarIds] = this[CalendarPrefKeys.hiddenCalendarIds] + id + if (entry.lastUsed && this[CalendarPrefKeys.lastUsedCalendarId] == null) { + this[CalendarPrefKeys.lastUsedCalendarId] = id + } + entry.eventDurationMinutes?.let { + this[SettingsKeys.perCalendarEventDuration] = + this[SettingsKeys.perCalendarEventDuration] + (id to it.clampDuration()) + } + entry.reminders?.let { + this[SettingsKeys.perCalendarReminderOverride] = this[SettingsKeys.perCalendarReminderOverride] + (id to it) + } + entry.allDayReminders?.let { + this[SettingsKeys.perCalendarAllDayReminderOverride] = + this[SettingsKeys.perCalendarAllDayReminderOverride] + (id to it) + } + if (entry.hiddenInViews.isNotEmpty()) { + this[SettingsKeys.perCalendarHiddenViews] = this[SettingsKeys.perCalendarHiddenViews] + (id to entry.hiddenInViews) + } + if (!entry.notifications) this[SettingsKeys.mutedReminderCalendarIds] = this[SettingsKeys.mutedReminderCalendarIds] + id + entry.alertStyle?.let { this[SettingsKeys.reminderAlertStyles] = this[SettingsKeys.reminderAlertStyles] + (id to it) } + val fixed = when (val override = entry.fixedTimeReminder) { + FixedTimeOverride.Inherit -> null + FixedTimeOverride.Off -> id to null + is FixedTimeOverride.At -> id to override.reminder + } + fixed?.let { + this[SettingsKeys.perCalendarFixedTimeReminderOverride] = this[SettingsKeys.perCalendarFixedTimeReminderOverride] + it + } + if (!entry.inDailyDigest) this[SettingsKeys.digestExcludedCalendarIds] = this[SettingsKeys.digestExcludedCalendarIds] + id + when (entry.autoBackup) { + true -> this[SettingsKeys.autoBackupIncluded] = this[SettingsKeys.autoBackupIncluded] + id + false -> this[SettingsKeys.autoBackupExcluded] = this[SettingsKeys.autoBackupExcluded] + id + null -> Unit + } +} + +fun CalendarIdentity.skipped(ambiguous: Boolean = false): SkippedSetting = + SkippedSetting.Calendar(displayName, accountName, ambiguous) + +fun SettingsImportPlan.summary(calendarsMatched: Int, more: List = emptyList()) = + SettingsImportSummary( + calendarsMatched = calendarsMatched, + skipped = skipped + more, + ) + +private fun CalendarSource.matches(identity: CalendarIdentity): Boolean = + accountType == identity.accountType && + accountName == identity.accountName && + displayName == identity.displayName + +/** The same range the per-calendar duration setter clamps to. */ +private fun Int.clampDuration(): Int = coerceIn(SettingsPrefs.MIN_EVENT_DURATION, SettingsPrefs.MAX_EVENT_DURATION) + +private fun FontRole.fontPref(): Pref = when (this) { + FontRole.BRAND -> SettingsKeys.brandFont + FontRole.PLAIN -> SettingsKeys.plainFont +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/AllDayReminderEncoding.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/AllDayReminderEncoding.kt index 1ed2f599..5d88d4f6 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/AllDayReminderEncoding.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/AllDayReminderEncoding.kt @@ -54,6 +54,18 @@ internal fun toProviderAllDayMinutes( return if (raw == MINUTES_DEFAULT) MINUTES_DEFAULT - 1 else raw } +/** + * A lead time as the whole days an all-day reminder actually fires at: the + * sub-day part is dropped, matching [toProviderAllDayMinutes]'s day count. + * [MINUTES_DEFAULT] passes through. + */ +internal fun wholeDayLeadMinutes(minutes: Int): Int = + if (minutes == MINUTES_DEFAULT) minutes else minutes / MINUTES_PER_DAY * MINUTES_PER_DAY + +/** [wholeDayLeadMinutes] for a reminder list, merging lead times that land on the same day. */ +internal fun wholeDayLeadTimes(minutes: List): List = + minutes.map(::wholeDayLeadMinutes).distinct().sorted() + /** * The next date on or after [today] carrying [month]/[day] — the date to sample * a yearly all-day reminder's UTC offset at. A managed birthday's DTSTART is an diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt index 7f96a33e..3790ba81 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt @@ -30,11 +30,15 @@ import de.jeanlucmakiola.calendula.domain.Reminder import de.jeanlucmakiola.calendula.domain.SearchCandidate import de.jeanlucmakiola.calendula.domain.contacts.MANAGED_UID_PREFIX import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType +import de.jeanlucmakiola.calendula.domain.ics.CalendarRows +import de.jeanlucmakiola.calendula.domain.ics.OverrideRow +import de.jeanlucmakiola.calendula.domain.ics.MasterRow import de.jeanlucmakiola.calendula.domain.ics.IcsEvent import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent import de.jeanlucmakiola.calendula.domain.ics.semanticReminderMinutes import de.jeanlucmakiola.calendula.domain.ics.parseRfc2445DurationMillis import de.jeanlucmakiola.calendula.domain.rruleTruncatedAt +import de.jeanlucmakiola.calendula.domain.fixedReminderOffsets import de.jeanlucmakiola.calendula.domain.toEditForm import kotlinx.datetime.TimeZone import kotlinx.datetime.toJavaLocalDate @@ -90,15 +94,15 @@ interface CalendarDataSource { fun publishedEventColors(calendarId: Long): List /** - * Every master/one-off event of the writable local calendars, mapped for a - * whole-calendar `.ics` backup. Modified-occurrence and cancelled-exception - * rows are excluded (see [EventExportProjection]). When [calendarIds] is - * given, only those calendars are exported (still intersected with the - * eligible set); `null` exports every eligible calendar. - * [allDayReminderTimeMinutes]: needed to write all-day reminders as whole-day - * lead times rather than raw provider offsets (see [toIcsEvent]). + * Every event row of [calendarIds], whatever kind of calendar they are + * (local, synced, read-only): the masters/one-offs and the modified and + * cancelled exception rows, each with the keys that link it to its series + * and tagged with its calendar's name. A plain read: which calendars may be + * read for what is the caller's call. [allDayReminderTimeMinutes]: needed to + * write all-day reminders as whole-day lead times rather than raw provider + * offsets (see [toIcsEvent]). */ - fun exportableEvents(calendarIds: Set?, allDayReminderTimeMinutes: Int): List + fun calendarRows(calendarIds: Set, allDayReminderTimeMinutes: Int): CalendarRows /** * The non-empty `Events.UID_2445` values present in [calendarId] — used to @@ -301,6 +305,12 @@ interface CalendarDataSource { */ fun deleteOccurrence(eventId: Long, beginMillis: Long) + /** The account [calendarId] belongs to; null when the row is gone or unreadable. */ + fun calendarAccount(calendarId: Long): SyncAccount? + + /** The calendar event [eventId] lives in; null when the row is gone or unreadable. */ + fun eventCalendarId(eventId: Long): Long? + fun registerChangeListener(listener: () -> Unit) fun unregisterChangeListener(listener: () -> Unit) } @@ -776,47 +786,94 @@ class AndroidCalendarDataSource @Inject constructor( ?: emptyList() } - override fun exportableEvents( - calendarIds: Set?, - allDayReminderTimeMinutes: Int, - ): List { - // Only the local calendars the app owns and can write — synced calendars - // already have a backup (their server). Exclude the managed special-dates - // mirror calendars: their events are derived from contacts, not authored - // here, and re-materialise from the contact sync — backing them up would - // just duplicate them on restore. A non-null [calendarIds] narrows the - // export to the user's chosen subset. Map id → display name for the - // X-CALENDULA-CALENDAR tag a restore uses to fan back out. - val names = calendars() - .filter { - it.isLocal && it.canModifyContents && !it.isManaged && - (calendarIds == null || it.id in calendarIds) - } - .associate { it.id to it.displayName } - if (names.isEmpty()) return emptyList() + override fun calendarRows(calendarIds: Set, allDayReminderTimeMinutes: Int): CalendarRows { + if (calendarIds.isEmpty()) return CalendarRows(emptyList(), emptyList()) + // The name tags each event for a combined backup's restore to fan back + // out; an id that no longer exists drops out here. + val calendars = calendars().filter { it.id in calendarIds }.associateBy { it.id } + if (calendars.isEmpty()) return CalendarRows(emptyList(), emptyList()) - val idList = names.keys.joinToString(",") - return resolver.query( + val selection = "${CalendarContract.Events.CALENDAR_ID} IN (${calendars.keys.joinToString(",")}) AND " + + "${CalendarContract.Events.DELETED} = 0" + val series = mutableListOf() + val overrides = mutableListOf() + forEachExportRow(selection, allDayReminderTimeMinutes) { event -> + val calendarId = getLong(EventExportProjection.IDX_CALENDAR_ID) + val calendar = calendars[calendarId] + // An adapter may stamp the calendar colour on every row; a palette key means it was chosen. + val color = getIntOrNull(EventExportProjection.IDX_EVENT_COLOR)?.takeIf { + it != calendar?.color || !getString(EventExportProjection.IDX_EVENT_COLOR_KEY).isNullOrEmpty() + } + val mapped = event(calendar?.displayName).copy(color = color) + val selfStatus = getIntOrNull(EventExportProjection.IDX_SELF_ATTENDEE_STATUS) + val declined = selfStatus == CalendarContract.Attendees.ATTENDEE_STATUS_DECLINED + val originalId = getLongOrNull(EventExportProjection.IDX_ORIGINAL_ID) + val originalSyncId = getString(EventExportProjection.IDX_ORIGINAL_SYNC_ID)?.takeIf { it.isNotEmpty() } + // Without a link the provider shows the row as an event of its own. + if (originalId == null && originalSyncId == null) { + series += MasterRow( + eventId = getLong(EventExportProjection.IDX_ID), + calendarId = calendarId, + syncId = getString(EventExportProjection.IDX_SYNC_ID)?.takeIf { it.isNotEmpty() }, + event = mapped, + declined = declined, + ) + } else { + // An exception without its occurrence time can't name what it replaces. + val originalInstance = getLongOrNull(EventExportProjection.IDX_ORIGINAL_INSTANCE_TIME) + ?: return@forEachExportRow + overrides += OverrideRow( + calendarId = calendarId, + originalId = originalId, + originalSyncId = originalSyncId, + originalInstance = originalInstance.toKotlinInstantFromEpochMillis(), + event = mapped, + declined = declined, + accepted = selfStatus == CalendarContract.Attendees.ATTENDEE_STATUS_ACCEPTED || + selfStatus == CalendarContract.Attendees.ATTENDEE_STATUS_TENTATIVE, + ) + } + } + return CalendarRows(series, overrides) + } + + /** + * Hand each Events row matching [selection], oldest first, to [row] with a + * mapper to [IcsEvent] that takes the calendar name to tag it with. + * Reminders are read in one batched pass ahead of the rows. + */ + private fun forEachExportRow( + selection: String, + allDayReminderTimeMinutes: Int, + row: ColumnReader.(event: (calendarName: String?) -> IcsEvent) -> Unit, + ) { + val eventIds = resolver.query( + CalendarContract.Events.CONTENT_URI, + arrayOf(CalendarContract.Events._ID), + selection, + null, + null, + )?.use { c -> c.mapRows { getLong(0) } }.orEmpty() + val reminders = resolver.reminderMinutesByEvent(eventIds, alertsOnly = false) + resolver.query( CalendarContract.Events.CONTENT_URI, EventExportProjection.COLUMNS, - // Skip soft-deleted rows and exception rows (modified occurrences / - // cancellations) — v1 exports masters + one-offs only. - "${CalendarContract.Events.CALENDAR_ID} IN ($idList) AND " + - "${CalendarContract.Events.DELETED} = 0 AND " + - "${CalendarContract.Events.ORIGINAL_ID} IS NULL", + selection, null, CalendarContract.Events.DTSTART + " ASC", )?.use { c -> - c.mapRows { - val eventId = getLong(EventExportProjection.IDX_ID) - val calendarId = getLong(EventExportProjection.IDX_CALENDAR_ID) - toIcsEvent( - reminderMinutes = queryReminders(eventId).map { it.minutes }, - calendarName = names[calendarId], - allDayReminderTimeMinutes = allDayReminderTimeMinutes, - ) + val reader = CursorColumnReader(c) + while (c.moveToNext()) { + val eventId = reader.getLong(EventExportProjection.IDX_ID) + reader.row { calendarName -> + reader.toIcsEvent( + reminderMinutes = reminders[eventId].orEmpty(), + calendarName = calendarName, + allDayReminderTimeMinutes = allDayReminderTimeMinutes, + ) + } } - } ?: emptyList() + } } override fun existingUids(calendarId: Long): Set = resolver.query( @@ -865,24 +922,30 @@ class AndroidCalendarDataSource @Inject constructor( } else { null } - event.semanticReminderMinutes().forEach { minutes -> - val providerMinutes = if (reminderDate != null) { - toProviderAllDayMinutes( - semanticMinutes = minutes, - startDate = reminderDate, - zone = zone, - timeOfDayMinutes = allDayReminderTimeMinutes, - ) - } else { - minutes + // All or nothing: a row whose reminders failed would count as not added + // and still be there. + try { + event.semanticReminderMinutes().forEach { minutes -> + val providerMinutes = if (reminderDate != null) { + toProviderAllDayMinutes( + semanticMinutes = minutes, + startDate = reminderDate, + zone = zone, + timeOfDayMinutes = allDayReminderTimeMinutes, + ) + } else { + minutes + } + insertReminderRow(eventId, providerMinutes) } - insertReminderRow(eventId, providerMinutes) + } catch (t: Throwable) { + runCatching { resolver.delete(eventUri(eventId), null, null) } + throw t } return eventId } - /** The account a calendar belongs to, for scoping a `Colors` lookup. */ - private fun calendarAccount(calendarId: Long): CalendarAccount? = resolver.query( + override fun calendarAccount(calendarId: Long): SyncAccount? = resolver.query( ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI, calendarId), arrayOf( CalendarContract.Calendars.ACCOUNT_NAME, @@ -891,13 +954,17 @@ class AndroidCalendarDataSource @Inject constructor( null, null, null, )?.use { c -> if (c.moveToFirst()) { - CalendarAccount(name = c.getString(0).orEmpty(), type = c.getString(1).orEmpty()) + SyncAccount(name = c.getString(0).orEmpty(), type = c.getString(1).orEmpty()) } else { null } } - private data class CalendarAccount(val name: String, val type: String) + override fun eventCalendarId(eventId: Long): Long? = resolver.query( + ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventId), + arrayOf(CalendarContract.Events.CALENDAR_ID), + null, null, null, + )?.use { c -> if (c.moveToFirst() && !c.isNull(0)) c.getLong(0) else null } /** * The raw provider `MINUTES` to store for one of [form]'s reminders: an @@ -919,11 +986,15 @@ class AndroidCalendarDataSource @Inject constructor( minutes } - /** [form]'s reminders as the distinct raw provider offsets to store. */ + /** + * [form]'s reminders as the distinct raw provider offsets to store, its + * fixed-time ones (#459) measured from the start it is saved with. + */ private fun encodedReminders(form: EventForm, allDayReminderTimeMinutes: Int): List = - form.reminders - .map { providerReminderMinutes(form, it, allDayReminderTimeMinutes) } - .distinct() + ( + form.reminders.map { providerReminderMinutes(form, it, allDayReminderTimeMinutes) } + + form.fixedReminderOffsets(TimeZone.currentSystemDefault()) + ).distinct() override fun insertEvent(form: EventForm, allDayReminderTimeMinutes: Int): Long { // A globally-unique UID so a later .ics backup/restore can identify @@ -1024,9 +1095,12 @@ class AndroidCalendarDataSource @Inject constructor( updateEventRow(eventId, values.toContentValues(), "update event id=$eventId") } // Untouched reminder sets are left alone so unrelated edits can't - // disturb provider rows the form never knew about. The diff is on the - // form's semantic minutes; reconcile works in encoded provider minutes. - if (updated.reminders.toSet() != original.reminders.toSet()) { + // disturb provider rows the form never knew about. A fixed-time reminder + // also changes when the start's day or time does. + val zone = TimeZone.currentSystemDefault() + if (remindersNeedRewrite(original, updated) || + updated.fixedReminderOffsets(zone).toSet() != original.fixedReminderOffsets(zone).toSet() + ) { reconcileReminders(eventId, encodedReminders(updated, allDayReminderTimeMinutes)) } // Same untouched-set guard for guests: only reconcile when the form's @@ -1196,7 +1270,7 @@ class AndroidCalendarDataSource @Inject constructor( form: EventForm, allDayReminderTimeMinutes: Int, ): Long { - val row = querySeriesRow(eventId) + val row = querySeriesRow(eventId, beginMillis) // Not a series, so there is no occurrence to single out: the row *is* the // event, and an exception with nothing to be an exception to would leave // an orphan holding the edit (the same test deleteOccurrence makes). @@ -1227,8 +1301,9 @@ class AndroidCalendarDataSource @Inject constructor( ) } // Whether the provider copied the parent's reminder rows is its - // business — reconciling against the actual rows handles both ways. - reconcileReminders(exceptionId, encodedReminders(form, allDayReminderTimeMinutes)) + // business — reconciling against the actual rows handles both ways. The + // exception is a one-off, so a fixed-time reminder takes real minutes. + reconcileReminders(exceptionId, encodedReminders(form.toDetachedOccurrence(), allDayReminderTimeMinutes)) reconcileAttendees(exceptionId, form.attendees) return exceptionId } @@ -1274,6 +1349,8 @@ class AndroidCalendarDataSource @Inject constructor( // Reminders, guests and colour come along like any new event, and so does // a fresh UID — the detached row is a separate event now, and sharing the // parent's would collide with it in .ics restore dedup. + // Fail before inserting: the EXDATE write below needs a usable length. + row.writeDuration() val detachedId = insertEvent(form.toDetachedOccurrence(), allDayReminderTimeMinutes) // Rows touched, not occurrences excluded — 1 whenever the series row still // exists. It catches the row disappearing under us, not an EXDATE the @@ -1309,7 +1386,7 @@ class AndroidCalendarDataSource @Inject constructor( updated: EventForm, allDayReminderTimeMinutes: Int, ): Long { - val row = querySeriesRow(eventId) + val row = querySeriesRow(eventId, beginMillis) // From the first occurrence on (or with no rule to split) this is // just a series update. if (row.rrule.isNullOrBlank() || beginMillis <= row.dtStartMillis) { @@ -1317,6 +1394,8 @@ class AndroidCalendarDataSource @Inject constructor( return eventId } // Insert the new series first: if it fails, the original is untouched. + // Fail before inserting: truncating the original needs a usable length. + row.writeDuration() val newEventId = insertEvent(updated, allDayReminderTimeMinutes) carrySplitExdate(newEventId, row, beginMillis, original, updated) truncateSeries(eventId, row, beginMillis) @@ -1372,7 +1451,7 @@ class AndroidCalendarDataSource @Inject constructor( } override fun deleteEventFromOccurrence(eventId: Long, beginMillis: Long) { - val row = querySeriesRow(eventId) + val row = querySeriesRow(eventId, beginMillis) // From the first occurrence on = the whole series; also the fallback // when there is no RRULE to truncate. if (row.rrule.isNullOrBlank() || beginMillis <= row.dtStartMillis) { @@ -1401,8 +1480,12 @@ class AndroidCalendarDataSource @Inject constructor( updateEventRow(eventId, values, "truncate series event id=$eventId begin=$beginMillis") } - /** The series anchor: every time-related column of the Events row. */ - private fun querySeriesRow(eventId: Long): SeriesRow = resolver.query( + /** + * The series anchor: every time-related column of the Events row. A recurring + * row with no usable DURATION gets one derived ([seriesDuration]), from the + * expanded occurrence at [occurrenceMillis] when DTEND can't supply it. + */ + private fun querySeriesRow(eventId: Long, occurrenceMillis: Long? = null): SeriesRow = resolver.query( eventUri(eventId), arrayOf( CalendarContract.Events.DTSTART, @@ -1413,11 +1496,12 @@ class AndroidCalendarDataSource @Inject constructor( CalendarContract.Events._SYNC_ID, CalendarContract.Events.EXDATE, CalendarContract.Events.RDATE, + CalendarContract.Events.DTEND, ), null, null, null, )?.use { c -> if (c.moveToFirst()) { - SeriesRow( + val row = SeriesRow( dtStartMillis = c.getLong(0), rrule = c.getString(1), timezone = c.getString(2), @@ -1427,11 +1511,27 @@ class AndroidCalendarDataSource @Inject constructor( exdate = c.getString(6), rdate = c.getString(7), ) + if (!row.recurs || !row.duration.isNullOrBlank()) return@use row + row.copy( + dtEndMillis = if (c.isNull(8)) null else c.getLong(8), + occurrenceSpanMillis = occurrenceMillis?.let { occurrenceSpan(eventId, it) }, + ) } else { null } } ?: throw WriteFailedException("read series row of event id=$eventId") + /** Length of the already-expanded occurrence of [eventId] starting at [beginMillis]. */ + private fun occurrenceSpan(eventId: Long, beginMillis: Long): Long? { + return resolver.query( + instancesUri(beginMillis, beginMillis + 1), + arrayOf(CalendarContract.Instances.BEGIN, CalendarContract.Instances.END), + "${CalendarContract.Instances.EVENT_ID} = ? AND ${CalendarContract.Instances.BEGIN} = ?", + arrayOf(eventId.toString(), beginMillis.toString()), + null, + )?.use { c -> if (c.moveToFirst()) c.getLong(1) - c.getLong(0) else null } + } + private data class SeriesRow( val dtStartMillis: Long, val rrule: String?, @@ -1442,6 +1542,9 @@ class AndroidCalendarDataSource @Inject constructor( val syncId: String? = null, val exdate: String? = null, val rdate: String? = null, + /** Only read for a series with no DURATION, to derive one ([writeDuration]). */ + val dtEndMillis: Long? = null, + val occurrenceSpanMillis: Long? = null, ) { /** * Whether this row expands into more than itself. RDATE counts as much as @@ -1451,14 +1554,23 @@ class AndroidCalendarDataSource @Inject constructor( */ val recurs: Boolean get() = !rrule.isNullOrBlank() || !rdate.isNullOrBlank() + /** + * DURATION for a write that re-expands the series. Refuses rather than + * writing none, which would leave the provider nothing to expand (#502). + */ + fun writeDuration(): String = duration?.takeIf { it.isNotBlank() } + ?: seriesDuration(dtStartMillis, dtEndMillis, occurrenceSpanMillis, allDay != 0) + ?: throw WriteFailedException("series has no usable length") + /** * The time/recurrence set a series write carries together: the provider * re-expands instances only from what the update itself holds. */ fun timeColumns(): ContentValues = ContentValues().apply { put(CalendarContract.Events.DTSTART, dtStartMillis) + putNull(CalendarContract.Events.DTEND) put(CalendarContract.Events.RRULE, rrule) - put(CalendarContract.Events.DURATION, duration) + put(CalendarContract.Events.DURATION, writeDuration()) put(CalendarContract.Events.EVENT_TIMEZONE, timezone) put(CalendarContract.Events.ALL_DAY, allDay) } @@ -1470,7 +1582,7 @@ class AndroidCalendarDataSource @Inject constructor( dtStartMillis = dtStartMillis, rrule = rrule, rdate = rdate, - duration = duration, + duration = writeDuration(), timezone = timezone, allDay = allDay, ) @@ -1657,7 +1769,7 @@ class AndroidCalendarDataSource @Inject constructor( } override fun deleteOccurrence(eventId: Long, beginMillis: Long) { - val row = querySeriesRow(eventId) + val row = querySeriesRow(eventId, beginMillis) // Not a series, so the row *is* the event: an exclusion would put a // recurrence set on a one-off, an exception would leave an orphan. if (!row.recurs) { @@ -1687,7 +1799,7 @@ class AndroidCalendarDataSource @Inject constructor( val values = buildOccurrenceCancelValues( originalInstanceMillis = beginMillis, dtStartMillis = beginMillis, - duration = row.duration, + duration = row.writeDuration(), timezone = row.timezone, allDay = row.allDay, ) @@ -1785,3 +1897,11 @@ class AndroidCalendarDataSource @Inject constructor( const val MAX_SEARCH_TOKENS = 8 } } + +/** + * Whether an update must rewrite the reminder rows. The diff is on the form's + * semantic minutes, but the provider stores encoded minutes, so switching all-day + * on or off re-encodes an otherwise unchanged set. + */ +internal fun remindersNeedRewrite(original: EventForm, updated: EventForm): Boolean = + updated.reminders.toSet() != original.reminders.toSet() || updated.isAllDay != original.isAllDay diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt index 3d1308c7..b3d78961 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt @@ -11,6 +11,7 @@ import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emptyFlow +import kotlinx.coroutines.flow.flowOf import kotlin.time.Instant interface CalendarRepository { @@ -61,18 +62,41 @@ interface CalendarRepository { suspend fun setCalendarsVisible(ids: Collection, visible: Boolean) /** - * Every event of the writable local calendars, ready to serialise into a - * whole-calendar `.ics` backup (see [CalendarDataSource.exportableEvents]). - * [calendarIds] narrows the export to a chosen subset; `null` exports all. + * Every event of [calendarIds], ready to serialise into an `.ics` backup + * (see [CalendarDataSource.calendarRows]). Any calendar can be read, + * synced and read-only ones included (#147). Exception rows come out + * flattened ([de.jeanlucmakiola.calendula.domain.ics.flattenOverrides]), + * so a restore keeps moved and deleted occurrences of a series. */ - suspend fun exportEvents(calendarIds: Set? = null): List + suspend fun exportEvents(calendarIds: Set): List /** * Bulk-import parsed `.ics` [events] into [targetCalendarId]. Events whose * UID already exists in the target are skipped (idempotent restore); the - * rest are inserted. See [CalendarDataSource.insertImportedEvent]. + * rest are inserted, as is a standalone occurrence whose series is already + * there ([ParsedIcsEvent.overrideOf]). See [CalendarDataSource.insertImportedEvent]. + * [onProgress] gets the count of events handled so far before each event + * after the first and once more when all were handled; it may throw to stop + * the import between events. */ - suspend fun importEvents(targetCalendarId: Long, events: List): IcsImportSummary + suspend fun importEvents( + targetCalendarId: Long, + events: List, + onProgress: (done: Int) -> Unit = {}, + ): IcsImportSummary + + /** + * Copy every event of [sourceCalendarId] into [targetCalendarId] (#325), + * exceptions included (see + * [de.jeanlucmakiola.calendula.domain.ics.planCalendarCopy]). The source is only read. Runs + * through [importEvents], so a re-run skips what an earlier one copied. + * [onProgress] gets (done, total) once the source is read and after each event. + */ + suspend fun copyEvents( + sourceCalendarId: Long, + targetCalendarId: Long, + onProgress: (done: Int, total: Int) -> Unit = { _, _ -> }, + ): IcsImportSummary /** Create a new event from a validated form; returns the new `Events._ID`. */ suspend fun createEvent(form: EventForm): Long @@ -134,6 +158,31 @@ interface CalendarRepository { /** Delete a recurring event from the occurrence at [beginMillis] onwards. */ suspend fun deleteEventFromOccurrence(eventId: Long, beginMillis: Long) + + /** + * Ask every account behind a visible synced calendar to sync now (#240). + * Only a request: the adapter may still run it late, or fail. + */ + suspend fun requestSync(): SyncRequest = SyncRequest(SyncRequestResult.NothingToSync) + + /** Wait for the syncs a [requestSync] reached to run, see [awaitSyncs]. */ + suspend fun awaitSyncs(accounts: Set): SyncWait = SyncWait.Unconfirmed + + /** + * The accounts behind visible calendars with a sync adapter, split by + * whether [requestSync] can reach them yet. Account access isn't observable: + * it is re-read on each collection and on every [refreshSyncAccess]. + */ + val syncTargets: Flow get() = flowOf(SyncTargets.None) + + /** Re-read account access for every [syncTargets] collector; it can change outside the app. */ + fun refreshSyncAccess() {} + + /** Stop or resume asking for [account]'s sync-request access. */ + suspend fun setSyncAccessDismissed(account: SyncAccount, dismissed: Boolean) {} + + /** Every provider notification and [refresh], including the app's own writes. */ + val providerChanges: Flow get() = emptyFlow() } class NoSuchEventException(eventId: Long) : diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt index 481ae7a4..07a61a36 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt @@ -14,10 +14,14 @@ import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.domain.SearchCandidate import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent +import de.jeanlucmakiola.calendula.domain.ics.flattenOverrides +import de.jeanlucmakiola.calendula.domain.ics.planCalendarCopy import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.drop @@ -30,6 +34,8 @@ import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.withContext import java.util.concurrent.atomic.AtomicLong import kotlin.time.Instant @@ -47,6 +53,7 @@ class CalendarRepositoryImpl @Inject constructor( private val prefs: CalendarPrefs, private val settingsPrefs: SettingsPrefs, @IoDispatcher private val io: CoroutineDispatcher, + private val syncRequester: SyncRequester, ) : CalendarRepository { /** The configured wall-clock fire time for all-day reminders, read per write. */ @@ -84,16 +91,172 @@ class CalendarRepositoryImpl @Inject constructor( onBufferOverflow = BufferOverflow.DROP_OLDEST, ) - /** Run a provider write on [io], then re-query whether or not it threw. */ - private suspend fun write(block: suspend () -> T): T = withContext(io) { + override val providerChanges: Flow get() = ticks + + /** + * Run a provider write on [io], then re-query whether or not it threw. The + * accounts behind [syncCalendars] (read before the write, which may delete + * the row) then get one sync nudge each (#303), also after a failure, which + * may have landed part of a multi-row write. Once per write, so a multi-row + * save or a whole import asks once per account. + */ + private suspend fun write( + syncCalendars: suspend () -> Collection, + block: suspend () -> T, + ): T = withContext(io) { + val accounts = syncAccountsOf(syncCalendars) try { block() } finally { refresh() writes.tryEmit(Unit) + requestSyncs(accounts, userInitiated = false) } } + private val noSync: suspend () -> Collection = { emptyList() } + + private suspend fun syncAccountsOf(calendarIds: suspend () -> Collection): Set = + try { + calendarIds().filterNotNull().distinct() + .mapNotNull { accountOf(it) } + .withAdapter() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "No sync nudge: the calendar account could not be read", e) + emptySet() + } + + /** From the shared per-tick read; a calendar newer than it is read on its own. */ + private suspend fun accountOf(calendarId: Long): SyncAccount? = + calendarsSnapshot().firstOrNull { it.id == calendarId } + ?.let { SyncAccount(it.accountName, it.accountType) } + ?: dataSource.calendarAccount(calendarId) + + /** The syncable accounts among these whose type has a calendar sync adapter. */ + private fun Collection.withAdapter(): Set { + val candidates = filter { it.isSyncable } + if (candidates.isEmpty()) return emptySet() + val adapterTypes = try { + syncRequester.adapterAccountTypes() + } catch (e: Exception) { + Log.w(TAG, "Sync adapters unreadable", e) + return emptySet() + } + return candidates.filterTo(linkedSetOf()) { it.type in adapterTypes } + } + + /** + * Splits [accounts] by whether a request may name them (see + * [SyncRequester.addressableAccounts]). The rest wait for the user's grant: + * an account-less request would reach them, but also every other calendar + * account on the device, so none is sent. + */ + private fun reach(accounts: Set): SyncTargets { + if (accounts.isEmpty()) return SyncTargets.None + // Unreadable access counts as reachable: a grant can't fix a failing read. + val addressable = try { + syncRequester.addressableAccounts(accounts.mapTo(mutableSetOf()) { it.type }) + } catch (e: Exception) { + Log.w(TAG, "Account visibility unreadable", e) + null + } + if (addressable == null) return SyncTargets(reachable = accounts, needsAccess = emptySet()) + val (reachable, hidden) = accounts.partition { it in addressable } + return SyncTargets(reachable.toSet(), hidden.toSet()) + } + + /** Ask each reachable one of [accounts] once. */ + private fun requestSyncs(accounts: Set, userInitiated: Boolean) { + reach(accounts).reachable.forEach { requestSync(it, userInitiated) } + } + + private fun requestSync(account: SyncAccount, userInitiated: Boolean): Boolean = try { + syncRequester.requestSync(account, userInitiated) + true + } catch (e: Exception) { + Log.w(TAG, "Sync request refused", e) + false + } + + /** The event's own calendar (from [original] when given, else read), plus [others]. */ + private fun eventCalendar( + eventId: Long, + original: EventForm? = null, + vararg others: Long?, + ): suspend () -> Collection = + { listOf(original?.calendarId ?: dataSource.eventCalendarId(eventId), *others) } + + private fun targetsOf(calendars: List, dismissed: Set): SyncTargets = + reach( + calendars.syncAccounts().withAdapter() + .sortedWith(compareBy({ it.name.lowercase() }, { it.type })) + .toSet(), + ).let { + if (dismissed.isEmpty()) { + it + } else { + it.copy(needsAccess = it.needsAccess - dismissed, dismissed = it.needsAccess intersect dismissed) + } + } + + private val accessChecks = MutableStateFlow(0) + + override val syncTargets: Flow + get() = combine(calendars(), prefs.syncAccessDismissed, accessChecks) { calendars, dismissed, _ -> + // One failed read leaves the rows off until the next change, not for good. + try { + targetsOf(calendars, dismissed) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Sync targets unreadable", e) + SyncTargets.None + } + }.flowOn(io) + + override fun refreshSyncAccess() { + accessChecks.update { it + 1 } + } + + override suspend fun setSyncAccessDismissed(account: SyncAccount, dismissed: Boolean) { + try { + prefs.setSyncAccessDismissed(account, dismissed) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Sync access dismissal not saved", e) + } + } + + override suspend fun requestSync(): SyncRequest = withContext(io) { + val targets = try { + targetsOf(calendars().first(), prefs.syncAccessDismissed.first()) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Sync request skipped: calendars unreadable", e) + return@withContext SyncRequest(SyncRequestResult.Failed) + } + if (targets.reachable.isEmpty()) { + return@withContext SyncRequest( + if (targets.needsAccess.isEmpty()) SyncRequestResult.NothingToSync else SyncRequestResult.NeedsAccess, + ) + } + val sent = targets.reachable.filterTo(linkedSetOf()) { requestSync(it, userInitiated = true) } + val result = when { + sent.isEmpty() -> SyncRequestResult.Failed + sent.size < targets.reachable.size -> SyncRequestResult.PartlyFailed + targets.needsAccess.isNotEmpty() -> SyncRequestResult.SomeNeedAccess + else -> SyncRequestResult.Requested + } + SyncRequest(result, sent) + } + + override suspend fun awaitSyncs(accounts: Set): SyncWait = + withContext(io) { syncRequester.awaitSyncs(accounts) } + override val localChanges: Flow = merge( writes, prefs.pendingDisabledCalendarIds.distinctUntilChanged().drop(1).map {}, @@ -218,7 +381,7 @@ class CalendarRepositoryImpl @Inject constructor( displayName: String, color: Int, description: String?, - ): Long = write { + ): Long = write(noSync) { dataSource.createLocalCalendar(displayName, color, description) } @@ -227,13 +390,14 @@ class CalendarRepositoryImpl @Inject constructor( displayName: String, color: Int, description: String?, - ) = write { dataSource.updateCalendar(id, displayName, color, description) } + ) = write(noSync) { dataSource.updateCalendar(id, displayName, color, description) } override suspend fun deleteCalendar(id: Long) = - write { dataSource.deleteCalendar(id) } + write(noSync) { dataSource.deleteCalendar(id) } override suspend fun setCalendarsVisible(ids: Collection, visible: Boolean) = - write { + // VISIBLE is device-local: nothing for an adapter to upload. + write(noSync) { val canWrite = dataSource.canWriteCalendars() if (canWrite) ids.forEach { dataSource.setCalendarVisible(it, visible) } // Nothing of ours is left waiting for the provider once the write @@ -247,13 +411,34 @@ class CalendarRepositoryImpl @Inject constructor( } } - override suspend fun exportEvents(calendarIds: Set?) = - withContext(io) { dataSource.exportableEvents(calendarIds, allDayReminderTimeMinutes()) } + override suspend fun exportEvents(calendarIds: Set) = withContext(io) { + flattenOverrides(dataSource.calendarRows(calendarIds, allDayReminderTimeMinutes()), ::formatExdateStamp) + } + + override suspend fun copyEvents( + sourceCalendarId: Long, + targetCalendarId: Long, + onProgress: (done: Int, total: Int) -> Unit, + ): IcsImportSummary { + val events = withContext(io) { + planCalendarCopy( + dataSource.calendarRows(setOf(sourceCalendarId), allDayReminderTimeMinutes()), + ::formatExdateStamp, + ) + } + onProgress(0, events.size) + val context = currentCoroutineContext() + return importEvents(targetCalendarId, events) { done -> + if (done < events.size) context.ensureActive() + onProgress(done, events.size) + } + } override suspend fun importEvents( targetCalendarId: Long, events: List, - ): IcsImportSummary = write { + onProgress: (done: Int) -> Unit, + ): IcsImportSummary = write({ listOf(targetCalendarId) }) { val existing = dataSource.existingUids(targetCalendarId) // Both are per-calendar, not per-event: looking them up once keeps a // thousand-event restore to two extra queries. The palette is the @@ -265,15 +450,21 @@ class CalendarRepositoryImpl @Inject constructor( var skipped = 0 var failed = 0 var notAttempted = 0 - for ((index, event) in events.withIndex()) { + // Occurrences whose standalone copy didn't land, by series UID: the series + // keeps them instead of excluding them for good. + val unexcluded = mutableMapOf>() + // Standalone occurrences ahead of the series they were cut from, however the file is ordered. + val ordered = events.sortedBy { it.overrideOf == null } + for ((index, event) in ordered.withIndex()) { + if (index > 0) onProgress(index) // A known UID means the event is already in this calendar — skip, // keeping a restore idempotent (no overwrite this pass). - if (event.uid != null && event.uid in existing) { + if (event.isAlreadyIn(existing)) { skipped++ continue } try { - dataSource.insertImportedEvent(event, targetCalendarId, allDayMinutes, palette) + dataSource.insertImportedEvent(event.keeping(unexcluded), targetCalendarId, allDayMinutes, palette) imported++ } catch (e: CancellationException) { throw e @@ -283,8 +474,8 @@ class CalendarRepositoryImpl @Inject constructor( Log.w(TAG, "Import stopped: the calendar is no longer writable", e) // A known UID would have been skipped whatever happened, so it is // no part of what a retry still has to import. - val remaining = events.drop(index) - val duplicates = remaining.count { it.uid?.let { uid -> uid in existing } == true } + val remaining = ordered.drop(index) + val duplicates = remaining.count { it.isAlreadyIn(existing) } skipped += duplicates notAttempted = remaining.size - duplicates break @@ -293,9 +484,13 @@ class CalendarRepositoryImpl @Inject constructor( // rest of the file — foreign exports do carry rows it rejects // outright (a malformed RRULE throws straight out of insert). failed++ + if (event.overrideOf != null && event.overrideAt != null) { + unexcluded.getOrPut(event.overrideOf) { mutableListOf() } += event.overrideAt + } Log.w(TAG, "Skipped an unimportable event", e) } } + if (notAttempted == 0) onProgress(events.size) IcsImportSummary( imported = imported, skippedDuplicate = skipped, @@ -304,7 +499,7 @@ class CalendarRepositoryImpl @Inject constructor( ) } - override suspend fun createEvent(form: EventForm): Long = write { + override suspend fun createEvent(form: EventForm): Long = write({ listOf(form.calendarId) }) { dataSource.insertEvent(form, allDayReminderTimeMinutes()) } @@ -312,11 +507,11 @@ class CalendarRepositoryImpl @Inject constructor( eventId: Long, original: EventForm, updated: EventForm, - ) = write { + ) = write(eventCalendar(eventId, original, updated.calendarId)) { dataSource.updateEvent(eventId, original, updated, allDayReminderTimeMinutes()) } - override suspend fun deleteEvent(eventId: Long) = write { + override suspend fun deleteEvent(eventId: Long) = write(eventCalendar(eventId)) { dataSource.deleteEvent(eventId) } @@ -325,7 +520,7 @@ class CalendarRepositoryImpl @Inject constructor( targetCalendarId: Long, original: EventForm, updated: EventForm, - ): Long = write { + ): Long = write(eventCalendar(eventId, original, targetCalendarId)) { dataSource.moveEvent( eventId, targetCalendarId, original, updated, allDayReminderTimeMinutes(), ) @@ -336,7 +531,7 @@ class CalendarRepositoryImpl @Inject constructor( beginMillis: Long, original: EventForm, form: EventForm, - ): Long = write { + ): Long = write(eventCalendar(eventId, original)) { dataSource.updateOccurrence( eventId, beginMillis, original, form, allDayReminderTimeMinutes(), ) @@ -347,7 +542,7 @@ class CalendarRepositoryImpl @Inject constructor( beginMillis: Long, original: EventForm, updated: EventForm, - ): Long = write { + ): Long = write(eventCalendar(eventId, original)) { dataSource.updateEventFromOccurrence( eventId, beginMillis, original, updated, allDayReminderTimeMinutes(), ) @@ -357,14 +552,14 @@ class CalendarRepositoryImpl @Inject constructor( override val seriesSplits: Flow = splits - override suspend fun deleteOccurrence(eventId: Long, beginMillis: Long) = write { + override suspend fun deleteOccurrence(eventId: Long, beginMillis: Long) = write(eventCalendar(eventId)) { dataSource.deleteOccurrence(eventId, beginMillis) } override suspend fun deleteEventFromOccurrence( eventId: Long, beginMillis: Long, - ) = write { + ) = write(eventCalendar(eventId)) { dataSource.deleteEventFromOccurrence(eventId, beginMillis) } @@ -376,3 +571,18 @@ class CalendarRepositoryImpl @Inject constructor( private fun Flow.reQuery(block: suspend () -> T): Flow = flow { collect { emit(block()) } } + +/** + * Whether [existing] UIDs already hold this event: its own UID, or — for a + * standalone occurrence of a backed-up or copied series — the series, which + * there carries the override itself. + */ +private fun ParsedIcsEvent.isAlreadyIn(existing: Set): Boolean = + (uid != null && uid in existing) || (overrideOf != null && overrideOf in existing) + +/** This series without the exclusions of [unexcluded] occurrences whose standalone copy failed. */ +private fun ParsedIcsEvent.keeping(unexcluded: Map>): ParsedIcsEvent { + val kept = uid?.let(unexcluded::get) ?: return this + val stamps = kept.map { formatExdateStamp(it.toEpochMilliseconds(), isAllDay) }.toSet() + return copy(exDates = exDates.filterNot { it in stamps }) +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapper.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapper.kt index 1317e9c6..980a38ad 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapper.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapper.kt @@ -369,7 +369,8 @@ internal fun buildMovedMasterValues( /** The recurring copy's DURATION: its own if present, else derived from DTEND. */ private fun MasterEventSnapshot.movedDuration(): String = duration?.takeIf { it.isNotBlank() } - ?: rfc2445Duration((dtEndMillis ?: dtStartMillis) - dtStartMillis, isAllDay) + ?: seriesDuration(dtStartMillis, dtEndMillis ?: dtStartMillis, occurrenceSpanMillis = null, isAllDay = isAllDay) + ?: throw WriteFailedException("move series with no usable length") /** * Raw provider snapshot of one exception row of a recurring series (a modified @@ -454,6 +455,29 @@ internal fun buildOccurrenceExdateValues( existingExdate, listOf(occurrenceMillis), dtStartMillis, rrule, rdate, duration, timezone, allDay, ) +/** + * DURATION for a series row that has none. Rows from other tools can carry a + * DTEND (sometimes 0) instead; rewriting them without a DURATION leaves the + * provider nothing to expand, and every occurrence vanishes (#502). The span of + * an occurrence the provider actually expanded wins over DTEND; null when + * neither gives a length (a DTEND before DTSTART), so the caller fails + * instead of guessing. + */ +internal fun seriesDuration( + dtStartMillis: Long, + dtEndMillis: Long?, + occurrenceSpanMillis: Long?, + isAllDay: Boolean, +): String? { + val span = occurrenceSpanMillis?.takeIf { it >= 0 } + ?: dtEndMillis?.minus(dtStartMillis)?.takeIf { it >= 0 } + ?: return null + if (!isAllDay) return rfc2445Duration(span, isAllDay = false) + // Whole days, rounded: a span read across a DST change or zone offset is a few hours off. + val days = ((span + MILLIS_PER_DAY / 2) / MILLIS_PER_DAY).coerceAtLeast(1) + return rfc2445Duration(days * MILLIS_PER_DAY, isAllDay = true) +} + /** [buildOccurrenceExdateValues] excluding every one of [occurrences] in one write. */ internal fun buildOccurrencesExdateValues( existingExdate: String?, @@ -469,6 +493,7 @@ internal fun buildOccurrencesExdateValues( mergedExdate(exdate, millis, allDay != 0, timezone) }, CalendarContract.Events.DTSTART to dtStartMillis, + CalendarContract.Events.DTEND to null, CalendarContract.Events.RRULE to rrule, CalendarContract.Events.RDATE to rdate, CalendarContract.Events.DURATION to duration, @@ -684,7 +709,7 @@ private const val TZID_PREFIX = "TZID=" * are UTC: the provider stores an all-day DTSTART at UTC midnight, so its date * reads off the UTC calendar day. */ -private fun formatExdateStamp(occurrenceMillis: Long, isAllDay: Boolean): String = +internal fun formatExdateStamp(occurrenceMillis: Long, isAllDay: Boolean): String = formatExdateStamp( local = Instant.ofEpochMilli(occurrenceMillis).atZone(ZoneOffset.UTC).toLocalDateTime(), isAllDay = isAllDay, @@ -851,10 +876,12 @@ internal fun buildImportedEventValues( put(CalendarContract.Events.TITLE, event.summary.trim()) put(CalendarContract.Events.ALL_DAY, if (event.isAllDay) 1 else 0) put(CalendarContract.Events.DTSTART, startMillis) - if (event.recurrenceRule == null) { + if (event.recurrenceRule == null && event.recurrenceDates.isEmpty()) { put(CalendarContract.Events.DTEND, endMillis) } else { - put(CalendarContract.Events.RRULE, event.recurrenceRule) + event.recurrenceRule?.let { put(CalendarContract.Events.RRULE, it) } + event.recurrenceDates.takeIf { it.isNotEmpty() } + ?.let { put(CalendarContract.Events.RDATE, it.joinToString(",")) } put( CalendarContract.Events.DURATION, importDuration(startMillis, endMillis, event.isAllDay), @@ -866,6 +893,9 @@ internal fun buildImportedEventValues( // timed rows keep the event's own zone. put(CalendarContract.Events.EVENT_TIMEZONE, if (event.isAllDay) "UTC" else event.zoneId) put(CalendarContract.Events.AVAILABILITY, event.availability.toProviderValue()) + if (event.accessLevel != AccessLevel.Default) { + put(CalendarContract.Events.ACCESS_LEVEL, event.accessLevel.toProviderValue()) + } put(CalendarContract.Events.STATUS, event.status.forNewEvent().toProviderStatus()) event.location?.trim()?.takeIf { it.isNotEmpty() } ?.let { put(CalendarContract.Events.EVENT_LOCATION, it) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapper.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapper.kt index 1657e5b4..4dec9b9a 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapper.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapper.kt @@ -1,9 +1,13 @@ package de.jeanlucmakiola.calendula.data.calendar import de.jeanlucmakiola.floret.time.toKotlinInstantFromEpochMillis +import de.jeanlucmakiola.calendula.domain.AccessLevel import de.jeanlucmakiola.calendula.domain.ics.IcsEvent import de.jeanlucmakiola.calendula.domain.ics.deriveIcsUid +import java.time.Instant +import java.time.LocalDate import java.time.ZoneId +import java.time.format.DateTimeFormatter /** * Map one Events row (read through [EventExportProjection]) into an [IcsEvent] @@ -28,6 +32,8 @@ internal fun ColumnReader.toIcsEvent( val dtStart = getLong(EventExportProjection.IDX_DTSTART) val rrule = getString(EventExportProjection.IDX_RRULE)?.takeIf { it.isNotBlank() } val isAllDay = getInt(EventExportProjection.IDX_ALL_DAY) != 0 + val timezone = getString(EventExportProjection.IDX_EVENT_TIMEZONE) + val rdates = exportRecurrenceDates(getString(EventExportProjection.IDX_RDATE), isAllDay, timezone, dtStart) // Unclamped: the writer renders DTEND as stored. val end = endMillis(dtStart, EventExportProjection.IDX_DTEND, EventExportProjection.IDX_DURATION) @@ -38,17 +44,12 @@ internal fun ColumnReader.toIcsEvent( start = dtStart.toKotlinInstantFromEpochMillis(), end = end.toKotlinInstantFromEpochMillis(), isAllDay = isAllDay, - zoneId = getString(EventExportProjection.IDX_EVENT_TIMEZONE)?.takeIf { it.isNotBlank() } - ?: "UTC", + zoneId = timezone?.takeIf { it.isNotBlank() } ?: "UTC", recurrenceRule = rrule, - exDates = if (rrule == null) { + exDates = if (rrule == null && rdates.isEmpty()) { emptyList() } else { - exportExDates( - getString(EventExportProjection.IDX_EXDATE), - isAllDay, - getString(EventExportProjection.IDX_EVENT_TIMEZONE), - ) + exportExDates(getString(EventExportProjection.IDX_EXDATE), isAllDay, timezone, dtStart) }, location = getString(EventExportProjection.IDX_LOCATION), description = getString(EventExportProjection.IDX_DESCRIPTION), @@ -63,6 +64,8 @@ internal fun ColumnReader.toIcsEvent( status = eventStatus(EventExportProjection.IDX_STATUS), availability = mapAvailability(getInt(EventExportProjection.IDX_AVAILABILITY)), calendarName = calendarName, + recurrenceDates = rdates, + accessLevel = getIntOrNull(EventExportProjection.IDX_ACCESS_LEVEL)?.let(::mapAccessLevel) ?: AccessLevel.Default, ) } @@ -94,16 +97,53 @@ internal fun exportExDates( exdate: String?, isAllDay: Boolean, eventTimezone: String? = null, + seriesStartMillis: Long? = null, ): List { if (exdate.isNullOrBlank()) return emptyList() - val zone = exdateListZone(exdate, eventTimezone) - return exdateStamps(exdate) - .map { stamp -> - if (isAllDay) { - stamp.substringBefore('T') - } else { - canonicalExdateStamp(stamp, isAllDay = false, listZone = zone) ?: stamp + // Several properties are stored one per line, each with its own zone prefix. + return exdate.lines().filter { it.isNotBlank() }.flatMap { line -> + val zone = exdateListZone(line, eventTimezone) + exdateStamps(line).mapNotNull { stamp -> + when { + isAllDay -> stamp.substringBefore('T') + // A bare day on a timed series means the occurrence at the series' time of day. + seriesStartMillis != null && BARE_DAY.matches(stamp) -> atSeriesTime(stamp, seriesStartMillis, zone) + else -> canonicalExdateStamp(stamp, isAllDay = false, listZone = zone) ?: stamp } } + } + .filter { (if (isAllDay) BARE_DAY else UTC_STAMP).matches(it) } .distinct() } + +/** + * The row's `RDATE` in the same shape [exportExDates] gives `EXDATE` — the list + * shares its `;` form. A `PERIOD` entry (`start/end`) keeps only its + * start: the occurrence then runs the series' own length. Anything that still + * isn't a date or a UTC stamp is dropped, since a file can't name it. + */ +internal fun exportRecurrenceDates( + rdate: String?, + isAllDay: Boolean, + eventTimezone: String? = null, + seriesStartMillis: Long? = null, +): List { + if (rdate.isNullOrBlank()) return emptyList() + // The zone prefix may hold a '/' of its own (Europe/Berlin), so only the stamps lose their period end. + val starts = rdate.lines().joinToString("\n") { line -> + val stamps = line.withoutExdateParameters() + line.dropLast(stamps.length) + stamps.split(',').joinToString(",") { it.substringBefore('/') } + } + return exportExDates(starts, isAllDay, eventTimezone, seriesStartMillis) +} + +/** [day] (`yyyyMMdd`) at the wall-clock time the series starts at in [zone], as a UTC stamp. */ +private fun atSeriesTime(day: String, seriesStartMillis: Long, zone: ZoneId): String? { + val date = runCatching { LocalDate.parse(day, DateTimeFormatter.BASIC_ISO_DATE) }.getOrNull() ?: return null + val time = Instant.ofEpochMilli(seriesStartMillis).atZone(zone).toLocalTime() + return formatExdateStamp(date.atTime(time).atZone(zone).toInstant().toEpochMilli(), isAllDay = false) +} + +private val BARE_DAY = Regex("""\d{8}""") +private val UTC_STAMP = Regex("""\d{8}T\d{6}Z""") + diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/Projections.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/Projections.kt index 5775d1a4..eeed00d7 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/Projections.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/Projections.kt @@ -152,14 +152,13 @@ internal object EventDetailProjection { } /** - * Master/one-off Events rows for a whole-calendar backup. Unlike + * Every Events row of a whole-calendar backup or copy. Unlike * [EventDetailProjection] this reads `UID_2445` (to keep a row's identity across * backups) and `DURATION` (recurring rows carry it instead of DTEND), plus - * `EXDATE` so a series exports the occurrences deleted from it. Modified- - * occurrence and cancelled-exception rows are filtered out by the query - * (`ORIGINAL_ID IS NULL`), so RECURRENCE-ID overrides aren't exported — a - * documented v1 limit (import skips them too). EXDATE is unaffected by that - * filter: it lives on the master row, not on an exception of its own. + * `EXDATE` so a series exports the occurrences deleted from it. Exception rows + * are read too and told apart by their series-link columns; see + * [de.jeanlucmakiola.calendula.domain.ics.flattenOverrides] for how they are + * written out. */ internal object EventExportProjection { val COLUMNS: Array = arrayOf( @@ -178,6 +177,15 @@ internal object EventExportProjection { CalendarContract.Events.STATUS, CalendarContract.Events.AVAILABILITY, CalendarContract.Events.CALENDAR_ID, + CalendarContract.Events.EVENT_COLOR, + CalendarContract.Events._SYNC_ID, + CalendarContract.Events.ORIGINAL_ID, + CalendarContract.Events.ORIGINAL_SYNC_ID, + CalendarContract.Events.ORIGINAL_INSTANCE_TIME, + CalendarContract.Events.RDATE, + CalendarContract.Events.ACCESS_LEVEL, + CalendarContract.Events.EVENT_COLOR_KEY, + CalendarContract.Events.SELF_ATTENDEE_STATUS, ) const val IDX_ID = 0 @@ -195,6 +203,15 @@ internal object EventExportProjection { const val IDX_STATUS = 12 const val IDX_AVAILABILITY = 13 const val IDX_CALENDAR_ID = 14 + const val IDX_EVENT_COLOR = 15 + const val IDX_SYNC_ID = 16 + const val IDX_ORIGINAL_ID = 17 + const val IDX_ORIGINAL_SYNC_ID = 18 + const val IDX_ORIGINAL_INSTANCE_TIME = 19 + const val IDX_RDATE = 20 + const val IDX_ACCESS_LEVEL = 21 + const val IDX_EVENT_COLOR_KEY = 22 + const val IDX_SELF_ATTENDEE_STATUS = 23 } /** diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/ReminderQueries.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/ReminderQueries.kt new file mode 100644 index 00000000..733167c2 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/ReminderQueries.kt @@ -0,0 +1,36 @@ +package de.jeanlucmakiola.calendula.data.calendar + +import android.content.ContentResolver +import android.provider.CalendarContract + +/** Ids per `IN (…)` list: they go into the SQL literally, which SQLite bounds. */ +private const val EVENT_ID_BATCH = 50 + +/** + * Reminder minutes of [eventIds], keyed by event, a batched query at a time + * rather than one per event. [alertsOnly] keeps just the notification ones. + */ +internal fun ContentResolver.reminderMinutesByEvent( + eventIds: Collection, + alertsOnly: Boolean, +): Map> { + if (eventIds.isEmpty()) return emptyMap() + val out = mutableMapOf>() + val method = if (alertsOnly) { + "${CalendarContract.Reminders.METHOD} = ${CalendarContract.Reminders.METHOD_ALERT} AND " + } else { + "" + } + eventIds.distinct().chunked(EVENT_ID_BATCH).forEach { batch -> + query( + CalendarContract.Reminders.CONTENT_URI, + arrayOf(CalendarContract.Reminders.EVENT_ID, CalendarContract.Reminders.MINUTES), + "$method${CalendarContract.Reminders.EVENT_ID} IN (${batch.joinToString(",")})", + null, + null, + )?.use { c -> + while (c.moveToNext()) out.getOrPut(c.getLong(0)) { mutableListOf() } += c.getInt(1) + } + } + return out +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt new file mode 100644 index 00000000..e6479672 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/SyncRequester.kt @@ -0,0 +1,215 @@ +package de.jeanlucmakiola.calendula.data.calendar + +import android.accounts.Account +import android.accounts.AccountManager +import android.content.ContentResolver +import android.content.Context +import android.content.Intent +import android.os.Build +import android.os.Bundle +import android.provider.CalendarContract +import dagger.hilt.android.qualifiers.ApplicationContext +import de.jeanlucmakiola.calendula.domain.CalendarSource +import kotlinx.coroutines.channels.awaitClose +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.callbackFlow +import kotlinx.coroutines.flow.channelFlow +import kotlinx.coroutines.flow.conflate +import kotlinx.coroutines.flow.filterNotNull +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull +import java.util.concurrent.atomic.AtomicBoolean +import javax.inject.Inject +import javax.inject.Singleton + +/** The account behind a calendar row (`ACCOUNT_NAME` / `ACCOUNT_TYPE`). */ +data class SyncAccount(val name: String, val type: String) { + /** Whether a sync adapter can stand behind it: device-only calendars have none. */ + val isSyncable: Boolean + get() = name.isNotBlank() && type.isNotBlank() && type != CalendarContract.ACCOUNT_TYPE_LOCAL +} + +/** + * Asks the system to run a calendar sync adapter sooner (#303, #240). The sync + * itself stays the adapter's job; this only schedules it. + */ +interface SyncRequester { + /** Account types with a calendar sync adapter installed; for any other a request does nothing. */ + fun adapterAccountTypes(): Set + + /** + * The accounts of [types] a request may name, or null when any may. From + * Android 13 a request for an account the app can't see is dropped without a word. + */ + fun addressableAccounts(types: Set): Set? + + /** + * Schedule a sync of [account]; may throw if the system refuses. [userInitiated] + * marks it manual, which also overrides master-sync-off — only for a user's tap. + */ + fun requestSync(account: SyncAccount, userInitiated: Boolean) + + /** Where [account]'s calendar sync stands, or null when the system won't say. */ + fun syncActivity(account: SyncAccount): SyncActivity? + + /** Fires whenever any sync on the device becomes pending, starts or ends. */ + fun syncActivityChanges(): Flow +} + +/** A calendar sync adapter's state for one account, from `READ_SYNC_STATS`. */ +enum class SyncActivity { Idle, Pending, Active } + +/** How waiting on requested syncs ended: seen through, or not confirmed in time. */ +enum class SyncWait { Completed, Unconfirmed } + +/** + * Waits until the syncs of [accounts] have run (#240): each account must have + * been seen pending or active and be idle again, or — for one that never showed + * up within [graceMillis] — be idle. A sync already running at the first look + * isn't the requested one, so it has to finish before the account counts. Unconfirmed after [timeoutMillis], or at + * once when the system won't report sync state. + */ +suspend fun SyncRequester.awaitSyncs( + accounts: Set, + timeoutMillis: Long = SYNC_WAIT_MILLIS, + graceMillis: Long = SYNC_GRACE_MILLIS, + pollMillis: Long = SYNC_POLL_MILLIS, +): SyncWait { + if (accounts.isEmpty()) return SyncWait.Completed + val seen = HashSet() + // One already running when asked is someone else's sync: it only counts once idle again. + var priorRuns: MutableSet? = null + val graceOver = AtomicBoolean(false) + return withTimeoutOrNull(timeoutMillis) { + channelFlow { + launch { syncActivityChanges().collect { send(Unit) } } + launch { + delay(graceMillis) + graceOver.set(true) + send(Unit) + } + // The listener alone can miss a change made before it was registered. + while (true) { + send(Unit) + delay(pollMillis) + } + }.conflate().map { + val states = accounts.associateWith { syncActivity(it) ?: return@map SyncWait.Unconfirmed } + val prior = priorRuns ?: states.filterValues { it == SyncActivity.Active }.keys.toMutableSet() + .also { priorRuns = it } + states.forEach { (account, state) -> + if (state != SyncActivity.Active) prior -= account + if (state != SyncActivity.Idle && account !in prior) seen += account + } + val done = states.all { (account, state) -> + state == SyncActivity.Idle && account !in prior && (account in seen || graceOver.get()) + } + if (done) SyncWait.Completed else null + }.filterNotNull().first() + } ?: SyncWait.Unconfirmed +} + +const val SYNC_WAIT_MILLIS = 60_000L +const val SYNC_GRACE_MILLIS = 5_000L +const val SYNC_POLL_MILLIS = 2_000L + +@Singleton +class AndroidSyncRequester @Inject constructor( + @ApplicationContext private val context: Context, +) : SyncRequester { + // Lists only adapters in packages visible to the app — hence the SyncAdapter entry. + override fun adapterAccountTypes(): Set = + ContentResolver.getSyncAdapterTypes() + .filter { it.authority == CalendarContract.AUTHORITY } + .mapTo(mutableSetOf()) { it.accountType } + + override fun addressableAccounts(types: Set): Set? { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return null + val manager = AccountManager.get(context) + return types.flatMapTo(mutableSetOf()) { type -> + manager.getAccountsByType(type).map { SyncAccount(it.name, it.type) } + } + } + + override fun requestSync(account: SyncAccount, userInitiated: Boolean) { + val extras = Bundle().apply { + putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true) + if (userInitiated) putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true) + } + ContentResolver.requestSync( + Account(account.name, account.type), + CalendarContract.AUTHORITY, + extras, + ) + } + + override fun syncActivity(account: SyncAccount): SyncActivity? = try { + val android = Account(account.name, account.type) + when { + ContentResolver.isSyncActive(android, CalendarContract.AUTHORITY) -> SyncActivity.Active + ContentResolver.isSyncPending(android, CalendarContract.AUTHORITY) -> SyncActivity.Pending + else -> SyncActivity.Idle + } + } catch (e: SecurityException) { + null + } + + override fun syncActivityChanges(): Flow = callbackFlow { + val handle = try { + ContentResolver.addStatusChangeListener( + ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE or ContentResolver.SYNC_OBSERVER_TYPE_PENDING, + ) { trySend(Unit) } + } catch (e: SecurityException) { + null + } + awaitClose { handle?.let(ContentResolver::removeStatusChangeListener) } + } +} + +/** The distinct non-local accounts behind the visible calendars — what a manual refresh asks. */ +fun List.syncAccounts(): Set = + filter { it.isVisibleInSystem } + .map { SyncAccount(it.accountName, it.accountType) } + .filterTo(linkedSetOf()) { it.isSyncable } + +/** + * Who a sync request can go to: [reachable] by name, [needsAccess] only once the + * user lets the app see the account (Android 13+, see [accountAccessIntent]). + * [dismissed] are hidden accounts the user said not to ask about. + */ +data class SyncTargets( + val reachable: Set, + val needsAccess: Set, + val dismissed: Set = emptySet(), +) { + companion object { + val None = SyncTargets(emptySet(), emptySet()) + } +} + +/** + * The system account picker, limited to [account]: once picked it becomes + * visible to the app, so sync requests can name it. + */ +fun accountAccessIntent(account: SyncAccount, description: String): Intent = + AccountManager.newChooseAccountIntent( + null, + listOf(Account(account.name, account.type)), + arrayOf(account.type), + description, + null, + null, + null, + ) + +/** + * Outcome of a user-triggered sync request (#240). [Completed] is only ever set + * once the requested syncs were seen through, see [awaitSyncs]. + */ +enum class SyncRequestResult { Requested, Completed, SomeNeedAccess, PartlyFailed, NeedsAccess, NothingToSync, Failed } + +/** A sync request's [result] and the [accounts] it actually reached. */ +data class SyncRequest(val result: SyncRequestResult, val accounts: Set = emptySet()) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/di/DataModule.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/di/DataModule.kt index 3d5e5800..197715e5 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/di/DataModule.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/di/DataModule.kt @@ -11,9 +11,11 @@ import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import de.jeanlucmakiola.calendula.data.calendar.AndroidCalendarDataSource +import de.jeanlucmakiola.calendula.data.calendar.AndroidSyncRequester import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository import de.jeanlucmakiola.calendula.data.calendar.CalendarRepositoryImpl +import de.jeanlucmakiola.calendula.data.calendar.SyncRequester import de.jeanlucmakiola.calendula.data.contacts.AndroidContactSpecialDatesDataSource import de.jeanlucmakiola.calendula.data.contacts.AndroidSpecialDatesCalendarSpec import de.jeanlucmakiola.calendula.data.contacts.ContactSpecialDatesDataSource @@ -49,6 +51,12 @@ abstract class DataBindModule { impl: CalendarRepositoryImpl, ): CalendarRepository + @Binds + @Singleton + abstract fun bindSyncRequester( + impl: AndroidSyncRequester, + ): SyncRequester + @Binds @Singleton abstract fun bindReminderInstanceSource( diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/ics/IcsExporter.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/ics/IcsExporter.kt index 5ad0967a..479dcb87 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/ics/IcsExporter.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/ics/IcsExporter.kt @@ -5,6 +5,10 @@ import android.net.Uri import androidx.core.content.FileProvider import androidx.documentfile.provider.DocumentFile import dagger.hilt.android.qualifiers.ApplicationContext +import de.jeanlucmakiola.floret.android.TreeListing +import de.jeanlucmakiola.floret.android.deleteTreeFiles +import de.jeanlucmakiola.floret.android.listTreeFiles +import de.jeanlucmakiola.floret.android.writeTreeFile import java.io.File import java.io.IOException import javax.inject.Inject @@ -29,34 +33,27 @@ class IcsExporter @Inject constructor( } ?: throw IOException("Could not open output stream for export (scheme=${uri.scheme})") } - /** - * Write [content] to [fileName] inside the persisted SAF tree [folder], - * overwriting it if it already exists (the automatic-backup destination). - * Requires a persisted write grant on [folder]. Throws on failure. - */ - fun writeToFolder(folder: Uri, fileName: String, content: String) { + /** The files in the persisted SAF tree [folder], the automatic-backup destination. Throws when unusable. */ + fun listFolder(folder: Uri): TreeListing { + writableFolder(folder) + return context.contentResolver.listTreeFiles(folder) + } + + /** Write the `.ics` [bytes] as [fileName] into [folder]; returns the name the file ended up with. */ + fun writeToFolder(folder: Uri, listing: TreeListing, fileName: String, bytes: ByteArray): String = + context.contentResolver.writeTreeFile(folder, listing, fileName, MIME_CALENDAR, bytes) + + /** Delete [names] from the listed folder; returns the ones that didn't go. */ + fun deleteFromFolder(listing: TreeListing, names: Collection): Set = + context.contentResolver.deleteTreeFiles(listing, names) + + private fun writableFolder(folder: Uri): DocumentFile { val dir = DocumentFile.fromTreeUri(context, folder) ?: throw IOException("Backup folder is not accessible") if (!dir.exists() || !dir.canWrite()) { throw IOException("Backup folder is missing or not writable") } - // Reuse the canonical file if present and clean up any "name (1).ics" - // duplicates SAF may have created if two runs ever raced — so we always - // converge on a single overwritten file. - val base = fileName.substringBeforeLast('.') - val ext = fileName.substringAfterLast('.', "") - var target: DocumentFile? = null - for (child in dir.listFiles()) { - val name = child.name ?: continue - when { - name == fileName -> target = child - name.startsWith("$base (") && name.endsWith(".$ext") -> child.delete() - } - } - val file = target - ?: dir.createFile(MIME_CALENDAR, fileName) - ?: throw IOException("Could not create backup file in the chosen folder") - writeDocument(file.uri, content) + return dir } /** diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/CalendarPrefs.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/CalendarPrefs.kt index f75b69a4..7f663ad9 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/CalendarPrefs.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/CalendarPrefs.kt @@ -7,6 +7,8 @@ import de.jeanlucmakiola.floret.prefs.PrefStore import de.jeanlucmakiola.floret.prefs.nullableBooleanPref import de.jeanlucmakiola.floret.prefs.nullableLongPref import de.jeanlucmakiola.floret.prefs.nullableStringPref +import de.jeanlucmakiola.floret.prefs.stringSetPref +import de.jeanlucmakiola.calendula.data.calendar.SyncAccount import kotlinx.coroutines.flow.Flow import javax.inject.Inject import javax.inject.Singleton @@ -28,9 +30,14 @@ class CalendarPrefs @Inject constructor( ) { private val prefs = PrefStore(store) - val hiddenCalendarIds: Flow> = prefs.flow(HIDDEN_IDS) + val hiddenCalendarIds: Flow> = prefs.flow(CalendarPrefKeys.hiddenCalendarIds) - suspend fun setHiddenCalendarIds(ids: Set) = prefs.set(HIDDEN_IDS, ids) + suspend fun setHiddenCalendarIds(ids: Set) = prefs.set(CalendarPrefKeys.hiddenCalendarIds, ids) + + /** Rewrite the drawer's hidden set atomically from its current value. */ + suspend fun updateHiddenCalendarIds(transform: (Set) -> Set) { + prefs.update(CalendarPrefKeys.hiddenCalendarIds, transform) + } /** * Switch-offs the provider does not know about yet, because writing @@ -41,10 +48,10 @@ class CalendarPrefs @Inject constructor( * second visibility model: `CalendarVisibilityReconciler` drains it entry by * entry as soon as the app may write, and nothing adds to it while it may. */ - val pendingDisabledCalendarIds: Flow> = prefs.flow(DISABLED_IDS) + val pendingDisabledCalendarIds: Flow> = prefs.flow(CalendarPrefKeys.pendingDisabledCalendarIds) suspend fun addPendingDisabledCalendarIds(ids: Collection) { - prefs.update(DISABLED_IDS) { it + ids } + prefs.update(CalendarPrefKeys.pendingDisabledCalendarIds) { it + ids } } /** @@ -52,7 +59,7 @@ class CalendarPrefs @Inject constructor( * them, so a run that fails part-way never re-applies what already landed. */ suspend fun removePendingDisabledCalendarIds(ids: Collection) { - prefs.update(DISABLED_IDS) { it - ids.toSet() } + prefs.update(CalendarPrefKeys.pendingDisabledCalendarIds) { it - ids.toSet() } } /** @@ -60,28 +67,50 @@ class CalendarPrefs @Inject constructor( * owed. Null until the reconciler has evaluated it (which needs the calendar * permission), false once it has been shown or was never needed. */ - val visibilityNoticePending: Flow = prefs.flow(VISIBILITY_NOTICE) + val visibilityNoticePending: Flow = prefs.flow(CalendarPrefKeys.visibilityNoticePending) - suspend fun setVisibilityNoticePending(pending: Boolean) = prefs.set(VISIBILITY_NOTICE, pending) + suspend fun setVisibilityNoticePending(pending: Boolean) = prefs.set(CalendarPrefKeys.visibilityNoticePending, pending) /** * The calendar the user last created an event in; preselected in the * event form. Null until the first event is created. */ - val lastUsedCalendarId: Flow = prefs.flow(LAST_USED_CALENDAR) + val lastUsedCalendarId: Flow = prefs.flow(CalendarPrefKeys.lastUsedCalendarId) - suspend fun setLastUsedCalendarId(id: Long) = prefs.set(LAST_USED_CALENDAR, id) + suspend fun setLastUsedCalendarId(id: Long) = prefs.set(CalendarPrefKeys.lastUsedCalendarId, id) - private companion object { - val HIDDEN_IDS = idSetPref("hidden_calendar_ids") - val DISABLED_IDS = idSetPref("disabled_calendar_ids") - val VISIBILITY_NOTICE = nullableBooleanPref("visibility_notice_pending") - val LAST_USED_CALENDAR = nullableLongPref("last_used_calendar_id") + /** + * Synced accounts the user chose never to be asked to grant sync-request + * access for (#240): no grant row, no "other accounts" receipt. + */ + val syncAccessDismissed: Flow> = prefs.flow(CalendarPrefKeys.syncAccessDismissed) + + suspend fun setSyncAccessDismissed(account: SyncAccount, dismissed: Boolean) { + prefs.update(CalendarPrefKeys.syncAccessDismissed) { if (dismissed) it + account else it - account } + } +} + +/** Every key [CalendarPrefs] stores; the names are on-disk data. */ +internal object CalendarPrefKeys { + val hiddenCalendarIds: Pref> = idSetPref("hidden_calendar_ids") + val pendingDisabledCalendarIds: Pref> = idSetPref("disabled_calendar_ids") + val visibilityNoticePending: Pref = nullableBooleanPref("visibility_notice_pending") + val lastUsedCalendarId: Pref = nullableLongPref("last_used_calendar_id") + val syncAccessDismissed: Pref> = stringSetPref("sync_access_dismissed").map( + { stored -> stored.mapNotNullTo(mutableSetOf()) { it.toSyncAccount() } }, + { accounts -> accounts.mapTo(mutableSetOf()) { "${it.type}$FIELD_SEPARATOR${it.name}" } }, + ) + + private const val FIELD_SEPARATOR = '\u001F' + + private fun String.toSyncAccount(): SyncAccount? { + val split = indexOf(FIELD_SEPARATOR) + return if (split <= 0) null else SyncAccount(name = substring(split + 1), type = substring(0, split)) } } /** A comma-joined id set; non-numeric tokens are dropped, and an empty set removes the key. */ -private fun idSetPref(name: String): Pref> = nullableStringPref(name).map( +internal fun idSetPref(name: String): Pref> = nullableStringPref(name).map( { stored -> stored.orEmpty().split(',').mapNotNull { it.trim().toLongOrNull() }.toSet() }, { ids -> if (ids.isEmpty()) null else ids.sorted().joinToString(",") }, ) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/ReminderStatePrefs.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/ReminderStatePrefs.kt index 47c008f8..125bf5d0 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/ReminderStatePrefs.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/ReminderStatePrefs.kt @@ -2,8 +2,11 @@ package de.jeanlucmakiola.calendula.data.prefs import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences +import de.jeanlucmakiola.floret.prefs.Pref import de.jeanlucmakiola.floret.prefs.PrefStore import de.jeanlucmakiola.floret.prefs.nullableLongPref +import de.jeanlucmakiola.floret.prefs.nullableStringPref +import java.time.LocalDate import javax.inject.Inject import javax.inject.Singleton @@ -23,11 +26,25 @@ class ReminderStatePrefs @Inject constructor( private val prefs = PrefStore(store) /** The watermark, or `null` before the first scan has ever run. */ - suspend fun lastScanMillis(): Long? = prefs.get(LAST_SCAN) + suspend fun lastScanMillis(): Long? = prefs.get(ReminderStateKeys.lastScanMillis) - suspend fun setLastScanMillis(millis: Long) = prefs.set(LAST_SCAN, millis) + suspend fun setLastScanMillis(millis: Long) = prefs.set(ReminderStateKeys.lastScanMillis, millis) - private companion object { - val LAST_SCAN = nullableLongPref("reminder_last_scan_millis") - } + /** + * The day the last daily summary listed (#459): recorded at once, so neither + * a pass failing after posting nor a later time picked the same evening + * lists it twice. + */ + suspend fun lastDigestDay(): LocalDate? = + prefs.get(ReminderStateKeys.lastDigestDay)?.let { runCatching { LocalDate.parse(it) }.getOrNull() } + + suspend fun setLastDigestDay(day: LocalDate) = prefs.set(ReminderStateKeys.lastDigestDay, day.toString()) + + suspend fun clearLastDigestDay() = prefs.set(ReminderStateKeys.lastDigestDay, null) +} + +/** The keys [ReminderStatePrefs] stores. */ +internal object ReminderStateKeys { + val lastScanMillis: Pref = nullableLongPref("reminder_last_scan_millis") + val lastDigestDay: Pref = nullableStringPref("reminder_last_digest_day") } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefs.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefs.kt index 793c01e9..719405ea 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefs.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefs.kt @@ -1,10 +1,34 @@ package de.jeanlucmakiola.calendula.data.prefs import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.MutablePreferences import androidx.datastore.preferences.core.Preferences +import de.jeanlucmakiola.calendula.data.calendar.wholeDayLeadTimes +import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.domain.DefaultCalendarRef import de.jeanlucmakiola.calendula.domain.EventFormField import de.jeanlucmakiola.calendula.domain.FontRole +import de.jeanlucmakiola.calendula.domain.backup.BackupSelection +import de.jeanlucmakiola.calendula.domain.backup.backupIntervalOn +import de.jeanlucmakiola.calendula.domain.backup.COMBINED_SERIES +import de.jeanlucmakiola.calendula.domain.backup.DEFAULT_BACKUP_KEEP +import de.jeanlucmakiola.calendula.domain.backup.LEGACY_BACKUP_FILE +import de.jeanlucmakiola.calendula.domain.backup.latestLedgerKey +import de.jeanlucmakiola.calendula.domain.backup.normalizeBackupKeep +import de.jeanlucmakiola.calendula.domain.backup.BackupLedger +import de.jeanlucmakiola.calendula.domain.backup.parseBackupLedger +import de.jeanlucmakiola.calendula.domain.backup.persistBackupLedger +import de.jeanlucmakiola.calendula.domain.backup.BackupFingerprints +import de.jeanlucmakiola.calendula.domain.backup.parseBackupFingerprints +import de.jeanlucmakiola.calendula.domain.backup.persistBackupFingerprints import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType +import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle +import de.jeanlucmakiola.calendula.domain.reminders.parseAlertStyles +import de.jeanlucmakiola.calendula.domain.reminders.toStoredAlertStyles +import de.jeanlucmakiola.calendula.domain.reminders.DEFAULT_DIGEST_TIME_MINUTES +import de.jeanlucmakiola.calendula.domain.reminders.DailyDigestSettings +import de.jeanlucmakiola.calendula.domain.reminders.DigestDay +import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder import de.jeanlucmakiola.calendula.ui.agenda.AgendaRange import de.jeanlucmakiola.calendula.ui.agenda.parseAgendaRange import de.jeanlucmakiola.calendula.ui.agenda.storageValue @@ -29,6 +53,7 @@ import de.jeanlucmakiola.floret.prefs.enumPref import de.jeanlucmakiola.floret.prefs.get import de.jeanlucmakiola.floret.prefs.intPref import de.jeanlucmakiola.floret.prefs.longPref +import de.jeanlucmakiola.floret.prefs.nullableBooleanPref import de.jeanlucmakiola.floret.prefs.nullableLongPref import de.jeanlucmakiola.floret.prefs.nullableStringPref import de.jeanlucmakiola.floret.prefs.set @@ -163,9 +188,15 @@ class SettingsPrefs @Inject constructor( val defaultFormFields: Flow> = prefs.flow(SettingsKeys.defaultFormFields) val recentTimeZones: Flow> = prefs.flow(SettingsKeys.recentTimeZones) val autofocusEventTitle: Flow = prefs.flow(SettingsKeys.autofocusEventTitle) + val defaultNewEventCalendar: Flow = prefs.flow(SettingsKeys.defaultNewEventCalendar) val defaultEventDurationMinutes: Flow = prefs.flow(SettingsKeys.defaultEventDurationMinutes) val perCalendarEventDuration: Flow> = prefs.flow(SettingsKeys.perCalendarEventDuration) + val perCalendarHiddenViews: Flow>> = prefs.flow(SettingsKeys.perCalendarHiddenViews) val remindersEnabled: Flow = prefs.flow(SettingsKeys.remindersEnabled) + val mutedReminderCalendarIds: Flow> = prefs.flow(SettingsKeys.mutedReminderCalendarIds) + val reminderAlertStyles: Flow> = prefs.flow(SettingsKeys.reminderAlertStyles) + val notificationCategoryHintDismissed: Flow = prefs.flow(SettingsKeys.notificationCategoryHintDismissed) + val reminderChannelVersions: Flow> = prefs.flow(SettingsKeys.reminderChannelVersions) val allowColorOnUnsupportedCalendars: Flow = prefs.flow(SettingsKeys.allowColorOnUnsupportedCalendars) val defaultReminderMinutes: Flow> = prefs.flow(SettingsKeys.defaultReminderMinutes) @@ -176,10 +207,35 @@ class SettingsPrefs @Inject constructor( prefs.flow(SettingsKeys.perCalendarReminderOverride) val perCalendarAllDayReminderOverride: Flow>> = prefs.flow(SettingsKeys.perCalendarAllDayReminderOverride) + val defaultFixedTimeReminder: Flow = prefs.flow(SettingsKeys.defaultFixedTimeReminder) + val perCalendarFixedTimeReminderOverride: Flow> = + prefs.flow(SettingsKeys.perCalendarFixedTimeReminderOverride) + + /** + * Every "N days before at HH:MM" the defaults name, so an offset landing on + * one reads back as that reminder rather than a lead time (#459). + */ + val knownFixedTimeReminders: Flow> = prefs.snapshot { + setOfNotNull(it[SettingsKeys.defaultFixedTimeReminder]) + + it[SettingsKeys.perCalendarFixedTimeReminderOverride].values.filterNotNull() + + it[SettingsKeys.recentFixedTimeReminders] + } + val dailyDigest: Flow = prefs.snapshot { it.dailyDigest } val autoBackupEnabled: Flow = prefs.flow(SettingsKeys.autoBackupEnabled) val autoBackupIntervalMinutes: Flow = prefs.flow(SettingsKeys.autoBackupIntervalMinutes) val autoBackupFolderUri: Flow = prefs.flow(SettingsKeys.autoBackupFolderUri) val autoBackupStatus: Flow = prefs.snapshot { it.autoBackupStatus } + val autoBackupSelection: Flow = prefs.snapshot { it.autoBackupSelection } + val autoBackupCombined: Flow = prefs.snapshot { it.autoBackupCombined } + val autoBackupKeep: Flow = prefs.flow(SettingsKeys.autoBackupKeep) + val autoBackupLedger: Flow = prefs.flow(SettingsKeys.autoBackupLedger) + val autoBackupOnChange: Flow = prefs.flow(SettingsKeys.autoBackupOnChange) + val autoBackupScheduled: Flow = prefs.snapshot { it.autoBackupScheduled } + + /** Read together, so the screen never shows one updated without the other. */ + val autoBackupOnChangeAndScheduled: Flow> = + prefs.snapshot { it[SettingsKeys.autoBackupOnChange] to it.autoBackupScheduled } + val autoBackupFingerprints: Flow = prefs.flow(SettingsKeys.autoBackupFingerprints) val specialDatesEnabled: Flow = prefs.flow(SettingsKeys.specialDatesEnabled) val specialDatesTypes: Flow> = prefs.snapshot { it.specialDatesTypes } val specialDatesCalendars: Flow> = prefs.snapshot { it.specialDatesCalendars } @@ -257,6 +313,10 @@ class SettingsPrefs @Inject constructor( suspend fun setAutofocusEventTitle(enabled: Boolean) = prefs.set(SettingsKeys.autofocusEventTitle, enabled) + /** [calendar] null goes back to Automatic. */ + suspend fun setDefaultNewEventCalendar(calendar: DefaultCalendarRef?) = + prefs.set(SettingsKeys.defaultNewEventCalendar, calendar) + suspend fun setDefaultEventDurationMinutes(minutes: Int) = prefs.set(SettingsKeys.defaultEventDurationMinutes, minutes) @@ -271,8 +331,50 @@ class SettingsPrefs @Inject constructor( } } + /** Show [calendarId] in every view again (#270), e.g. once it is deleted. */ + suspend fun clearCalendarHiddenViews(calendarId: Long) { + prefs.update(SettingsKeys.perCalendarHiddenViews) { current -> current - calendarId } + } + + /** Hide or show [calendarId] in one [view], against the stored set rather than a snapshot of it. */ + suspend fun setCalendarHiddenIn(calendarId: Long, view: CalendarView, hidden: Boolean) = + applyCalendarHiddenChanges(calendarId, mapOf(view to hidden)) + + /** Hide (true) or show (false) [calendarId] in each view of [changes], in one write; other views keep theirs. */ + suspend fun applyCalendarHiddenChanges(calendarId: Long, changes: Map) { + if (changes.isEmpty()) return + prefs.update(SettingsKeys.perCalendarHiddenViews) { current -> + val views = current[calendarId].orEmpty() + val next = views + changes.filterValues { it }.keys - changes.filterValues { !it }.keys + current.withHiddenViews(calendarId, next) + } + } + suspend fun setRemindersEnabled(enabled: Boolean) = prefs.set(SettingsKeys.remindersEnabled, enabled) + /** + * Reserve a new reminder channel version for each calendar in [floors], above + * both its stored high-water mark and its floor, and return them. Versions + * only grow: the system would restore a deleted channel's old settings if + * its id came back (#518). + */ + suspend fun reserveReminderChannelVersions(floors: Map): Map { + val stored = prefs.update(SettingsKeys.reminderChannelVersions) { current -> + current + floors.mapValues { (id, floor) -> maxOf((current[id] ?: 0) + 1, floor) } + } + return floors.keys.associateWith { stored.getValue(it) } + } + + suspend fun dismissNotificationCategoryHint() = prefs.set(SettingsKeys.notificationCategoryHintDismissed, true) + + suspend fun setCalendarRemindersEnabled(calendarId: Long, enabled: Boolean) { + prefs.update(SettingsKeys.mutedReminderCalendarIds) { if (enabled) it - calendarId else it + calendarId } + } + + suspend fun setCalendarAlertStyle(calendarId: Long, style: ReminderAlertStyle) { + prefs.update(SettingsKeys.reminderAlertStyles) { it + (calendarId to style) } + } + suspend fun setAllowColorOnUnsupportedCalendars(enabled: Boolean) = prefs.set(SettingsKeys.allowColorOnUnsupportedCalendars, enabled) @@ -324,12 +426,175 @@ class SettingsPrefs @Inject constructor( suspend fun setCalendarAllDayReminderOverride(calendarId: Long, override: ReminderOverride) = prefs.applyOverride(SettingsKeys.perCalendarAllDayReminderOverride, calendarId, override) + /** The replaced default stays a known pattern, so events that got it keep reading as it. */ + suspend fun setDefaultFixedTimeReminder(reminder: FixedTimeReminder?) { + prefs.edit { + val old = it[SettingsKeys.defaultFixedTimeReminder] + if (old != reminder) retireFixedTimeReminder(it, old) + it[SettingsKeys.defaultFixedTimeReminder] = reminder + } + } + + /** [override] [FixedTimeOverride.Inherit] drops the calendar's entry; a replaced value stays known. */ + suspend fun setCalendarFixedTimeReminderOverride(calendarId: Long, override: FixedTimeOverride) { + prefs.edit { + val current = it[SettingsKeys.perCalendarFixedTimeReminderOverride] + val old = current[calendarId] + if (old != (override as? FixedTimeOverride.At)?.reminder) retireFixedTimeReminder(it, old) + it[SettingsKeys.perCalendarFixedTimeReminderOverride] = when (override) { + FixedTimeOverride.Inherit -> current - calendarId + FixedTimeOverride.Off -> current + (calendarId to null) + is FixedTimeOverride.At -> current + (calendarId to override.reminder) + } + } + } + + /** + * Remember fixed-time reminders saved by hand (#459), so their rows read + * back as them; the defaults are known anyway and take no slot. + */ + suspend fun rememberFixedTimeReminders(reminders: Collection) { + prefs.edit { + val defaults = setOfNotNull(it[SettingsKeys.defaultFixedTimeReminder]) + + it[SettingsKeys.perCalendarFixedTimeReminderOverride].values.filterNotNull() + val fresh = reminders.filterNot { reminder -> reminder in defaults } + if (fresh.isNotEmpty()) { + it[SettingsKeys.recentFixedTimeReminders] = (fresh + it[SettingsKeys.recentFixedTimeReminders]).distinct() + } + } + } + + /** Keep a default being replaced known, unless it still is a default elsewhere. */ + private fun retireFixedTimeReminder(preferences: MutablePreferences, reminder: FixedTimeReminder?) { + if (reminder == null) return + val defaults = listOfNotNull(preferences[SettingsKeys.defaultFixedTimeReminder]) + + preferences[SettingsKeys.perCalendarFixedTimeReminderOverride].values.filterNotNull() + if (defaults.count { it == reminder } > 1) return + preferences[SettingsKeys.recentFixedTimeReminders] = + (listOf(reminder) + preferences[SettingsKeys.recentFixedTimeReminders]).distinct() + } + + suspend fun setDailyDigestEnabled(enabled: Boolean) = editDigest { it[SettingsKeys.dailyDigestEnabled] = enabled } + + suspend fun setDailyDigestTimeMinutes(minutesOfDay: Int) = + editDigest { it[SettingsKeys.dailyDigestTimeMinutes] = minutesOfDay } + + suspend fun setDailyDigestDay(day: DigestDay) = editDigest { it[SettingsKeys.dailyDigestDay] = day } + + /** + * Change when the summary arrives, stamping the moment: a summary whose time + * had already passed today is not owed by the change itself. + */ + private suspend fun editDigest(change: (MutablePreferences) -> Unit) { + prefs.edit { + change(it) + it[SettingsKeys.dailyDigestArmedAt] = System.currentTimeMillis() + } + } + + + suspend fun setCalendarInDailyDigest(calendarId: Long, included: Boolean) { + prefs.update(SettingsKeys.digestExcludedCalendarIds) { if (included) it - calendarId else it + calendarId } + } + suspend fun setAutoBackupEnabled(enabled: Boolean) = prefs.set(SettingsKeys.autoBackupEnabled, enabled) suspend fun setAutoBackupIntervalMinutes(minutes: Long) = prefs.set(SettingsKeys.autoBackupIntervalMinutes, minutes) - suspend fun setAutoBackupFolderUri(uri: String?) = prefs.set(SettingsKeys.autoBackupFolderUri, uri) + /** + * Also pins the file layout the first time it is written: an install that + * already had a folder before #411 keeps its single combined file, a new + * one starts on one file per calendar (see [Preferences.autoBackupCombined]). + */ + suspend fun setAutoBackupFolderUri(uri: String?) { + prefs.edit { + it.pinBackupLayout() + // The ledger says which files in the old folder are ours; in a new + // one a file of the same name may be the user's. + if (it[SettingsKeys.autoBackupFolderUri] != uri) { + it[SettingsKeys.autoBackupLedger] = emptyMap() + it[SettingsKeys.autoBackupFingerprints] = emptyMap() + } + it[SettingsKeys.autoBackupFolderUri] = uri + } + } + + suspend fun setAutoBackupCombined(combined: Boolean) { + prefs.edit { + it.pinBackupLayout() + it[SettingsKeys.autoBackupCombinedStored] = combined + } + } + + suspend fun setAutoBackupKeep(keep: Int) = prefs.set(SettingsKeys.autoBackupKeep, keep) + + /** Returns whether this switched the interval on or off. */ + suspend fun setAutoBackupOnChange(enabled: Boolean): Boolean = editAutoBackupScheduled { + applyAutoBackupOnChange(it, enabled) + } + + /** + * Off only sticks while backing up after changes is on; see + * [applyAutoBackupOnChange]. Returns whether this switched the interval. + */ + suspend fun setAutoBackupScheduled(enabled: Boolean): Boolean = editAutoBackupScheduled { + if (enabled || it[SettingsKeys.autoBackupOnChange]) it[SettingsKeys.autoBackupScheduledStored] = enabled + } + + private suspend fun editAutoBackupScheduled(transform: (MutablePreferences) -> Unit): Boolean { + var switched = false + prefs.edit { + val before = it.autoBackupScheduled + transform(it) + switched = it.autoBackupScheduled != before + } + return switched + } + + /** + * Atomic, so a run's ledger writes never undo one made meanwhile (pinning + * the layout). Dropped when the folder is no longer [folder]: a run still + * finishing must not carry the old folder's names into the new one's ledger. + * [fingerprints] updates the series' hashes (#516) in the same edit. + */ + suspend fun updateAutoBackupLedger( + folder: String, + fingerprints: ((BackupFingerprints) -> BackupFingerprints)? = null, + transform: (BackupLedger) -> BackupLedger, + ) { + prefs.edit { + if (it[SettingsKeys.autoBackupFolderUri] == folder) { + it[SettingsKeys.autoBackupLedger] = transform(it[SettingsKeys.autoBackupLedger]) + if (fingerprints != null) { + it[SettingsKeys.autoBackupFingerprints] = fingerprints(it[SettingsKeys.autoBackupFingerprints]) + } + } + } + } + + /** Like [updateAutoBackupLedger], for the series' hashes (#516) alone. */ + suspend fun updateAutoBackupFingerprints(folder: String, transform: (BackupFingerprints) -> BackupFingerprints) { + prefs.edit { + if (it[SettingsKeys.autoBackupFolderUri] == folder) { + it[SettingsKeys.autoBackupFingerprints] = transform(it[SettingsKeys.autoBackupFingerprints]) + } + } + } + + /** Record a pre-#411 install's old file as its combined series' stable copy (see [pinBackupLayout]). */ + suspend fun adoptLegacyBackupFile() { + prefs.edit { if (it.autoBackupLegacyInstall) it.adoptLegacyBackupFile() } + } + + /** Switch [calendar] in or out of the automatic backup (#147). */ + suspend fun setAutoBackupCalendar(calendar: CalendarSource, included: Boolean) { + prefs.edit { + val next = it.autoBackupSelection.with(calendar, included) + it[SettingsKeys.autoBackupIncluded] = next.included + it[SettingsKeys.autoBackupExcluded] = next.excluded + } + } /** Record an automatic run's outcome; resets the failure streak on success. */ suspend fun recordAutoBackupRun(success: Boolean, atMillis: Long) { @@ -373,6 +638,7 @@ class SettingsPrefs @Inject constructor( /** 09:00 as minutes from midnight; the default all-day reminder fire time. */ internal const val DEFAULT_ALLDAY_REMINDER_TIME = 540 internal const val MINUTES_PER_DAY = 1_440 + internal const val MAX_RECENT_FIXED_TIME_REMINDERS = 12 /** Default snooze delay for the notification "Snooze" action. */ const val DEFAULT_SNOOZE_MINUTES = 10 const val DEFAULT_MULTI_DAY_COUNT = 3 @@ -570,6 +836,14 @@ object SettingsKeys { */ val autofocusEventTitle: Pref = booleanPref("autofocus_event_title", true) + /** + * The calendar new events open in (#429); null is Automatic (the last-used + * calendar). Kept when the calendar stops being a target, which only makes + * it fall back for as long as that lasts. + */ + val defaultNewEventCalendar: Pref = + nullableStringPref("default_new_event_calendar").map(DefaultCalendarRef::decode) { it?.encode() } + /** * How long a new **timed** event lasts, in minutes (#54). Per-calendar * overrides in [perCalendarEventDuration] take precedence; all-day events @@ -588,12 +862,46 @@ object SettingsKeys { val perCalendarEventDuration: Pref> = nullableStringPref("per_calendar_event_duration").map(::parseDurationOverrides) { it.toStoredDurations() } + /** + * Views each calendar is hidden in (#270): a display-only filter on top of + * `Calendars.VISIBLE` and the drawer's filter, so reminders and search never + * see it. A calendar absent shows in every view. Serialised as + * `id=Month,Agenda;id=Week`. + */ + val perCalendarHiddenViews: Pref>> = + nullableStringPref("per_calendar_hidden_views").map(::parseHiddenViews) { it.toStoredHiddenViews() } + /** * Whether Calendula posts reminder notifications (v1.4). On by default — for * users whose only calendar app this is, reminders are essential. */ val remindersEnabled: Pref = booleanPref("reminders_enabled", true) + /** + * Calendars whose reminders Calendula doesn't post (#272), independent of + * `Calendars.VISIBLE`: the events still show, only the notifications stop. + */ + val mutedReminderCalendarIds: Pref> = idSetPref("muted_reminder_calendar_ids") + + /** Per-calendar alert styles (#171); a calendar absent from the map uses plain notifications. */ + val reminderAlertStyles: Pref> = + nullableStringPref("reminder_alert_styles").map(::parseAlertStyles) { it.toStoredAlertStyles() } + + /** + * Whether the one-time hint that some skins (Samsung) start new notification + * categories switched off has been dismissed (#145). + */ + val notificationCategoryHintDismissed: Pref = booleanPref("notification_category_hint_dismissed", false) + + /** + * The highest reminder channel version handed out per calendar (#518): a + * sound picked in the app recreates the channel under a new one. The + * channels themselves say which version is current; this only keeps ids + * from being reused. Serialised as `id=version;id=version`. + */ + val reminderChannelVersions: Pref> = + nullableStringPref("reminder_channel_versions").map(::parseChannelVersions) { it.toStoredVersions() } + /** * Whether to offer a custom event colour on calendars that publish no colour * palette; synced ones without a palette (some CalDAV) may drop or overwrite @@ -648,7 +956,8 @@ object SettingsKeys { * before the start of the day — day-scale ("1 day before"), so separate from * the timed default. */ - val defaultAllDayReminderMinutes: Pref> = reminderListPref("default_allday_reminder_minutes") + val defaultAllDayReminderMinutes: Pref> = + reminderListPref("default_allday_reminder_minutes", wholeDays = true) /** * Wall-clock time, as minutes from local midnight, at which **all-day** @@ -681,7 +990,49 @@ object SettingsKeys { /** Per-calendar overrides of [defaultAllDayReminderMinutes], as [perCalendarReminderOverride]. */ val perCalendarAllDayReminderOverride: Pref>> = - reminderOverridePref("per_calendar_allday_reminder_override") + reminderOverridePref("per_calendar_allday_reminder_override", wholeDays = true) + + /** + * The "N days before at HH:MM" reminder added to new **timed** events + * (#459), or null for none — the factory default. Stored as `days@minute`. + */ + val defaultFixedTimeReminder: Pref = + nullableStringPref("default_fixed_time_reminder").map(FixedTimeReminder::parse) { it?.toToken() } + + /** + * Per-calendar overrides of [defaultFixedTimeReminder]: present with a + * value replaces it, present as null turns it off, absent inherits. + * Serialised as `id=days@minute` or `id=none`, joined by `;`. + */ + val perCalendarFixedTimeReminderOverride: Pref> = + nullableStringPref("per_calendar_fixed_time_reminder").map(::parseFixedTimeOverrides) { + it.toStoredFixedTimeOverrides() + } + + /** The daily summary notification (#459): opt-in, and which day it lists at what time. */ + val dailyDigestEnabled: Pref = booleanPref("daily_digest_enabled", false) + val dailyDigestTimeMinutes: Pref = + intPref("daily_digest_time_minutes", DEFAULT_DIGEST_TIME_MINUTES).coerced { + it.coerceIn(0, SettingsPrefs.MINUTES_PER_DAY - 1) + } + val dailyDigestDay: Pref = enumPref("daily_digest_day", DigestDay.Tomorrow) + + /** Calendars left out of the daily summary; every other one is in. */ + val digestExcludedCalendarIds: Pref> = idSetPref("digest_excluded_calendar_ids") + + /** When the summary's switch, time or day last changed; a moment before it is never owed. */ + val dailyDigestArmedAt: Pref = longPref("daily_digest_armed_at", 0L) + + /** + * Fixed-time reminders last saved by hand, and defaults since replaced, + * newest first — with the current defaults, the patterns a stored offset is + * recognised as. Capped, so the oldest falls out of recognition. + */ + val recentFixedTimeReminders: Pref> = + nullableStringPref("recent_fixed_time_reminders").map( + { stored -> stored?.split(LIST_SEP).orEmpty().mapNotNull(FixedTimeReminder::parse).distinct() }, + { reminders -> reminders.take(SettingsPrefs.MAX_RECENT_FIXED_TIME_REMINDERS).joinToString(LIST_SEP) { it.toToken() } }, + ) /** Whether periodic automatic `.ics` export of local calendars is on (issue #8). */ val autoBackupEnabled: Pref = booleanPref("auto_backup_enabled", false) @@ -700,6 +1051,37 @@ object SettingsKeys { val autoBackupLastSuccess: Pref = booleanPref("auto_backup_last_success", true) val autoBackupFailures: Pref = intPref("auto_backup_failures", 0) + /** + * The automatic backup's calendar choice as deviations from the default + * (#147), read together as [Preferences.autoBackupSelection]. + */ + val autoBackupIncluded: Pref> = idSetPref("auto_backup_included_calendars") + val autoBackupExcluded: Pref> = idSetPref("auto_backup_excluded_calendars") + + /** + * Whether the automatic backup writes one combined file instead of one per + * calendar (#411). Unset until first pinned; read as [Preferences.autoBackupCombined]. + */ + val autoBackupCombinedStored: Pref = nullableBooleanPref("auto_backup_combined") + + /** How many files of each backup series to keep (#411). */ + val autoBackupKeep: Pref = + intPref("auto_backup_keep", DEFAULT_BACKUP_KEEP).coerced(::normalizeBackupKeep) + + /** The files the automatic backup wrote, per series; the only ones it ever prunes (#411). */ + val autoBackupLedger: Pref = + nullableStringPref("auto_backup_files").map(::parseBackupLedger, ::persistBackupLedger) + + /** Whether a change to a backed-up calendar also refreshes the stable copies (#516). Opt-in. */ + val autoBackupOnChange: Pref = booleanPref("auto_backup_on_change", false) + + /** Whether the dated backups run on the interval; read as [Preferences.autoBackupScheduled]. */ + val autoBackupScheduledStored: Pref = booleanPref("auto_backup_scheduled", true) + + /** Content hash of each series' stable copy, so a change run skips untouched ones (#516). */ + val autoBackupFingerprints: Pref = + nullableStringPref("auto_backup_fingerprints").map(::parseBackupFingerprints, ::persistBackupFingerprints) + /** Master switch for the contact special-dates mirror (issue #15). Opt-in. */ val specialDatesEnabled: Pref = booleanPref("special_dates_enabled", false) @@ -749,6 +1131,56 @@ val Preferences.autoBackupStatus: BackupStatus consecutiveFailures = this[SettingsKeys.autoBackupFailures], ) +val Preferences.autoBackupSelection: BackupSelection + get() = BackupSelection( + included = this[SettingsKeys.autoBackupIncluded], + excluded = this[SettingsKeys.autoBackupExcluded], + ) + +/** Whether the dated backups run on the interval; see [backupIntervalOn]. */ +val Preferences.autoBackupScheduled: Boolean + get() = backupIntervalOn(this[SettingsKeys.autoBackupScheduledStored], this[SettingsKeys.autoBackupOnChange]) + +/** + * Turning it off brings the interval back for good, and turning it on starts + * with the interval on, so an interval-off stored without it (a settings + * import) never takes effect. + */ +internal fun applyAutoBackupOnChange(prefs: MutablePreferences, enabled: Boolean) { + if (!enabled || !prefs[SettingsKeys.autoBackupOnChange]) prefs[SettingsKeys.autoBackupScheduledStored] = true + prefs[SettingsKeys.autoBackupOnChange] = enabled +} + +/** + * Unset means an install from before #411: one that already had a backup + * folder keeps the single file it was writing, anything else gets per-calendar + * files. Choosing a folder pins the answer (see [SettingsPrefs.setAutoBackupFolderUri]). + */ +val Preferences.autoBackupCombined: Boolean + get() = this[SettingsKeys.autoBackupCombinedStored] ?: autoBackupLegacyInstall + +/** + * Store the layout the install is on, if it's still derived. Pinning forgets + * it was a pre-#411 install, so its old file is recorded as the combined + * series' own stable copy at the same time. + */ +private fun MutablePreferences.pinBackupLayout() { + if (this[SettingsKeys.autoBackupCombinedStored] != null) return + val legacy = autoBackupLegacyInstall + if (legacy) adoptLegacyBackupFile() + this[SettingsKeys.autoBackupCombinedStored] = legacy +} + +private fun MutablePreferences.adoptLegacyBackupFile() { + val key = latestLedgerKey(COMBINED_SERIES) + val ledger = this[SettingsKeys.autoBackupLedger] + this[SettingsKeys.autoBackupLedger] = ledger + (key to (ledger[key].orEmpty() + LEGACY_BACKUP_FILE).distinct()) +} + +/** An install that set up automatic backup before #411 and hasn't been pinned since. */ +val Preferences.autoBackupLegacyInstall: Boolean + get() = this[SettingsKeys.autoBackupCombinedStored] == null && this[SettingsKeys.autoBackupFolderUri] != null + val Preferences.specialDatesTypes: Set get() = SettingsKeys.specialDateTypeEnabled.filterValues { this[it] }.keys @@ -785,11 +1217,24 @@ private fun Pref.coerced(clamp: (T) -> T): Pref = map(clamp, clamp) private fun agendaRangePref(name: String): Pref = nullableStringPref(name).map({ parseAgendaRange(it, AgendaRange.Month) }, { it.storageValue() }) -private fun reminderListPref(name: String): Pref> = - nullableStringPref(name).map({ it.toReminderList() }, { it.toStoredReminders() }) +/** + * [wholeDays] reads an all-day list as the whole days it fires at, so a sub-day + * value stored before the all-day pickers were limited to days shows truthfully. + */ +private fun reminderListPref(name: String, wholeDays: Boolean = false): Pref> = + nullableStringPref(name).map( + { stored -> stored.toReminderList().let { if (wholeDays) wholeDayLeadTimes(it) else it } }, + { it.toStoredReminders() }, + ) -private fun reminderOverridePref(name: String): Pref>> = - nullableStringPref(name).map(reminderOverrideCodec::parse, reminderOverrideCodec::serialize) +private fun reminderOverridePref(name: String, wholeDays: Boolean = false): Pref>> = + nullableStringPref(name).map( + { stored -> + reminderOverrideCodec.parse(stored) + .let { map -> if (wholeDays) map.mapValues { wholeDayLeadTimes(it.value) } else map } + }, + reminderOverrideCodec::serialize, + ) private suspend fun PrefStore.applyOverride( pref: Pref>>, @@ -817,9 +1262,11 @@ private fun parseFormFields(stored: String?): Set = when (stored private fun parseViewOrder(stored: String?): List = completeViewOrder( stored?.split(',').orEmpty() - .mapNotNull { name -> CalendarView.entries.firstOrNull { it.name == name.trim() } }, + .mapNotNull { it.trim().toCalendarViewOrNull() }, ) +private fun String.toCalendarViewOrNull(): CalendarView? = CalendarView.entries.firstOrNull { it.name == this } + /** Parse the quick-switch config; "!"-prefixed names are disabled. */ private fun parseQuickSwitch(stored: String?): QuickSwitchConfig { if (stored == null) return QuickSwitchConfig.Default @@ -827,7 +1274,7 @@ private fun parseQuickSwitch(stored: String?): QuickSwitchConfig { val token = raw.trim() val disabled = token.startsWith("!") val name = if (disabled) token.drop(1) else token - CalendarView.entries.firstOrNull { it.name == name }?.let { it to disabled } + name.toCalendarViewOrNull()?.let { it to disabled } } val order = completeViewOrder(parsed.map { it.first }) // Only views explicitly stored disabled are excluded; anything appended @@ -879,6 +1326,57 @@ data class BackupStatus( val consecutiveFailures: Int, ) +/** The daily summary's settings, read together. */ +internal val Preferences.dailyDigest: DailyDigestSettings + get() = DailyDigestSettings( + enabled = this[SettingsKeys.dailyDigestEnabled], + timeMinutes = this[SettingsKeys.dailyDigestTimeMinutes], + day = this[SettingsKeys.dailyDigestDay], + excludedCalendarIds = this[SettingsKeys.digestExcludedCalendarIds], + armedAtMillis = this[SettingsKeys.dailyDigestArmedAt], + ) + +/** A calendar's choice for the fixed-time default, as a picker returns it. */ +sealed interface FixedTimeOverride { + data object Inherit : FixedTimeOverride + data object Off : FixedTimeOverride + data class At(val reminder: FixedTimeReminder) : FixedTimeOverride +} + +/** [calendarId]'s entry read as a [FixedTimeOverride]. */ +fun Map.fixedTimeOverrideFor(calendarId: Long): FixedTimeOverride = when { + !containsKey(calendarId) -> FixedTimeOverride.Inherit + else -> getValue(calendarId)?.let { FixedTimeOverride.At(it) } ?: FixedTimeOverride.Off +} + +/** The fixed-time reminder a new timed event on [calendarId] gets, or null for none. */ +fun resolveDefaultFixedTimeReminder( + global: FixedTimeReminder?, + overrides: Map, + calendarId: Long?, +): FixedTimeReminder? = + if (calendarId != null && overrides.containsKey(calendarId)) overrides[calendarId] else global + +private fun parseFixedTimeOverrides(stored: String?): Map = + stored?.split(ENTRY_SEP).orEmpty().mapNotNull { entry -> + val parts = entry.split(KEY_VALUE_SEP) + if (parts.size != 2) return@mapNotNull null + val calendarId = parts[0].trim().toLongOrNull() ?: return@mapNotNull null + val value = parts[1].trim() + if (value == NONE) return@mapNotNull calendarId to null + val reminder = FixedTimeReminder.parse(value) ?: return@mapNotNull null + calendarId to reminder + }.toMap() + +private fun Map.toStoredFixedTimeOverrides(): String? = + if (isEmpty()) { + null + } else { + entries.sortedBy { it.key }.joinToString(ENTRY_SEP) { (id, reminder) -> + "$id$KEY_VALUE_SEP${reminder?.toToken() ?: NONE}" + } + } + /** * The lead times to prefill on a new event: the matching per-calendar override * if [calendarId] has one for this event kind, otherwise the global default for @@ -977,6 +1475,45 @@ private fun parseDurationOverrides(stored: String?): Map = calendarId to minutes }.toMap() +private fun parseChannelVersions(stored: String?): Map = + stored?.split(ENTRY_SEP).orEmpty().mapNotNull { entry -> + val parts = entry.split(KEY_VALUE_SEP) + if (parts.size != 2) return@mapNotNull null + val calendarId = parts[0].trim().toLongOrNull() ?: return@mapNotNull null + val version = parts[1].trim().toIntOrNull()?.takeIf { it > 0 } ?: return@mapNotNull null + calendarId to version + }.toMap() + +private fun Map.toStoredVersions(): String? = + if (isEmpty()) null else entries.sortedBy { it.key }.joinToString(ENTRY_SEP) { (id, v) -> "$id$KEY_VALUE_SEP$v" } + +/** + * Parse the per-calendar hidden-views map (`id=View,View` entries joined by `;`). + * Unknown view names and malformed entries are dropped; an entry left with no + * views is dropped with them. + */ +internal fun parseHiddenViews(stored: String?): Map> = + stored?.split(ENTRY_SEP).orEmpty().mapNotNull { entry -> + val parts = entry.split(KEY_VALUE_SEP) + if (parts.size != 2) return@mapNotNull null + val calendarId = parts[0].trim().toLongOrNull() ?: return@mapNotNull null + val views = parts[1].split(LIST_SEP) + .mapNotNullTo(mutableSetOf()) { it.trim().toCalendarViewOrNull() } + if (views.isEmpty()) null else calendarId to views + }.toMap() + +private fun Map>.withHiddenViews( + calendarId: Long, + views: Set, +): Map> = if (views.isEmpty()) this - calendarId else this + (calendarId to views) + +internal fun Map>.toStoredHiddenViews(): String? = + entries.filter { it.value.isNotEmpty() }.sortedBy { it.key } + .joinToString(ENTRY_SEP) { (id, views) -> + "$id$KEY_VALUE_SEP" + views.sortedBy { it.ordinal }.joinToString(LIST_SEP) { it.name } + } + .ifEmpty { null } + private fun Map.toStoredDurations(): String = entries.sortedBy { it.key }.joinToString(ENTRY_SEP) { (id, minutes) -> "$id$KEY_VALUE_SEP$minutes" diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/DailyDigestNotifier.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/DailyDigestNotifier.kt new file mode 100644 index 00000000..026f2261 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/DailyDigestNotifier.kt @@ -0,0 +1,155 @@ +package de.jeanlucmakiola.calendula.data.reminders + +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.util.Log +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import dagger.hilt.android.qualifiers.ApplicationContext +import de.jeanlucmakiola.calendula.MainActivity +import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs +import de.jeanlucmakiola.calendula.data.prefs.is24Hour +import de.jeanlucmakiola.calendula.data.prefs.resolveFirstDay +import de.jeanlucmakiola.calendula.domain.reminders.ReminderEventInstance +import de.jeanlucmakiola.floret.locale.capitalizeStart +import de.jeanlucmakiola.floret.locale.localizedDateFormatter +import kotlinx.coroutines.flow.first +import kotlinx.datetime.isoDayNumber +import kotlinx.datetime.toKotlinLocalDate +import java.time.DayOfWeek +import java.time.LocalDate +import java.time.ZoneId +import java.util.Locale +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Posts the daily summary (#459): one notification listing a day's events, on + * its own channel, replacing the one before it. Tapping opens that day. + */ +@Singleton +class DailyDigestNotifier @Inject constructor( + @ApplicationContext private val context: Context, + private val settingsPrefs: SettingsPrefs, +) { + + /** + * Post the summary of [day] listing [listed], or withdraw the last one when + * there is nothing to list — yesterday's would otherwise stand in for it. + */ + suspend fun post(day: LocalDate, listed: List) { + val manager = NotificationManagerCompat.from(context) + if (listed.isEmpty()) { + manager.cancel(TAG_DIGEST, NOTIFICATION_ID) + return + } + ensureChannel() + val zone = ZoneId.systemDefault() + val locale = Locale.getDefault() + val is24Hour = settingsPrefs.timeFormat.first() + .is24Hour(android.text.format.DateFormat.is24HourFormat(context)) + val today = LocalDate.now(zone) + val firstDayOfWeek = DayOfWeek.of(settingsPrefs.weekStart.first().resolveFirstDay(locale).isoDayNumber) + // The date rides along: the summary stays up into the day it lists, + // when "Tomorrow" alone would point at the wrong one. + val date = localizedDateFormatter(locale, "EEEdMMM").format(day) + val dayLabel = when (day) { + today -> context.getString(R.string.digest_day_relative, context.getString(R.string.reminder_day_today), date) + today.plusDays(1) -> + context.getString(R.string.digest_day_relative, context.getString(R.string.reminder_day_tomorrow), date) + else -> date.capitalizeStart(locale) + } + val allDay = context.getString(R.string.event_detail_all_day) + val lines = listed.map { entry -> + // Read against the listed day, so a timed event on it shows its bare + // range and one crossing midnight its dates. + val time = if (entry.isAllDay) allDay else reminderTimeText( + beginMillis = entry.beginMillis, + endMillis = entry.endMillis, + isAllDay = entry.isAllDay, + zone = zone, + locale = locale, + is24Hour = is24Hour, + today = day, + firstDayOfWeek = firstDayOfWeek, + todayLabel = allDay, + tomorrowLabel = context.getString(R.string.reminder_day_tomorrow), + yesterdayLabel = context.getString(R.string.reminder_day_yesterday), + ) + context.getString(R.string.digest_line, time, entry.title.ifBlank { context.getString(R.string.event_untitled) }) + } + val title = context.resources.getQuantityString(R.plurals.digest_title, listed.size, dayLabel, listed.size) + val style = NotificationCompat.InboxStyle().setBigContentTitle(title) + lines.take(MAX_LINES).forEach(style::addLine) + if (lines.size > MAX_LINES) { + val more = lines.size - MAX_LINES + style.setSummaryText(context.resources.getQuantityString(R.plurals.digest_more, more, more)) + } + val notification = NotificationCompat.Builder(context, CHANNEL_ID) + .setSmallIcon(R.drawable.ic_notification) + .setContentTitle(title) + .setContentText(listed.joinToString(", ") { it.title.ifBlank { context.getString(R.string.event_untitled) } }) + .setStyle(style) + .setCategory(NotificationCompat.CATEGORY_REMINDER) + .setAutoCancel(true) + // Gone once its day is over; "Tomorrow" would read wrong by then anyway. + .setTimeoutAfter( + (day.plusDays(1).atStartOfDay(zone).toInstant().toEpochMilli() - System.currentTimeMillis()) + .coerceAtLeast(1L), + ) + .setContentIntent(openDay(day)) + .build() + try { + manager.notify(TAG_DIGEST, NOTIFICATION_ID, notification) + } catch (e: SecurityException) { + Log.w(TAG, "Could not post the daily summary", e) + } + } + + /** Whether the summary's own channel is switched off in the system settings. */ + fun isChannelOff(): Boolean = + context.getSystemService(NotificationManager::class.java) + .getNotificationChannel(CHANNEL_ID)?.importance == NotificationManager.IMPORTANCE_NONE + + /** Withdraw the summary showing, if any. */ + fun cancel() { + NotificationManagerCompat.from(context).cancel(TAG_DIGEST, NOTIFICATION_ID) + } + + /** The summary's channel id, created if missing — for the settings deep-link. */ + fun channelId(): String { + ensureChannel() + return CHANNEL_ID + } + + /** Creates the channel, or renames it after a language change; the user's settings on it stay. */ + private fun ensureChannel() { + val manager = context.getSystemService(NotificationManager::class.java) + manager.createNotificationChannel( + NotificationChannel( + CHANNEL_ID, + context.getString(R.string.digest_channel_name), + NotificationManager.IMPORTANCE_DEFAULT, + ).apply { description = context.getString(R.string.digest_channel_description) }, + ) + } + + private fun openDay(day: LocalDate): PendingIntent = PendingIntent.getActivity( + context, + REQUEST_CODE, + MainActivity.openDayIntent(context, day.toKotlinLocalDate()), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + + private companion object { + const val TAG = "DailyDigestNotifier" + const val CHANNEL_ID = "daily_digest" + const val TAG_DIGEST = "daily_digest" + const val NOTIFICATION_ID = 2 + const val REQUEST_CODE = 0xD16E + const val MAX_LINES = 6 + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt new file mode 100644 index 00000000..cfc415eb --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt @@ -0,0 +1,85 @@ +package de.jeanlucmakiola.calendula.data.reminders + +import kotlinx.coroutines.channels.BufferOverflow +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.asSharedFlow +import java.util.concurrent.ConcurrentHashMap +import javax.inject.Inject +import javax.inject.Singleton + +/** + * What the full-screen alerts (#171) share within the process: the reminder + * [ReminderRingService] is ringing for, and the reminders just dismissed or + * snoozed, so an alert screen showing one closes whichever way it was handled. + */ +@Singleton +class FullScreenAlerts @Inject constructor() { + + /** Written only by [ReminderRingService], on the main thread, for as long as it rings. */ + @Volatile + var ringing: ReminderAlert? = null + internal set + + /** Rings handed to [ReminderRingService] that have not reached it yet, with how many starts each. */ + private val pending = ConcurrentHashMap>() + + /** Set when the service is stopped from outside but its ring should go back to the shade. */ + @Volatile + internal var handBackOnDestroy = false + + internal fun addPending(alert: ReminderAlert) { + pending.compute(alert.key) { _, entry -> alert to ((entry?.second ?: 0) + 1) } + } + + internal fun removePending(alert: ReminderAlert) { + pending.computeIfPresent(alert.key) { _, entry -> if (entry.second <= 1) null else entry.first to entry.second - 1 } + } + + internal fun isPending(alert: ReminderAlert): Boolean = pending.containsKey(alert.key) + + internal val anyPending: Boolean get() = pending.isNotEmpty() + + /** + * Whether a ring going or on its way [match]es, so a stop is worth sending. + * Pending first: the service sets [ringing] before it lets a start go. + */ + fun mayRing(match: RingMatch): Boolean = + pending.values.any { match.matches(it.first) } || ringing?.let(match::matches) == true + + private val handledKeys = MutableSharedFlow( + extraBufferCapacity = 8, + onBufferOverflow = BufferOverflow.DROP_OLDEST, + ) + + /** The [ReminderAlert.key]s of reminders as they are dismissed, snoozed or handed back. */ + val handled: SharedFlow = handledKeys.asSharedFlow() + + fun markHandled(alert: ReminderAlert) { + handledKeys.tryEmit(alert.key) + } +} + +/** What becomes of a ring once its settings are re-read. */ +enum class RingVerdict { Ring, HandBack, Drop } + +/** Which ring a stop is for. */ +sealed interface RingMatch { + fun matches(alert: ReminderAlert): Boolean + + data class Key(val key: Long) : RingMatch { + override fun matches(alert: ReminderAlert) = alert.key == key + } + + data class Occurrence(val occurrenceKey: Long) : RingMatch { + override fun matches(alert: ReminderAlert) = alert.occurrenceKey == occurrenceKey + } + + data class Calendar(val calendarId: Long) : RingMatch { + override fun matches(alert: ReminderAlert) = alert.calendarId == calendarId + } + + data object Any : RingMatch { + override fun matches(alert: ReminderAlert) = true + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderActionReceiver.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderActionReceiver.kt index c0bd7569..7329fd06 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderActionReceiver.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderActionReceiver.kt @@ -13,8 +13,8 @@ import javax.inject.Inject /** * Handles the "Snooze" and "Dismiss" actions on a reminder notification, plus * the internal re-show when a snooze elapses. All three are app-internal - * intents (notification action buttons and our own [ReminderSnoozeScheduler] - * alarm), so the receiver is not exported. + * intents (notification action buttons, the full-screen alert's buttons and + * our own [ReminderSnoozeScheduler] alarm), so the receiver is not exported. * * - **Dismiss** just cancels the notification — the scan's watermark has moved * past this reminder, so nothing re-posts it. @@ -74,6 +74,9 @@ class ReminderActionReceiver : BroadcastReceiver() { */ const val ACTION_OPEN = "de.jeanlucmakiola.calendula.reminders.OPEN" + /** Not handled here either: the slot of the full-screen alert's own intent (#171). */ + const val ACTION_ALERT_SCREEN = "de.jeanlucmakiola.calendula.reminders.ALERT_SCREEN" + private const val EXTRA_ALERT_KEY = "alert_key" private const val EXTRA_EVENT_ID = "event_id" private const val EXTRA_CALENDAR_ID = "calendar_id" @@ -94,16 +97,21 @@ class ReminderActionReceiver : BroadcastReceiver() { Intent(context, ReminderActionReceiver::class.java).apply { this.action = action data = "calendula://reminder/${identity(alert, action)}".toUri() - putExtra(EXTRA_ALERT_KEY, alert.key) - putExtra(EXTRA_EVENT_ID, alert.eventId) - putExtra(EXTRA_CALENDAR_ID, alert.calendarId) - putExtra(EXTRA_BEGIN, alert.beginMillis) - putExtra(EXTRA_END, alert.endMillis) - putExtra(EXTRA_TITLE, alert.title) - putExtra(EXTRA_LOCATION, alert.location) - putExtra(EXTRA_ALL_DAY, alert.isAllDay) + putAlert(alert) } + /** Carries [alert] as extras, for [alertFrom] to read back. */ + fun Intent.putAlert(alert: ReminderAlert): Intent = apply { + putExtra(EXTRA_ALERT_KEY, alert.key) + putExtra(EXTRA_EVENT_ID, alert.eventId) + putExtra(EXTRA_CALENDAR_ID, alert.calendarId) + putExtra(EXTRA_BEGIN, alert.beginMillis) + putExtra(EXTRA_END, alert.endMillis) + putExtra(EXTRA_TITLE, alert.title) + putExtra(EXTRA_LOCATION, alert.location) + putExtra(EXTRA_ALL_DAY, alert.isAllDay) + } + /** * A stable request code per (alert, action), so one notification's * PendingIntents stay distinct. The shift keeps the action slot intact; @@ -115,6 +123,7 @@ class ReminderActionReceiver : BroadcastReceiver() { ACTION_DISMISS -> 2 ACTION_SHOW -> 3 ACTION_OPEN -> 4 + ACTION_ALERT_SCREEN -> 5 else -> 0 } return (identity(alert, action).toInt() shl 3) + actionOffset @@ -123,7 +132,7 @@ class ReminderActionReceiver : BroadcastReceiver() { private fun identity(alert: ReminderAlert, action: String): Long = if (action == ACTION_SHOW) alert.occurrenceKey else alert.key - private fun alertFrom(intent: Intent): ReminderAlert? { + fun alertFrom(intent: Intent): ReminderAlert? { if (!intent.hasExtra(EXTRA_ALERT_KEY)) return null return ReminderAlert( key = intent.getLongExtra(EXTRA_ALERT_KEY, 0L), diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlan.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlan.kt new file mode 100644 index 00000000..57b70487 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlan.kt @@ -0,0 +1,211 @@ +package de.jeanlucmakiola.calendula.data.reminders + +import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.ui.common.groupByAccount + +/** The single channel every reminder posted on before they moved per calendar (#145). */ +const val LEGACY_REMINDER_CHANNEL_ID = "reminders" + +/** The silent channel ringing full-screen alerts post on (#171); outside the per-calendar namespace. */ +const val RING_CHANNEL_ID = "reminders_ring" + +private const val CHANNEL_PREFIX = "reminders.calendar." +private const val GROUP_PREFIX = "reminders.account." +private const val LOCAL_GROUP_ID = GROUP_PREFIX + "local" + +private const val VERSION_SEPARATOR = ".v" + +/** + * The notification channel [calendarId]'s reminders post on. A sound picked in + * the app moves it to a new [version] (#518), since a channel's sound is fixed + * once created; version 0 is the unversioned id #145 introduced. + */ +fun reminderChannelId(calendarId: Long, version: Int = 0): String = + if (version == 0) "$CHANNEL_PREFIX$calendarId" else "$CHANNEL_PREFIX$calendarId$VERSION_SEPARATOR$version" + +/** The calendar and version a reminder channel id names, or null for any other id. */ +fun parseReminderChannelId(channelId: String): Pair? { + if (!isReminderChannelId(channelId)) return null + val rest = channelId.removePrefix(CHANNEL_PREFIX) + val calendar = rest.substringBefore(VERSION_SEPARATOR).toLongOrNull() ?: return null + if (VERSION_SEPARATOR !in rest) return calendar to 0 + val version = rest.substringAfter(VERSION_SEPARATOR).toIntOrNull()?.takeIf { it > 0 } ?: return null + return calendar to version +} + +/** + * Each calendar's current channel version: the highest one that exists, so a + * new version only takes over once it is written. A calendar with none falls + * back to its [highWater] mark — re-creating that id restores its own settings. + */ +fun currentReminderChannelVersions(existingChannelIds: Collection, highWater: Map): Map { + val existing = existingChannelIds.mapNotNull(::parseReminderChannelId) + .groupBy({ it.first }, { it.second }) + .mapValues { (_, versions) -> versions.max() } + return highWater + existing +} + +/** Whether [channelId] is one of the per-calendar reminder channels. */ +fun isReminderChannelId(channelId: String): Boolean = channelId.startsWith(CHANNEL_PREFIX) + +/** Whether [groupId] is one of the per-account reminder channel groups. */ +fun isReminderGroupId(groupId: String): Boolean = groupId.startsWith(GROUP_PREFIX) + +/** + * One account's channel group, labelled as the calendar manager labels it. The + * app's own device calendars share a single group ([isLocal]); [ambiguous] + * marks a [label] another group shows too, so it should name the source app. + */ +data class ReminderChannelGroupSpec( + val id: String, + val label: String, + val accountType: String, + val isLocal: Boolean, + val ambiguous: Boolean, +) + +data class ReminderChannelSpec( + val id: String, + val calendarId: Long, + val name: String, + /** Null only for a channel created before its calendar could be looked up. */ + val groupId: String?, + /** + * Whether a sync creates it up front. A calendar that syncs no events never + * fires, so its channel only appears once something posts on it. + */ + val upFront: Boolean = true, +) + +/** What a channel already looks like in the system, as far as the plan compares it. */ +data class ExistingReminderChannel(val id: String, val name: String, val description: String?, val groupId: String?) + +data class ReminderChannelPlan( + val groups: List, + val channels: List, + /** + * The [channels] a sync writes: missing up-front ones, and existing ones + * whose name or (localized) description changed, or that still lack a group. + */ + val channelsToWrite: List, + /** The [groups] holding a channel that exists or is about to be written. */ + val groupsInUse: List, + val staleChannelIds: List, + val staleGroupIds: List, + /** Stale channels kept for now, because a notification on them is still showing. */ + val keptChannelIds: List = emptyList(), +) + +/** + * What the reminder channels should look like for [calendars]: one channel per + * calendar inside a group per account, which of them need writing, and the + * reminder channels and groups in [existing] / [existingGroupIds] no calendar + * claims any more. Ids outside the reminder namespace (the backup channel, the + * legacy channel) are never touched. + */ +fun planReminderChannels( + calendars: List, + existing: Collection, + existingGroupIds: Collection, + unnamed: String, + description: String, + versions: Map = emptyMap(), + showingChannelIds: Set = emptySet(), +): ReminderChannelPlan { + val (local, synced) = calendars.partition { it.isLocal } + val groups = buildList { + if (local.isNotEmpty()) { + add(ReminderChannelGroupSpec(LOCAL_GROUP_ID, "", local.first().accountType, isLocal = true, ambiguous = false)) + } + synced.groupByAccount().forEach { group -> + add( + ReminderChannelGroupSpec( + id = accountGroupId(group.key.type, group.key.name), + label = group.label, + accountType = group.accountType, + isLocal = false, + ambiguous = group.ambiguous, + ), + ) + } + } + val existingById = existing.associateBy { it.id } + val channels = calendars.map { calendar -> + ReminderChannelSpec( + id = reminderChannelId(calendar.id, versions[calendar.id] ?: 0), + calendarId = calendar.id, + name = calendar.displayName.ifBlank { unnamed }, + groupId = if (calendar.isLocal) LOCAL_GROUP_ID else accountGroupId(calendar.accountType, calendar.accountName), + upFront = calendar.isLocal || calendar.syncsEvents, + ) + } + val wantedChannels = channels.mapTo(HashSet()) { it.id } + val wantedGroups = groups.mapTo(HashSet()) { it.id } + val toWrite = channels.filter { spec -> + val current = existingById[spec.id] + if (current == null) { + spec.upFront + } else { + current.name != spec.name || current.description != description || + (current.groupId == null && spec.groupId != null) + } + } + val usedGroupIds = channels + .filter { it.id in existingById || it in toWrite } + .mapNotNullTo(HashSet()) { it.groupId } + val (kept, stale) = existingById.keys + .filter { isReminderChannelId(it) && it !in wantedChannels } + .partition { it in showingChannelIds } + val keptGroups = kept.mapNotNullTo(HashSet()) { existingById.getValue(it).groupId } + return ReminderChannelPlan( + groups = groups, + channels = channels, + channelsToWrite = toWrite, + groupsInUse = groups.filter { it.id in usedGroupIds }, + staleChannelIds = stale, + staleGroupIds = existingGroupIds.filter { isReminderGroupId(it) && it !in wantedGroups && it !in keptGroups }, + keptChannelIds = kept, + ) +} + +private fun accountGroupId(type: String, name: String): String = "$GROUP_PREFIX$type/$name" + +/** A channel as far as its blocked state goes: switched off itself, and the group it sits in. */ +data class ReminderChannelState(val blocked: Boolean, val groupId: String?) + +/** Reminder notifications the system blocks, while Calendula would post them. */ +data class ReminderChannelStatus( + val appBlocked: Boolean = false, + val blockedCalendarIds: Set = emptySet(), + /** The blocked ones whose whole account group is off, which only the app's own screen can undo. */ + val groupBlockedCalendarIds: Set = emptySet(), + /** The shared ring channel (#171) is switched off, so ringing calendars only sound once. */ + val ringBlocked: Boolean = false, +) + +/** + * What the system blocks of [calendarIds]' reminders: all of them while the + * app's notifications are off, otherwise those whose channel, or the group it + * sits in, is switched off. A calendar without a channel yet isn't blocked. + */ +fun reminderChannelStatus( + calendarIds: Collection, + appEnabled: Boolean, + channels: Map, + blockedGroupIds: Set, + versions: Map = emptyMap(), +): ReminderChannelStatus { + fun channel(calendarId: Long) = channels[reminderChannelId(calendarId, versions[calendarId] ?: 0)] + val groupBlocked = calendarIds.filterTo(HashSet()) { channel(it)?.groupId in blockedGroupIds } + val blocked = if (!appEnabled) { + calendarIds.toSet() + } else { + calendarIds.filterTo(HashSet()) { channel(it)?.blocked == true } + groupBlocked + } + return ReminderChannelStatus( + appBlocked = !appEnabled, + blockedCalendarIds = blocked, + groupBlockedCalendarIds = groupBlocked, + ringBlocked = appEnabled && channels[RING_CHANNEL_ID]?.blocked == true, + ) +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt new file mode 100644 index 00000000..be7b2a5c --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt @@ -0,0 +1,416 @@ +package de.jeanlucmakiola.calendula.data.reminders + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationChannelGroup +import android.app.NotificationManager +import android.app.NotificationManager.IMPORTANCE_DEFAULT +import android.app.NotificationManager.IMPORTANCE_LOW +import android.app.NotificationManager.IMPORTANCE_MIN +import android.content.Context +import android.media.AudioAttributes +import android.net.Uri +import android.util.Log +import dagger.hilt.android.qualifiers.ApplicationContext +import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource +import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs +import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle +import de.jeanlucmakiola.calendula.ui.common.sourceAppLabel +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import java.util.Locale +import javax.inject.Inject +import javax.inject.Singleton + +/** + * The reminder notification channels: one per calendar, grouped by account + * (#145), created up front so each calendar can be muted or given its own sound + * in the system settings before it ever fires. + * + * A channel the user has touched keeps their settings; [sync] only creates the + * missing ones, renames changed ones, and deletes those whose calendar is gone. + * A sound picked in the app ([setSound], #518) recreates the channel under the + * calendar's next version; the old one goes once nothing shows on it. + */ +@Singleton +class ReminderChannels @Inject constructor( + @ApplicationContext private val context: Context, + private val calendarDataSource: CalendarDataSource, + private val settingsPrefs: SettingsPrefs, +) { + private val manager: NotificationManager + get() = context.getSystemService(NotificationManager::class.java) + + /** What the last [sync] saw, so an unchanged provider costs no channel writes. */ + @Volatile + private var lastSync: Any? = null + + /** + * Bring the channels in line with the provider's calendars. An empty + * snapshot changes nothing: that is a provider hiccup far more often than + * every calendar gone at once. + */ + @Synchronized + fun sync() { + val calendars = calendarDataSource.calendars() + if (calendars.isEmpty()) return + val manager = manager + val existing = manager.notificationChannels + val existingIds = existing.mapTo(HashSet()) { it.id } + val versions = currentVersions(existingIds).also { knownVersions = it } + if (syncKey(calendars, existingIds, versions) == lastSync && LEGACY_REMINDER_CHANNEL_ID !in existingIds) return + val groups = manager.notificationChannelGroups + val groupIds = groups.map { it.id } + // Active notifications are only read when there is something stale to protect. + val plan = plan(calendars, existing, groupIds, versions).let { draft -> + if (draft.staleChannelIds.isEmpty()) draft else plan(calendars, existing, groupIds, versions, showingChannelIds(draft.staleChannelIds)) + } + plan.staleChannelIds.forEach(manager::deleteNotificationChannel) + plan.staleGroupIds.forEach(manager::deleteNotificationChannelGroup) + val groupNames = groups.associate { it.id to it.name?.toString() } + write( + groups = plan.groupsInUse.filter { groupNames[it.id] != groupLabel(it) }, + channels = plan.channelsToWrite, + existing = existing, + ) + if (RING_CHANNEL_ID in existingIds) ensureRingChannel() + val ids = existingIds - plan.staleChannelIds.toSet() + plan.channelsToWrite.map { it.id } + val legacyGone = retireLegacyChannel() + // A kept channel still has to go once its notification does, so don't cache. + lastSync = if (plan.keptChannelIds.isEmpty()) { + syncKey(calendars, if (legacyGone) ids - LEGACY_REMINDER_CHANNEL_ID else ids, versions) + } else { + null + } + } + + private fun syncKey(calendars: List, channelIds: Set, versions: Map): Any = listOf( + calendars.map { listOf(it.id, it.displayName, it.accountName, it.accountType, it.isLocal, it.syncsEvents) }, + Locale.getDefault(), + channelIds, + versions, + ) + + /** + * The current versions last resolved under the lock ([sync], [channelFor]). + * Only [recreate], under the same lock, moves a calendar higher and updates + * it, so a hit whose channel still exists is current. + */ + @Volatile + private var knownVersions: Map = emptyMap() + + private fun currentVersions(existingChannelIds: Collection): Map = + currentReminderChannelVersions(existingChannelIds, runBlocking { settingsPrefs.reminderChannelVersions.first() }) + + /** Channels with a notification on screen; on failure all of [candidates] count, so none is deleted. */ + private fun showingChannelIds(candidates: Collection): Set = runCatching { + manager.activeNotifications.mapNotNullTo(HashSet()) { it.notification.channelId } + }.getOrElse { e -> + Log.w(TAG, "Could not read active notifications", e) + candidates.toSet() + } + + /** + * The channel to post [calendarId]'s reminder on, created first if a sync + * has not got to it yet. Null when the calendar no longer exists. Should the + * calendar lookup fail or come back empty, the channel is still created, + * plainly named and ungrouped, for the next sync to name and file — a + * reminder is never lost to its channel. A ringing [style] posts on the + * shared ring channel instead, once the calendar is known to exist. + */ + @Synchronized + fun channelFor(calendarId: Long, style: ReminderAlertStyle = ReminderAlertStyle.Notification): String? { + val calendarChannel = calendarChannelFor(calendarId) ?: return null + return if (style == ReminderAlertStyle.FullScreenRing) ringChannel() else calendarChannel + } + + /** + * The channel a ringing full-screen alert (#171) posts on, shared by every + * calendar. Silent: the ring service owns the sound and vibration, so the + * channel adds neither. High importance keeps the heads-up a denied + * full-screen intent degrades to. + */ + private fun ringChannel(): String { + ensureRingChannel() + return RING_CHANNEL_ID + } + + /** + * Creates the ring channel, or renames it after a language change. Called + * as soon as a calendar is set to ring, so the channel can be checked in + * system settings (and switched on, where a skin starts it off) before the + * first ring. + */ + @Synchronized + fun ensureRingChannel() { + val manager = manager + val name = context.getString(R.string.reminder_ring_channel_name) + val description = context.getString(R.string.reminder_ring_channel_description) + val current = manager.getNotificationChannel(RING_CHANNEL_ID) + if (current != null && current.name?.toString() == name && current.description == description) return + manager.createNotificationChannel( + NotificationChannel( + RING_CHANNEL_ID, + name, + NotificationManager.IMPORTANCE_HIGH, + ).apply { + this.description = description + setSound(null, null) + enableVibration(false) + lockscreenVisibility = Notification.VISIBILITY_PUBLIC + }, + ) + } + + /** + * Whether a ring may sound for [calendarId]: neither its own channel, its + * account's group nor the ring channel is blocked, since the service plays + * the sound itself. + */ + fun canRing(calendarId: Long): Boolean { + val status = status(listOf(calendarId)) + return !status.appBlocked && calendarId !in status.blockedCalendarIds && !status.ringBlocked + } + + private fun calendarChannelFor(calendarId: Long): String? { + val manager = manager + knownVersions[calendarId]?.let { version -> + val known = reminderChannelId(calendarId, version) + if (manager.getNotificationChannel(known) != null) return known + } + val existing = manager.notificationChannels + val versions = currentVersions(existing.map { it.id }).also { knownVersions = it } + val id = reminderChannelId(calendarId, versions[calendarId] ?: 0) + if (existing.any { it.id == id }) return id + val calendars = try { + calendarDataSource.calendars() + } catch (e: Exception) { + Log.w(TAG, "Could not look up calendar $calendarId for its channel", e) + emptyList() + } + val fallback = ReminderChannelSpec(id, calendarId, context.getString(R.string.reminder_channel_name), null) + if (calendars.isEmpty()) { + write(emptyList(), listOf(fallback), existing) + return id + } + val plan = plan(calendars, existing, emptyList(), versions) + val spec = plan.channels.firstOrNull { it.calendarId == calendarId } ?: return null + try { + val knownGroups = manager.notificationChannelGroups.mapTo(HashSet()) { it.id } + write( + groups = plan.groups.filter { it.id == spec.groupId && it.id !in knownGroups }, + channels = listOf(spec), + existing = existing, + ) + } catch (e: RuntimeException) { + Log.w(TAG, "Could not file the channel of calendar $calendarId", e) + write(emptyList(), listOf(fallback), existing) + } + return id + } + + /** + * Run [block] with [calendarId]'s channel held: no sound pick or sync can + * move or retire it until [block] returns. Null, without running [block], + * when the calendar is gone or its channel can't be made; [block]'s own + * failures propagate. + */ + @Synchronized + fun withChannel(calendarId: Long, block: (String) -> T): T? { + val channelId = try { + channelFor(calendarId) + } catch (e: Exception) { + Log.w(TAG, "No channel for calendar $calendarId", e) + null + } + return channelId?.let(block) + } + + /** What the system currently lets through for [calendarIds]' reminders (#145). */ + fun status(calendarIds: Collection): ReminderChannelStatus { + val manager = manager + val appEnabled = manager.areNotificationsEnabled() + val existing = manager.notificationChannels + val channels = existing.associate { + it.id to ReminderChannelState(it.importance == NotificationManager.IMPORTANCE_NONE, it.group) + } + val blockedGroups = manager.notificationChannelGroups.filter { it.isBlocked }.mapTo(HashSet()) { it.id } + return reminderChannelStatus(calendarIds, appEnabled, channels, blockedGroups, currentVersions(channels.keys)) + } + + /** A "Silent" (low) channel keeps its sound but never plays it. */ + private fun NotificationChannel.audibleSound(): Uri? = + sound.takeUnless { importance in IMPORTANCE_MIN..IMPORTANCE_LOW } + + /** + * The sound each of [calendarIds]' channels plays; null is silent. A + * calendar whose channel doesn't exist yet is left out. + */ + fun sounds(calendarIds: Collection): Map { + val byId = manager.notificationChannels.associateBy { it.id } + val versions = currentVersions(byId.keys) + return calendarIds.mapNotNull { id -> + byId[reminderChannelId(id, versions[id] ?: 0)]?.let { id to it.audibleSound() } + }.toMap() + } + + /** + * Give [calendarIds]' reminders [sound] (null = silent). A channel's sound is + * fixed once created, so each moves to a new channel version carrying over + * everything else, and the old one retires in the sync that follows (#518). Calendars without a + * channel are skipped unless [createMissing]. Returns whether every move + * went through. + */ + suspend fun setSound(calendarIds: Collection, sound: Uri?, createMissing: Boolean): Boolean { + if (createMissing) calendarIds.forEach(::channelFor) + val existingIds = manager.notificationChannels.mapTo(HashSet()) { it.id } + val current = currentVersions(existingIds) + val floors = calendarIds + .filter { reminderChannelId(it, current[it] ?: 0) in existingIds } + .associateWith { (current[it] ?: 0) + 1 } + if (floors.isEmpty()) return false + val applied = recreate(settingsPrefs.reserveReminderChannelVersions(floors), sound) + // Retire the old versions now, or each calendar shows twice in system settings until the next scan. + try { + sync() + } catch (e: RuntimeException) { + Log.w(TAG, "Old channel versions left to the next sync", e) + } + return applied + } + + /** + * Create each calendar's [versions] from its current channel. The old one is + * left to the next [sync], which retires it once nothing shows on it. + */ + @Synchronized + private fun recreate(versions: Map, sound: Uri?): Boolean { + val manager = manager + val byId = manager.notificationChannels.associateBy { it.id } + val current = currentReminderChannelVersions(byId.keys, emptyMap()) + var allApplied = true + versions.forEach { (calendarId, version) -> + val from = current[calendarId]?.takeIf { it < version } + val old = from?.let { byId[reminderChannelId(calendarId, it)] } + if (old == null) { + allApplied = false + return@forEach + } + try { + // Picking a sound asks for one, which a "Silent" (low) channel would never play. + val importance = if (sound != null && old.importance in IMPORTANCE_MIN..IMPORTANCE_LOW) { + IMPORTANCE_DEFAULT + } else { + old.importance + } + manager.createNotificationChannel( + NotificationChannel(reminderChannelId(calendarId, version), old.name, importance).apply { + description = old.description + old.group?.let { group = it } + inheritFrom(old) + setSound(sound, old.audioAttributes ?: DEFAULT_AUDIO_ATTRIBUTES) + }, + ) + knownVersions = knownVersions + (calendarId to version) + } catch (e: RuntimeException) { + Log.w(TAG, "Could not move calendar $calendarId to a new sound", e) + allApplied = false + } + } + lastSync = null + return allApplied + } + + private fun plan( + calendars: List, + existing: List, + existingGroupIds: List, + versions: Map, + showingChannelIds: Set = emptySet(), + ): ReminderChannelPlan = planReminderChannels( + calendars = calendars, + existing = existing.map { ExistingReminderChannel(it.id, it.name.toString(), it.description, it.group) }, + existingGroupIds = existingGroupIds, + unnamed = context.getString(R.string.calendar_unnamed), + description = context.getString(R.string.reminder_channel_description), + versions = versions, + showingChannelIds = showingChannelIds, + ) + + private fun write( + groups: List, + channels: List, + existing: List, + ) { + val manager = manager + if (groups.isNotEmpty()) { + manager.createNotificationChannelGroups(groups.map { NotificationChannelGroup(it.id, groupLabel(it)) }) + } + if (channels.isEmpty()) return + val byId = existing.associateBy { it.id } + val description = context.getString(R.string.reminder_channel_description) + val template = byId[LEGACY_REMINDER_CHANNEL_ID] + // Importance only applies on creation; an existing channel keeps its own. + manager.createNotificationChannels( + channels.map { spec -> + val current = byId[spec.id] + NotificationChannel( + spec.id, + spec.name, + current?.importance ?: template?.importance ?: NotificationManager.IMPORTANCE_HIGH, + ).apply { + this.description = description + spec.groupId?.let { group = it } + if (current == null && template != null) inheritFrom(template) + } + }, + ) + } + + /** + * Carry a channel's sound, vibration, lights and badge over to a new one: the + * legacy channel to a per-calendar one on upgrade, or a calendar's channel to + * its next version (#518). Lock-screen visibility and a DND override can't + * follow: the system resets both on channels an app creates. + */ + private fun NotificationChannel.inheritFrom(template: NotificationChannel) { + setSound(template.sound, template.audioAttributes) + // The pattern setter also flips vibration on or off, so it goes first. + vibrationPattern = template.vibrationPattern + enableVibration(template.shouldVibrate()) + enableLights(template.shouldShowLights()) + lightColor = template.lightColor + setShowBadge(template.canShowBadge()) + // Only honoured with Do Not Disturb access, so usually left to the user. + setBypassDnd(template.canBypassDnd()) + } + + /** + * Delete the pre-#145 channel once the per-calendar ones carry its settings, + * but not while a reminder posted on it is still on screen — deleting the + * channel would take that notification with it. Returns whether it is gone. + */ + private fun retireLegacyChannel(): Boolean { + val manager = manager + if (manager.getNotificationChannel(LEGACY_REMINDER_CHANNEL_ID) == null) return true + val showing = LEGACY_REMINDER_CHANNEL_ID in showingChannelIds(listOf(LEGACY_REMINDER_CHANNEL_ID)) + if (!showing) manager.deleteNotificationChannel(LEGACY_REMINDER_CHANNEL_ID) + return !showing + } + + private fun groupLabel(group: ReminderChannelGroupSpec): String { + if (group.isLocal) return context.getString(R.string.calendars_local_header) + val name = group.label.ifBlank { context.getString(R.string.calendar_unnamed) } + if (!group.ambiguous) return name + return context.getString(R.string.calendars_account_from_source, name, sourceAppLabel(context, group.accountType)) + } + + private companion object { + const val TAG = "ReminderChannels" + + val DEFAULT_AUDIO_ATTRIBUTES: AudioAttributes = Notification.AUDIO_ATTRIBUTES_DEFAULT + } +} + diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderInstanceSource.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderInstanceSource.kt index 29b140dc..71f7549d 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderInstanceSource.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderInstanceSource.kt @@ -4,6 +4,7 @@ import android.content.Context import android.provider.CalendarContract import dagger.hilt.android.qualifiers.ApplicationContext import de.jeanlucmakiola.calendula.data.calendar.instancesUri +import de.jeanlucmakiola.calendula.data.calendar.reminderMinutesByEvent import de.jeanlucmakiola.calendula.domain.reminders.ReminderEventInstance import javax.inject.Inject import javax.inject.Singleton @@ -72,28 +73,8 @@ class ProviderReminderInstanceSource @Inject constructor( } ?: emptyList() } - override fun reminderMinutes(eventIds: Collection): Map> { - if (eventIds.isEmpty()) return emptyMap() - val out = mutableMapOf>() - // Batched: the ids go into the selection literally, and an unbounded - // `IN (...)` would grow the SQL past what SQLite takes. - eventIds.distinct().chunked(EVENT_ID_BATCH).forEach { batch -> - context.contentResolver.query( - CalendarContract.Reminders.CONTENT_URI, - REMINDER_PROJECTION, - "${CalendarContract.Reminders.METHOD} = " + - "${CalendarContract.Reminders.METHOD_ALERT} AND " + - "${CalendarContract.Reminders.EVENT_ID} IN (${batch.joinToString(",")})", - null, - null, - )?.use { c -> - while (c.moveToNext()) { - out.getOrPut(c.getLong(0)) { mutableListOf() } += c.getInt(1) - } - } - } - return out - } + override fun reminderMinutes(eventIds: Collection): Map> = + context.contentResolver.reminderMinutesByEvent(eventIds, alertsOnly = true) override fun longestReminderMinutes(): Int = context.contentResolver.query( CalendarContract.Reminders.CONTENT_URI, @@ -105,8 +86,6 @@ class ProviderReminderInstanceSource @Inject constructor( )?.use { c -> if (c.moveToFirst()) c.getInt(0) else 0 } ?: 0 private companion object { - const val EVENT_ID_BATCH = 50 - val OCCURRENCE_PROJECTION = arrayOf( CalendarContract.Instances.EVENT_ID, CalendarContract.Instances.CALENDAR_ID, @@ -116,10 +95,5 @@ class ProviderReminderInstanceSource @Inject constructor( CalendarContract.Instances.EVENT_LOCATION, CalendarContract.Instances.ALL_DAY, ) - - val REMINDER_PROJECTION = arrayOf( - CalendarContract.Reminders.EVENT_ID, - CalendarContract.Reminders.MINUTES, - ) } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt index 215554b4..093fc97c 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt @@ -1,10 +1,11 @@ package de.jeanlucmakiola.calendula.data.reminders import android.Manifest -import android.app.NotificationChannel -import android.app.NotificationManager +import android.app.Notification import android.app.PendingIntent import android.content.Context +import android.content.Intent +import androidx.core.net.toUri import android.os.Build import android.os.Bundle import android.util.Log @@ -18,7 +19,14 @@ import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.data.prefs.is24Hour import de.jeanlucmakiola.calendula.data.prefs.resolveFirstDay +import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle +import de.jeanlucmakiola.calendula.domain.reminders.alertStyleFor +import de.jeanlucmakiola.calendula.ui.reminders.ReminderAlertActivity import de.jeanlucmakiola.floret.android.hasPermission +import de.jeanlucmakiola.floret.ring.canUseFullScreenIntent +import de.jeanlucmakiola.calendula.domain.reminders.reminderLink +import de.jeanlucmakiola.calendula.domain.reminders.reminderMapQuery +import de.jeanlucmakiola.floret.android.resolvableMapsSearchIntent import kotlinx.coroutines.flow.first import kotlinx.datetime.isoDayNumber import java.time.DayOfWeek @@ -29,8 +37,9 @@ import javax.inject.Inject import javax.inject.Singleton /** - * Posts one notification per occurrence on a dedicated channel. Tapping opens - * the event's detail screen. + * Posts one notification per occurrence on its calendar's channel + * ([ReminderChannels], #145), or as a full-screen alert where the calendar + * asks for one (#171). Tapping opens the event's detail screen. * * The tag is the [occurrenceKey], so each reminder for an occurrence replaces * the one before it in place (#463). A different reminder alerts afresh; the @@ -43,6 +52,8 @@ class ReminderNotifier @Inject constructor( private val settingsPrefs: SettingsPrefs, private val calendarPrefs: CalendarPrefs, private val calendarDataSource: CalendarDataSource, + private val channels: ReminderChannels, + private val alerts: FullScreenAlerts, ) { /** False when the user declined `POST_NOTIFICATIONS` or muted the app. */ @@ -53,20 +64,96 @@ class ReminderNotifier @Inject constructor( } /** - * The single choke point for "this calendar is switched off", covering the - * two paths that reach [post] around the scan's own filter: a snooze armed - * before the switch-off, and a read-only install whose switch lives in - * [CalendarPrefs]. + * The single choke point for "this calendar posts no reminders": switched + * off (also covering a snooze armed before the switch-off, and a read-only + * install whose switch lives in [CalendarPrefs]), or its notifications + * turned off in Calendula's own settings (#272). */ private suspend fun isSilenced(calendarId: Long): Boolean = - calendarId in calendarPrefs.pendingDisabledCalendarIds.first() || + calendarId in settingsPrefs.mutedReminderCalendarIds.first() || + calendarId in calendarPrefs.pendingDisabledCalendarIds.first() || calendarDataSource.isCalendarVisible(calendarId) == false - /** Post [alert], unless its calendar is switched off. */ - suspend fun post(alert: ReminderAlert) { + /** + * Post [alert] in its calendar's alert style (#171), unless the calendar is + * silenced or gone. [ring] false posts a ringing style as a full-screen + * alert that sounds once instead; [quiet] posts a plain notification that + * makes no sound. Both are how a ring hands a reminder back to the shade. + */ + suspend fun post(alert: ReminderAlert, quiet: Boolean = false, ring: Boolean = true) { if (isSilenced(alert.calendarId)) return - ensureChannel() + var style = when { + quiet -> ReminderAlertStyle.Notification + else -> effectiveStyle(alert).let { + if (it == ReminderAlertStyle.FullScreenRing && !ring) ReminderAlertStyle.FullScreen else it + } + } + // Rung already and handed back to the shade: a catch-up post leaves it there. + if (style == ReminderAlertStyle.FullScreenRing && (isShowing(alert) || alerts.isPending(alert))) return val title = displayTitle(alert) + val text = contentText(alert) + if (style == ReminderAlertStyle.FullScreenRing) { + val ringChannel = channelFor(alert, style) + if (ringChannel != null && + ReminderRingService.start(context, alerts, alert, build(alert, ringChannel, title, text, style, quiet = false)) + ) { + // An earlier reminder for this occurrence gives way to the ring. + NotificationManagerCompat.from(context).cancel(alert.occurrenceKey.toString(), NOTIFICATION_ID) + cancelLegacy(alert) + return + } + // No ring channel, or Android refused the ring: still full-screen, sounding once on the calendar's channel. + if (ringChannel != null) stopRing(RingMatch.Occurrence(alert.occurrenceKey)) + style = ReminderAlertStyle.FullScreen + } else if (ring) { + // A fresh reminder replaces a ring for its occurrence from before the style changed. + stopRing(RingMatch.Occurrence(alert.occurrenceKey)) + } + // Under the channel lock, so a sound picked meanwhile (#518) can't move it mid-post. + val posted = channels.withChannel(alert.calendarId) { channelId -> + notify(alert, build(alert, channelId, title, text, style, quiet)) + } + if (posted == null) { + Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: no channel for calendar ${alert.calendarId}") + } + } + + /** Whether a ring for [alert] should go on, now that settings may have changed since it started. */ + suspend fun ringVerdict(alert: ReminderAlert): RingVerdict = when { + !settingsPrefs.remindersEnabled.first() || !canPost() || isSilenced(alert.calendarId) || + calendarDataSource.isCalendarVisible(alert.calendarId) == null -> RingVerdict.Drop + effectiveStyle(alert) != ReminderAlertStyle.FullScreenRing -> RingVerdict.HandBack + else -> RingVerdict.Ring + } + + /** Whether a live ring for [alert] may go on: its notification can still be seen, and its calendar still notifies. */ + suspend fun canStillRing(alert: ReminderAlert): Boolean = + canPost() && channels.canRing(alert.calendarId) && !isSilenced(alert.calendarId) + + /** The calendar's style, short of ringing where the user blocked its calendar, group or the ring channel. */ + private suspend fun effectiveStyle(alert: ReminderAlert): ReminderAlertStyle { + val chosen = settingsPrefs.reminderAlertStyles.first().alertStyleFor(alert.calendarId) + return if (chosen == ReminderAlertStyle.FullScreenRing && !channels.canRing(alert.calendarId)) { + ReminderAlertStyle.FullScreen + } else { + chosen + } + } + + private fun channelFor(alert: ReminderAlert, style: ReminderAlertStyle): String? = try { + channels.channelFor(alert.calendarId, style).also { + if (it == null) Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: calendar ${alert.calendarId} is gone") + } + } catch (e: Exception) { + Log.w(TAG, "No channel for the reminder of event ${alert.eventId}", e) + null + } + + private suspend fun contentText(alert: ReminderAlert): String = + listOfNotNull(timeText(alert), alert.location).joinToString(" · ") + + /** When [alert]'s occurrence happens, as its notification words it. */ + suspend fun timeText(alert: ReminderAlert): String { val is24Hour = settingsPrefs.timeFormat.first() .is24Hour(android.text.format.DateFormat.is24HourFormat(context)) val zone = ZoneId.systemDefault() @@ -74,7 +161,7 @@ class ReminderNotifier @Inject constructor( // resolveFirstDay yields a kotlinx.datetime day; bridge it to java.time by // its shared ISO number (1..7) for the date math in reminderTimeText. val firstDayOfWeek = DayOfWeek.of(settingsPrefs.weekStart.first().resolveFirstDay(locale).isoDayNumber) - val time = reminderTimeText( + return reminderTimeText( beginMillis = alert.beginMillis, endMillis = alert.endMillis, isAllDay = alert.isAllDay, @@ -87,19 +174,35 @@ class ReminderNotifier @Inject constructor( tomorrowLabel = context.getString(R.string.reminder_day_tomorrow), yesterdayLabel = context.getString(R.string.reminder_day_yesterday), ) - val text = listOfNotNull(time, alert.location).joinToString(" · ") - val notification = NotificationCompat.Builder(context, CHANNEL_ID) + } + + /** + * The reminder's notification in [style]. A ringing one belongs to + * [ReminderRingService]: ongoing and opening the alert screen. A full-screen + * one adds the alert screen as a full-screen intent where Android allows + * it, degrading to a heads-up where it does not, and is dismissed by a + * swipe, so its screen closes too. + */ + private fun build( + alert: ReminderAlert, + channelId: String, + title: String, + text: String, + style: ReminderAlertStyle, + quiet: Boolean, + ): Notification { + val ringing = style == ReminderAlertStyle.FullScreenRing + val fullScreen = style.isFullScreen + val builder = NotificationCompat.Builder(context, channelId) .setSmallIcon(R.drawable.ic_notification) .setContentTitle(title) .setContentText(text) .setWhen(alert.beginMillis) .setShowWhen(false) - .setCategory(NotificationCompat.CATEGORY_EVENT) - .setPriority(NotificationCompat.PRIORITY_HIGH) - .setAutoCancel(true) - .setOnlyAlertOnce(shownKey(alert) == alert.key) + .setCategory(if (ringing) NotificationCompat.CATEGORY_ALARM else NotificationCompat.CATEGORY_EVENT) + .setPriority(if (ringing) NotificationCompat.PRIORITY_MAX else NotificationCompat.PRIORITY_HIGH) .addExtras(Bundle().apply { putLong(EXTRA_REMINDER_KEY, alert.key) }) - .setContentIntent(detailIntent(alert)) + .setContentIntent(if (ringing) alertScreenIntent(alert) else detailIntent(alert)) .addAction( R.drawable.ic_notification_snooze, context.getString(R.string.reminder_action_snooze), @@ -110,7 +213,27 @@ class ReminderNotifier @Inject constructor( context.getString(R.string.reminder_action_dismiss), actionIntent(alert, ReminderActionReceiver.ACTION_DISMISS), ) - .build() + // Room for one more button: a meeting link beats the place, being the likelier next step. + // A ring leaves it to the alert screen, so opening something can't leave it sounding. + if (!ringing) { + linkIntent(alert)?.let { + builder.addAction(R.drawable.ic_notification_link, context.getString(R.string.reminder_action_open_link), it) + } ?: mapIntent(alert)?.let { + builder.addAction(R.drawable.ic_notification_map, context.getString(R.string.event_detail_open_in_maps), it) + } + } + if (fullScreen) builder.setDeleteIntent(actionIntent(alert, ReminderActionReceiver.ACTION_DISMISS)) + if (ringing) { + builder.setOngoing(true).setVisibility(NotificationCompat.VISIBILITY_PUBLIC) + } else { + builder.setAutoCancel(true).setOnlyAlertOnce(shownKey(alert) == alert.key) + } + if (quiet) builder.setSilent(true) + if (fullScreen && context.canUseFullScreenIntent()) builder.setFullScreenIntent(alertScreenIntent(alert), true) + return builder.build() + } + + private fun notify(alert: ReminderAlert, notification: Notification) { val manager = NotificationManagerCompat.from(context) cancelLegacy(alert) try { @@ -131,10 +254,25 @@ class ReminderNotifier @Inject constructor( if (shownKey(alert) == alert.key) manager.cancel(alert.occurrenceKey.toString(), NOTIFICATION_ID) // Posted before reminders shared a notification, under the reminder's own key. manager.cancel(alert.key.toString(), NOTIFICATION_ID) + stopRing(RingMatch.Key(alert.key)) + alerts.markHandled(alert) + } + + /** Stop the ring if it is for a reminder [match]es; [handBack] keeps it in the shade, quietly. */ + fun stopRing(match: RingMatch, handBack: Boolean = false) { + if (alerts.mayRing(match)) ReminderRingService.stop(context, alerts, match, handBack) } /** Whether a different reminder for [alert]'s occurrence is on screen now. */ - fun isSuperseded(alert: ReminderAlert): Boolean = shownKey(alert).let { it != null && it != alert.key } + fun isSuperseded(alert: ReminderAlert): Boolean { + val ringing = alerts.ringing?.takeIf { it.occurrenceKey == alert.occurrenceKey } + if (ringing != null) return ringing.key != alert.key + return shownKey(alert).let { it != null && it != alert.key } + } + + /** Whether [alert] itself is still on screen, as a notification or ringing. */ + fun isShowing(alert: ReminderAlert): Boolean = + alerts.ringing?.key == alert.key || shownKey(alert) == alert.key /** The key of the reminder showing for [alert]'s occurrence, if any. */ private fun shownKey(alert: ReminderAlert): Long? { @@ -153,7 +291,7 @@ class ReminderNotifier @Inject constructor( private fun cancelLegacy(alert: ReminderAlert) { val manager = NotificationManagerCompat.from(context) manager.activeNotifications - .filter { it.id == NOTIFICATION_ID && it.notification.channelId == CHANNEL_ID } + .filter { it.id == NOTIFICATION_ID && it.notification.channelId == LEGACY_REMINDER_CHANNEL_ID } .filter { !it.notification.extras.containsKey(EXTRA_REMINDER_KEY) } .filter { it.notification.`when` == alert.beginMillis } .filter { it.notification.extras.getCharSequence(NotificationCompat.EXTRA_TITLE)?.toString() == displayTitle(alert) } @@ -171,6 +309,13 @@ class ReminderNotifier @Inject constructor( PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, ) + private fun alertScreenIntent(alert: ReminderAlert): PendingIntent = PendingIntent.getActivity( + context, + ReminderActionReceiver.requestCode(alert, ReminderActionReceiver.ACTION_ALERT_SCREEN), + ReminderAlertActivity.intent(context, alert), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + private fun detailIntent(alert: ReminderAlert): PendingIntent = PendingIntent.getActivity( context, // Shares the per-(alert, action) request-code scheme with the buttons. @@ -181,21 +326,44 @@ class ReminderNotifier @Inject constructor( PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, ) - /** Channel creation is idempotent; re-running refreshes the localized name. */ - private fun ensureChannel() { - val channel = NotificationChannel( - CHANNEL_ID, - context.getString(R.string.reminder_channel_name), - NotificationManager.IMPORTANCE_HIGH, - ).apply { - description = context.getString(R.string.reminder_channel_description) - } - NotificationManagerCompat.from(context).createNotificationChannel(channel) + /** + * Opens the first web link in [alert]'s location, e.g. a meeting, started + * directly like [mapIntent]. Null without a link or an app to open it. + */ + private fun linkIntent(alert: ReminderAlert): PendingIntent? { + val link = reminderLink(alert.location) ?: return null + val intent = Intent(Intent.ACTION_VIEW, link.toUri()) + .addCategory(Intent.CATEGORY_BROWSABLE) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + if (intent.resolveActivity(context.packageManager) == null) return null + return PendingIntent.getActivity( + context, + /* requestCode = */ 0, + intent, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + } + + /** + * Opens [alert]'s location in maps like the detail screen does, started + * directly (no receiver trampoline). Leaves the notification up for a later + * snooze or dismiss. Null without a place to look up (a bare meeting link + * isn't one) or an app to open it. + */ + private fun mapIntent(alert: ReminderAlert): PendingIntent? { + val query = reminderMapQuery(alert.location) ?: return null + val intent = context.resolvableMapsSearchIntent(query) ?: return null + return PendingIntent.getActivity( + context, + // An implicit activity intent: filterEquals already keeps it apart from the others. + /* requestCode = */ 0, + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) } private companion object { const val TAG = "ReminderNotifier" - const val CHANNEL_ID = "reminders" // One id, distinct tags: the tag (occurrence) already keys the // notification, so a fixed id keeps cancellation/replacement simple. diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt new file mode 100644 index 00000000..47244dd3 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt @@ -0,0 +1,354 @@ +package de.jeanlucmakiola.calendula.data.reminders + +import android.app.Notification +import android.app.Service +import android.content.Context +import android.content.Intent +import android.media.RingtoneManager +import android.os.IBinder +import android.util.Log +import androidx.core.app.NotificationManagerCompat +import androidx.core.content.IntentCompat +import dagger.hilt.android.AndroidEntryPoint +import de.jeanlucmakiola.calendula.data.di.ApplicationScope +import de.jeanlucmakiola.calendula.data.reminders.ReminderActionReceiver.Companion.putAlert +import de.jeanlucmakiola.floret.ring.RingVibrator +import de.jeanlucmakiola.floret.ring.RingWakeLock +import de.jeanlucmakiola.floret.ring.TonePlayer +import de.jeanlucmakiola.floret.ring.isInCall +import de.jeanlucmakiola.floret.ring.startRingForeground +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import javax.inject.Inject + +/** + * Rings a reminder whose calendar asks for "Ring until dismissed" (#171): the + * alarm sound looped with vibration, for as long as the reminder is neither + * dismissed nor snoozed, up to [RING_TIMEOUT_MILLIS]. Then it goes quiet and + * hands the reminder back to the shade as an ordinary notification. + * + * One reminder rings at a time. A new one takes over, and the one it replaces + * goes back to the shade, silently, unless it was for the same occurrence. + * Starts and stops both arrive as commands, so they are handled on the main + * thread in the order they were sent. + */ +@AndroidEntryPoint +class ReminderRingService : Service() { + + @Inject lateinit var alerts: FullScreenAlerts + @Inject lateinit var notifier: ReminderNotifier + + @Inject @ApplicationScope + lateinit var appScope: CoroutineScope + + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + + private val tones by lazy { TonePlayer(this) } + private val vibrator by lazy { RingVibrator(this) } + private val wakeLock by lazy { RingWakeLock(this, WAKE_LOCK_TAG, RING_TIMEOUT_MILLIS) } + + private var ringing: Job? = null + private var timeout: Job? = null + private var notificationId = RING_NOTIFICATION_ID + private var lastStartId: Int? = null + + /** The start the system would redeliver, so a takeover can mark it done. */ + private var ringStartId: Int? = null + + /** Whether the ring's players were ever built, so a stop-only service builds none. */ + private var rang = false + + override fun onBind(intent: Intent?): IBinder? = null + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + lastStartId = startId + if (intent?.action == ACTION_STOP) { + stop(intent) + return START_NOT_STICKY + } + val alert = intent?.let(ReminderActionReceiver::alertFrom) + if (intent == null || alert == null) { + stopIfIdle() + return START_NOT_STICKY + } + try { + return startRing(intent, alert, startId) + } finally { + // Only now, once alerts.ringing says whether it rings, so a stop sent meanwhile is never skipped. + if (flags and START_FLAG_REDELIVERY == 0) alerts.removePending(alert) + } + } + + private fun startRing(intent: Intent, alert: ReminderAlert, startId: Int): Int { + val notification = IntentCompat.getParcelableExtra(intent, EXTRA_NOTIFICATION, Notification::class.java) + if (notification == null) { + stopIfIdle() + return START_NOT_STICKY + } + val previous = alerts.ringing + // A different reminder posts under the other id, so it is a new + // notification whose full-screen intent opens; an update would not. + val replacing = previous != null && previous.key != alert.key + val shown = notificationId + if (replacing) notificationId = if (shown == RING_NOTIFICATION_ID) OTHER_RING_NOTIFICATION_ID else RING_NOTIFICATION_ID + val foreground = runCatching { startRingForeground(notificationId, notification) } + if (foreground.isFailure) { + // A restart after a process death may be refused a foreground start: + // the reminder still shows full-screen, sounding once. + Log.w(TAG, "Could not ring for event ${alert.eventId}", foreground.exceptionOrNull()) + notificationId = shown + handBack(alert, quiet = false) + stopIfIdle() + return START_NOT_STICKY + } + if (replacing) NotificationManagerCompat.from(this).cancel(shown) + // A duplicate start for this very ring leaves the original in charge of redelivery. + if (previous?.key == alert.key) return START_NOT_STICKY + // Only the newest start is redelivered after a process death; the older + // ones are done, so a handled reminder never rings again. + ringStartId?.let { stopSelfResult(it) } + ringStartId = startId + alerts.ringing = alert + if (previous != null) { + // Its screen closes either way; another occurrence goes back to the shade. + if (previous.occurrenceKey != alert.occurrenceKey) handBack(previous) else alerts.markHandled(previous) + } + val since = intent.getLongExtra(EXTRA_SINCE, System.currentTimeMillis()) + ring(alert, remaining = since + RING_TIMEOUT_MILLIS - System.currentTimeMillis()) + return START_REDELIVER_INTENT + } + + override fun onDestroy() { + if (rang) releaseRing() + // Stopped from outside: its screen must not stay up for a ring that is gone. + alerts.ringing?.let { if (alerts.handBackOnDestroy) handBack(it) else alerts.markHandled(it) } + alerts.handBackOnDestroy = false + alerts.ringing = null + scope.cancel() + super.onDestroy() + } + + /** Rings for what is left of the ring's time, so a ring restarted after a process death does not begin again. */ + private fun ring(alert: ReminderAlert, remaining: Long) { + releaseRing() + rang = true + wakeLock.acquire() + timeout = scope.launch { + delay(remaining.coerceAtLeast(0L)) + giveUp() + } + ringing = scope.launch { + // Settings changed while this ring was on its way apply before it makes a sound. + val verdict = try { + withContext(Dispatchers.IO) { notifier.ringVerdict(alert) } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Could not re-check the ring for event ${alert.eventId}", e) + RingVerdict.Ring + } + if (verdict != RingVerdict.Ring) { + // Never heard yet, so it alerts once in its new style. + if (verdict == RingVerdict.HandBack) handBack(alert, quiet = false) + end() + return@launch + } + sound(alert) + } + } + + /** + * Tone and vibration, paused for a phone call and back after it, until the + * user hides the ring's notification, which would leave no way to stop it. + */ + private suspend fun sound(alert: ReminderAlert) { + var sounding = false + var tick = 0 + while (true) { + if (tick++ % VISIBILITY_CHECK_TICKS == 0 && !stillRings(alert)) { + handBack(alert) + end() + return + } + val inCall = isInCall() + if (inCall && sounding) { + tones.stop() + vibrator.stop() + sounding = false + } else if (!inCall && !sounding) { + vibrator.start() + tones.play(scope, ringSources()) + sounding = true + } + delay(CALL_CHECK_MILLIS) + } + } + + private suspend fun stillRings(alert: ReminderAlert): Boolean = try { + withContext(Dispatchers.IO) { notifier.canStillRing(alert) } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Could not re-check the ring for event ${alert.eventId}", e) + true + } + + private fun stop(intent: Intent) { + val current = alerts.ringing + if (current != null && matchFrom(intent).matches(current)) { + if (intent.getBooleanExtra(EXTRA_HAND_BACK, false)) handBack(current) + end() + } else { + stopIfIdle() + } + } + + /** Rung long enough: back to the shade quietly. */ + private fun giveUp() { + timeout = null + alerts.ringing?.let(::handBack) + end() + } + + /** Ends the ring, closes its screen, and stops the service unless a newer command is on its way. */ + private fun end() { + alerts.ringing?.let(alerts::markHandled) + releaseRing() + alerts.ringing = null + stopForeground(STOP_FOREGROUND_REMOVE) + stopIfIdle() + } + + /** Declines while a newer command is still on its way. */ + private fun stopIfIdle() { + if (alerts.ringing == null) lastStartId?.let { stopSelfResult(it) } + } + + /** + * [alert] back in the shade, in the app's scope so a service stopped + * meanwhile cannot cancel it, and its alert screen closed. A newer reminder + * for the occurrence that took its place meanwhile is left alone. + */ + private fun handBack(alert: ReminderAlert, quiet: Boolean = true) { + alerts.markHandled(alert) + appScope.launch { + try { + if (!notifier.isSuperseded(alert)) notifier.post(alert, quiet = quiet, ring = false) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Could not hand the reminder of event ${alert.eventId} back", e) + } + } + } + + private fun releaseRing() { + ringing?.cancel() + ringing = null + timeout?.cancel() + timeout = null + tones.stop() + vibrator.stop() + wakeLock.release() + } + + /** The device's alarm sound; "None", or none opening, leaves the vibration. */ + private fun ringSources() = listOfNotNull( + RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM), + RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM), + ) + + companion object { + private const val TAG = "ReminderRingService" + private const val ACTION_RING = "de.jeanlucmakiola.calendula.reminders.RING" + private const val ACTION_STOP = "de.jeanlucmakiola.calendula.reminders.RING_STOP" + private const val EXTRA_NOTIFICATION = "notification" + private const val EXTRA_SINCE = "since" + private const val CALL_CHECK_MILLIS = 1_000L + + /** How many call checks between re-reading whether the ring's notification can still be seen. */ + private const val VISIBILITY_CHECK_TICKS = 5 + private const val EXTRA_MATCH_KIND = "match_kind" + private const val EXTRA_MATCH_VALUE = "match_value" + private const val EXTRA_HAND_BACK = "hand_back" + private const val WAKE_LOCK_TAG = "calendula:reminder-ring" + + /** Clear of the reminders' tagged id 1 and the backup notice's 2. */ + private const val RING_NOTIFICATION_ID = 171 + private const val OTHER_RING_NOTIFICATION_ID = 172 + + /** How long a reminder rings unanswered before it goes quiet. */ + const val RING_TIMEOUT_MILLIS = 10L * 60 * 1000 + + /** + * Rings [alert] under [notification]. False when Android refused to + * start the service from where the reminder fired. + */ + fun start(context: Context, alerts: FullScreenAlerts, alert: ReminderAlert, notification: Notification): Boolean { + val intent = Intent(context, ReminderRingService::class.java) + .setAction(ACTION_RING) + .putAlert(alert) + .putExtra(EXTRA_NOTIFICATION, notification) + .putExtra(EXTRA_SINCE, System.currentTimeMillis()) + alerts.addPending(alert) + return try { + RingWakeLock.handOff(context, WAKE_LOCK_TAG) + context.startForegroundService(intent) + true + } catch (e: Exception) { + Log.w(TAG, "Could not start the ring for event ${alert.eventId}", e) + alerts.removePending(alert) + false + } + } + + /** + * Stops the ring if it is for a reminder [match]es, in order with the + * starts sent before it. [handBack] puts it back in the shade quietly. + * A command rather than `stopService`, which would also drop a start + * still on its way; sent while the ring's foreground service keeps the + * app allowed to. + */ + fun stop(context: Context, alerts: FullScreenAlerts, match: RingMatch, handBack: Boolean = false) { + val (kind, value) = when (match) { + is RingMatch.Key -> 0 to match.key + is RingMatch.Occurrence -> 1 to match.occurrenceKey + is RingMatch.Calendar -> 2 to match.calendarId + RingMatch.Any -> 3 to 0L + } + val intent = Intent(context, ReminderRingService::class.java) + .setAction(ACTION_STOP) + .putExtra(EXTRA_MATCH_KIND, kind) + .putExtra(EXTRA_MATCH_VALUE, value) + .putExtra(EXTRA_HAND_BACK, handBack) + try { + context.startService(intent) + } catch (e: Exception) { + Log.w(TAG, "Could not stop the ring", e) + // Refused from the background: nothing must ring on regardless, + // unless a start is still on its way, which this would crash. + if (!alerts.anyPending) { + alerts.handBackOnDestroy = handBack + context.stopService(Intent(context, ReminderRingService::class.java)) + } + } + } + + private fun matchFrom(intent: Intent): RingMatch { + val value = intent.getLongExtra(EXTRA_MATCH_VALUE, 0L) + return when (intent.getIntExtra(EXTRA_MATCH_KIND, 3)) { + 0 -> RingMatch.Key(value) + 1 -> RingMatch.Occurrence(value) + 2 -> RingMatch.Calendar(value) + else -> RingMatch.Any + } + } + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderScanner.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderScanner.kt index a67c9b6a..7a1e7f24 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderScanner.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderScanner.kt @@ -6,9 +6,13 @@ import android.util.Log import dagger.hilt.android.qualifiers.ApplicationContext import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource import de.jeanlucmakiola.calendula.data.calendar.withoutProviderDefaults +import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs import de.jeanlucmakiola.calendula.data.prefs.ReminderStatePrefs import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs +import de.jeanlucmakiola.calendula.domain.reminders.DailyDigestSettings +import de.jeanlucmakiola.calendula.domain.reminders.digestEntries import de.jeanlucmakiola.calendula.domain.reminders.planReminders +import de.jeanlucmakiola.calendula.domain.reminders.scheduleDigest import de.jeanlucmakiola.calendula.domain.reminders.reminderQueryHorizon import de.jeanlucmakiola.calendula.domain.reminders.reminderWatermark import de.jeanlucmakiola.calendula.domain.reminders.scheduleReminders @@ -43,9 +47,12 @@ class ReminderScanner @Inject constructor( private val source: ReminderInstanceSource, private val calendarDataSource: CalendarDataSource, private val notifier: ReminderNotifier, + private val digestNotifier: DailyDigestNotifier, + private val channels: ReminderChannels, private val snoozes: ReminderSnoozeScheduler, private val alarms: ReminderAlarmScheduler, private val state: ReminderStatePrefs, + private val calendarPrefs: CalendarPrefs, private val settingsPrefs: SettingsPrefs, @IoDispatcher private val io: kotlinx.coroutines.CoroutineDispatcher, ) { @@ -77,18 +84,37 @@ class ReminderScanner @Inject constructor( val now = System.currentTimeMillis() if (!hasReadCalendar()) return - if (!settingsPrefs.remindersEnabled.first()) { - // Reminders off: drop the wake-up, but keep the watermark moving - // so switching them back on doesn't replay the backlog. - alarms.cancelScan() - state.setLastScanMillis(now) - return + val lastFired = reminderWatermark(state.lastScanMillis(), now) + val horizon = now + MAX_ALARM_INTERVAL_MILLIS + val digestSettings = settingsPrefs.dailyDigest.first() + val nextDigest = if (digestSettings.enabled) postDigest(digestSettings, lastFired, now) else null + val nextReminder = try { + if (settingsPrefs.remindersEnabled.first()) reminders(lastFired, now, horizon) else null + } catch (e: Exception) { + // The watermark stays, so the next pass owes these reminders again; + // keep that pass, and the summary's next moment, armed. + alarms.scheduleScan(minOf(nextDigest ?: horizon, now + RETRY_AFTER_FAILURE_MILLIS)) + throw e } + // Advance even when nothing could be posted, so muting notifications + // doesn't build a backlog — and while both are off, so switching one + // back on doesn't replay it. + state.setLastScanMillis(now) + val next = listOfNotNull(nextReminder, nextDigest).minOrNull() + if (next == null) alarms.cancelScan() else alarms.scheduleScan(minOf(next, horizon)) + } + + /** Post the event reminders that are due; returns the next wake-up they need. */ + private suspend fun reminders(lastFired: Long, now: Long, horizon: Long): Long { + syncChannels() val lookahead = reminderQueryHorizon(LOOKAHEAD_MILLIS, source.longestReminderMinutes()) // Reach into the past too: an all-day "at time of event" encodes to a // negative offset, and a catch-up pass needs the occurrences it missed. + // Calendars muted in-app (#272) plan nothing, so they arm no wake-ups. + val muted = settingsPrefs.mutedReminderCalendarIds.first() val occurrences = source.occurrences(now - PAST_WINDOW_MILLIS, now + lookahead) + .filter { it.calendarId !in muted } val planned = planReminders( instances = occurrences, minutesByEvent = source.reminderMinutes(occurrences.map { it.eventId }) @@ -99,9 +125,9 @@ class ReminderScanner @Inject constructor( val schedule = scheduleReminders( planned = planned, - lastFiredMillis = reminderWatermark(state.lastScanMillis(), now), + lastFiredMillis = lastFired, nowMillis = now, - horizonMillis = now + MAX_ALARM_INTERVAL_MILLIS, + horizonMillis = horizon, ) if (notifier.canPost()) { @@ -111,10 +137,61 @@ class ReminderScanner @Inject constructor( notifier.post(alert) } } - // Advance even when nothing could be posted, so muting notifications - // doesn't build a backlog. - state.setLastScanMillis(now) - alarms.scheduleScan(schedule.nextAlarmMillis) + return schedule.nextAlarmMillis + } + + /** + * Post the daily summary if it is owed (#459); returns its next moment. It + * leaves out calendars excluded from it, not those muted for reminders — + * a calendar too noisy to ping per event can still belong in the overview. + */ + private suspend fun postDigest(settings: DailyDigestSettings, lastFired: Long, now: Long): Long { + val zone = ZoneId.systemDefault() + val listed = try { + state.lastDigestDay() + } catch (e: Exception) { + Log.w(TAG, "Could not read the last daily summary", e) + null + } + val schedule = scheduleDigest( + timeMinutes = settings.timeMinutes, + day = settings.day, + zone = zone, + // A moment that passed before the summary was last changed is not owed. + lastFiredMillis = maxOf(lastFired, settings.armedAtMillis), + nowMillis = now, + lastListedDay = listed, + ) + val day = schedule.dueDay + // A blocked channel would swallow it; the day stays owed until allowed. + if (day != null && notifier.canPost() && !digestNotifier.isChannelOff()) { + // A failed summary must not cost the event reminders this pass owes. + try { + // A day either side: all-day occurrences sit at UTC midnight, which + // can fall outside the local day they stand for. + val from = day.minusDays(1).atStartOfDay(zone).toInstant().toEpochMilli() + val to = day.plusDays(2).atStartOfDay(zone).toInstant().toEpochMilli() + val left = settings.excludedCalendarIds + calendarPrefs.pendingDisabledCalendarIds.first() + digestNotifier.post(day, digestEntries(source.occurrences(from, to), day, zone, left)) + state.setLastDigestDay(day) + } catch (e: Exception) { + Log.w(TAG, "Daily summary failed", e) + } + } + return schedule.nextAlarmMillis + } + + /** + * A provider change re-scans, so a calendar added, renamed or removed keeps + * its channel in step here. Skipped while reminders are off, when the + * channels have nothing to do. A failure never costs the reminders. + */ + private fun syncChannels() { + try { + channels.sync() + } catch (e: Exception) { + Log.w(TAG, "Reminder channel sync failed", e) + } } private fun hasReadCalendar(): Boolean = context.hasPermission(Manifest.permission.READ_CALENDAR) @@ -158,5 +235,8 @@ class ReminderScanner @Inject constructor( const val MAX_ALARM_INTERVAL_MILLIS = 24L * 60 * 60 * 1000 const val PROVIDER_CHANGE_DEBOUNCE_MILLIS = 2_000L + + /** How soon a pass whose reminders failed is tried again. */ + const val RETRY_AFTER_FAILURE_MILLIS = 15L * 60 * 1000 } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderTimeText.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderTimeText.kt index 9e983d80..d9183015 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderTimeText.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderTimeText.kt @@ -2,6 +2,7 @@ package de.jeanlucmakiola.calendula.data.reminders import de.jeanlucmakiola.calendula.domain.runsMidnightToMidnight import de.jeanlucmakiola.calendula.ui.common.timeOfDayFormatter +import de.jeanlucmakiola.floret.locale.capitalizeStart import java.time.DayOfWeek import java.time.Instant import java.time.LocalDate @@ -121,7 +122,7 @@ private fun relativeDayPrefix( 1L -> tomorrowLabel -1L -> yesterdayLabel else -> if (isSameWeek(day, today, firstDayOfWeek)) { - day.dayOfWeek.getDisplayName(TextStyle.SHORT, locale) + day.dayOfWeek.getDisplayName(TextStyle.SHORT, locale).capitalizeStart(locale) } else { dateFormat.format(day) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/EventForm.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/EventForm.kt index 3afbed56..75163801 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/EventForm.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/EventForm.kt @@ -1,5 +1,7 @@ package de.jeanlucmakiola.calendula.domain +import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder +import de.jeanlucmakiola.calendula.domain.reminders.splitTimedReminders import kotlinx.datetime.LocalDate import kotlinx.datetime.LocalDateTime import kotlinx.datetime.LocalTime @@ -40,6 +42,12 @@ data class EventForm( val description: String = "", /** Reminder lead times in minutes before the start, deduplicated. */ val reminders: List = emptyList(), + /** + * "N days before at HH:MM" reminders of a timed event (#459), written as lead + * times measured from [start] at save time. Ignored while [isAllDay], so a + * round trip through all-day keeps them. + */ + val fixedReminders: List = emptyList(), val availability: Availability = Availability.Busy, val accessLevel: AccessLevel = AccessLevel.Default, /** Confirmed / Tentative / Cancelled (#388). */ @@ -286,7 +294,7 @@ fun EventForm.populatedFields(): Set = buildSet { if (location.isNotBlank()) add(EventFormField.Location) if (description.isNotBlank()) add(EventFormField.Description) if (timezone != null) add(EventFormField.Timezone) - if (reminders.isNotEmpty()) add(EventFormField.Reminders) + if (reminders.isNotEmpty() || (!isAllDay && fixedReminders.isNotEmpty())) add(EventFormField.Reminders) if (rrule != null) add(EventFormField.Recurrence) if (availability != Availability.Busy) add(EventFormField.Availability) if (status != EventStatus.Confirmed) add(EventFormField.Status) @@ -320,17 +328,40 @@ fun EventForm.problems(deviceZone: TimeZone): Set = buildSet { /** * A create form seeded from this occurrence, to save a copy as a new, * independent event (#52). The recurrence is dropped — a duplicate is a single - * event. The source calendar is kept only when [canModify], otherwise the id is - * cleared so the create resolves to a writable calendar, which lets a read-only - * event be copied into an editable one. [instance]'s own times carry over. + * event. The source calendar is only requested: the editor keeps it while it can + * take new events and otherwise resolves the calendar like a new event, which + * lets a read-only event be copied into an editable one. [instance]'s own times + * carry over. */ -fun EventDetail.toDuplicateForm(canModify: Boolean, zone: TimeZone): EventForm = +fun EventDetail.toDuplicateForm( + zone: TimeZone, + knownFixed: Set = emptySet(), +): EventForm = toEditForm( beginMillis = instance.start.toEpochMilliseconds(), endMillis = instance.end.toEpochMilliseconds(), zone = zone, - ).copy( + ).withFixedTimeRemindersRead(knownFixed, zone).copy( rrule = null, - calendarId = instance.calendarId.takeIf { canModify }, status = status.forNewEvent(), ) + +/** + * This form with its timed reminders read back into lead times and + * [EventForm.fixedReminders] ([splitTimedReminders]), the wall clock taken in + * [deviceZone]. All-day forms come back untouched. + */ +fun EventForm.withFixedTimeRemindersRead(known: Set, deviceZone: TimeZone): EventForm { + if (isAllDay || reminders.isEmpty()) return this + val split = splitTimedReminders( + reminders, startInstant(resolvedZone(deviceZone)), deviceZone, known, wallClock = rrule != null, + ) + return copy(reminders = split.leadMinutes, fixedReminders = (fixedReminders + split.fixed).distinct()) +} + +/** The offsets [EventForm.fixedReminders] store for this form's start; empty for an all-day form. */ +fun EventForm.fixedReminderOffsets(deviceZone: TimeZone): List { + if (isAllDay || fixedReminders.isEmpty()) return emptyList() + val start = startInstant(resolvedZone(deviceZone)) + return fixedReminders.map { it.offsetMinutes(start, deviceZone, wallClock = rrule != null) } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/InsertEventForm.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/InsertEventForm.kt index 0a6c0c18..ea4a8a2b 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/InsertEventForm.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/InsertEventForm.kt @@ -13,9 +13,9 @@ import kotlin.time.Instant * back to the same defaults the in-app "new event" uses — a timed start at the * next full hour, and a placeholder hour for a missing end that the form then * stretches to the default-duration setting (the intent is opened as - * `ImportSource.InsertOpenEnded`, #54). [EventForm.calendarId] is left null so - * it resolves to the last-used / first-writable calendar, exactly like the - * `.ics` single-event and plain new-event paths. + * `ImportSource.InsertOpenEnded`, #54). [calendarId] is the calendar the + * intent names, if any; the editor preselects it while it is a target and otherwise + * resolves the calendar like a plain new event (#429). * * Pure (no Android types) so it is unit-testable; the intent parsing that reads * the extras lives in `MainActivity.insertFormOrNull`. @@ -28,6 +28,7 @@ fun buildInsertEventForm( description: String?, location: String? = null, rrule: String? = null, + calendarId: Long? = null, zone: TimeZone, now: Instant, ): EventForm { @@ -44,7 +45,7 @@ fun buildInsertEventForm( startAt.toFormTime(zone) to endAt.toFormTime(zone) } return EventForm( - calendarId = null, + calendarId = calendarId, title = title.orEmpty(), isAllDay = isAllDay, start = start, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/Models.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/Models.kt index 11e39eb8..6f0cfe08 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/Models.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/Models.kt @@ -309,3 +309,7 @@ enum class FailureReason { EventNotFound, Unknown, } + +/** [this] without the events of [hidden] calendars. */ +fun List.withoutCalendars(hidden: Set): List = + if (hidden.isEmpty()) this else filterNot { it.calendarId in hidden } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/NewEventCalendar.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/NewEventCalendar.kt new file mode 100644 index 00000000..5e35ece8 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/NewEventCalendar.kt @@ -0,0 +1,76 @@ +package de.jeanlucmakiola.calendula.domain + +/** + * The calendar chosen as default for new events (#429). Provider ids are + * device-local and get reassigned when an account is re-added or a backup is + * restored onto another device, so the account and name ride along: see [find]. + */ +data class DefaultCalendarRef( + val id: Long, + val accountType: String, + val accountName: String, + val displayName: String, +) { + /** + * The calendar this refers to: the exact one, else the account's calendar of + * that name (the id changed), else the id within the account (it was renamed). + */ + fun find(calendars: List): CalendarSource? { + val inAccount = calendars.filter { it.accountType == accountType && it.accountName == accountName } + return inAccount.firstOrNull { it.id == id && it.displayName == displayName } + ?: inAccount.singleOrNull { it.displayName == displayName } + ?: inAccount.firstOrNull { it.id == id } + } + + fun encode(): String = listOf(id.toString(), accountType, accountName, displayName).joinToString(SEPARATOR) + + companion object { + private const val SEPARATOR = "\u001F" + + fun of(calendar: CalendarSource) = + DefaultCalendarRef(calendar.id, calendar.accountType, calendar.accountName, calendar.displayName) + + fun decode(stored: String?): DefaultCalendarRef? { + val parts = stored?.split(SEPARATOR, limit = 4)?.takeIf { it.size == 4 } ?: return null + val id = parts[0].toLongOrNull() ?: return null + return DefaultCalendarRef(id, parts[1], parts[2], parts[3]) + } + } +} + +/** + * What decides a new event's calendar when the user hasn't picked one (#429). + * [requested] is a calendar named by whoever opened the form (an insert intent, + * a duplicate's source), [default] the "default calendar" setting and + * [lastUsed] the calendar the last new event went into. + */ +data class NewEventCalendarHints( + val requested: Long? = null, + val default: DefaultCalendarRef? = null, + val lastUsed: Long? = null, +) + +/** + * The calendar the event form targets: [picked] when set, otherwise the first of + * the requested, default and last-used calendar that is still an event target, + * then the first target. + */ +fun resolveEventCalendar( + picked: Long?, + hints: NewEventCalendarHints, + calendars: List, +): Long? { + fun Long.ifTarget() = takeIf { id -> calendars.any { it.id == id && it.isEventTarget } } + return picked + ?: hints.requested?.ifTarget() + ?: effectiveDefaultCalendar(hints.default, calendars)?.id + ?: hints.lastUsed?.ifTarget() + ?: calendars.firstOrNull { it.isEventTarget }?.id +} + +/** + * The default calendar setting as it applies now: null ("Automatic") when unset, + * or when the stored calendar is gone, read-only or switched off. + */ +fun effectiveDefaultCalendar(default: DefaultCalendarRef?, calendars: List): CalendarSource? = + default?.find(calendars)?.takeIf { it.isEventTarget } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/backup/BackupPlan.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/backup/BackupPlan.kt new file mode 100644 index 00000000..dbed2c78 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/backup/BackupPlan.kt @@ -0,0 +1,426 @@ +package de.jeanlucmakiola.calendula.domain.backup + +import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.domain.ics.IcsEvent +import de.jeanlucmakiola.calendula.domain.ics.flattenOverrides +import de.jeanlucmakiola.calendula.domain.isNotSynced +import de.jeanlucmakiola.floret.android.safeFileName +import java.security.MessageDigest +import java.time.LocalDateTime +import java.time.format.DateTimeFormatter + +/** + * Whether this calendar can be backed up at all. Any calendar the provider + * holds can be *read* (#147), whatever its visibility or access level. Left out: + * the managed special-dates mirrors, rebuilt from contacts so a restore would + * only duplicate them, and calendars whose events aren't synced to the device. + */ +val CalendarSource.isBackupCandidate: Boolean + get() = !isManaged && !isNotSynced + +/** + * Whether a backup includes this calendar until the user says otherwise: the + * app's own writable local calendars, which have no other copy anywhere. Synced + * calendars already live on their server, so they are opt-in. + */ +val CalendarSource.isBackedUpByDefault: Boolean + get() = isLocal && canModifyContents && !isManaged + +/** + * Which calendars the automatic backup covers, stored as deviations from + * [isBackedUpByDefault] so a calendar created later still follows the default: + * [included] opts a calendar in, [excluded] opts one out. + */ +data class BackupSelection( + val included: Set = emptySet(), + val excluded: Set = emptySet(), +) { + fun selects(calendar: CalendarSource): Boolean = when { + !calendar.isBackupCandidate -> false + calendar.id in included -> true + calendar.id in excluded -> false + else -> calendar.isBackedUpByDefault + } + + /** The selection with [calendar] switched [on]; a choice matching the default leaves no trace. */ + fun with(calendar: CalendarSource, on: Boolean): BackupSelection { + val id = calendar.id + val default = calendar.isBackedUpByDefault + return BackupSelection( + included = if (on && !default) included + id else included - id, + excluded = if (!on && default) excluded + id else excluded - id, + ) + } +} + +/** One backup file series: the calendars it holds and the name its files start with. */ +data class BackupTarget( + /** Stable identity of the series in the [BackupLedger]: the calendar id, or [COMBINED_SERIES]. */ + val key: String, + val calendarIds: Set, + val baseName: String, + /** The calendar name written into the file, or null for a combined file. */ + val calendarName: String?, +) + +/** What one run writes and which earlier files it removes afterwards. */ +data class BackupFilePlan( + val target: BackupTarget, + val fileName: String, + /** Earlier files of this series that stay, oldest first. */ + val keep: List, + /** Earlier files of this series beyond the retention count, oldest first. */ + val prune: List, + /** + * The stable, undated copy overwritten every run (`.ics`), for tools + * that follow one path. Null when a file of that name is in the folder but + * isn't one this backup wrote: the user's own file is never overwritten. + */ + val latestName: String?, + /** This series' earlier stable copies under a name it no longer uses (a rename), to delete. */ + val staleLatest: List = emptyList(), + /** + * Stable copies this series held that another series of the run now takes + * over: kept on record until that series has claimed them. + */ + val handOff: List = emptyList(), +) + +/** + * The files the automatic backup has written, per series key, oldest first. + * Pruning only ever deletes names recorded here, so a series is its files, not + * whatever currently matches a calendar's name: renames, same-named calendars + * and the user's own files in the folder can't pull in the wrong ones. A + * series' stable copy is recorded apart, under [latestLedgerKey]. + */ +typealias BackupLedger = Map> + +const val COMBINED_SERIES = "combined" + +/** The combined file's series name; also the fixed name used before #411. */ +const val COMBINED_BACKUP_BASE = "calendula-backup" + +/** + * The single file every automatic backup overwrote before #411: the combined + * series' stable copy now, so an old setup keeps its path. + */ +val LEGACY_BACKUP_FILE: String = latestFileName(COMBINED_BACKUP_BASE) + +private const val LATEST_PREFIX = "latest-" + +/** Where the ledger records the stable copy of the series [key]. */ +fun latestLedgerKey(key: String): String = "$LATEST_PREFIX$key" + +/** The retention choices the settings offer, newest kept first. */ +val BACKUP_KEEP_OPTIONS: List = listOf(1, 2, 3, 5, 7, 10) + +const val DEFAULT_BACKUP_KEEP = 3 + +/** Room for the id suffix and the stamp within a file system's 255-byte name limit. */ +private const val MAX_BASE_BYTES = 120 +private const val ICS_EXTENSION = ".ics" +private const val STAMP_PATTERN = "yyyy-MM-dd_HH-mm-ss" +private val STAMP_FORMAT: DateTimeFormatter = DateTimeFormatter.ofPattern(STAMP_PATTERN) + +/** + * The file series the automatic backup writes: one combined file, or one per + * calendar named after it. Calendars whose names clash case-insensitively (a + * local and a synced "Personal") must not write the same file, and a path + * something follows shouldn't move because another calendar took the same + * name. So the series holding the stable copy of the name in [ledger] keeps + * it, then one holding dated files under it; series that already write under + * their id suffix keep that, clash or not; with no claim at all the lowest id keeps the + * name. The others take their id as a suffix until every name in the run is + * distinct. A stable copy a series outside the run still holds (a calendar + * taken out of the backup) is kept, so a calendar now named like it is + * suffixed too. Ledger names gone from the folder ([existing], when known) + * claim nothing. A calendar named like the combined file is always suffixed. + */ +fun backupTargets( + calendars: List, + combined: Boolean, + ledger: BackupLedger = emptyMap(), + existing: Set? = null, +): List { + if (calendars.isEmpty()) return emptyList() + if (combined) { + return listOf( + BackupTarget(COMBINED_SERIES, calendars.map { it.id }.toSet(), COMBINED_BACKUP_BASE, calendarName = null), + ) + } + val present = if (existing == null) ledger else ledger.mapValues { (_, names) -> names.filter { it in existing } } + val bases = calendars.associateTo(LinkedHashMap()) { + val base = safeFileName(it.displayName, MAX_BASE_BYTES, fallback = "calendar") + val suffixed = "$base-${it.id}" + it.id to if (present.holdsLatest(it.id.toString(), suffixed)) suffixed else base + } + val runKeys = calendars.map { latestLedgerKey(it.id.toString()) }.toSet() + val heldOutside = present.filterKeys { it.startsWith(LATEST_PREFIX) && it !in runKeys } + .values.flatten().map { it.lowercase() }.toSet() + while (true) { + val clashing = bases.entries.groupBy({ it.value.lowercase() }, { it.key }) + .filter { (lower, ids) -> ids.size > 1 || lower == COMBINED_BACKUP_BASE.lowercase() } + if (clashing.isNotEmpty()) { + clashing.forEach { (lower, ids) -> + val keeper = if (lower == COMBINED_BACKUP_BASE.lowercase()) null else present.keeperOf(ids, bases) + ids.filter { it != keeper }.forEach { id -> bases[id] = "${bases.getValue(id)}-$id" } + } + continue + } + val taken = bases.filterValues { latestFileName(it).lowercase() in heldOutside }.keys + if (taken.isEmpty()) break + taken.forEach { id -> bases[id] = "${bases.getValue(id)}-$id" } + } + return calendars.map { calendar -> + BackupTarget( + key = calendar.id.toString(), + calendarIds = setOf(calendar.id), + baseName = bases.getValue(calendar.id), + calendarName = calendar.displayName, + ) + } +} + +/** Which of the clashing [ids] keeps its name in [bases], or null when all take their suffix. */ +private fun BackupLedger.keeperOf(ids: List, bases: Map): Long? { + fun base(id: Long) = bases.getValue(id) + return ids.filter { holdsLatest(it.toString(), base(it)) }.minOrNull() + ?: ids.filter { holdsDated(it.toString(), base(it)) }.minOrNull() + ?: ids.filterNot { holdsLatest(it.toString(), "${base(it)}-$it") || holdsDated(it.toString(), "${base(it)}-$it") } + .minOrNull() +} + +private fun BackupLedger.holdsLatest(key: String, base: String): Boolean = + this[latestLedgerKey(key)].orEmpty().any { it.equals(latestFileName(base), ignoreCase = true) } + +/** Dated files of [base], including ones a provider renamed (`… (1).ics`). */ +private fun BackupLedger.holdsDated(key: String, base: String): Boolean { + val dated = Regex( + "${Regex.escape(base)}_\\d{4}-\\d{2}-\\d{2}_\\d{2}-\\d{2}-\\d{2}.*\\.ics", + RegexOption.IGNORE_CASE, + ) + return this[key].orEmpty().any { dated.matches(it) } +} + +/** `Work_2026-11-13_14-30-05.ics`: the series name and the local time of the run. */ +fun backupFileName(baseName: String, at: LocalDateTime): String = + "${baseName}_${at.format(STAMP_FORMAT)}$ICS_EXTENSION" + +/** + * Plan one run: a new dated file per target, and which of the series' recorded + * files ([ledger]) fall out of the newest [keep], the new one included. Recorded + * files no longer in the folder ([existing]) are forgotten. Each target also + * gets its stable copy, which retention never touches. A stable name is only + * written when the file is absent or this series owns it — or a series of this + * run that is moving off it (a rename hand-off). + */ +fun planBackupFiles( + targets: List, + ledger: BackupLedger, + existing: Set, + at: LocalDateTime, + keep: Int, +): List { + val retain = keep.coerceAtLeast(1) + val runKeys = targets.map { it.key }.toSet() + val owners = ledger.filterKeys { it.startsWith(LATEST_PREFIX) } + .flatMap { (key, names) -> names.map { it to key.removePrefix(LATEST_PREFIX) } } + .toMap() + val currentLatest = targets.map { latestFileName(it.baseName) }.toSet() + return targets.map { target -> + val fileName = backupFileName(target.baseName, at) + val latest = latestFileName(target.baseName) + val earlier = ledger[target.key].orEmpty() + .filter { it in existing && it != fileName && it != latest } + .distinct() + val kept = earlier.takeLast(retain - 1) + val owner = owners[latest] + val writable = latest !in existing || (owner != null && owner in runKeys) + BackupFilePlan( + target = target, + fileName = fileName, + keep = kept, + prune = earlier.dropLast(kept.size), + latestName = latest.takeIf { writable }, + staleLatest = ledger[latestLedgerKey(target.key)].orEmpty() + .filter { it in existing && it != latest && it !in currentLatest }, + handOff = ledger[latestLedgerKey(target.key)].orEmpty() + .filter { it in existing && it != latest && it in currentLatest }, + ) + } +} + +/** + * Stable copies the current layout replaced, per ledger key: a calendar's own + * copy once the combined file holds it, or the combined copy once each calendar + * has its own. Left in place they would keep serving old data under a path + * something may follow. A calendar taken out of the backup keeps its copy. + */ +fun replacedLatestCopies( + targets: List, + ledger: BackupLedger, + existing: Set, +): Map> { + val runKeys = targets.map { it.key }.toSet() + val covered = targets.flatMap { it.calendarIds }.map { it.toString() }.toSet() + val currentLatest = targets.map { latestFileName(it.baseName) }.toSet() + val combinedRun = COMBINED_SERIES in runKeys + return ledger.filterKeys { it.startsWith(LATEST_PREFIX) } + .mapKeys { it.key.removePrefix(LATEST_PREFIX) } + .filterKeys { key -> + key !in runKeys && (if (key == COMBINED_SERIES) !combinedRun else combinedRun && key in covered) + } + .mapValues { (_, names) -> names.filter { it in existing && it !in currentLatest } } + .filterValues { it.isNotEmpty() } +} + +/** + * The ledger with [key]'s files set to [files] (empty drops the entry). Entries + * of deleted calendars go ([liveKeys]); their files stay, unrecorded. Others + * stay, so a calendar taken out of the backup still has its files pruned if it + * is put back. + */ +fun withLedgerEntry( + previous: BackupLedger, + key: String, + files: List, + liveKeys: Set, +): BackupLedger { + val next = previous.filterKeys { entry -> + val series = entry.removePrefix(LATEST_PREFIX) + series in liveKeys || series == COMBINED_SERIES + }.toMutableMap() + next[key] = files.distinct() + // A stable copy has one owner: claiming it takes it off any other series. + if (key.startsWith(LATEST_PREFIX)) { + next.keys.filter { it != key && it.startsWith(LATEST_PREFIX) }.forEach { other -> + next[other] = next.getValue(other) - files.toSet() + } + } + return next.filterValues { it.isNotEmpty() } +} + +/** Stable copies recorded under any series but [key] — a hand-off that has already been claimed. */ +fun BackupLedger.latestHeldElsewhere(key: String): Set = + filterKeys { it.startsWith(LATEST_PREFIX) && it != latestLedgerKey(key) }.values.flatten().toSet() + +/** `Work.ics`: the series' stable copy. */ +fun latestFileName(baseName: String): String = "$baseName$ICS_EXTENSION" + +private const val LEDGER_ENTRY_SEP = "|" +private const val LEDGER_KEY_SEP = "/" + +/** Stores the ledger; both separators are characters no name this app writes can hold. */ +fun persistBackupLedger(ledger: BackupLedger): String? = + ledger.filterValues { it.isNotEmpty() }.takeIf { it.isNotEmpty() } + ?.entries?.sortedBy { it.key } + ?.joinToString(LEDGER_ENTRY_SEP) { (key, names) -> (listOf(key) + names).joinToString(LEDGER_KEY_SEP) } + +fun parseBackupLedger(stored: String?): BackupLedger = + stored?.split(LEDGER_ENTRY_SEP).orEmpty().mapNotNull { entry -> + val parts = entry.split(LEDGER_KEY_SEP) + val names = parts.drop(1).filter { it.isNotEmpty() } + parts.first().takeIf { it.isNotEmpty() && names.isNotEmpty() }?.let { it to names } + }.toMap() + +/** The interval can only be off while backing up after changes is on (#516), or nothing would ever run. */ +fun backupIntervalOn(stored: Boolean, onChange: Boolean): Boolean = stored || !onChange + +/** Without the interval there are no dated files, so every run only refreshes the stable copies. */ +fun backupRunLatestOnly(changeRun: Boolean, intervalOn: Boolean): Boolean = changeRun || !intervalOn + +/** + * Whether a run can back this series up at all: without dated files, only + * through its stable copy, which a file of the user's can block. + */ +fun BackupFilePlan.backedUp(intervalOn: Boolean): Boolean = intervalOn || latestName != null + +/** Closest offered retention count to [stored], so a stray value still shows a row. */ +fun normalizeBackupKeep(stored: Int): Int = + BACKUP_KEEP_OPTIONS.minBy { kotlin.math.abs(it - stored) } + +/** + * Content hash of a series' file, per series key (#516), so a run started by a + * change can tell whether the calendars it covers changed at all. + */ +typealias BackupFingerprints = Map + +/** + * Hash of a series' file, leaving out the run's `DTSTAMP`s so equal events give + * an equal hash, and bound to the stable copy's [fileName], so a copy under + * another name never passes as current. + */ +fun backupFingerprint(ics: String, fileName: String): String { + val digest = MessageDigest.getInstance("SHA-256") + digest.update(fileName.toByteArray(Charsets.UTF_8)) + digest.update(LINE_BREAK) + ics.lineSequence().filterNot { it.startsWith(DTSTAMP_PREFIX) } + .forEach { + digest.update(it.toByteArray(Charsets.UTF_8)) + digest.update(LINE_BREAK) + } + return digest.digest().take(FINGERPRINT_BYTES).joinToString("") { "%02x".format(it) } +} + +/** [previous] with [key] set to [fingerprint]; entries of deleted calendars go, as in [withLedgerEntry]. */ +fun withFingerprint( + previous: BackupFingerprints, + key: String, + fingerprint: String, + liveKeys: Set, +): BackupFingerprints = + previous.filterKeys { it in liveKeys || it == COMBINED_SERIES } + (key to fingerprint) + +private const val FINGERPRINT_BYTES = 16 +private const val DTSTAMP_PREFIX = "DTSTAMP:" +private val LINE_BREAK = byteArrayOf('\n'.code.toByte()) +private const val FINGERPRINT_SEP = "=" + +fun persistBackupFingerprints(fingerprints: BackupFingerprints): String? = + fingerprints.takeIf { it.isNotEmpty() } + ?.entries?.sortedBy { it.key } + ?.joinToString(LEDGER_ENTRY_SEP) { (key, hash) -> "$key$FINGERPRINT_SEP$hash" } + +fun parseBackupFingerprints(stored: String?): BackupFingerprints = + stored?.split(LEDGER_ENTRY_SEP).orEmpty().mapNotNull { entry -> + val key = entry.substringBefore(FINGERPRINT_SEP, "") + val hash = entry.substringAfter(FINGERPRINT_SEP, "") + if (key.isEmpty() || hash.isEmpty()) null else key to hash + }.toMap() + +/** + * Whether a run started by a change (#516) rewrites this series' stable copy: + * only when its content moved on from what the copy holds (a rename changes + * the name written into it), or the copy is missing. Never when the name belongs to a file of the user's, + * nor when a [complete]-less listing doesn't show the copy: writing then would + * add a duplicate beside it, so that is left to the next run that isn't a change run. + */ +fun BackupFilePlan.needsRefresh( + fingerprint: String, + stored: BackupFingerprints, + listed: Set, + complete: Boolean, +): Boolean { + val latest = latestName ?: return false + if (latest !in listed) return complete + return stored[target.key] != fingerprint +} + +/** + * The events in a fixed order, their lists sorted, so the same content always + * writes the same file and hashes the same, however the provider returned it. + * Standalone occurrences stay first, as [flattenOverrides] puts them. + */ +fun List.inBackupOrder(): List = + map { + it.copy( + reminderMinutes = it.reminderMinutes.sorted(), + exDates = it.exDates.sorted(), + recurrenceDates = it.recurrenceDates.sorted(), + ) + }.sortedWith( + compareBy( + { it.overrideOf == null }, { it.start }, { it.uid }, { it.overrideAt }, { it.calendarName }, + { it.toString() }, + ), + ) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt new file mode 100644 index 00000000..13046a57 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt @@ -0,0 +1,74 @@ +package de.jeanlucmakiola.calendula.domain.ics + +import de.jeanlucmakiola.calendula.domain.EventStatus +import kotlin.time.Duration.Companion.days + +/** + * The events a calendar copy (#325) inserts into its target, in the shape + * `importEvents` takes: the source's rows flattened as [flattenOverrides] does + * for a backup, minus cancelled series and one-offs, which would arrive live + * (an insert can't be cancelled), and declined invitations and occurrences. Attendees and organizer are never read. + * + * Idempotent per snapshot: `importEvents` skips a UID the target already holds, + * and an [IcsEvent.overrideOf] occurrence whose series it holds, so a re-run + * keeps the earlier copy of an occurrence changed since rather than adding a + * second one beside it. + */ +fun planCalendarCopy( + rows: CalendarRows, + exdateStamp: (occurrenceMillis: Long, isAllDay: Boolean) -> String, +): List { + val declinedSeries = rows.series.filter { it.declined } + val declinedIds = declinedSeries.map { it.eventId }.toSet() + val declinedSyncIds = declinedSeries.filter { it.syncId != null }.map { it.calendarId to it.syncId }.toSet() + fun OverrideRow.ofDeclinedSeries() = + originalId in declinedIds || (originalSyncId != null && (calendarId to originalSyncId) in declinedSyncIds) + val live = CalendarRows( + series = rows.series.filterNot { it.event.status == EventStatus.Cancelled }, + // A declined occurrence is as good as deleted here, and so is one of a + // declined series the user didn't accept on its own. + overrides = rows.overrides.map { + if (it.declined || (it.ofDeclinedSeries() && !it.accepted)) { + it.copy(event = it.event.copy(status = EventStatus.Cancelled)) + } else { + it + } + }, + ) + // A declined series still hands its accepted occurrences on before it goes. + // The flattened series follow the standalone occurrences, one per row in order. + val flat = flattenOverrides(live, exdateStamp) + val standalone = flat.size - live.series.size + return flat.filterIndexed { i, _ -> i < standalone || live.series[i - standalone].eventId !in declinedIds } + .map { it.toParsedIcsEvent() } +} + +/** + * [IcsEvent] read back as if [IcsWriter] had written it and [IcsParser] had read + * it, without the text in between. Unlike that round trip it keeps a one-off's + * own time zone (the writer pins it to UTC) and the event's colour (not part of + * the file format). + */ +fun IcsEvent.toParsedIcsEvent(): ParsedIcsEvent = ParsedIcsEvent( + uid = uid, + summary = summary, + start = start, + // RFC 5545 §3.6.1: an all-day event lasts at least its one day; zero-length + // it expands into no instance at all. + end = if (isAllDay && end <= start) start + 1.days else end, + isAllDay = isAllDay, + zoneId = zoneId, + recurrenceRule = recurrenceRule?.takeIf { it.isNotBlank() }?.removePrefix("RRULE:"), + recurrenceDates = recurrenceDates.filter { it.isNotBlank() }.distinct(), + location = location, + description = description, + // The writer emits only lead times; a negative one would be an alarm after the start. + reminderMinutes = reminderMinutes.filter { it >= 0 }.distinct(), + status = status, + availability = availability, + accessLevel = accessLevel, + color = color, + overrideOf = overrideOf, + overrideAt = overrideAt, + exDates = if (recurs) exDates.filter { it.isNotBlank() }.distinct() else emptyList(), +) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt new file mode 100644 index 00000000..2258e6ce --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt @@ -0,0 +1,99 @@ +package de.jeanlucmakiola.calendula.domain.ics + +import de.jeanlucmakiola.calendula.domain.EventStatus +import kotlin.time.Instant + +/** + * A master or one-off Events row of a calendar being backed up or copied, with + * the provider keys its exception rows point back through. + */ +data class MasterRow( + val eventId: Long, + val calendarId: Long, + val syncId: String?, + val event: IcsEvent, + /** The user declined this invitation. */ + val declined: Boolean = false, +) + +/** + * An exception row: a modified or cancelled occurrence of the series named by + * [originalId] / [originalSyncId] in [calendarId], standing in for the + * occurrence that would have started at [originalInstance]. + */ +data class OverrideRow( + val calendarId: Long, + val originalId: Long?, + val originalSyncId: String?, + val originalInstance: Instant, + val event: IcsEvent, + /** The user declined this occurrence. */ + val declined: Boolean = false, + /** The user accepted (or tentatively accepted) this occurrence on its own. */ + val accepted: Boolean = false, +) { + val isCancelled: Boolean get() = event.status == EventStatus.Cancelled +} + +/** Every event row a backup or copy reads: series/one-offs and their exception rows. */ +data class CalendarRows( + val series: List, + val overrides: List, +) + +/** + * [rows] as plain events with no exception rows left, the shape both a backup + * file and a copied calendar need: neither can hold an exception row, since one + * only attaches to its series through a `_sync_id` (and an `.ics` restore skips + * `RECURRENCE-ID` overrides). + * + * Every override excludes its occurrence from the series (`EXDATE`), and a + * modified one comes along as a standalone event at its own times, marked + * [IcsEvent.overrideOf] its series — what Calendula itself writes for "only this + * event" on an unsynced series. Its UID is derived from the series' UID and the + * occurrence, so it is the same on every run. Overrides whose series isn't + * among the rows are left out; the provider doesn't show them either. + * + * Standalone occurrences come first; `importEvents` enforces that order for + * any file, so an import cut short leaves at worst an occurrence missing its + * series, never a series missing an occurrence. + * + * [exdateStamp] formats an occurrence as an `EXDATE` entry in the provider's + * shape, the same one Calendula's own exclusions use. A cancelled series' + * modified occurrences stay cancelled. + */ +fun flattenOverrides( + rows: CalendarRows, + exdateStamp: (occurrenceMillis: Long, isAllDay: Boolean) -> String, +): List { + val byId = rows.series.associateBy { it.eventId } + // Sync ids are only unique within an account, so the link is per calendar. + val bySyncId = rows.series.filter { it.syncId != null }.associateBy { it.calendarId to it.syncId } + val excluded = mutableMapOf>() + val detached = mutableListOf>() + for (override in rows.overrides) { + val parent = override.originalId?.let(byId::get)?.takeIf { it.calendarId == override.calendarId } + ?: override.originalSyncId?.let { bySyncId[override.calendarId to it] } + ?: continue + // An exception to a one-off overrides nothing a plain event could carry. + if (!parent.event.recurs) continue + val occurrence = override.originalInstance.toEpochMilliseconds() + excluded.getOrPut(parent.eventId) { mutableListOf() } += exdateStamp(occurrence, parent.event.isAllDay) + if (override.isCancelled || parent.event.status == EventStatus.Cancelled) continue + detached += override.calendarId to override.event.copy( + uid = "$occurrence-${parent.event.uid}", + recurrenceRule = null, + recurrenceDates = emptyList(), + exDates = emptyList(), + overrideOf = parent.event.uid, + overrideAt = override.originalInstance, + ) + } + // Two exception rows for one occurrence would derive the same UID; the same + // series in two calendars legitimately does. + return detached.distinctBy { (calendarId, event) -> calendarId to event.uid }.map { it.second } + + rows.series.map { s -> + val extra = excluded[s.eventId].orEmpty() + if (extra.isEmpty()) s.event else s.event.copy(exDates = (s.event.exDates + extra).distinct()) + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsEvent.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsEvent.kt index 19da17bb..bf708821 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsEvent.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsEvent.kt @@ -1,5 +1,6 @@ package de.jeanlucmakiola.calendula.domain.ics +import de.jeanlucmakiola.calendula.domain.AccessLevel import de.jeanlucmakiola.calendula.domain.Availability import de.jeanlucmakiola.calendula.domain.EventStatus import kotlin.time.Instant @@ -36,8 +37,25 @@ data class IcsEvent( val availability: Availability = Availability.Busy, /** Source calendar name, emitted as `X-CALENDULA-CALENDAR` so a combined backup can fan back out. */ val calendarName: String? = null, + /** Extra occurrences (`RDATE`), in the same shape as [exDates]. */ + val recurrenceDates: List = emptyList(), + /** Carried by a calendar copy, not written to a file. */ + val accessLevel: AccessLevel = AccessLevel.Default, + /** The event's own colour, null when it shows its calendar's; carried by a calendar copy, not written to a file. */ + val color: Int? = null, + /** + * For a modified occurrence written out on its own ([flattenOverrides]): the + * UID of the series it replaces an occurrence of, as `X-CALENDULA-OVERRIDE-OF`. + */ + val overrideOf: String? = null, + /** The occurrence of [overrideOf] this event replaces, as `X-CALENDULA-OVERRIDE-AT`. */ + val overrideAt: Instant? = null, ) +/** Whether this is a series: by rule, or by listed dates alone. */ +val IcsEvent.recurs: Boolean + get() = !recurrenceRule.isNullOrBlank() || recurrenceDates.isNotEmpty() + /** * The UID to export for a provider event. A row that already carries a UID * (`Events.UID_2445`) keeps it; otherwise we synthesise a **stable** one from diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsParser.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsParser.kt index 75d40206..757e2290 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsParser.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsParser.kt @@ -1,5 +1,6 @@ package de.jeanlucmakiola.calendula.domain.ics +import de.jeanlucmakiola.calendula.domain.AccessLevel import de.jeanlucmakiola.calendula.domain.Availability import de.jeanlucmakiola.calendula.domain.EventStatus import de.jeanlucmakiola.calendula.domain.zoneOrNull @@ -45,6 +46,17 @@ data class ParsedIcsEvent( val exDates: List = emptyList(), /** True when this came from a `VTODO` rather than a `VEVENT`. */ val isTask: Boolean = false, + /** + * The UID of the series this standalone occurrence replaces one occurrence + * of (`X-CALENDULA-OVERRIDE-OF`). An import skips it where that series + * already is, since the series there carries its own override. + */ + val overrideOf: String? = null, + /** The occurrence of [overrideOf] this event replaces (`X-CALENDULA-OVERRIDE-AT`). */ + val overrideAt: Instant? = null, + /** Extra occurrences (`RDATE`), in the same shape as [exDates]. */ + val recurrenceDates: List = emptyList(), + val accessLevel: AccessLevel = AccessLevel.Default, ) /** @@ -212,7 +224,10 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault var calendarColor: Int? = null val reminders = mutableListOf() val exDateLines = mutableListOf() + val rDateLines = mutableListOf() var skipAsOverride = false + var overrideOf: String? = null + var overrideAt: Instant? = null var i = 0 while (i < body.size) { @@ -233,6 +248,7 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault "DURATION" -> duration = line.value.trim() "RRULE" -> rrule = line.value.trim().ifEmpty { null } "EXDATE" -> exDateLines.add(line) + "RDATE" -> rDateLines.add(line) "LOCATION" -> location = unescapeText(line.value).ifEmpty { null } "DESCRIPTION" -> description = unescapeText(line.value).ifEmpty { null } "STATUS" -> status = mapIcsStatus(line.value) @@ -241,6 +257,8 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault else Availability.Busy "RECURRENCE-ID" -> skipAsOverride = true "ATTENDEE" -> warnings.add(IcsParseWarning.AttendeesIgnored) + "X-CALENDULA-OVERRIDE-OF" -> overrideOf = unescapeText(line.value).trim().ifEmpty { null } + "X-CALENDULA-OVERRIDE-AT" -> overrideAt = parseBasicDateTime(line.value.trim())?.toInstant(TimeZone.UTC) "X-CALENDULA-CALENDAR" -> calendarName = unescapeText(line.value).trim().ifEmpty { calendarName } // Fossify names the source calendar per event; it never writes @@ -279,6 +297,7 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault val recurrence = sanitizeRrule(rrule) if (recurrence.repaired) warnings.add(IcsParseWarning.RecurrenceRuleRepaired) val end = resolveEnd(start, dtEnd, duration) + val recurrenceDates = normalizeExDates(rDateLines, start) return ParsedIcsEvent( uid = uid, summary = summary, @@ -294,12 +313,15 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault availability = availability, calendarName = calendarName ?: category, color = eventColor ?: calendarColor, - exDates = if (recurrence.rule == null) { + exDates = if (recurrence.rule == null && recurrenceDates.isEmpty()) { emptyList() } else { normalizeExDates(exDateLines, start) }, + recurrenceDates = recurrenceDates, isTask = isTask, + overrideOf = overrideOf, + overrideAt = overrideAt, ) } @@ -334,13 +356,16 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault * still means the day it spells out; resolving it to an instant first and * reading *that* back in UTC would roll a midnight east of UTC onto the day * before and exclude an occurrence that doesn't exist. + * + * `RDATE` shares the value form and is read here too. */ private fun normalizeExDates(lines: List, start: IcsDateTime): List { if (lines.isEmpty()) return emptyList() val startZone = zoneOrNull(start.zoneId) ?: deviceZone val startTime = start.instant.toLocalDateTime(startZone).time return lines - .flatMap { line -> line.value.split(',').map { line to it.trim() } } + // An RDATE PERIOD (`start/end`) counts by its start. + .flatMap { line -> line.value.split(',').map { line to it.trim().substringBefore('/') } } .mapNotNull { (line, token) -> when { token.isEmpty() -> null diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsWriter.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsWriter.kt index 2d5ee6ba..1cf5e806 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsWriter.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsWriter.kt @@ -25,12 +25,14 @@ const val ICS_PROD_ID: String = "-//Jean-Luc Makiola//Calendula//EN" */ class IcsWriter(private val prodId: String = ICS_PROD_ID) { - fun writeCalendar(events: List, dtStamp: Instant): String { + /** [calendarName], when given, names the whole file (`X-WR-CALNAME`), as a one-calendar backup does. */ + fun writeCalendar(events: List, dtStamp: Instant, calendarName: String? = null): String { val lines = buildList { add("BEGIN:VCALENDAR") add("VERSION:2.0") add("PRODID:$prodId") add("CALSCALE:GREGORIAN") + calendarName?.takeIf { it.isNotBlank() }?.let { add("X-WR-CALNAME:${escapeText(it)}") } events.forEach { appendEvent(it, dtStamp) } add("END:VCALENDAR") } @@ -45,6 +47,7 @@ class IcsWriter(private val prodId: String = ICS_PROD_ID) { appendTimes(event) event.recurrenceRule?.takeIf { it.isNotBlank() } ?.let { add("RRULE:${it.removePrefix("RRULE:")}") } + appendRecurrenceDates(event) appendExDates(event) event.location?.takeIf { it.isNotBlank() } ?.let { add("LOCATION:${escapeText(it)}") } @@ -54,6 +57,9 @@ class IcsWriter(private val prodId: String = ICS_PROD_ID) { add("TRANSP:${transpValue(event.availability)}") event.calendarName?.takeIf { it.isNotBlank() } ?.let { add("X-CALENDULA-CALENDAR:${escapeText(it)}") } + event.overrideOf?.takeIf { it.isNotBlank() } + ?.let { add("X-CALENDULA-OVERRIDE-OF:${escapeText(it)}") } + event.overrideAt?.let { add("X-CALENDULA-OVERRIDE-AT:${it.toUtcBasic()}") } event.reminderMinutes.filter { it >= 0 }.distinct().forEach { minutes -> appendAlarm(minutes, event.summary) } @@ -66,7 +72,7 @@ class IcsWriter(private val prodId: String = ICS_PROD_ID) { add("DTEND;VALUE=DATE:${event.end.toLocalDateTime(TimeZone.UTC).date.toBasic()}") } // Recurring: anchor to wall-clock in the event's own zone. - event.recurrenceRule?.isNotBlank() == true -> { + event.recurs -> { val zone = zoneOrNull(event.zoneId) if (zone != null) { add("DTSTART;TZID=${event.zoneId}:${event.start.toLocalDateTime(zone).toBasic()}") @@ -83,6 +89,14 @@ class IcsWriter(private val prodId: String = ICS_PROD_ID) { } } + /** Extra occurrences: the same UTC stamps / `VALUE=DATE` days as [appendExDates]. */ + private fun MutableList.appendRecurrenceDates(event: IcsEvent) { + val stamps = event.recurrenceDates.filter { it.isNotBlank() }.distinct() + if (stamps.isEmpty()) return + val prefix = if (event.isAllDay) "RDATE;VALUE=DATE:" else "RDATE:" + add(prefix + stamps.joinToString(",")) + } + /** * The series' deleted occurrences. RFC 5545 ties `EXDATE`'s value type to * `DTSTART`'s, so an all-day series needs the explicit `VALUE=DATE` — without @@ -90,7 +104,7 @@ class IcsWriter(private val prodId: String = ICS_PROD_ID) { * recurring event: an exclusion names an occurrence, and a one-off has none. */ private fun MutableList.appendExDates(event: IcsEvent) { - if (event.recurrenceRule.isNullOrBlank()) return + if (!event.recurs) return val stamps = event.exDates.filter { it.isNotBlank() }.distinct() if (stamps.isEmpty()) return val prefix = if (event.isAllDay) "EXDATE;VALUE=DATE:" else "EXDATE:" diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/ParsedIcsForm.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/ParsedIcsForm.kt index 436e8ac8..de62c985 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/ParsedIcsForm.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/ParsedIcsForm.kt @@ -10,7 +10,7 @@ import kotlinx.datetime.toLocalDateTime /** * Prefill the create form from a single parsed `.ics` event (the "open one - * event" path). [calendarId] is left null so the form preselects the last-used + * event" path). [calendarId] is left null so the form preselects the default * calendar, exactly like a fresh create — the user confirms the target and * reviews everything before saving. Mirrors `EventDetail.toEditForm`'s all-day * handling (provider all-day times are UTC midnights with an exclusive end). diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/reminders/DailyDigest.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/reminders/DailyDigest.kt new file mode 100644 index 00000000..b4dd6444 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/reminders/DailyDigest.kt @@ -0,0 +1,87 @@ +package de.jeanlucmakiola.calendula.domain.reminders + +import java.time.Instant +import java.time.LocalDate +import java.time.LocalTime +import java.time.ZoneId +import java.time.ZoneOffset + +/** Which day the daily summary (#459) lists, counted from the day it arrives. */ +enum class DigestDay(val daysAhead: Long) { Today(0), Tomorrow(1) } + +/** 20:00, when the daily summary arrives until changed. */ +const val DEFAULT_DIGEST_TIME_MINUTES = 1_200 + +/** + * The daily summary's settings. Calendars in [excludedCalendarIds] are left out + * of it; [armedAtMillis] is when its switch, time or day last changed. + */ +data class DailyDigestSettings( + val enabled: Boolean = false, + val timeMinutes: Int = DEFAULT_DIGEST_TIME_MINUTES, + val day: DigestDay = DigestDay.Tomorrow, + val excludedCalendarIds: Set = emptySet(), + val armedAtMillis: Long = 0L, +) + +/** + * What one scan concluded for the summary: list [dueDay] now (null when nothing + * is owed), and wake up again at [nextAlarmMillis]. + */ +data class DigestSchedule( + val dueDay: LocalDate?, + val nextAlarmMillis: Long, +) + +/** + * When the summary is owed: a moment in `(lastFiredMillis, nowMillis]` is due. + * Only the latest such moment counts — a phone off for three evenings gets one + * summary, not three — and only while the day it lists has not passed and is + * not [lastListedDay]: each day is listed once. + */ +fun scheduleDigest( + timeMinutes: Int, + day: DigestDay, + zone: ZoneId, + lastFiredMillis: Long, + nowMillis: Long, + lastListedDay: LocalDate? = null, +): DigestSchedule { + val time = LocalTime.of(timeMinutes / 60, timeMinutes % 60) + val fireAt = { date: LocalDate -> date.atTime(time).atZone(zone).toInstant().toEpochMilli() } + val today = Instant.ofEpochMilli(nowMillis).atZone(zone).toLocalDate() + val latestDate = if (fireAt(today) <= nowMillis) today else today.minusDays(1) + val listed = latestDate.plusDays(day.daysAhead) + val dueAt = fireAt(latestDate) + val dueDay = listed.takeIf { dueAt > lastFiredMillis && !it.isBefore(today) && it != lastListedDay } + return DigestSchedule(dueDay = dueDay, nextAlarmMillis = fireAt(latestDate.plusDays(1))) +} + +/** + * The occurrences the summary for [day] lists: all-day ones covering it (their + * UTC dates), then timed ones overlapping it in [zone], each group in start + * order. Calendars in [excludedCalendarIds] are left out. + */ +fun digestEntries( + instances: List, + day: LocalDate, + zone: ZoneId, + excludedCalendarIds: Set, +): List { + val dayStart = day.atStartOfDay(zone).toInstant().toEpochMilli() + val dayEnd = day.plusDays(1).atStartOfDay(zone).toInstant().toEpochMilli() + val utcDay = day.atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli() + return instances + .asSequence() + .filter { it.calendarId !in excludedCalendarIds } + .filter { + if (it.isAllDay) { + it.beginMillis <= utcDay && maxOf(it.endMillis, it.beginMillis + 1) > utcDay + } else { + it.beginMillis < dayEnd && maxOf(it.endMillis, it.beginMillis + 1) > dayStart + } + } + .distinctBy { occurrenceKey(it.eventId, it.beginMillis) } + .sortedWith(compareBy({ !it.isAllDay }, { it.beginMillis }, { it.title })) + .toList() +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/reminders/FixedTimeReminder.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/reminders/FixedTimeReminder.kt new file mode 100644 index 00000000..86ca2940 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/reminders/FixedTimeReminder.kt @@ -0,0 +1,142 @@ +package de.jeanlucmakiola.calendula.domain.reminders + +import kotlinx.datetime.DateTimeUnit +import kotlinx.datetime.LocalDateTime +import kotlinx.datetime.LocalTime +import kotlinx.datetime.TimeZone +import kotlinx.datetime.minus +import kotlinx.datetime.toInstant +import kotlinx.datetime.toLocalDateTime +import kotlin.time.Duration.Companion.minutes +import kotlin.time.Instant + +/** + * A timed event's reminder "[daysBefore] days before, at [minuteOfDay]" (#459). + * + * The provider only knows lead times, so it is stored as an ordinary `Reminders` + * row whose offset is the distance from that wall-clock moment to the start + * ([offsetMinutes]) — it fires on every device and in every app. The pattern is + * only known to Calendula while it can be read back ([classifyTimedReminder]); the + * editor then re-derives the offset whenever the start moves. + */ +data class FixedTimeReminder(val daysBefore: Int, val minuteOfDay: Int) { + + init { + require(daysBefore in 1..MAX_DAYS_BEFORE) { "daysBefore out of range: $daysBefore" } + require(minuteOfDay in 0 until MINUTES_PER_DAY) { "minuteOfDay out of range: $minuteOfDay" } + } + + /** The wall clock this reminder names for an event starting at [start], read in [zone]. */ + private fun alarmWallClock(start: Instant, zone: TimeZone): LocalDateTime { + val day = start.toLocalDateTime(zone).date.minus(daysBefore, DateTimeUnit.DAY) + return LocalDateTime(day, LocalTime(minuteOfDay / 60, minuteOfDay % 60)) + } + + /** + * The provider offset to store for an event starting at [start]: the real + * minutes to that moment, or with [wallClock] the minutes on the clock face. + * A recurring series stores one offset for every occurrence, so it takes the + * wall-clock reading — otherwise an occurrence opened next to a DST change + * would bake that hour into all the others. + */ + fun offsetMinutes(start: Instant, zone: TimeZone, wallClock: Boolean = false): Int { + val alarm = alarmWallClock(start, zone) + return if (wallClock) { + (start.toLocalDateTime(zone).toInstant(TimeZone.UTC) - alarm.toInstant(TimeZone.UTC)).inWholeMinutes.toInt() + } else { + (start - alarm.toInstant(zone)).inWholeMinutes.toInt() + } + } + + /** The stored form, `days@minuteOfDay`. */ + fun toToken(): String = "$daysBefore$TOKEN_SEP$minuteOfDay" + + companion object { + /** Two weeks, well inside the four weeks Google Calendar takes for a reminder. */ + const val MAX_DAYS_BEFORE = 14 + private const val TOKEN_SEP = "@" + + /** [toToken] read back; null for anything malformed or out of range. */ + fun parse(token: String?): FixedTimeReminder? { + val parts = token?.trim()?.split(TOKEN_SEP) ?: return null + if (parts.size != 2) return null + val days = parts[0].toIntOrNull() ?: return null + val minute = parts[1].toIntOrNull() ?: return null + if (days !in 1..MAX_DAYS_BEFORE || minute !in 0 until MINUTES_PER_DAY) return null + return FixedTimeReminder(days, minute) + } + } +} + +/** + * The "N days before at HH:MM" a raw offset lands on for an event starting at + * [start], or null when it fires on the start's own day (or after it), or + * further back than [FixedTimeReminder.MAX_DAYS_BEFORE]. [wallClock] reads the + * offset as [FixedTimeReminder.offsetMinutes] wrote it. + */ +fun fixedTimeReminderAt( + offsetMinutes: Int, + start: Instant, + zone: TimeZone, + wallClock: Boolean = false, +): FixedTimeReminder? { + if (offsetMinutes <= 0) return null + val startLocal = start.toLocalDateTime(zone) + val alarm = if (wallClock) { + (startLocal.toInstant(TimeZone.UTC) - offsetMinutes.minutes).toLocalDateTime(TimeZone.UTC) + } else { + (start - offsetMinutes.minutes).toLocalDateTime(zone) + } + val startDate = startLocal.date + val days = startDate.toEpochDays() - alarm.date.toEpochDays() + if (days !in 1..FixedTimeReminder.MAX_DAYS_BEFORE) return null + return FixedTimeReminder(days.toInt(), alarm.hour * 60 + alarm.minute) +} + +/** A timed event's reminders, read back: plain lead times and the fixed-time ones. */ +data class TimedReminders( + val leadMinutes: List, + val fixed: List, +) + +/** + * The fixed-time reminder [offsetMinutes] stands for on an event starting at + * [start], or null when it reads as a plain lead time. The provider can't say + * which an offset was meant as, so only the patterns in [known] — the configured + * defaults, past and present, and the ones saved by hand on this device — are + * recognised: guessing from the offset's shape alone would turn ordinary leads + * ("12 hours before") into fixed-time ones. Where a lead and a known pattern + * coincide ("1 day before" on an event at the default's own time) the pattern + * wins. A wrong reading fires at the same moment; only a later change of the + * start's time of day then treats the reminder the other way. + */ +fun classifyTimedReminder( + offsetMinutes: Int, + start: Instant, + zone: TimeZone, + known: Set, + wallClock: Boolean = false, +): FixedTimeReminder? = fixedTimeReminderAt(offsetMinutes, start, zone, wallClock)?.takeIf { it in known } + +/** Sort a timed event's raw offsets into lead times and fixed-time reminders ([classifyTimedReminder]). */ +fun splitTimedReminders( + offsets: List, + start: Instant, + zone: TimeZone, + known: Set, + wallClock: Boolean = false, +): TimedReminders { + val leads = mutableListOf() + val fixed = mutableListOf() + offsets.distinct().forEach { offset -> + val pattern = classifyTimedReminder(offset, start, zone, known, wallClock) + if (pattern != null) fixed += pattern else leads += offset + } + return TimedReminders(leads.sorted(), fixed.distinct().sortedWith(FIXED_ORDER)) +} + +/** Most days before first, then by time — the order they fire in. */ +val FIXED_ORDER: Comparator = + compareByDescending { it.daysBefore }.thenBy { it.minuteOfDay } + +private const val MINUTES_PER_DAY = 1_440 diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderAlertStyle.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderAlertStyle.kt new file mode 100644 index 00000000..850efaad --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderAlertStyle.kt @@ -0,0 +1,43 @@ +package de.jeanlucmakiola.calendula.domain.reminders + +/** How a calendar's reminders get the user's attention (#171). */ +enum class ReminderAlertStyle(val storageValue: String) { + /** An ordinary notification on the calendar's channel. */ + Notification("notification"), + + /** A full-screen alert that sounds the calendar's notification sound once and stays until handled. */ + FullScreen("full_screen"), + + /** A full-screen alert that rings and vibrates like an alarm until handled. */ + FullScreenRing("full_screen_ring"), + ; + + val isFullScreen: Boolean get() = this != Notification + + companion object { + fun fromStorage(value: String): ReminderAlertStyle? = entries.firstOrNull { it.storageValue == value } + } +} + +/** [calendarId]'s alert style; a calendar without one uses plain notifications. */ +fun Map.alertStyleFor(calendarId: Long): ReminderAlertStyle = + this[calendarId] ?: ReminderAlertStyle.Notification + +/** + * Parse `id=style` entries joined by `;`. Malformed entries and unknown styles + * are dropped, so a garbled value degrades to plain notifications. + */ +fun parseAlertStyles(stored: String?): Map = + stored?.split(";").orEmpty().mapNotNull { entry -> + val parts = entry.split("=") + if (parts.size != 2) return@mapNotNull null + val calendarId = parts[0].trim().toLongOrNull() ?: return@mapNotNull null + val style = ReminderAlertStyle.fromStorage(parts[1].trim()) ?: return@mapNotNull null + calendarId to style + }.toMap() + +/** The stored form of [parseAlertStyles]; plain-notification entries are left out. */ +fun Map.toStoredAlertStyles(): String = + entries.filter { it.value != ReminderAlertStyle.Notification } + .sortedBy { it.key } + .joinToString(";") { (id, style) -> "$id=${style.storageValue}" } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderMapQuery.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderMapQuery.kt new file mode 100644 index 00000000..7438626a --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderMapQuery.kt @@ -0,0 +1,18 @@ +package de.jeanlucmakiola.calendula.domain.reminders + +// Same link shape the detail screen linkifies (ui/detail/WebLinks.kt). +private val webLinkRegex = Regex("""https?://[^\s<>"]+""", RegexOption.IGNORE_CASE) + +/** + * What a reminder's "Open in maps" button looks up for [location] — the same + * text the detail screen's location card opens in maps — or null when there is + * no place to find: blank, or nothing but web (meeting) links. + */ +fun reminderMapQuery(location: String?): String? { + val trimmed = location?.trim()?.takeIf { it.isNotEmpty() } ?: return null + return trimmed.takeIf { webLinkRegex.replace(it, "").any(Char::isLetterOrDigit) } +} + +/** The first web (meeting) link in [location], for the reminder's "Open link" button; null without one. */ +fun reminderLink(location: String?): String? = + location?.let { webLinkRegex.find(it)?.value?.trimEnd('.', ',', ';', ')', '>') } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt index d3b8bfb1..812ac5fa 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt @@ -35,6 +35,7 @@ import androidx.compose.runtime.saveable.listSaver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource import de.jeanlucmakiola.calendula.ui.common.rememberHeld import de.jeanlucmakiola.calendula.ui.common.screen import de.jeanlucmakiola.calendula.ui.common.ViewScreen @@ -52,6 +53,14 @@ import de.jeanlucmakiola.calendula.ui.calendars.CalendarsScreen import de.jeanlucmakiola.calendula.ui.common.BelowTopBarClip import de.jeanlucmakiola.calendula.ui.common.StayingPut import de.jeanlucmakiola.calendula.ui.common.CalendarDrawer +import de.jeanlucmakiola.calendula.ui.common.DrawerSync +import de.jeanlucmakiola.calendula.ui.common.SyncViewModel +import de.jeanlucmakiola.calendula.ui.common.RefreshSyncAccessOnOpen +import de.jeanlucmakiola.calendula.ui.common.rememberSyncChipOutcome +import de.jeanlucmakiola.calendula.ui.common.SyncAccessSheet +import de.jeanlucmakiola.calendula.data.calendar.SyncTargets +import de.jeanlucmakiola.calendula.ui.common.rememberSyncAccessPicker +import de.jeanlucmakiola.calendula.ui.common.messageRes import de.jeanlucmakiola.calendula.ui.common.CalendarFab import de.jeanlucmakiola.calendula.ui.common.CalendarTopBar import de.jeanlucmakiola.calendula.ui.common.ChromeHost @@ -97,6 +106,8 @@ import de.jeanlucmakiola.calendula.ui.month.MonthScreen import de.jeanlucmakiola.calendula.ui.search.SearchScreen import de.jeanlucmakiola.calendula.ui.settings.SettingsScreen import de.jeanlucmakiola.calendula.ui.week.TimelineScreen +import de.jeanlucmakiola.calendula.ui.filter.FilterViewModel +import de.jeanlucmakiola.calendula.ui.filter.ViewCalendarsPicker import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.withContext import kotlinx.coroutines.launch @@ -114,11 +125,12 @@ import kotlin.time.Instant * * The stack's bottom is the user's [CalendarHostViewModel.defaultView] home view. * A lateral switch (pill / drawer) builds a visit history so back retraces it - * (see [selectView]); a widget launch resets the stack to its own view; a date - * tap drills the day view on top. Pressing back pops one level, and the - * base-level [BackHandler] hands off to the system to exit once only the home - * view remains. So back from a widget-opened screen returns to that widget's - * view, then home; and back through pill switches walks the views in reverse. + * (see [selectView]); a widget event or header launch resets the stack to the + * widget's view; a date tap or date launch drills the day view on top. Pressing + * back pops one level, and the base-level [BackHandler] hands off to the system + * to exit once only the home view remains. Back from a widget-opened day or + * event leaves the app at once (#530), until the user navigates on from it; and + * back through pill switches walks the views in reverse. * * [requests] carries what notifications, widgets and other apps asked to * open. A tapped reminder's occurrence opens the detail overlay exactly like an @@ -171,7 +183,9 @@ fun CalendarHost( val switchTo: ((List) -> List) -> Unit = { move -> navigationVersion++ returnedFromDay = false - viewStack = move(viewStack) + val moved = move(viewStack) + requests.leaveTarget = requests.leaveTarget.afterMove(viewStack, moved) + viewStack = moved } val onSelectView: (CalendarView) -> Unit = { target -> switchTo { it.selectView(target) } } val onOpenDay: (LocalDate) -> Unit = { date -> @@ -190,12 +204,33 @@ fun CalendarHost( // Like every overlay below, it draws its last key through the slide-out // ([rememberHeld]) rather than a placeholder. var detailKey by rememberSaveable { mutableStateOf(null) } + LaunchedEffect(detailKey) { requests.leaveTarget = requests.leaveTarget.afterDetail(detailKey) } val onOpenDetail: (EventInstance) -> Unit = { event -> detailKey = event.occurrenceKey() } + // The drawer's "Hide in “” view" picker (#517). It is its own window over + // everything here, so each external request below closes it first. + var showViewCalendars by rememberSaveable { mutableStateOf(false) } + + // Back left a widget's day or event (#530): the app comes back on the home + // view. Ahead of the other requests, so one arriving with the return opens over it. + val resetToHome = requests.resetToHome + LaunchedEffect(resetToHome) { + if (resetToHome) { + navigationVersion++ + returnedFromDay = false + detailKey = null + focus.navigateTo(currentDate()) + viewStack = listOf(defaultView) + requests.leaveTarget = null + requests.resetToHome = false + } + } + // A tapped reminder notification asks for a specific occurrence. val requestedDetailKey = requests.detailKey LaunchedEffect(requestedDetailKey) { if (requestedDetailKey != null) { + showViewCalendars = false detailKey = requestedDetailKey requests.detailKey = null } @@ -211,6 +246,7 @@ fun CalendarHost( // top bar. Sits below the detail/edit overlays so tapping a result reveals // the detail on top and backing out returns to the results. var showSearch by rememberSaveable { mutableStateOf(false) } + val filterViewModel: FilterViewModel = hiltViewModel() val onOpenSearch = { showSearch = true } // Calendar manager (reached from Settings) — its own overlay so it slides @@ -316,6 +352,7 @@ fun CalendarHost( requests.importUri = null return@LaunchedEffect } + showViewCalendars = false importUri = requestedImportUri importForceMany = false importSession++ @@ -333,6 +370,7 @@ fun CalendarHost( requests.insert = null return@LaunchedEffect } + showViewCalendars = false if (importForm == null) { openImportForm(requestedInsert.form, requestedInsert.source, fromRequest = true) } else { @@ -349,6 +387,7 @@ fun CalendarHost( fun dismissCoveringOverlays(keepCreate: Boolean = false) { showSettings = false showSearch = false + showViewCalendars = false showCalendars = false showBackup = false detailKey = null @@ -383,8 +422,7 @@ fun CalendarHost( // A home-screen widget launch asks to open a date (→ day view), open an // event's detail, or start a create. Handled once and cleared, mirroring - // the detail request. Date/event opens root the stack in the widget's own - // view so backing out returns there (then home), not to the default. + // the detail request. A widget's day or event leaves the app on back (#530). val widgetNavRequest = requests.nav LaunchedEffect(widgetNavRequest) { if (widgetNavRequest != null) { @@ -393,13 +431,12 @@ fun CalendarHost( } when (val req = widgetNavRequest) { is WidgetNavRequest.OpenDate -> { - // Drill the day view in over the widget's view: drop any overlay - // that would cover it, so the open doesn't land under Settings/form. + // Drop any overlay that would cover the day, so the open doesn't + // land under Settings/form. dismissCoveringOverlays() focus.navigateTo(LocalDate.parse(req.dateIso)) - // No widget source (an external date tap) roots over the default - // home view, so backing out of the day returns home then exits. - viewStack = viewBaseStack(defaultView, req.source ?: defaultView).drillToDay() + viewStack = listOf(defaultView).drillToDay() + requests.leaveTarget = req.leaveTarget requests.nav = null } is WidgetNavRequest.OpenEvent -> { @@ -408,6 +445,7 @@ fun CalendarHost( dismissCoveringOverlays() viewStack = viewBaseStack(defaultView, req.source) detailKey = longArrayOf(req.eventId, req.beginMillis, req.endMillis) + requests.leaveTarget = req.leaveTarget requests.nav = null } is WidgetNavRequest.OpenView -> { @@ -418,6 +456,7 @@ fun CalendarHost( dismissCoveringOverlays() focus.navigateTo(currentDate()) viewStack = viewBaseStack(defaultView, req.view ?: defaultView) + requests.leaveTarget = null requests.nav = null } is WidgetNavRequest.Create -> { @@ -441,6 +480,17 @@ fun CalendarHost( val eventActions: EventActionsViewModel = hiltViewModel() val moveOutcome by reschedule.outcome.collectAsStateWithLifecycle() val selectionFailure by eventActions.failure.collectAsStateWithLifecycle() + // "Sync now" in the drawer (#240): its outcome shows in the drawer row, or in + // the move chip when it lands with the drawer closed. + val sync: SyncViewModel = hiltViewModel() + val loadedSyncTargets by sync.targets.collectAsStateWithLifecycle() + val syncTargets = loadedSyncTargets ?: SyncTargets.None + val syncInFlight by sync.inFlight.collectAsStateWithLifecycle() + val syncResult by sync.result.collectAsStateWithLifecycle() + val selectionFailureMessage = eventActionFailureMessage(selectionFailure) + val syncRowMessage = syncResult?.let { stringResource(it.messageRes()) } + val launchAccessPicker = rememberSyncAccessPicker(sync) + var showSyncAccess by rememberSaveable { mutableStateOf(false) } val onEditEvent: (EventInstance) -> Unit = { event -> editKey = event.occurrenceKey() } // A tap opens the edit form instead of the detail screen when the user chose // so (#178) — only for events whose calendar takes writes. Both are read at @@ -503,7 +553,12 @@ fun CalendarHost( val viewTransition = remember { SeekableTransitionState(view) } LaunchedEffect(view) { viewTransition.animateTo(view) } val reduceMotion = rememberReduceMotion() - val viewBackEnabled = !anyOverlayVisible && viewStack.size > 1 + val leaveOnBack = requests.leaveTarget.leaves(detailKey, anyOverlayVisible) + val viewBackEnabled = !anyOverlayVisible && viewStack.size > 1 && !leaveOnBack + // The app goes to the background and comes back on the home view. Overlays + // opened over a widget's detail register later, so their own back still wins. + // A refused move (screen pinning) falls back to the in-app back from then on. + BackHandler(enabled = leaveOnBack) { if (!requests.onLeave()) requests.leaveTarget = null } if (reduceMotion) { BackHandler(enabled = viewBackEnabled) { navigationVersion++ @@ -538,6 +593,9 @@ fun CalendarHost( val stayingPut = remember { StayingPut() } val chromeHost = remember { ChromeHost() } val drawerState = rememberDrawerState(DrawerValue.Closed) + RefreshSyncAccessOnOpen(drawerState, sync) + val syncChip = rememberSyncChipOutcome(drawerState, sync) + val syncChipMessage = syncChip.value?.let { stringResource(it.messageRes()) } val density = LocalDensity.current val topBarBottom = TopAppBarDefaults.windowInsets.getTop(density) + with(density) { TopAppBarDefaults.TopAppBarExpandedHeight.toPx() } @@ -558,6 +616,15 @@ fun CalendarHost( // (#239); nothing else in the calendar surfaces navigates here. LocalManageCalendars provides remember { { showCalendars = true } }, ) { + if (showViewCalendars) { + val filterState by filterViewModel.state.collectAsStateWithLifecycle() + ViewCalendarsPicker( + view = view, + state = filterState, + onSetHidden = { id, hidden -> filterViewModel.setHiddenIn(id, view, hidden) }, + onDismiss = { showViewCalendars = false }, + ) + } // One drawer, top bar and FAB for every screen (#184): a switch changes // what they say, from what the screen on show publishes, rather than // swapping them for another screen's. @@ -588,6 +655,21 @@ fun CalendarHost( onOpenSettings() switchScope.launch { drawerState.close() } }, + sync = remember(syncTargets, syncInFlight, syncRowMessage) { + DrawerSync( + canSync = syncTargets.reachable.isNotEmpty(), + inFlight = syncInFlight, + outcome = syncRowMessage, + needsAccess = syncTargets.needsAccess.isNotEmpty(), + // Stays open, so the row's progress and the result are seen. + onSync = { sync.requestSync() }, + onGrantAccess = { showSyncAccess = true }, + ) + }, + onHideInView = { + showViewCalendars = true + switchScope.launch { drawerState.close() } + }, ) }, ) { @@ -613,10 +695,12 @@ fun CalendarHost( // A fresh event, like a duplicate from the detail screen (#52). openImportForm(form, ImportSource.Insert) }, - chipShown = moveOutcome != null || selectionFailure != null, + chipShown = moveOutcome != null || selectionFailure != null || syncChip.value != null, onDismissChip = { reschedule.consumeOutcome() eventActions.consumeFailure() + // Only the chip on show: a receipt queued behind it still gets its turn. + if (moveOutcome == null && selectionFailure == null) syncChip.value = null }, ) CalendarFab(chromeHost, todayInToolbar, fabSelection) @@ -679,10 +763,21 @@ fun CalendarHost( EventMoveHost( reschedule, modifier = Modifier.fillMaxSize(), - actionFailure = eventActionFailureMessage(selectionFailure), - onActionFailureShown = eventActions::consumeFailure, + notice = selectionFailureMessage ?: syncChipMessage, + onNoticeShown = { + if (selectionFailureMessage != null) eventActions.consumeFailure() else syncChip.value = null + }, ) + if (showSyncAccess) { + SyncAccessSheet( + accounts = loadedSyncTargets?.needsAccess?.toList(), + onGrant = launchAccessPicker, + onDismissAccount = sync::dismissAccess, + onDismiss = { showSyncAccess = false }, + ) + } + // The delete prompt and failure chip of a selected event's actions (#141). EventSelectionHost(host = chromeHost, viewModel = eventActions) @@ -713,6 +808,8 @@ fun CalendarHost( detailKey = null }, visible = detailKey != null, + // A widget's own detail leaves the app on back, through the handler above. + backEnabled = !leaveOnBack, ) } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/ExternalRequests.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/ExternalRequests.kt index 8993e10a..dbd195ca 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/ExternalRequests.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/ExternalRequests.kt @@ -15,10 +15,15 @@ import de.jeanlucmakiola.calendula.ui.edit.ImportSource * it, so a later recomposition can't act on it twice. * * [onExternalFormClosed] runs when a form opened for [insert] closes, so the - * activity can hand control back to the app that asked. + * activity can hand control back to the app that asked. [onLeave] sends the app + * to the background when back leaves a widget's day or event ([leaveTarget]), + * false when the system refused. */ @Stable -class ExternalRequests(val onExternalFormClosed: () -> Unit = {}) { +class ExternalRequests( + val onExternalFormClosed: () -> Unit = {}, + val onLeave: () -> Boolean = { false }, +) { /** A tapped reminder notification's occurrence (eventId, begin, end), for the detail screen. */ var detailKey by mutableStateOf(null) @@ -37,6 +42,12 @@ class ExternalRequests(val onExternalFormClosed: () -> Unit = {}) { /** An external "edit this event" (ACTION_EDIT), in the detail key's shape. */ var editKey by mutableStateOf(null) + /** What back leaves the app from (#530). Cleared once the user leaves the app. */ + var leaveTarget by mutableStateOf(null) + + /** Set when the app comes back after [onLeave]: show the home view. */ + var resetToHome by mutableStateOf(false) + /** Whether these came from re-reading the launch intent on a recreation. */ var replayed = false } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/WidgetNavRequest.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/WidgetNavRequest.kt index 985806bd..9c0f54a7 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/WidgetNavRequest.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/WidgetNavRequest.kt @@ -1,27 +1,25 @@ package de.jeanlucmakiola.calendula.ui import de.jeanlucmakiola.calendula.ui.common.CalendarView +import java.io.Serializable /** * A navigation a home-screen widget asked the app to perform when launched. * Parsed from the launch intent in MainActivity and consumed once by - * [CalendarHost]. Every request carries the [source] view of the widget it came - * from (the agenda widget → [CalendarView.Agenda], the month widget → - * [CalendarView.Month]) so the in-app back stack roots itself in that view: - * backing out of the opened date/event returns to the widget's own view, not the - * default home. (Reminder notifications are not widgets — they keep the separate - * detail-key channel and leave the base view untouched.) + * [CalendarHost]. An event open carries the [OpenEvent.source] view of the + * widget it came from (the agenda widget → [CalendarView.Agenda]) as the view + * under its detail. (Reminder notifications are not widgets — they keep the + * separate detail-key channel and leave the base view untouched.) */ -sealed interface WidgetNavRequest { +sealed interface WidgetNavRequest : Serializable { /** - * Open the day view anchored on [dateIso] (an ISO `yyyy-MM-dd` date), over - * [source]. A null [source] means the request came from outside the app (a - * launcher/clock date tap, issue #9) rather than a widget, so it roots over - * the default home view instead of a widget's view. + * Open the day view anchored on [dateIso] (an ISO `yyyy-MM-dd` date), over the + * default home view. [fromWidget] makes back leave the app at once (#530); a + * launcher/clock date tap (issue #9) or the daily summary backs out to home. */ - data class OpenDate(val dateIso: String, val source: CalendarView?) : WidgetNavRequest + data class OpenDate(val dateIso: String, val fromWidget: Boolean) : WidgetNavRequest - /** Open one occurrence's detail (an agenda-widget event tap), over [source]. */ + /** Open one occurrence's detail (a widget event tap), over [source]; back leaves the app (#530). */ data class OpenEvent( val eventId: Long, val beginMillis: Long, @@ -41,3 +39,38 @@ sealed interface WidgetNavRequest { */ data class OpenView(val view: CalendarView?) : WidgetNavRequest } + +/** What back leaves the app from (#530): a widget's day, or a widget's event detail. */ +sealed interface LeaveTarget : Serializable { + /** The view a widget opened, while no overlay covers it. */ + data object View : LeaveTarget + + /** The detail of the occurrence a widget opened. */ + data class Detail(val eventId: Long, val beginMillis: Long, val endMillis: Long) : LeaveTarget { + fun matches(key: LongArray?): Boolean = + key != null && key.size == 3 && key[0] == eventId && key[1] == beginMillis && key[2] == endMillis + } +} + +/** What back leaves the app from after this request: a widget's day or event, else nothing. */ +val WidgetNavRequest.leaveTarget: LeaveTarget? + get() = when (this) { + is WidgetNavRequest.OpenDate -> LeaveTarget.View.takeIf { fromWidget } + is WidgetNavRequest.OpenEvent -> LeaveTarget.Detail(eventId, beginMillis, endMillis) + else -> null + } + +/** The target after a move from [before] to [after]: kept only while the user stays on the same views. */ +fun LeaveTarget?.afterMove(before: List, after: List): LeaveTarget? = + takeIf { before == after } + +/** The target once the detail shows [shown]: a widget's detail is dropped once it closes or changes. */ +fun LeaveTarget?.afterDetail(shown: LongArray?): LeaveTarget? = + if (this is LeaveTarget.Detail && !matches(shown)) null else this + +/** Whether back leaves the app now, given the open detail and whether any overlay is up. */ +fun LeaveTarget?.leaves(detail: LongArray?, overlayVisible: Boolean): Boolean = when (this) { + LeaveTarget.View -> !overlayVisible + is LeaveTarget.Detail -> matches(detail) + null -> false +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaRange.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaRange.kt index 645a93e3..72fc9215 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaRange.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaRange.kt @@ -1,5 +1,6 @@ package de.jeanlucmakiola.calendula.ui.agenda +import de.jeanlucmakiola.floret.locale.capitalizeStart import de.jeanlucmakiola.floret.locale.localizedDateFormatter import kotlinx.datetime.DayOfWeek import kotlinx.datetime.LocalDate @@ -118,7 +119,7 @@ fun agendaRangeWindowSummary( val startFmt = if (start.year == end.year) dayMonth else dayMonthYear "${startFmt.format(javaStart)} – ${dayMonthYear.format(javaEnd)}" } - } + }.capitalizeStart(locale) } private const val CUSTOM_PREFIX = "CUSTOM:" diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaRows.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaRows.kt index 06df9351..826ab584 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaRows.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaRows.kt @@ -46,6 +46,7 @@ import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.positionOf import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme import de.jeanlucmakiola.floret.identity.animateItemMotion +import de.jeanlucmakiola.floret.locale.capitalizeStart import de.jeanlucmakiola.floret.locale.currentLocale import de.jeanlucmakiola.floret.locale.localizedDateFormatter import kotlinx.datetime.DateTimeUnit @@ -212,7 +213,7 @@ private fun formatAgendaDate(date: LocalDate): String { val java = date.toJavaLocalDate() // Weekday + date in the locale's own field order (e.g. "Wed, Jun 17, 2026" // vs "Mi., 17. Juni 2026") rather than a hardcoded day-month-year layout. - return localizedDateFormatter(locale, "EEEdMMMy").format(java) + return localizedDateFormatter(locale, "EEEdMMMy").format(java).capitalizeStart(locale) } /** diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaViewModel.kt index 3832eaf8..da497a86 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/agenda/AgendaViewModel.kt @@ -15,6 +15,9 @@ import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.domain.FailureReason import de.jeanlucmakiola.calendula.domain.calendarListFailure +import de.jeanlucmakiola.calendula.ui.common.CalendarView +import de.jeanlucmakiola.calendula.ui.common.calendarsHiddenIn +import de.jeanlucmakiola.calendula.ui.common.instancesWithout import de.jeanlucmakiola.floret.android.stateWhileSubscribed import de.jeanlucmakiola.floret.di.IoDispatcher import kotlinx.coroutines.CoroutineDispatcher @@ -46,6 +49,8 @@ class AgendaViewModel @Inject constructor( @IoDispatcher private val io: CoroutineDispatcher, ) : ViewModel() { + private val hiddenHere = settingsPrefs.perCalendarHiddenViews.calendarsHiddenIn(CalendarView.Agenda, viewModelScope) + // The saved agenda range plus the range-bar visibility toggle. private val agendaSettings = combine( settingsPrefs.agendaScreenRange, @@ -138,7 +143,7 @@ class AgendaViewModel @Inject constructor( ) combine( repository.calendars(), - repository.instances(window), + repository.instancesWithout(window, hiddenHere), today, ) { calendars, instances, today -> buildState(params, calendars, instances, today) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt index d319ff0c..f07846e8 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt @@ -10,15 +10,16 @@ import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ContentCopy import androidx.compose.material.icons.filled.FileDownload import androidx.compose.material.icons.filled.FileUpload import androidx.compose.material.icons.filled.Schedule import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button -import androidx.compose.material3.Checkbox import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.SnackbarHost @@ -49,11 +50,13 @@ import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.data.prefs.BackupStatus import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.domain.CalendarSource -import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip +import de.jeanlucmakiola.calendula.domain.backup.BACKUP_KEEP_OPTIONS +import de.jeanlucmakiola.calendula.domain.backup.BackupSelection +import de.jeanlucmakiola.calendula.domain.backup.isBackedUpByDefault +import de.jeanlucmakiola.calendula.ui.common.CalendarCheckGroups import de.jeanlucmakiola.calendula.ui.common.CalendarFailure import de.jeanlucmakiola.calendula.ui.common.LeadingAvatar import de.jeanlucmakiola.calendula.ui.common.LocalManageCalendars -import de.jeanlucmakiola.calendula.ui.common.orUnnamed import de.jeanlucmakiola.floret.components.CollapsingScaffold import de.jeanlucmakiola.floret.components.DialogAmountField import de.jeanlucmakiola.floret.components.DialogUnitDropdown @@ -61,8 +64,9 @@ import de.jeanlucmakiola.floret.components.FullScreenPicker import de.jeanlucmakiola.floret.components.GroupedHint import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.GroupedSectionHeader +import de.jeanlucmakiola.floret.components.GroupedSwitchRow +import de.jeanlucmakiola.floret.components.OptionPicker import de.jeanlucmakiola.floret.components.Position -import de.jeanlucmakiola.floret.components.positionOf import de.jeanlucmakiola.floret.locale.relativeTimeAgo import java.time.LocalDate @@ -75,8 +79,10 @@ private val RESTORE_MIME_TYPES = arrayOf( ) /** - * Backup & restore (#69): `.ics` export and restore for local calendars, with - * optional automatic backup. Shares [CalendarsViewModel] with the manager. + * Backup & restore (#69): `.ics` export and restore, with + * optional automatic backup, and the app's settings as JSON (#481). Shares + * [CalendarsViewModel] with the manager; the settings block works whatever + * state the calendar list is in. * * A full-screen destination hoisted in `CalendarHost`; [onBack] pops it, * [onImport] hands a picked file to the app's normal .ics import flow. @@ -87,19 +93,27 @@ fun BackupScreen( onImport: (Uri) -> Unit, visible: Boolean = true, viewModel: CalendarsViewModel = hiltViewModel(), + copyViewModel: CopyEventsViewModel = hiltViewModel(), + settingsBackup: SettingsBackupViewModel = hiltViewModel(), ) { val state by viewModel.backupState.collectAsStateWithLifecycle() + val copyRun by copyViewModel.run.collectAsStateWithLifecycle() + var showCopy by rememberSaveable { mutableStateOf(false) } val backupResult by viewModel.backupResult.collectAsStateWithLifecycle() val autoBackup by viewModel.autoBackup.collectAsStateWithLifecycle() val context = LocalContext.current val snackbarHostState = remember { SnackbarHostState() } - // Exports everything eligible (null); the per-calendar selector owns its - // own launcher. + // The one-calendar shortcut; the per-calendar selector owns its own launcher. + var shortcutExportId by rememberSaveable { mutableStateOf(null) } val createBackup = rememberLauncherForActivityResult( contract = ActivityResultContracts.CreateDocument("text/calendar"), - ) { uri -> uri?.let { viewModel.exportBackup(it, null) } } + ) { uri -> + val id = shortcutExportId + if (uri != null && id != null) viewModel.exportBackup(uri, setOf(id)) + shortcutExportId = null + } var showExportPicker by rememberSaveable { mutableStateOf(false) } // Restore runs the picked file through the normal .ics import flow. @@ -112,6 +126,9 @@ fun BackupScreen( contract = ActivityResultContracts.OpenDocumentTree(), ) { uri -> uri?.let(viewModel::setAutoBackupFolder) } var showInterval by remember { mutableStateOf(false) } + var showBackupCalendars by rememberSaveable { mutableStateOf(false) } + var selectionBefore by remember { mutableStateOf(null) } + var showKeep by rememberSaveable { mutableStateOf(false) } val backupFailedText = stringResource(R.string.calendars_backup_failed) LaunchedEffect(backupResult) { @@ -132,36 +149,72 @@ fun BackupScreen( } } + val settings = rememberSettingsBackupActions(settingsBackup) + CollapsingScaffold( title = stringResource(R.string.settings_section_backup), onBack = onBack, - // Loading and failure fill the screen and centre themselves, which they - // can only do in an unscrolled column — the scrolling one measures them - // against an unbounded height and leaves them hanging under the header. - scrollable = state is BackupUiState.Ready, snackbarHost = { SnackbarHost(snackbarHostState) }, predictiveBack = true, visible = visible, ) { + // Loading and failure get a fixed-height slot in the scrolling column (it + // can't centre them in an unbounded height); the settings block below + // works in every state. when (val s = state) { - BackupUiState.Loading -> BackupLoading() - is BackupUiState.Failure -> CalendarFailure(reason = s.reason, onRetry = onBack) + BackupUiState.Loading -> { + StateSlot { BackupLoading() } + SettingsBackupSection(settings) + } + is BackupUiState.Failure -> { + StateSlot { CalendarFailure(reason = s.reason, onRetry = onBack) } + SettingsBackupSection(settings) + } is BackupUiState.Ready -> BackupContent( exportable = s.exportable, canImport = s.canImport, + canCopy = s.canCopy, + copyRun = copyRun, + onCopy = { showCopy = true }, autoBackup = autoBackup, viewModel = viewModel, onRestore = { runCatching { openBackup.launch(RESTORE_MIME_TYPES) } }, onPickFolder = { runCatching { pickFolder.launch(null) } }, - onExportAll = { + onExportOnly = { + shortcutExportId = s.exportable.singleOrNull()?.id runCatching { createBackup.launch(defaultBackupName()) } }, onExportPick = { showExportPicker = true }, onEditInterval = { showInterval = true }, + onEditCalendars = { + selectionBefore = autoBackup.selection + showBackupCalendars = true + }, + onEditKeep = { showKeep = true }, + settings = settings, ) } } + // Not gated on Ready: a running copy keeps its progress and Cancel whatever the list does. + if (showCopy) { + val calendars by copyViewModel.calendars.collectAsStateWithLifecycle() + val selection by copyViewModel.selection.collectAsStateWithLifecycle() + CopyEventsScreen( + calendars = calendars, + selection = selection, + run = copyRun, + onSelectSource = copyViewModel::setSource, + onSelectTarget = copyViewModel::setTarget, + onStart = copyViewModel::start, + onCancel = copyViewModel::cancel, + onClearFinished = copyViewModel::clearFinished, + onDismiss = { + showCopy = false + copyViewModel.clearFinished() + }, + ) + } // Gated on Ready rather than resetting the flag when the state leaves it: // flipping it here would be a write during composition. (state as? BackupUiState.Ready)?.let { ready -> @@ -172,7 +225,36 @@ fun BackupScreen( onDismiss = { showExportPicker = false }, ) } + if (showBackupCalendars) { + AutoBackupCalendarPicker( + calendars = ready.exportable, + selection = autoBackup.selection, + onCheckedChange = viewModel::setAutoBackupCalendar, + onDismiss = { + showBackupCalendars = false + viewModel.autoBackupCalendarsChosen(selectionBefore ?: autoBackup.selection) + }, + ) + } } + if (showKeep) { + OptionPicker( + title = stringResource(R.string.calendars_auto_backup_keep), + header = { + GroupedHint( + stringResource(R.string.calendars_auto_backup_keep_hint), + style = MaterialTheme.typography.bodySmall, + ) + }, + predictiveBack = true, + options = BACKUP_KEEP_OPTIONS, + selected = autoBackup.keep, + label = { backupKeepLabel(it) }, + onSelect = viewModel::setAutoBackupKeep, + onDismiss = { showKeep = false }, + ) + } + SettingsBackupDialogs(settings, settingsBackup, snackbarHostState) if (showInterval) { BackupIntervalDialog( currentMinutes = autoBackup.intervalMinutes, @@ -182,6 +264,14 @@ fun BackupScreen( } } +@Composable +private fun StateSlot(content: @Composable () -> Unit) { + Box( + modifier = Modifier.fillMaxWidth().heightIn(min = STATE_MIN_HEIGHT), + contentAlignment = Alignment.Center, + ) { content() } +} + /** The screen's loading state, centred in the scaffold's content column. */ @Composable private fun BackupLoading() { @@ -197,7 +287,7 @@ private fun BackupLoading() { private fun defaultBackupName(): String = "calendula-backup-${LocalDate.now()}.ics" /** - * The working screen: export (when there are local calendars to export), restore, + * The working screen: export (when any calendar can be backed up), restore, * and the automatic-backup block. Restore is always on screen — when nothing can * receive the events it says so and routes to the calendar manager rather than * disappearing, which is what #304 reported as an invisible button. @@ -206,13 +296,19 @@ private fun defaultBackupName(): String = "calendula-backup-${LocalDate.now()}.i private fun BackupContent( exportable: List, canImport: Boolean, + canCopy: Boolean, + copyRun: CopyRunState, + onCopy: () -> Unit, autoBackup: AutoBackupUiState, viewModel: CalendarsViewModel, onRestore: () -> Unit, onPickFolder: () -> Unit, - onExportAll: () -> Unit, + onExportOnly: () -> Unit, onExportPick: () -> Unit, onEditInterval: () -> Unit, + onEditCalendars: () -> Unit, + onEditKeep: () -> Unit, + settings: SettingsBackupActions, ) { val manageCalendars = LocalManageCalendars.current // Restore never depends on export eligibility, and never disappears: when no @@ -229,10 +325,12 @@ private fun BackupContent( GroupedHint(restoreSummary, style = MaterialTheme.typography.bodySmall) GroupedRow( title = stringResource(R.string.calendars_restore_action), - position = Position.Alone, + position = if (copyRun != CopyRunState.Idle) Position.Top else Position.Alone, leading = { LeadingAvatar(Icons.Default.FileUpload) }, onClick = onRestoreClick, ) + if (copyRun != CopyRunState.Idle) CopyEventsRow(copyRun, Position.Bottom, onCopy) + SettingsBackupSection(settings) return } @@ -242,7 +340,7 @@ private fun BackupContent( position = Position.Top, leading = { LeadingAvatar(Icons.Default.FileDownload) }, // A single exportable calendar skips the selector. - onClick = if (exportable.size == 1) onExportAll else onExportPick, + onClick = if (exportable.size == 1) onExportOnly else onExportPick, ) GroupedRow( title = stringResource(R.string.calendars_restore_action), @@ -251,6 +349,8 @@ private fun BackupContent( leading = { LeadingAvatar(Icons.Default.FileUpload) }, onClick = onRestoreClick, ) + // A running or finished copy keeps its row, the way back to its sheet. + if (canCopy || copyRun != CopyRunState.Idle) CopyEventsRow(copyRun, Position.Middle, onCopy) GroupedRow( title = stringResource(R.string.calendars_auto_backup), summary = stringResource(R.string.calendars_auto_backup_hint), @@ -271,23 +371,104 @@ private fun BackupContent( ) GroupedRow( title = stringResource(R.string.calendars_auto_backup_interval), - summary = backupIntervalLabel(autoBackup.intervalMinutes), - position = Position.Bottom, - onClick = onEditInterval, + summary = if (autoBackup.scheduled) { + backupIntervalLabel(autoBackup.intervalMinutes) + } else { + stringResource(R.string.calendars_auto_backup_interval_off) + }, + position = Position.Middle, + // Off is only offered alongside backing up after changes, or nothing would run. + trailing = if (autoBackup.onChange) { + { Switch(checked = autoBackup.scheduled, onCheckedChange = viewModel::setAutoBackupScheduled) } + } else { + null + }, + onClick = if (autoBackup.scheduled) onEditInterval else ({ viewModel.setAutoBackupScheduled(true) }), + ) + GroupedSwitchRow( + title = stringResource(R.string.calendars_auto_backup_on_change), + summary = stringResource( + if (autoBackup.scheduled) { + R.string.calendars_auto_backup_on_change_summary + } else { + R.string.calendars_auto_backup_on_change_only_summary + }, + ), + checked = autoBackup.onChange, + onCheckedChange = viewModel::setAutoBackupOnChange, + position = Position.Middle, + ) + val selectedCount = exportable.count(autoBackup.selection::selects) + GroupedRow( + title = stringResource(R.string.calendars_auto_backup_calendars), + summary = if (selectedCount == 0) { + stringResource(R.string.calendars_auto_backup_calendars_none) + } else { + pluralStringResource(R.plurals.calendars_auto_backup_calendars_count, selectedCount, selectedCount) + }, + position = Position.Middle, + onClick = onEditCalendars, + ) + GroupedSwitchRow( + title = stringResource(R.string.calendars_auto_backup_combined), + summary = stringResource( + if (autoBackup.combined) { + R.string.calendars_auto_backup_combined_on + } else { + R.string.calendars_auto_backup_combined_off + }, + ), + checked = autoBackup.combined, + onCheckedChange = viewModel::setAutoBackupCombined, + position = if (autoBackup.scheduled) Position.Middle else Position.Bottom, + ) + // Retention only applies to the dated files the interval writes. + if (autoBackup.scheduled) { + GroupedRow( + title = stringResource(R.string.calendars_auto_backup_keep), + summary = backupKeepLabel(autoBackup.keep), + position = Position.Bottom, + onClick = onEditKeep, + ) + } + GroupedHint( + if (selectedCount == 0) { + stringResource(R.string.calendars_auto_backup_nothing_selected) + } else { + backupStatusText(autoBackup.status) + }, + style = MaterialTheme.typography.bodySmall, ) - GroupedHint(backupStatusText(autoBackup.status), style = MaterialTheme.typography.bodySmall) } + SettingsBackupSection(settings) +} + +@Composable +private fun CopyEventsRow(copyRun: CopyRunState, position: Position, onClick: () -> Unit) { + GroupedRow( + title = stringResource(R.string.calendars_copy_action), + summary = when (copyRun) { + is CopyRunState.Running -> copyProgressText(copyRun) + is CopyRunState.Done -> stringResource(copyRun.titleRes) + CopyRunState.Cancelled -> stringResource(R.string.calendars_copy_cancelled) + CopyRunState.Failed -> stringResource(R.string.calendars_copy_failed) + CopyRunState.Idle -> stringResource(R.string.calendars_copy_summary) + }, + position = position, + leading = { LeadingAvatar(Icons.Default.ContentCopy) }, + onClick = onClick, + ) } /** - * Choose which local calendars to include in a one-time `.ics` export. Defaults - * to all selected; the Export action opens the SAF save dialog and hands back + * Choose which calendars to include in a one-time `.ics` export. Starts on the + * calendars a backup covers by default, or on all of them when none is; the Export action opens the SAF save dialog and hands back * the picked file with the chosen calendar ids. */ @Composable private fun ExportCalendarPicker( calendars: List, - onExport: (Uri, Set?) -> Unit, + onExport: (Uri, Set) -> Unit, onDismiss: () -> Unit, ) { // Deliberately not keyed on [calendars]: that list is observer-driven, so @@ -298,7 +479,8 @@ private fun ExportCalendarPicker( restore = { it.toSet() }, ), ) { - mutableStateOf(calendars.map { it.id }.toSet()) + val defaults = calendars.filter { it.isBackedUpByDefault }.ifEmpty { calendars } + mutableStateOf(defaults.map { it.id }.toSet()) } val createBackup = rememberLauncherForActivityResult( contract = ActivityResultContracts.CreateDocument("text/calendar"), @@ -315,29 +497,16 @@ private fun ExportCalendarPicker( predictiveBack = true, ) { GroupedHint(stringResource(R.string.calendars_export_hint), style = MaterialTheme.typography.bodySmall) - calendars.forEachIndexed { index, calendar -> - val isSelected = calendar.id in selected - GroupedRow( - title = calendar.displayName.orUnnamed(), - summary = calendar.description, - position = positionOf(index, calendars.size), - leading = { CalendarColorChip(calendar.color) }, - trailing = { - Checkbox( - checked = isSelected, - onCheckedChange = { checked -> - selected = if (checked) selected + calendar.id else selected - calendar.id - }, - ) - }, - onClick = { - selected = if (isSelected) selected - calendar.id else selected + calendar.id - }, - ) - } + CalendarCheckGroups( + calendars = calendars, + isChecked = { it.id in selected }, + onCheckedChange = { calendar, checked -> + selected = if (checked) selected + calendar.id else selected - calendar.id + }, + ) Button( onClick = { - runCatching { createBackup.launch("calendula-backup-${LocalDate.now()}.ics") } + runCatching { createBackup.launch(defaultBackupName()) } }, enabled = selected.isNotEmpty(), modifier = Modifier @@ -349,6 +518,39 @@ private fun ExportCalendarPicker( } } +/** + * Choose which calendars the automatic backup covers (#147). Each tick is saved + * at once, as a deviation from the default, so there is nothing to confirm. + */ +@Composable +private fun AutoBackupCalendarPicker( + calendars: List, + selection: BackupSelection, + onCheckedChange: (CalendarSource, Boolean) -> Unit, + onDismiss: () -> Unit, +) { + FullScreenPicker( + title = stringResource(R.string.calendars_auto_backup_calendars), + onDismiss = onDismiss, + predictiveBack = true, + ) { + GroupedHint( + stringResource(R.string.calendars_auto_backup_calendars_hint), + style = MaterialTheme.typography.bodySmall, + ) + CalendarCheckGroups( + calendars = calendars, + isChecked = selection::selects, + onCheckedChange = onCheckedChange, + ) + } +} + +/** "Only the latest" / "The latest 3". */ +@Composable +private fun backupKeepLabel(keep: Int): String = + pluralStringResource(R.plurals.calendars_auto_backup_keep_count, keep, keep) + /** Readable name of the persisted backup folder, resolved from its tree Uri. */ @Composable private fun rememberFolderName(uriString: String?): String? { @@ -433,5 +635,6 @@ private fun BackupIntervalDialog( ) } +private val STATE_MIN_HEIGHT = 360.dp private const val MINUTES_PER_DAY = 1_440L private const val MINUTES_PER_WEEK = 10_080L diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiState.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiState.kt index 3be7c6bc..55a70958 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiState.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiState.kt @@ -2,6 +2,7 @@ package de.jeanlucmakiola.calendula.ui.calendars import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.FailureReason +import de.jeanlucmakiola.calendula.domain.backup.isBackupCandidate import de.jeanlucmakiola.calendula.domain.calendarListFailure import de.jeanlucmakiola.calendula.domain.isEventTarget @@ -23,31 +24,52 @@ sealed interface BackupUiState { data class Ready( val exportable: List, val canImport: Boolean, + /** Some calendar can be copied into a different one (#325). */ + val canCopy: Boolean = false, ) : BackupUiState } /** * What the screen can offer for this calendar list. * - * Export covers the app's own local calendars; managed special-dates mirrors are - * rebuilt from contacts, so they are excluded. Restore can target anything the - * import picker offers ([isEventTarget]). + * Export can read any calendar (#147) — the local ones are only its default; + * managed special-dates mirrors are rebuilt from contacts, so they are excluded + * ([isBackupCandidate]). Restore can target anything the import picker offers + * ([isEventTarget]). * * A failure is raised only when *neither* is possible — deliberately not * [calendarListFailure] on its own, which would call an all-hidden device a - * failure while its local calendars are still perfectly exportable. When both - * halves are dead the list itself usually says why (no calendars, everything - * switched off); [FailureReason.NoImportTarget] covers the remaining case, where - * calendars exist and are visible but every one of them is read-only, managed or - * not synced to the device. + * failure while its calendars are still perfectly exportable. Since export + * reads hidden and read-only calendars too, both halves are dead only when there + * is no calendar at all, or every one is managed or not synced to the device + * ([FailureReason.NoImportTarget] unless the list itself says why). */ fun backupUiState(calendars: List): BackupUiState { - val exportable = calendars.filter { it.isLocal && it.canModifyContents && !it.isManaged } + val exportable = calendars.filter { it.isBackupCandidate } val canImport = calendars.any { it.isEventTarget } if (exportable.isEmpty() && !canImport) { return BackupUiState.Failure( calendarListFailure(calendars) ?: FailureReason.NoImportTarget, ) } - return BackupUiState.Ready(exportable = exportable, canImport = canImport) + return BackupUiState.Ready( + exportable = exportable, + canImport = canImport, + canCopy = copySources(calendars).isNotEmpty(), + ) } + +/** + * Calendars a copy can read from: any a backup can (#325), synced and read-only + * ones included, as long as some other calendar can take their events. + */ +fun copySources(calendars: List): List { + val targets = calendars.filter { it.isEventTarget } + val onlyTarget = targets.singleOrNull()?.id + if (targets.isEmpty()) return emptyList() + return calendars.filter { it.isBackupCandidate && it.id != onlyTarget } +} + +/** Calendars a copy from [sourceId] can write into: the import targets, minus the source itself. */ +fun copyTargets(calendars: List, sourceId: Long?): List = + calendars.filter { it.isEventTarget && it.id != sourceId } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsScreen.kt index 5be7aacf..9b9b6a35 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsScreen.kt @@ -3,6 +3,7 @@ package de.jeanlucmakiola.calendula.ui.calendars import android.accounts.AccountManager import android.content.Context import android.content.Intent +import android.icu.text.ListFormatter import android.provider.Settings import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.background @@ -45,6 +46,7 @@ import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable @@ -54,6 +56,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.contentDescription @@ -72,6 +75,10 @@ import de.jeanlucmakiola.calendula.domain.stateLabels import de.jeanlucmakiola.calendula.data.calendar.CalendarColorPalette import de.jeanlucmakiola.calendula.ui.common.AccountKey import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip +import de.jeanlucmakiola.calendula.ui.common.CalendarView +import de.jeanlucmakiola.calendula.ui.common.IMPLEMENTED_VIEWS +import de.jeanlucmakiola.calendula.ui.common.icon +import de.jeanlucmakiola.calendula.ui.common.label import de.jeanlucmakiola.calendula.ui.common.CalendarVisibilitySwitch import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle import de.jeanlucmakiola.calendula.ui.common.groupByAccount @@ -85,6 +92,11 @@ import de.jeanlucmakiola.calendula.ui.common.curatedSourcePackage import de.jeanlucmakiola.calendula.ui.common.orUnnamed import de.jeanlucmakiola.floret.components.CollapsingScaffold import de.jeanlucmakiola.floret.components.GroupedHint +import de.jeanlucmakiola.calendula.data.calendar.SyncAccount +import de.jeanlucmakiola.calendula.ui.common.SyncAccountRow +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LifecycleEventEffect +import de.jeanlucmakiola.floret.components.positionOf import de.jeanlucmakiola.floret.components.GroupedSectionHeader import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme import de.jeanlucmakiola.floret.identity.collapseExit @@ -92,6 +104,7 @@ import de.jeanlucmakiola.floret.identity.expandEnter import de.jeanlucmakiola.floret.identity.predictiveBack import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.InlineTextField +import de.jeanlucmakiola.floret.components.MultiOptionPicker import de.jeanlucmakiola.floret.components.Position import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.heightIn @@ -130,14 +143,21 @@ fun CalendarsScreen( val calendars by viewModel.calendars.collectAsStateWithLifecycle() val deleteLockedIds by viewModel.deleteLockedCalendarIds.collectAsStateWithLifecycle() val error by viewModel.error.collectAsStateWithLifecycle() + val syncAccessDismissed by viewModel.syncAccessDismissed.collectAsStateWithLifecycle() + LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { viewModel.refreshAccess() } + val loadedHiddenViews by viewModel.hiddenViews.collectAsStateWithLifecycle() + val hiddenViews = loadedHiddenViews.orEmpty() // null = list; NEW_CALENDAR_ID = create; any other id = edit that calendar. // [editorSession] bumps on every open so the editor's field state resets for // a fresh open while still surviving configuration changes within one open. var editorId by rememberSaveable { mutableStateOf(null) } var editorSession by rememberSaveable { mutableStateOf(0) } + // A synced calendar has no editor; tapping it opens its hidden-views picker. + var hidingId by rememberSaveable { mutableStateOf(null) } - if (editorId != null) { + // The editor and the picker seed from the stored hidden views, so both wait for the first read. + if (editorId != null && loadedHiddenViews != null) { val editing = calendars.firstOrNull { it.id == editorId } CalendarEditor( sessionKey = editorSession, @@ -145,13 +165,15 @@ fun CalendarsScreen( initialName = editing?.displayName.orEmpty(), initialColor = editing?.color ?: CalendarColorPalette.all.first(), initialDescription = editing?.description.orEmpty(), + showHiddenViews = true, + initialHiddenViews = editing?.let { hiddenViews[it.id] }.orEmpty(), deleteLocked = editing != null && editing.id in deleteLockedIds, - onSave = { name, color, description -> + onSave = { name, color, description, views -> val id = editorId if (id == null || id == NEW_CALENDAR_ID) { - viewModel.createCalendar(name, color, description) + viewModel.createCalendar(name, color, description, views) } else { - viewModel.updateCalendar(id, name, color, description) + viewModel.updateCalendar(id, name, color, description, views) } editorId = null }, @@ -165,6 +187,7 @@ fun CalendarsScreen( CalendarsList( local = calendars.filter { it.isLocal }, synced = calendars.filterNot { it.isLocal }, + hiddenViews = hiddenViews, error = error, onConsumeError = viewModel::consumeError, onOpenBackup = onOpenBackup, @@ -172,9 +195,28 @@ fun CalendarsScreen( visible = visible, onAdd = { editorSession++; editorId = NEW_CALENDAR_ID }, onEdit = { calendar -> editorSession++; editorId = calendar.id }, + onEditHiddenViews = { calendar -> hidingId = calendar.id }, onSetVisible = viewModel::setCalendarVisible, onSetAccountVisible = viewModel::setAccountVisible, + syncAccessDismissed = syncAccessDismissed, + onAskSyncAccessAgain = viewModel::askSyncAccessAgain, ) + hidingId?.let { id -> + val calendar = calendars.firstOrNull { it.id == id } + // Gone while the picker was up; an empty list is one still loading, not a deletion. + if (calendar == null && calendars.isNotEmpty()) { + LaunchedEffect(id) { hidingId = null } + } else if (calendar != null && loadedHiddenViews != null) { + key(id) { + HiddenViewsPicker( + calendarName = calendar.displayName.orUnnamed(), + hidden = hiddenViews[id].orEmpty(), + onToggle = { view, hide -> viewModel.setHiddenIn(id, view, hide) }, + onDismiss = { hidingId = null }, + ) + } + } + } } } @@ -182,6 +224,7 @@ fun CalendarsScreen( private fun CalendarsList( local: List, synced: List, + hiddenViews: Map>, error: Boolean, onConsumeError: () -> Unit, onOpenBackup: () -> Unit, @@ -189,8 +232,11 @@ private fun CalendarsList( visible: Boolean, onAdd: () -> Unit, onEdit: (CalendarSource) -> Unit, + onEditHiddenViews: (CalendarSource) -> Unit, onSetVisible: (Long, Boolean) -> Unit, onSetAccountVisible: (Collection, Boolean) -> Unit, + syncAccessDismissed: List, + onAskSyncAccessAgain: (SyncAccount) -> Unit, ) { val context = LocalContext.current val snackbarHostState = remember { SnackbarHostState() } @@ -241,6 +287,7 @@ private fun CalendarsList( local.forEachIndexed { index, calendar -> CalendarManagerRow( calendar = calendar, + hiddenViews = hiddenViews[calendar.id].orEmpty(), last = index == local.lastIndex, onSetVisible = onSetVisible, onClick = { onEdit(calendar) }, @@ -315,12 +362,28 @@ private fun CalendarsList( ordered.forEachIndexed { index, calendar -> CalendarManagerRow( calendar = calendar, + hiddenViews = hiddenViews[calendar.id].orEmpty(), last = index == ordered.lastIndex, onSetVisible = onSetVisible, + onClick = { onEditHiddenViews(calendar) }, ) } } } + + if (syncAccessDismissed.isNotEmpty()) { + Spacer(Modifier.height(16.dp)) + GroupedSectionHeader(stringResource(R.string.calendars_sync_access_header)) + GroupedHint(stringResource(R.string.calendars_sync_access_hint), style = MaterialTheme.typography.bodySmall) + syncAccessDismissed.forEachIndexed { index, account -> + SyncAccountRow( + account = account, + position = positionOf(index, syncAccessDismissed.size), + actionLabel = stringResource(R.string.calendars_sync_access_ask_again), + onAction = { onAskSyncAccessAgain(account) }, + ) + } + } } } @@ -339,19 +402,32 @@ internal fun CalendarEditor( initialName: String, initialColor: Int, initialDescription: String, - onSave: (name: String, color: Int, description: String?) -> Unit, + onSave: (name: String, color: Int, description: String?, hiddenChanges: Map) -> Unit, onDelete: () -> Unit, onClose: () -> Unit, deleteLocked: Boolean = false, + showHiddenViews: Boolean = false, + initialHiddenViews: Set = emptySet(), ) { var name by rememberSaveable(sessionKey) { mutableStateOf(initialName) } + val seededHiddenViews = rememberSaveable(sessionKey) { initialHiddenViews } + var hiddenViews by rememberSaveable(sessionKey) { mutableStateOf(initialHiddenViews) } + var pickHiddenViews by rememberSaveable(sessionKey) { mutableStateOf(false) } var color by rememberSaveable(sessionKey) { mutableStateOf(initialColor) } var description by rememberSaveable(sessionKey) { mutableStateOf(initialDescription) } var confirmDelete by remember { mutableStateOf(false) } val focusRequester = remember { FocusRequester() } val valid = name.isNotBlank() - val commit = { if (valid) onSave(name.trim(), color, description.trim().ifEmpty { null }) } + val commit = { + if (valid) { + // Only the views toggled here are written, so a save never resets ones it didn't load. + val changes = IMPLEMENTED_VIEWS + .filter { (it in hiddenViews) != (it in seededHiddenViews) } + .associateWith { it in hiddenViews } + onSave(name.trim(), color, description.trim().ifEmpty { null }, changes) + } + } FullScreenPicker( title = stringResource( @@ -403,6 +479,16 @@ internal fun CalendarEditor( } } + if (showHiddenViews) { + Spacer(Modifier.height(20.dp)) + GroupedRow( + title = stringResource(R.string.calendars_hide_in_views), + summary = hiddenViewsSummary(hiddenViews), + position = Position.Alone, + onClick = { pickHiddenViews = true }, + ) + } + if (!isNew && !deleteLocked) { Spacer(Modifier.height(24.dp)) DeleteCalendarRow(onClick = { confirmDelete = true }) @@ -410,6 +496,17 @@ internal fun CalendarEditor( Spacer(Modifier.height(24.dp)) } + if (pickHiddenViews) { + HiddenViewsPicker( + calendarName = name.trim().orUnnamed(), + hidden = hiddenViews, + onToggle = { view, hide -> + hiddenViews = if (hide) hiddenViews + view else hiddenViews - view + }, + onDismiss = { pickHiddenViews = false }, + ) + } + if (confirmDelete) { AlertDialog( onDismissRequest = { confirmDelete = false }, @@ -636,7 +733,7 @@ private fun EditorSectionLabel(text: String) { * plain writable one (#76), then its own description. */ @Composable -private fun calendarRowSummary(calendar: CalendarSource): String? { +private fun calendarRowSummary(calendar: CalendarSource, hiddenViews: Set): String? { val states = calendar.stateLabels().map { label -> stringResource( when (label) { @@ -646,7 +743,8 @@ private fun calendarRowSummary(calendar: CalendarSource): String? { }, ) } - val parts = states + listOfNotNull(calendar.description?.takeIf { it.isNotBlank() }) + val hidden = if (hiddenViews.isEmpty()) null else hiddenViewsSummary(hiddenViews) + val parts = states + listOfNotNull(hidden, calendar.description?.takeIf { it.isNotBlank() }) return parts.joinToString(" · ").ifEmpty { null } } @@ -662,6 +760,7 @@ private fun calendarRowSummary(calendar: CalendarSource): String? { @Composable private fun CalendarManagerRow( calendar: CalendarSource, + hiddenViews: Set, last: Boolean, onSetVisible: (Long, Boolean) -> Unit, onClick: (() -> Unit)? = null, @@ -669,7 +768,7 @@ private fun CalendarManagerRow( val disabled = !calendar.isVisibleInSystem || calendar.isNotSynced GroupedRow( title = calendar.displayName.orUnnamed(), - summary = calendarRowSummary(calendar), + summary = calendarRowSummary(calendar, hiddenViews), position = if (last) Position.Bottom else Position.Middle, container = MaterialTheme.colorScheme.surfaceContainerHighest, dimmed = disabled, @@ -689,6 +788,51 @@ private fun CalendarManagerRow( ) } +/** + * Which views one calendar stays out of (#270); display only, so reminders and + * search keep the calendar. [onToggle] decides when a toggle lands: at once for + * a synced calendar, on Save inside the local editor. + */ +@Composable +private fun HiddenViewsPicker( + calendarName: String, + hidden: Set, + onToggle: (CalendarView, Boolean) -> Unit, + onDismiss: () -> Unit, +) { + // Seeded once and then ahead of the store: the picker is the only writer while + // it is open, so following each write back would only flicker a quick second tap. + var shown by remember { mutableStateOf(hidden) } + MultiOptionPicker( + title = stringResource(R.string.calendars_hide_in_views), + options = IMPLEMENTED_VIEWS, + selected = shown, + label = { it.label() }, + onToggle = { view, hide -> + shown = if (hide) shown + view else shown - view + onToggle(view, hide) + }, + onDismiss = onDismiss, + leading = { Icon(it.icon, contentDescription = null) }, + header = { + GroupedHint( + stringResource(R.string.calendars_hide_in_views_hint, calendarName), + verticalPadding = 8.dp, + ) + }, + predictiveBack = true, + ) +} + +/** "Shown in every view", or the views [hidden] names, in the app's view order. */ +@Composable +private fun hiddenViewsSummary(hidden: Set): String { + if (hidden.isEmpty()) return stringResource(R.string.calendars_hide_in_views_none) + val names = IMPLEMENTED_VIEWS.filter { it in hidden }.map { it.label() } + val locale = LocalConfiguration.current.locales[0] + return stringResource(R.string.calendars_hidden_in, ListFormatter.getInstance(locale).format(names)) +} + /** Fade a leading element to the M3 disabled emphasis when [disabled]. */ private fun dimIf(disabled: Boolean): Modifier = if (disabled) Modifier.alpha(0.38f) else Modifier diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt index 861f4525..2e81d0c9 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt @@ -3,21 +3,29 @@ package de.jeanlucmakiola.calendula.ui.calendars import android.content.Context import android.content.Intent import android.net.Uri +import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext import de.jeanlucmakiola.calendula.data.backup.BackupScheduler import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository +import de.jeanlucmakiola.calendula.data.calendar.SyncAccount import de.jeanlucmakiola.calendula.data.ics.IcsExporter import de.jeanlucmakiola.calendula.data.prefs.BackupStatus import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.FailureReason +import de.jeanlucmakiola.calendula.domain.backup.BackupSelection +import de.jeanlucmakiola.calendula.domain.backup.DEFAULT_BACKUP_KEEP import de.jeanlucmakiola.calendula.domain.ics.IcsWriter +import de.jeanlucmakiola.calendula.ui.common.CalendarView +import de.jeanlucmakiola.calendula.ui.common.hidingNothingOnError import de.jeanlucmakiola.floret.android.stateWhileSubscribed import de.jeanlucmakiola.floret.di.IoDispatcher import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Job +import kotlinx.coroutines.joinAll import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow @@ -56,6 +64,23 @@ class CalendarsViewModel @Inject constructor( initialValue = emptyList(), ) + /** + * Accounts the drawer was told not to ask sync-request access for (#240), + * limited to those still behind a visible calendar and still unreachable. + */ + val syncAccessDismissed: StateFlow> = + repository.syncTargets + .map { it.dismissed.toList() } + .catch { emit(emptyList()) } + .stateWhileSubscribed(scope = viewModelScope, initialValue = emptyList()) + + /** Re-read account access, which can change outside the app; called on resume. */ + fun refreshAccess() = repository.refreshSyncAccess() + + fun askSyncAccessAgain(account: SyncAccount) { + viewModelScope.launch { repository.setSyncAccessDismissed(account, dismissed = false) } + } + /** * The Backup & restore screen's own view of that list, with the loading and * failure states [calendars] flattens away — it starts empty and catches to @@ -73,12 +98,20 @@ class CalendarsViewModel @Inject constructor( /** Automatic-backup settings + last-run status, for the Backup section UI. */ val autoBackup: StateFlow = combine( - settingsPrefs.autoBackupEnabled, - settingsPrefs.autoBackupIntervalMinutes, - settingsPrefs.autoBackupFolderUri, - settingsPrefs.autoBackupStatus, - ) { enabled, interval, folder, status -> - AutoBackupUiState(enabled, interval, folder, status) + combine( + settingsPrefs.autoBackupEnabled, + settingsPrefs.autoBackupIntervalMinutes, + settingsPrefs.autoBackupFolderUri, + settingsPrefs.autoBackupStatus, + ) { enabled, interval, folder, status -> + AutoBackupUiState(enabled, interval, folder, status) + }, + settingsPrefs.autoBackupSelection, + settingsPrefs.autoBackupCombined, + settingsPrefs.autoBackupKeep, + settingsPrefs.autoBackupOnChangeAndScheduled, + ) { base, selection, combined, keep, (onChange, scheduled) -> + base.copy(selection = selection, combined = combined, keep = keep, onChange = onChange, scheduled = scheduled) } .flowOn(io) .stateWhileSubscribed( @@ -104,6 +137,19 @@ class CalendarsViewModel @Inject constructor( initialValue = emptySet(), ) + /** The views each calendar is hidden in (#270); null until first read. */ + val hiddenViews: StateFlow>?> = + settingsPrefs.perCalendarHiddenViews + .hidingNothingOnError() + .stateWhileSubscribed( + scope = viewModelScope, + initialValue = null, + ) + + fun setHiddenIn(id: Long, view: CalendarView, hidden: Boolean) = write { + settingsPrefs.setCalendarHiddenIn(id, view, hidden) + } + private val _error = MutableStateFlow(false) val error: StateFlow = _error.asStateFlow() @@ -115,18 +161,22 @@ class CalendarsViewModel @Inject constructor( fun consumeBackupResult() { _backupResult.value = null } /** - * Serialise every event of the writable local calendars into the chosen SAF - * document [uri] as one `VCALENDAR`. Result (event count, or failure) lands + * Serialise every event of [calendarIds] into the chosen SAF document [uri] + * as one `VCALENDAR`. Result (event count, or failure) lands * in [backupResult] for a one-shot message. */ - fun exportBackup(uri: Uri, calendarIds: Set? = null) { + fun exportBackup(uri: Uri, calendarIds: Set) { viewModelScope.launch { _backupResult.value = try { val count = withContext(io) { val events = repository.exportEvents(calendarIds) + // A one-calendar file is named after it, as the automatic backup's are. + val name = calendarIds.singleOrNull()?.let { id -> + repository.calendars().first().firstOrNull { it.id == id }?.displayName + } icsExporter.writeDocument( uri = uri, - content = IcsWriter().writeCalendar(events, Clock.System.now()), + content = IcsWriter().writeCalendar(events, Clock.System.now(), name), ) events.size } @@ -139,16 +189,41 @@ class CalendarsViewModel @Inject constructor( } } - fun createCalendar(displayName: String, color: Int, description: String?) = write { - repository.createLocalCalendar(displayName, color, description) + fun createCalendar( + displayName: String, + color: Int, + description: String?, + hiddenChanges: Map, + ) = write { + val id = repository.createLocalCalendar(displayName, color, description) + settingsPrefs.applyCalendarHiddenChanges(id, hiddenChanges) } - fun updateCalendar(id: Long, displayName: String, color: Int, description: String?) = write { + fun updateCalendar( + id: Long, + displayName: String, + color: Int, + description: String?, + hiddenChanges: Map, + ) = write { repository.updateCalendar(id, displayName, color, description) + settingsPrefs.applyCalendarHiddenChanges(id, hiddenChanges) } fun deleteCalendar(id: Long) = write { repository.deleteCalendar(id) + // Tidy-up only: the delete already landed, so a failure here isn't its failure. + bestEffort { settingsPrefs.clearCalendarHiddenViews(id) } + } + + private suspend fun bestEffort(block: suspend () -> Unit) { + try { + block() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w("CalendarsViewModel", "Hidden-views write failed", e) + } } /** @@ -204,13 +279,71 @@ class CalendarsViewModel @Inject constructor( } } + /** Selection writes since the calendar picker opened; the run after it waits for them. */ + private val selectionWrites = mutableListOf() + + fun setAutoBackupCalendar(calendar: CalendarSource, included: Boolean) { + selectionWrites += viewModelScope.launch { settingsPrefs.setAutoBackupCalendar(calendar, included) } + } + + fun setAutoBackupCombined(combined: Boolean) { + viewModelScope.launch { + if (settingsPrefs.autoBackupCombined.first() == combined) return@launch + settingsPrefs.setAutoBackupCombined(combined) + runBackupIfActive() + } + } + + fun setAutoBackupOnChange(enabled: Boolean) { + viewModelScope.launch { + val switched = settingsPrefs.setAutoBackupOnChange(enabled) + reschedule() + if (switched) runBackupIfActive() + } + } + + /** + * Switching the interval backs up right away: back on, rather than an + * interval later; off, so a series only its dated files covered shows up. + */ + fun setAutoBackupScheduled(enabled: Boolean) { + viewModelScope.launch { + val switched = settingsPrefs.setAutoBackupScheduled(enabled) + reschedule() + if (switched) runBackupIfActive() + } + } + + fun setAutoBackupKeep(keep: Int) { + viewModelScope.launch { + if (settingsPrefs.autoBackupKeep.first() == keep) return@launch + settingsPrefs.setAutoBackupKeep(keep) + runBackupIfActive() + } + } + + /** + * After the calendar choice is closed, back up what is now selected rather + * than at the next interval — only if it changed, since every run rotates + * an older backup out. + */ + fun autoBackupCalendarsChosen(before: BackupSelection) { + val pending = selectionWrites.toList() + selectionWrites.clear() + viewModelScope.launch { + pending.joinAll() + if (settingsPrefs.autoBackupSelection.first() != before) runBackupIfActive() + } + } + + private suspend fun runBackupIfActive() { + if (settingsPrefs.autoBackupEnabled.first() && settingsPrefs.autoBackupFolderUri.first() != null) { + BackupScheduler.runNow(context) + } + } + private suspend fun reschedule() { - BackupScheduler.apply( - context = context, - enabled = settingsPrefs.autoBackupEnabled.first(), - intervalMinutes = settingsPrefs.autoBackupIntervalMinutes.first(), - hasFolder = settingsPrefs.autoBackupFolderUri.first() != null, - ) + BackupScheduler.reconcile(context, settingsPrefs) } private inline fun write(crossinline block: suspend () -> Unit) { @@ -232,6 +365,11 @@ data class AutoBackupUiState( val intervalMinutes: Long = SettingsPrefs.DEFAULT_BACKUP_INTERVAL, val folderUri: String? = null, val status: BackupStatus = BackupStatus(lastRun = 0L, lastSuccess = true, consecutiveFailures = 0), + val selection: BackupSelection = BackupSelection(), + val combined: Boolean = false, + val keep: Int = DEFAULT_BACKUP_KEEP, + val onChange: Boolean = false, + val scheduled: Boolean = true, ) /** Outcome of a whole-calendar backup, surfaced once to the screen. */ diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsScreen.kt new file mode 100644 index 00000000..546059ca --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsScreen.kt @@ -0,0 +1,386 @@ +package de.jeanlucmakiola.calendula.ui.calendars + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.outlined.Info +import androidx.compose.material.icons.rounded.ArrowDownward +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi +import androidx.compose.material3.Icon +import androidx.compose.material3.LinearWavyProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.TextButton +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.domain.FailureReason +import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip +import de.jeanlucmakiola.calendula.ui.common.CalendarFailure +import de.jeanlucmakiola.calendula.ui.common.CalendarPickerGroups +import de.jeanlucmakiola.calendula.ui.common.ImportSummaryStats +import de.jeanlucmakiola.calendula.ui.common.ResultBadge +import de.jeanlucmakiola.calendula.ui.common.ResultMessage +import de.jeanlucmakiola.calendula.ui.common.importSummaryNotes +import de.jeanlucmakiola.floret.components.OnboardingPrimaryButton +import de.jeanlucmakiola.floret.components.ResultBadge as FloretResultBadge +import de.jeanlucmakiola.calendula.ui.common.orUnnamed +import de.jeanlucmakiola.floret.components.FullScreenPicker +import de.jeanlucmakiola.floret.components.GroupedHint +import de.jeanlucmakiola.floret.components.GroupedListInset +import de.jeanlucmakiola.floret.components.IconInfoCard + +/** + * Copy every event of one calendar into another (#325), in the import flow's + * steps: pick the source, pick the target and copy, watch it run, see the result. + * The run lives in [CopyEventsViewModel], so the screen can be closed and + * reopened mid-copy. + */ +@Composable +fun CopyEventsScreen( + calendars: CopyCalendars, + selection: CopySelection, + run: CopyRunState, + onSelectSource: (Long) -> Unit, + onSelectTarget: (Long) -> Unit, + onStart: () -> Unit, + onCancel: () -> Unit, + onClearFinished: () -> Unit, + onDismiss: () -> Unit, +) { + val list = (calendars as? CopyCalendars.Ready)?.calendars.orEmpty() + val sources = remember(list) { copySources(list) } + val source = sources.firstOrNull { it.id == selection.sourceId } + val targets = remember(list, source?.id) { copyTargets(list, source?.id) } + val target = targets.firstOrNull { it.id == selection.targetId } + var step by rememberSaveable { mutableStateOf(CopyStep.Source) } + val idle = run == CopyRunState.Idle + // The run's ends, held once seen so a calendar gone or a list reloading mid-run doesn't blank them. + val runSource = rememberLastSeen(selection.sourceId, list) + val runTarget = rememberLastSeen(selection.targetId, list) + // A source that stopped qualifying sends the target step back to the start. + // Keyed on the chosen id too: right after a pick the selection may not have arrived yet. + LaunchedEffect(step, selection.sourceId, source, calendars) { + val gone = selection.sourceId != null && source == null && calendars is CopyCalendars.Ready + if (step == CopyStep.Target && gone) step = CopyStep.Source + } + + FullScreenPicker( + title = stringResource( + when { + !idle -> R.string.calendars_copy_action + step == CopyStep.Source -> R.string.calendars_copy_from_title + else -> R.string.calendars_copy_to_title + }, + ), + onDismiss = { if (idle && step == CopyStep.Target) step = CopyStep.Source else onDismiss() }, + // The target step's back only steps back, so it mustn't preview closing the screen. + predictiveBack = !(idle && step == CopyStep.Target), + scrollable = idle, + actions = { + if (idle && step == CopyStep.Target) { + Button( + onClick = onStart, + enabled = source != null && target != null, + modifier = Modifier.padding(end = 12.dp), + ) { + Text(stringResource(R.string.calendars_copy_start)) + } + } + }, + ) { + if (!idle) { + val copyMore = { + onClearFinished() + step = CopyStep.Source + } + CopyRun( + run = run, + source = runSource, + target = runTarget, + onCancel = onCancel, + // A retry only where the picker would still offer both ends; otherwise pick again. + onRetry = if (source != null && target != null) onStart else copyMore, + onCopyMore = copyMore, + onClose = onDismiss, + ) + return@FullScreenPicker + } + when (calendars) { + CopyCalendars.Loading -> { + Box(Modifier.fillMaxWidth().padding(32.dp), contentAlignment = Alignment.Center) { + CircularProgressIndicator() + } + return@FullScreenPicker + } + CopyCalendars.Failure -> { + CalendarFailure(reason = FailureReason.ProviderUnavailable, onRetry = onDismiss) + return@FullScreenPicker + } + is CopyCalendars.Ready -> Unit + } + if (sources.isEmpty()) { + GroupedHint(stringResource(R.string.calendars_copy_none)) + return@FullScreenPicker + } + when (step) { + CopyStep.Source -> { + IconInfoCard( + icon = Icons.Outlined.Info, + iconContentDescription = null, + modifier = Modifier.padding(horizontal = GroupedListInset), + ) { + Text(stringResource(R.string.calendars_copy_hint), style = MaterialTheme.typography.bodyMedium) + } + Spacer(Modifier.height(16.dp)) + CalendarPickerGroups( + calendars = sources, + selectedId = source?.id, + onSelect = { + onSelectSource(it) + step = CopyStep.Target + }, + ) + } + CopyStep.Target -> { + CopyRouteCard(source, target, Modifier.padding(horizontal = GroupedListInset)) + Spacer(Modifier.height(16.dp)) + CalendarPickerGroups( + calendars = targets, + selectedId = target?.id, + onSelect = onSelectTarget, + ) + } + } + } +} + +private enum class CopyStep { Source, Target } + +/** Progress while the copy runs, then its outcome; both under the route it took. */ +@Composable +private fun ColumnScope.CopyRun( + run: CopyRunState, + source: CalendarSource?, + target: CalendarSource?, + onCancel: () -> Unit, + onRetry: () -> Unit, + onCopyMore: () -> Unit, + onClose: () -> Unit, +) { + // Centred where it fits, scrolling where it doesn't (landscape, large fonts). + BoxWithConstraints(Modifier.fillMaxWidth().weight(1f)) { + Column( + Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .heightIn(min = maxHeight) + .padding(horizontal = GroupedListInset) + .padding(top = 8.dp, bottom = 24.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.SpaceBetween, + ) { + CopyRouteCard(source, target, pickable = false) + Column(Modifier.fillMaxWidth().padding(vertical = 24.dp), horizontalAlignment = Alignment.CenterHorizontally) { + when (run) { + is CopyRunState.Running -> CopyProgress(run) + is CopyRunState.Done -> CopyDone(run) + CopyRunState.Cancelled -> { + FloretResultBadge( + Icons.Default.Close, + MaterialTheme.colorScheme.secondaryContainer, + MaterialTheme.colorScheme.onSecondaryContainer, + ) + ResultMessage(stringResource(R.string.calendars_copy_cancelled)) + } + CopyRunState.Failed -> { + ResultBadge(error = true) + ResultMessage(stringResource(R.string.calendars_copy_failed)) + } + CopyRunState.Idle -> Unit + } + } + when (run) { + is CopyRunState.Running -> TextButton(onClick = onCancel, modifier = Modifier.fillMaxWidth()) { + Text(stringResource(R.string.dialog_cancel)) + } + is CopyRunState.Done -> CopyEndButtons( + primary = stringResource(R.string.import_close), + onPrimary = onClose, + secondary = stringResource(R.string.calendars_copy_more), + onSecondary = onCopyMore, + ) + CopyRunState.Cancelled, CopyRunState.Failed -> CopyEndButtons( + primary = stringResource(R.string.state_retry), + onPrimary = onRetry, + secondary = stringResource(R.string.import_close), + onSecondary = onClose, + ) + CopyRunState.Idle -> Unit + } + } + } +} + +/** The calendar with [id] in [list], or the last one seen under that id while it is missing. */ +@Composable +private fun rememberLastSeen(id: Long?, list: List): CalendarSource? { + val held = remember(id) { mutableStateOf(null) } + list.firstOrNull { it.id == id }?.let { held.value = it } + return held.value +} + +@OptIn(ExperimentalMaterial3ExpressiveApi::class) +@Composable +private fun CopyProgress(run: CopyRunState.Running) { + val total = run.total + if (total == null || total == 0) { + LinearWavyProgressIndicator(modifier = Modifier.fillMaxWidth()) + } else { + LinearWavyProgressIndicator(progress = { run.done.toFloat() / total }, modifier = Modifier.fillMaxWidth()) + } + Spacer(Modifier.height(16.dp)) + Text( + text = copyProgressText(run), + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) +} + +/** "Reading events…" until the source is read, then "120 of 2,400 events". */ +@Composable +fun copyProgressText(run: CopyRunState.Running): String { + val total = run.total ?: return stringResource(R.string.calendars_copy_reading) + return pluralStringResource(R.plurals.calendars_copy_progress, total, run.done, total) +} + +@Composable +private fun CopyDone(run: CopyRunState.Done) { + val summary = run.summary + // As on the import: only a run the target cut short reads as an error. + ResultBadge(error = run.stopped) + ResultMessage( + title = stringResource(run.titleRes), + notes = importSummaryNotes( + summary, + stoppedNote = if (run.stopped) { + pluralStringResource(R.plurals.calendars_copy_stopped, summary.notAttempted, summary.notAttempted) + } else { + null + }, + ), + ) + Spacer(Modifier.height(24.dp)) + ImportSummaryStats(summary) +} + +/** The way on ([secondary], e.g. Copy more) above the way out (Close). */ +@Composable +private fun CopyEndButtons(primary: String, onPrimary: () -> Unit, secondary: String, onSecondary: () -> Unit) { + Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) { + OnboardingPrimaryButton(text = primary, onClick = onPrimary) + TextButton(onClick = onSecondary, modifier = Modifier.fillMaxWidth()) { Text(secondary) } + } +} + +/** + * Where the events come from and go to, with an arrow between. A missing end + * reads "Choose a calendar" while [pickable], or as unnamed on the run screens. + */ +@Composable +private fun CopyRouteCard( + source: CalendarSource?, + target: CalendarSource?, + modifier: Modifier = Modifier, + pickable: Boolean = true, +) { + Surface( + modifier = modifier.fillMaxWidth(), + shape = RoundedCornerShape(24.dp), + color = MaterialTheme.colorScheme.surfaceContainerHigh, + ) { + Column(Modifier.padding(16.dp)) { + CopyRouteEnd(stringResource(R.string.calendars_copy_from), source, pickable) + Box(Modifier.width(40.dp).padding(vertical = 4.dp), contentAlignment = Alignment.Center) { + Surface(shape = CircleShape, color = MaterialTheme.colorScheme.primaryContainer) { + Icon( + Icons.Rounded.ArrowDownward, + contentDescription = null, + tint = MaterialTheme.colorScheme.onPrimaryContainer, + modifier = Modifier.padding(6.dp).size(20.dp), + ) + } + } + CopyRouteEnd(stringResource(R.string.calendars_copy_to), target, pickable) + } + } +} + +@Composable +private fun CopyRouteEnd(label: String, calendar: CalendarSource?, pickable: Boolean) { + Row(verticalAlignment = Alignment.CenterVertically) { + if (calendar != null) { + CalendarColorChip(calendar.color) + } else { + Surface( + modifier = Modifier.size(40.dp), + shape = CircleShape, + color = MaterialTheme.colorScheme.surfaceContainerHigh, + border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant), + ) {} + } + Spacer(Modifier.width(16.dp)) + Column { + Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text( + calendar?.displayName?.orUnnamed() + ?: if (pickable) stringResource(R.string.calendars_copy_choose) else "".orUnnamed(), + style = MaterialTheme.typography.titleMedium, + color = if (calendar != null) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (calendar != null) { + Text( + if (calendar.isLocal) stringResource(R.string.calendars_local_header) else calendar.accountName, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt new file mode 100644 index 00000000..d94fe9c4 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt @@ -0,0 +1,150 @@ +package de.jeanlucmakiola.calendula.ui.calendars + +import android.util.Log +import androidx.annotation.StringRes +import androidx.lifecycle.SavedStateHandle +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import dagger.hilt.android.lifecycle.HiltViewModel +import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository +import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary +import de.jeanlucmakiola.floret.android.stateWhileSubscribed +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.catch +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.launch +import kotlin.coroutines.cancellation.CancellationException +import javax.inject.Inject + +/** + * Copy events from one calendar into another (#325). Scoped to the activity, so + * a copy keeps running across rotation and while the Backup screen is closed; + * finishing the activity or losing the process stops it like [cancel] does, + * and a re-run picks up where it ended. + */ +@HiltViewModel +class CopyEventsViewModel @Inject constructor( + private val repository: CalendarRepository, + private val savedState: SavedStateHandle, +) : ViewModel() { + + val calendars: StateFlow = + repository.calendars() + .map, CopyCalendars> { CopyCalendars.Ready(it) } + .catch { emit(CopyCalendars.Failure) } + .stateWhileSubscribed(scope = viewModelScope, initialValue = CopyCalendars.Loading) + + val selection: StateFlow = combine( + savedState.getStateFlow(KEY_SOURCE, null), + savedState.getStateFlow(KEY_TARGET, null), + ) { source, target -> CopySelection(source, target) } + .stateIn(viewModelScope, SharingStarted.Eagerly, CopySelection()) + + private val _run = MutableStateFlow(CopyRunState.Idle) + val run: StateFlow = _run.asStateFlow() + + private var job: Job? = null + + private val busy: Boolean get() = job?.isCompleted == false + + private fun current() = CopySelection(savedState[KEY_SOURCE], savedState[KEY_TARGET]) + + private fun select(selection: CopySelection) { + savedState[KEY_SOURCE] = selection.sourceId + savedState[KEY_TARGET] = selection.targetId + } + + fun setSource(id: Long) { + if (busy) return + select(current().withSource(id)) + clearFinished() + } + + fun setTarget(id: Long) { + if (busy) return + select(current().copy(targetId = id)) + clearFinished() + } + + fun start() { + val source = current().sourceId ?: return + val target = current().targetId ?: return + if (busy) return + _run.value = CopyRunState.Running(done = 0, total = null) + job = viewModelScope.launch { + try { + val summary = repository.copyEvents(source, target) { done, total -> + if (done == 0 || done == total || done % (total / 200).coerceAtLeast(1) == 0) { + _run.value = CopyRunState.Running(done, total) + } + } + _run.value = CopyRunState.Done(summary) + } catch (e: CancellationException) { + _run.value = CopyRunState.Cancelled + throw e + } catch (e: Exception) { + Log.w(TAG, "Copy events failed", e) + _run.value = CopyRunState.Failed + } + } + } + + fun cancel() { + job?.cancel() + } + + /** Back to idle once a finished run's outcome has been seen. */ + fun clearFinished() { + if (!busy) _run.value = CopyRunState.Idle + } + + private companion object { + const val KEY_SOURCE = "copy_source" + const val KEY_TARGET = "copy_target" + const val TAG = "CopyEvents" + } +} + +/** The calendars a copy runs between. */ +data class CopySelection(val sourceId: Long? = null, val targetId: Long? = null) { + /** A target equal to the new source is dropped: a calendar is never copied into itself. */ + fun withSource(id: Long): CopySelection = + CopySelection(sourceId = id, targetId = targetId?.takeIf { it != id }) +} + +/** The calendar list the copy screen picks from. */ +sealed interface CopyCalendars { + data object Loading : CopyCalendars + data object Failure : CopyCalendars + data class Ready(val calendars: List) : CopyCalendars +} + +sealed interface CopyRunState { + data object Idle : CopyRunState + + /** [total] is null while the source calendar is still being read. */ + data class Running(val done: Int, val total: Int?) : CopyRunState + + data class Done(val summary: IcsImportSummary) : CopyRunState { + /** The target stopped taking events part way, so some were never tried. */ + val stopped: Boolean get() = summary.notAttempted > 0 + + /** How the run ended, the same words on the row and on the result screen. */ + @get:StringRes + val titleRes: Int get() = when { + stopped -> R.string.calendars_copy_stopped_title + summary.failed > 0 -> R.string.calendars_copy_partial + else -> R.string.calendars_copy_done + } + } + data object Cancelled : CopyRunState + data object Failed : CopyRunState +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/SettingsBackupSection.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/SettingsBackupSection.kt new file mode 100644 index 00000000..be4ffa1a --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/SettingsBackupSection.kt @@ -0,0 +1,224 @@ +package de.jeanlucmakiola.calendula.ui.calendars + +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.FileDownload +import androidx.compose.material.icons.filled.FileUpload +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.MutableState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.core.net.toUri +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.data.backup.SettingsImportSummary +import de.jeanlucmakiola.calendula.data.backup.SkippedSetting +import de.jeanlucmakiola.calendula.domain.FontRole +import de.jeanlucmakiola.calendula.ui.common.LeadingAvatar +import de.jeanlucmakiola.floret.backup.BackupProblem +import de.jeanlucmakiola.floret.components.GroupedHint +import de.jeanlucmakiola.floret.components.GroupedListInset +import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.GroupedSectionHeader +import de.jeanlucmakiola.floret.components.Position +import de.jeanlucmakiola.floret.locale.AppLanguage +import java.time.LocalDate + +// What the import picker accepts: providers label .json inconsistently. +private val SETTINGS_MIME_TYPES = arrayOf("application/json", "text/plain", "application/octet-stream") + +/** The Settings block's pickers and the import waiting for its confirmation. */ +class SettingsBackupActions internal constructor( + val busy: Boolean, + internal val pendingImport: MutableState, + val export: () -> Unit, + val import: () -> Unit, +) + +@Composable +fun rememberSettingsBackupActions(viewModel: SettingsBackupViewModel): SettingsBackupActions { + val busy by viewModel.busy.collectAsStateWithLifecycle() + val pendingImport = rememberSaveable { mutableStateOf(null) } + val createFile = rememberLauncherForActivityResult( + ActivityResultContracts.CreateDocument("application/json"), + ) { uri -> uri?.let(viewModel::export) } + val openFile = rememberLauncherForActivityResult( + ActivityResultContracts.OpenDocument(), + ) { uri -> pendingImport.value = uri?.toString() } + return SettingsBackupActions( + busy = busy, + pendingImport = pendingImport, + export = { runCatching { createFile.launch("calendula-settings-${LocalDate.now()}.json") } }, + import = { runCatching { openFile.launch(SETTINGS_MIME_TYPES) } }, + ) +} + +/** Settings export and import (#481), below the events' backup. */ +@Composable +fun SettingsBackupSection(actions: SettingsBackupActions) { + GroupedSectionHeader(stringResource(R.string.settings_backup_header)) + GroupedHint(stringResource(R.string.settings_backup_hint), style = MaterialTheme.typography.bodySmall) + GroupedRow( + title = stringResource(R.string.settings_backup_export), + summary = stringResource(R.string.settings_backup_export_summary), + position = Position.Top, + leading = { LeadingAvatar(Icons.Default.FileDownload) }, + dimmed = actions.busy, + onClick = { if (!actions.busy) actions.export() }, + ) + GroupedRow( + title = stringResource(R.string.settings_backup_import), + summary = stringResource(R.string.settings_backup_import_summary), + position = Position.Bottom, + leading = { LeadingAvatar(Icons.Default.FileUpload) }, + dimmed = actions.busy, + onClick = { if (!actions.busy) actions.import() }, + ) + if (actions.busy) { + LinearProgressIndicator( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = GroupedListInset, vertical = 16.dp), + ) + } +} + +/** + * The import's confirmation and summary dialogs, and the snackbars for + * everything else. + */ +@Composable +fun SettingsBackupDialogs( + actions: SettingsBackupActions, + viewModel: SettingsBackupViewModel, + snackbarHostState: SnackbarHostState, +) { + val result by viewModel.result.collectAsStateWithLifecycle() + val exported = stringResource(R.string.settings_backup_export_done) + val exportFailed = stringResource(R.string.settings_backup_export_failed) + val importFailed = BackupProblem.entries.associateWith { stringResource(it.messageRes()) } + + LaunchedEffect(result) { + val message = when (val r = result) { + is SettingsBackupResult.Exported -> exported + is SettingsBackupResult.ExportFailed -> exportFailed + is SettingsBackupResult.ImportFailed -> importFailed.getValue(r.problem) + is SettingsBackupResult.Imported, null -> return@LaunchedEffect + } + snackbarHostState.showSnackbar(message) + viewModel.consumeResult() + } + + (result as? SettingsBackupResult.Imported)?.let { imported -> + ImportSummaryDialog(imported.summary, onDismiss = viewModel::consumeResult) + } + + actions.pendingImport.value?.let { uri -> + AlertDialog( + onDismissRequest = { actions.pendingImport.value = null }, + title = { Text(stringResource(R.string.settings_backup_import_confirm_title)) }, + text = { Text(stringResource(R.string.settings_backup_import_confirm_message)) }, + confirmButton = { + TextButton( + onClick = { + actions.pendingImport.value = null + viewModel.import(uri.toUri()) + }, + ) { Text(stringResource(R.string.settings_backup_import_confirm_action)) } + }, + dismissButton = { + TextButton(onClick = { actions.pendingImport.value = null }) { + Text(stringResource(R.string.dialog_cancel)) + } + }, + ) + } +} + +@Composable +private fun ImportSummaryDialog(summary: SettingsImportSummary, onDismiss: () -> Unit) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.settings_backup_imported_title)) }, + text = { + Column( + verticalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier.verticalScroll(rememberScrollState()), + ) { + Text(stringResource(R.string.settings_backup_imported_body)) + if (summary.calendarsMatched > 0) { + Text( + pluralStringResource( + R.plurals.settings_backup_imported_calendars, + summary.calendarsMatched, + summary.calendarsMatched, + ), + ) + } + if (summary.skipped.isNotEmpty()) { + Text( + stringResource(R.string.settings_backup_imported_skipped), + style = MaterialTheme.typography.titleSmall, + ) + summary.skipped.forEach { skipped -> + Text( + "• " + skipped.label(), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + }, + confirmButton = { + TextButton(onClick = onDismiss) { Text(stringResource(R.string.dialog_ok)) } + }, + ) +} + +@Composable +private fun SkippedSetting.label(): String = when (this) { + is SkippedSetting.Calendar -> stringResource( + if (ambiguous) R.string.settings_backup_skipped_calendar_ambiguous else R.string.settings_backup_skipped_calendar, + displayName, + accountName, + ) + SkippedSetting.CalendarsUnavailable -> stringResource(R.string.settings_backup_skipped_calendars_unavailable) + is SkippedSetting.CustomFont -> stringResource( + when (role) { + FontRole.BRAND -> R.string.settings_backup_skipped_font_headings + FontRole.PLAIN -> R.string.settings_backup_skipped_font_body + }, + ) + SkippedSetting.SpecialDates -> stringResource(R.string.settings_backup_skipped_special_dates) + SkippedSetting.AutoBackupFolder -> stringResource(R.string.settings_backup_skipped_auto_backup) + is SkippedSetting.Language -> stringResource(R.string.settings_backup_skipped_language, AppLanguage.displayName(tag)) +} + +private fun BackupProblem.messageRes(): Int = when (this) { + BackupProblem.NOT_A_BACKUP -> R.string.settings_backup_import_failed_not_backup + BackupProblem.NEWER_VERSION -> R.string.settings_backup_import_failed_newer + BackupProblem.INVALID_DATA -> R.string.settings_backup_import_failed_invalid + BackupProblem.TOO_LARGE -> R.string.settings_backup_import_failed_too_large + BackupProblem.UNREADABLE -> R.string.settings_backup_import_failed_unreadable + BackupProblem.NOT_APPLIED -> R.string.settings_backup_import_failed +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/SettingsBackupViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/SettingsBackupViewModel.kt new file mode 100644 index 00000000..7949e2d6 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/SettingsBackupViewModel.kt @@ -0,0 +1,108 @@ +package de.jeanlucmakiola.calendula.ui.calendars + +import android.content.Context +import android.net.Uri +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import dagger.hilt.android.lifecycle.HiltViewModel +import dagger.hilt.android.qualifiers.ApplicationContext +import de.jeanlucmakiola.calendula.data.backup.SettingsBackupEngine +import de.jeanlucmakiola.calendula.data.backup.SettingsImportSummary +import de.jeanlucmakiola.floret.android.DocumentTooLargeException +import de.jeanlucmakiola.floret.android.readDocumentBytes +import de.jeanlucmakiola.floret.android.writeDocumentBytes +import de.jeanlucmakiola.floret.backup.BackupProblem +import de.jeanlucmakiola.floret.backup.BackupResult +import de.jeanlucmakiola.floret.di.IoDispatcher +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import javax.inject.Inject + +/** + * The outcome of a settings export or import, held until the screen has shown + * it. Plain classes, not data ones: two equal outcomes in a row must each count. + */ +sealed interface SettingsBackupResult { + class Exported : SettingsBackupResult + class ExportFailed : SettingsBackupResult + class Imported(val summary: SettingsImportSummary) : SettingsBackupResult + class ImportFailed(val problem: BackupProblem) : SettingsBackupResult +} + +/** + * Settings export/import on the Backup & restore screen (#481). The file is a + * single SAF document the user picked; the engine knows nothing about it. + * The result is state rather than an event, so an import that changes the + * app language — and recreates the activity — still shows its summary. + */ +@HiltViewModel +class SettingsBackupViewModel @Inject constructor( + private val engine: SettingsBackupEngine, + @ApplicationContext private val context: Context, + @IoDispatcher private val io: CoroutineDispatcher, +) : ViewModel() { + + private val _busy = MutableStateFlow(false) + val busy: StateFlow = _busy.asStateFlow() + + private val _result = MutableStateFlow(null) + val result: StateFlow = _result.asStateFlow() + + fun export(uri: Uri) = launchWork { + try { + val text = engine.export() + withContext(io) { context.contentResolver.writeDocumentBytes(uri, text.toByteArray(Charsets.UTF_8)) } + SettingsBackupResult.Exported() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + SettingsBackupResult.ExportFailed() + } + } + + /** Call only once the user has confirmed replacing their settings. */ + fun import(uri: Uri) = launchWork { + val text = try { + withContext(io) { + context.contentResolver.readDocumentBytes(uri, engine.maxImportBytes).toString(Charsets.UTF_8) + } + } catch (e: CancellationException) { + throw e + } catch (e: DocumentTooLargeException) { + return@launchWork SettingsBackupResult.ImportFailed(BackupProblem.TOO_LARGE) + } catch (e: Exception) { + return@launchWork SettingsBackupResult.ImportFailed(BackupProblem.UNREADABLE) + } + try { + when (val imported = engine.import(text)) { + is BackupResult.Success -> SettingsBackupResult.Imported(imported.value) + is BackupResult.Failure -> SettingsBackupResult.ImportFailed(imported.problem) + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + SettingsBackupResult.ImportFailed(BackupProblem.NOT_APPLIED) + } + } + + fun consumeResult() { + _result.value = null + } + + private fun launchWork(work: suspend () -> SettingsBackupResult) { + if (_busy.value) return + _busy.value = true + viewModelScope.launch { + try { + _result.value = work() + } finally { + _busy.value = false + } + } + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/AccountGroups.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/AccountGroups.kt index c92c1ce3..d2a56674 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/AccountGroups.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/AccountGroups.kt @@ -1,5 +1,6 @@ package de.jeanlucmakiola.calendula.ui.common +import android.content.Context import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext @@ -72,11 +73,13 @@ fun accountGroupTitle(group: CalendarAccountGroup): String { @Composable fun sourceAppName(accountType: String): String { val context = LocalContext.current - return remember(accountType) { - val pm = context.packageManager - val packages = sourceAppPackages(context, accountType) - packages.firstNotNullOfOrNull { pkg -> - runCatching { pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString() }.getOrNull() - } ?: accountType - } + return remember(accountType) { sourceAppLabel(context, accountType) } +} + +/** [sourceAppName] outside composition, e.g. for notification channel groups. */ +fun sourceAppLabel(context: Context, accountType: String): String { + val pm = context.packageManager + return sourceAppPackages(context, accountType).firstNotNullOfOrNull { pkg -> + runCatching { pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString() }.getOrNull() + } ?: accountType } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt index e2a1d028..ca7c2c9d 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarDrawer.kt @@ -20,8 +20,12 @@ import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.DateRange import androidx.compose.material.icons.filled.Settings +import androidx.compose.material.icons.filled.ManageAccounts +import androidx.compose.material.icons.filled.Sync import androidx.compose.material3.DrawerState +import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.Icon +import androidx.compose.material3.LoadingIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalDrawerSheet import androidx.compose.material3.Text @@ -38,6 +42,8 @@ import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.stateDescription import androidx.compose.ui.unit.dp import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.ui.filter.CalendarFilterList @@ -61,6 +67,8 @@ import kotlinx.datetime.LocalDate * * [currentDate] seeds the jump-to-date picker (the visible day/week-start/month * anchor); [onJumpToDate] navigates the active view to the chosen day. + * [sync] adds "Sync now" beside it while there is a synced calendar (#240), + * and a row to grant account access while some account can't be reached yet. */ @Composable fun CalendarDrawer( @@ -70,7 +78,9 @@ fun CalendarDrawer( onSelectView: (CalendarView) -> Unit, onJumpToDate: (LocalDate) -> Unit, onSettings: () -> Unit, + onHideInView: () -> Unit, viewOrder: List = IMPLEMENTED_VIEWS, + sync: DrawerSync? = null, ) { var showDatePicker by remember { mutableStateOf(false) } val scope = rememberCoroutineScope() @@ -103,16 +113,17 @@ fun CalendarDrawer( Spacer(Modifier.height(16.dp)) GroupedRow( title = stringResource(R.string.drawer_jump_to_date), - position = Position.Alone, + position = if (sync?.hasRows == true) Position.Top else Position.Alone, minHeight = 56.dp, leading = { DrawerLeadingIcon(Icons.Filled.DateRange) }, onClick = { showDatePicker = true }, ) + if (sync != null) SyncRows(sync) Spacer(Modifier.height(16.dp)) DrawerSectionHeader(stringResource(R.string.filter_title)) - CalendarFilterList() + CalendarFilterList(currentView = currentView, onHideInView = onHideInView) Spacer(Modifier.height(16.dp)) GroupedRow( @@ -138,6 +149,64 @@ fun CalendarDrawer( } } +/** + * The drawer's sync rows: "Sync now" when [canSync] ([inFlight] shows progress + * and ignores taps, [outcome] the last request's result while the drawer stays + * open), and a grant row while some account [needsAccess]. + */ +data class DrawerSync( + val canSync: Boolean, + val inFlight: Boolean, + val outcome: String?, + val needsAccess: Boolean, + val onSync: () -> Unit, + val onGrantAccess: () -> Unit, +) { + val hasRows: Boolean get() = canSync || needsAccess +} + +@Composable +private fun SyncRows(sync: DrawerSync) { + if (sync.canSync) { + SyncNowRow(sync, if (sync.needsAccess) Position.Middle else Position.Bottom) + } + if (sync.needsAccess) { + GroupedRow( + title = stringResource(R.string.drawer_sync_access), + summary = stringResource(R.string.drawer_sync_access_summary), + position = Position.Bottom, + minHeight = 56.dp, + leading = { DrawerLeadingIcon(Icons.Filled.ManageAccounts) }, + onClick = sync.onGrantAccess, + ) + } +} + +@OptIn(ExperimentalMaterial3ExpressiveApi::class) +@Composable +private fun SyncNowRow(sync: DrawerSync, position: Position) { + val inFlightText = stringResource(R.string.sync_in_progress) + GroupedRow( + title = stringResource(R.string.drawer_sync_now), + summary = if (sync.inFlight) inFlightText else sync.outcome, + position = position, + modifier = if (sync.inFlight) { + Modifier.semantics { stateDescription = inFlightText } + } else { + Modifier + }, + dimmed = sync.inFlight, + minHeight = 56.dp, + leading = { DrawerLeadingIcon(Icons.Filled.Sync) }, + trailing = if (sync.inFlight) { + { LoadingIndicator(Modifier.size(32.dp)) } + } else { + null + }, + onClick = sync.onSync.takeIf { !sync.inFlight }, + ) +} + /** Leading slot for the drawer's plain icons: the same 40.dp footprint * [CalendarColorChip] takes, so every leading glyph shares one vertical axis. */ @Composable diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarPickerGroups.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarPickerGroups.kt index af5c46df..f4ae7e9b 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarPickerGroups.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarPickerGroups.kt @@ -15,6 +15,7 @@ import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight import androidx.compose.material.icons.filled.Cloud import androidx.compose.material.icons.filled.PhoneAndroid import androidx.compose.material.icons.filled.VisibilityOff +import androidx.compose.material3.Checkbox import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable @@ -55,28 +56,13 @@ fun ColumnScope.CalendarPickerGroups( onSelect: (Long) -> Unit, onManageCalendars: (() -> Unit)? = null, ) { - val local = remember(calendars) { calendars.filter { it.isLocal } } - val syncedGroups = remember(calendars) { - calendars.filterNot { it.isLocal }.groupByAccount() - } - - if (local.isNotEmpty()) { - CalendarPickerGroup( - title = stringResource(R.string.calendars_local_header), - leading = { LeadingAvatar(Icons.Default.PhoneAndroid) }, - calendars = local, - selectedId = selectedId, - onSelect = onSelect, - ) - } - syncedGroups.forEachIndexed { index, group -> - if (local.isNotEmpty() || index > 0) Spacer(Modifier.height(16.dp)) - CalendarPickerGroup( - title = accountGroupTitle(group), - leading = { SourceLogo(group.accountType) }, - calendars = group.calendars, - selectedId = selectedId, - onSelect = onSelect, + CalendarAccountSections(calendars) { calendar, position -> + GroupedRow( + title = calendar.displayName.orUnnamed(), + position = position, + checked = calendar.id == selectedId, + leading = { CalendarColorChip(calendar.color) }, + onClick = { onSelect(calendar.id) }, ) } if (onManageCalendars != null) { @@ -98,14 +84,68 @@ fun ColumnScope.CalendarPickerGroups( } } -/** One account's category header (avatar + name) atop its selectable calendars. */ +/** + * A multi-select take on [CalendarPickerGroups]: the same sections, with a + * checkbox per calendar instead of a single check. + */ @Composable -private fun CalendarPickerGroup( +fun ColumnScope.CalendarCheckGroups( + calendars: List, + isChecked: (CalendarSource) -> Boolean, + onCheckedChange: (CalendarSource, Boolean) -> Unit, +) { + CalendarAccountSections(calendars) { calendar, position -> + val checked = isChecked(calendar) + GroupedRow( + title = calendar.displayName.orUnnamed(), + summary = calendar.description, + position = position, + leading = { CalendarColorChip(calendar.color) }, + trailing = { + Checkbox(checked = checked, onCheckedChange = { onCheckedChange(calendar, it) }) + }, + onClick = { onCheckedChange(calendar, !checked) }, + ) + } +} + +/** The app's own calendars, then one section per synced account, each under its category header. */ +@Composable +private fun CalendarAccountSections( + calendars: List, + row: @Composable (CalendarSource, Position) -> Unit, +) { + val local = remember(calendars) { calendars.filter { it.isLocal } } + val syncedGroups = remember(calendars) { + calendars.filterNot { it.isLocal }.groupByAccount() + } + + if (local.isNotEmpty()) { + CalendarAccountSection( + title = stringResource(R.string.calendars_local_header), + leading = { LeadingAvatar(Icons.Default.PhoneAndroid) }, + calendars = local, + row = row, + ) + } + syncedGroups.forEachIndexed { index, group -> + if (local.isNotEmpty() || index > 0) Spacer(Modifier.height(16.dp)) + CalendarAccountSection( + title = accountGroupTitle(group), + leading = { SourceLogo(group.accountType) }, + calendars = group.calendars, + row = row, + ) + } +} + +/** One account's category header (avatar + name) atop its calendars. */ +@Composable +private fun CalendarAccountSection( title: String, leading: @Composable () -> Unit, calendars: List, - selectedId: Long?, - onSelect: (Long) -> Unit, + row: @Composable (CalendarSource, Position) -> Unit, ) { GroupedRow( title = title, @@ -113,13 +153,7 @@ private fun CalendarPickerGroup( leading = leading, ) calendars.forEachIndexed { index, calendar -> - GroupedRow( - title = calendar.displayName.orUnnamed(), - position = if (index == calendars.lastIndex) Position.Bottom else Position.Middle, - checked = calendar.id == selectedId, - leading = { CalendarColorChip(calendar.color) }, - onClick = { onSelect(calendar.id) }, - ) + row(calendar, if (index == calendars.lastIndex) Position.Bottom else Position.Middle) } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarTitle.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarTitle.kt index ccac0372..4bd1d9a8 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarTitle.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarTitle.kt @@ -1,5 +1,6 @@ package de.jeanlucmakiola.calendula.ui.common +import de.jeanlucmakiola.floret.locale.capitalizeStart import de.jeanlucmakiola.floret.locale.localizedDateFormatter import java.util.Locale @@ -30,5 +31,5 @@ fun formatCalendarTitle( forceYear: Boolean = false, ): String { val fields = if (date.year == currentYear && !forceYear) skeleton else skeleton + "y" - return localizedDateFormatter(locale, fields).format(date) + return localizedDateFormatter(locale, fields).format(date).capitalizeStart(locale) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarView.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarView.kt index 7715ee27..256ae93b 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarView.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/CalendarView.kt @@ -112,11 +112,11 @@ data class QuickSwitchConfig( * top; switching to one already in the stack pops back to it (collapsing the * loop, so the depth stays bounded by the number of distinct views). Selecting * the home view collapses to just `[default]`. - * - [viewBaseStack] — the stack a widget launch resets to: just `[default]` when + * - [viewBaseStack] — the stack a widget event or header launch resets to: just `[default]` when * the widget's view is the home view, else `[default, source]`. A widget entry * starts a fresh context rather than extending in-app history. - * - [drillToDay] — pushes the day view on top (a date tap from the month grid or - * a widget), unless the day view is already current. + * - [drillToDay] — pushes the day view on top (a date tap from the month grid, a + * widget or a launcher), unless the day view is already current. */ fun List.selectView(target: CalendarView): List { val existing = indexOf(target) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventActionsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventActionsViewModel.kt index 333c25de..49a6d822 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventActionsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventActionsViewModel.kt @@ -15,6 +15,7 @@ import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.domain.RecurringWriteScope import de.jeanlucmakiola.calendula.domain.atOccurrence import de.jeanlucmakiola.calendula.domain.toDuplicateForm +import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.floret.android.stateWhileSubscribed import de.jeanlucmakiola.floret.di.IoDispatcher import kotlinx.coroutines.CoroutineDispatcher @@ -43,6 +44,7 @@ class EventActionsViewModel @Inject constructor( private val icsExporter: IcsExporter, @IoDispatcher private val io: CoroutineDispatcher, private val zoneSource: ZoneSource, + private val settingsPrefs: SettingsPrefs, ) : ViewModel() { /** Every calendar by id, for what a selected event's bar may offer. */ @@ -64,8 +66,7 @@ class EventActionsViewModel @Inject constructor( /** A create form copying [event], or null when it can't be read. */ suspend fun duplicateForm(event: EventInstance): EventForm? { val detail = load(event) ?: return null - val canModify = calendars.value[event.calendarId]?.canModifyContents == true - return detail.toDuplicateForm(canModify, zoneSource.current()) + return detail.toDuplicateForm(zoneSource.current(), settingsPrefs.knownFixedTimeReminders.first()) } /** A staged `.ics` for [event], or null — reported — when it can't be built. */ diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventMoveHost.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventMoveHost.kt index 542222aa..2a0b539e 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventMoveHost.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventMoveHost.kt @@ -51,8 +51,8 @@ private val FAB_BAND = 88.dp fun EventMoveHost( viewModel: RescheduleViewModel, modifier: Modifier = Modifier, - actionFailure: String? = null, - onActionFailureShown: () -> Unit = {}, + notice: String? = null, + onNoticeShown: () -> Unit = {}, ) { val prompt by viewModel.scopePrompt.collectAsStateWithLifecycle() val outcome by viewModel.outcome.collectAsStateWithLifecycle() @@ -81,7 +81,7 @@ fun EventMoveHost( } // A failed selection action (#141) shares the chip rather than stacking on it. val message = when (outcome) { - null -> actionFailure + null -> notice is MoveOutcome.Moved -> if (resizedLabel != null) { stringResource(R.string.event_resize_done, resizedLabel) } else { @@ -116,10 +116,10 @@ fun EventMoveHost( viewModel.consumeOutcome() } // A failure waits for the chip to be free, then has its own turn. - LaunchedEffect(actionFailure, outcome == null) { - if (actionFailure == null || outcome != null) return@LaunchedEffect + LaunchedEffect(notice, outcome == null) { + if (notice == null || outcome != null) return@LaunchedEffect delay(CHIP_MILLIS) - onActionFailureShown() + onNoticeShown() } BoxWithConstraints(modifier = modifier.fillMaxSize()) { @@ -138,7 +138,7 @@ fun EventMoveHost( // write anyway, so offering it would be a button that does nothing. val undo = content.undo?.takeIf { !writeInFlight } SnackChip( - visible = outcome != null || actionFailure != null, + visible = outcome != null || notice != null, message = content.message, maxWidth = chipMaxWidth, actionLabel = stringResource(R.string.event_move_undo).takeIf { undo != null }, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/FixedTimeReminderUi.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/FixedTimeReminderUi.kt new file mode 100644 index 00000000..13ffcadb --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/FixedTimeReminderUi.kt @@ -0,0 +1,220 @@ +package de.jeanlucmakiola.calendula.ui.common + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.FilledTonalButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.Saver +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride +import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder +import de.jeanlucmakiola.floret.components.CustomExpandRow +import de.jeanlucmakiola.floret.components.DialogAmountField +import de.jeanlucmakiola.floret.components.FullScreenPicker +import de.jeanlucmakiola.floret.components.GroupedHint +import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.Position +import de.jeanlucmakiola.floret.locale.currentLocale +import kotlinx.datetime.LocalTime + +/** "1 day before at 20:00", in the app's 12/24-hour convention. */ +@Composable +fun fixedTimeReminderLabel(reminder: FixedTimeReminder): String = stringResource( + R.string.reminder_fixed_time, + pluralStringResource(R.plurals.reminder_days, reminder.daysBefore, reminder.daysBefore), + formatMinuteOfDay(reminder.minuteOfDay, LocalUse24HourFormat.current, currentLocale()), +) + +/** + * The "N days before at HH:MM" editor (#459): a day count and a time, read as + * one sentence. Seeded from [initial]; [onValueChange] follows every edit (null + * while the day count is out of range). With a [confirmLabel] it carries its own + * confirm, reporting through [onConfirm]; without one the host picker commits + * from its actions slot. [connected] gives it the shape that meets a row above it. + */ +@Composable +fun FixedTimeReminderEditor( + initial: FixedTimeReminder, + modifier: Modifier = Modifier, + confirmLabel: String? = null, + onConfirm: (FixedTimeReminder) -> Unit = {}, + onValueChange: (FixedTimeReminder?) -> Unit = {}, + connected: Boolean = true, +) { + var daysText by rememberSaveable { mutableStateOf(initial.daysBefore.toString()) } + var minuteOfDay by rememberSaveable { mutableStateOf(initial.minuteOfDay) } + var pickingTime by rememberSaveable { mutableStateOf(false) } + val days = daysText.toIntOrNull()?.takeIf { it in 1..FixedTimeReminder.MAX_DAYS_BEFORE } + val value = days?.let { FixedTimeReminder(it, minuteOfDay) } + LaunchedEffect(value) { onValueChange(value) } + + Surface( + color = MaterialTheme.colorScheme.surfaceContainerHigh, + shape = if (connected) { + RoundedCornerShape(topStart = 6.dp, topEnd = 6.dp, bottomStart = 22.dp, bottomEnd = 22.dp) + } else { + RoundedCornerShape(22.dp) + }, + modifier = modifier + .fillMaxWidth() + .padding(horizontal = 16.dp), + ) { + Column( + modifier = Modifier.padding(16.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + DialogAmountField(value = daysText, onValueChange = { daysText = it }, placeholder = "1") + Spacer(Modifier.width(12.dp)) + Text( + text = stringResource(R.string.reminder_fixed_days_before_at), + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.weight(1f, fill = false), + ) + Spacer(Modifier.width(12.dp)) + FilledTonalButton(onClick = { pickingTime = true }) { + Text(formatMinuteOfDay(minuteOfDay, LocalUse24HourFormat.current, currentLocale())) + } + } + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + text = value?.let { fixedTimeReminderLabel(it) } + ?: stringResource(R.string.reminder_fixed_days_range, FixedTimeReminder.MAX_DAYS_BEFORE), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.weight(1f), + ) + if (confirmLabel != null) { + Spacer(Modifier.width(16.dp)) + FilledTonalButton( + enabled = value != null, + onClick = { value?.let(onConfirm) }, + ) { Text(confirmLabel) } + } + } + } + } + if (pickingTime) { + TimePickerAlert( + initial = LocalTime(minuteOfDay / 60, minuteOfDay % 60), + onConfirm = { + minuteOfDay = it.hour * 60 + it.minute + pickingTime = false + }, + onDismiss = { pickingTime = false }, + ) + } +} + +/** + * Picker for a fixed-time default (#459), full-screen: off, or a reminder at a + * set time edited in place — and, on a per-calendar picker ([inheritedLabel] + * non-null), deferring to the global default, [inherited], which also seeds the + * editor. Applies live; the user leaves via back, or through [footer], which + * follows the options and gets [onDismiss]. + */ +@Composable +fun FixedTimeReminderPicker( + title: String, + selected: FixedTimeOverride, + onSelect: (FixedTimeOverride) -> Unit, + onDismiss: () -> Unit, + inheritedLabel: String? = null, + inherited: FixedTimeReminder? = null, + footer: @Composable ColumnScope.(dismiss: () -> Unit) -> Unit = {}, +) { + var current by rememberSaveable(stateSaver = FixedTimeOverrideSaver) { mutableStateOf(selected) } + var editing by rememberSaveable { mutableStateOf(false) } + // Mirrors [selected] until the first pick, as ReminderDefaultPicker does. + var userEdited by rememberSaveable { mutableStateOf(false) } + LaunchedEffect(selected) { + if (!userEdited) current = selected + } + fun apply(choice: FixedTimeOverride) { + userEdited = true + current = choice + onSelect(choice) + } + val chosen = (current as? FixedTimeOverride.At)?.reminder + + FullScreenPicker(title = title, onDismiss = onDismiss) { + GroupedHint(text = stringResource(R.string.settings_fixed_reminder_hint)) + Spacer(Modifier.height(8.dp)) + val rowCount = if (inheritedLabel != null) 3 else 2 + if (inheritedLabel != null) { + GroupedRow( + title = stringResource(R.string.reminder_use_default), + summary = inheritedLabel, + position = Position.Top, + checked = current is FixedTimeOverride.Inherit, + onClick = { apply(FixedTimeOverride.Inherit) }, + ) + } + GroupedRow( + title = stringResource(R.string.reminder_none), + position = if (rowCount == 3) Position.Middle else Position.Top, + checked = current is FixedTimeOverride.Off, + onClick = { apply(FixedTimeOverride.Off) }, + ) + CustomExpandRow( + title = stringResource(R.string.reminder_fixed_at_set_time), + summary = chosen?.let { fixedTimeReminderLabel(it) }, + position = Position.Bottom, + expanded = editing, + onExpandedChange = { editing = it }, + checked = chosen != null, + ) { + FixedTimeReminderEditor( + initial = chosen ?: inherited ?: DEFAULT_FIXED_TIME_REMINDER, + confirmLabel = stringResource(R.string.reminder_custom_set), + onConfirm = { + apply(FixedTimeOverride.At(it)) + editing = false + }, + ) + } + footer(onDismiss) + } +} + +/** What the editor offers first: the evening before. */ +val DEFAULT_FIXED_TIME_REMINDER = FixedTimeReminder(daysBefore = 1, minuteOfDay = 20 * 60) + +private val FixedTimeOverrideSaver = Saver( + save = { + when (it) { + FixedTimeOverride.Inherit -> "inherit" + FixedTimeOverride.Off -> "off" + is FixedTimeOverride.At -> it.reminder.toToken() + } + }, + restore = { + when (it) { + "inherit" -> FixedTimeOverride.Inherit + "off" -> FixedTimeOverride.Off + else -> FixedTimeReminder.parse(it)?.let(FixedTimeOverride::At) ?: FixedTimeOverride.Off + } + }, +) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/Picker.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/Picker.kt index f2505b2e..15cb7422 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/Picker.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/Picker.kt @@ -6,6 +6,7 @@ import androidx.compose.material3.Checkbox import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable @@ -38,8 +39,8 @@ import kotlinx.datetime.toLocalDateTime import kotlin.time.Clock /** - * Reminder-default picker, full-screen and **multi-select**: each [presets] - * lead time (plus any chosen custom value) is a checkbox row that toggles + * Reminder-default picker, full-screen and **multi-select**: each preset + * lead time ([reminderPresets] for [isAllDay]) (plus any chosen custom value) is a checkbox row that toggles * independently, so a default can carry several reminders ("1 week before" *and* * "on the day"). Two exclusive checkmark rows sit above the list: an explicit * "No reminder" (both pickers, so the empty state stays visible and reachable) @@ -59,7 +60,7 @@ import kotlin.time.Clock @Composable fun ReminderDefaultPicker( title: String, - presets: List, + isAllDay: Boolean, selected: ReminderOverride, allowInherit: Boolean, onSelect: (ReminderOverride) -> Unit, @@ -87,14 +88,17 @@ fun ReminderDefaultPicker( // Custom (non-preset) lead times seen this session, so unchecking one keeps // its row (unchecked) until the picker closes instead of vanishing mid-tap, // which would strand a hand-entered value with no way to re-check it. + val presets = reminderPresets(isAllDay) + val units = customReminderUnits(isAllDay) val seenCustom = remember { mutableSetOf() } seenCustom += selectedMinutes.filter { it !in presets } // Presets plus every custom value seen this session, each as its own row. - val rows = presets + seenCustom.sorted() + val rows = presets + seenCustom var customExpanded by rememberSaveable { mutableStateOf(false) } var amountText by rememberSaveable { mutableStateOf("") } - var unit by rememberSaveable { mutableStateOf(ReminderUnit.Minutes) } + var pickedUnit by rememberSaveable { mutableStateOf(units.first()) } + val unit = pickedUnit.takeIf { it in units } ?: units.first() fun apply(override: ReminderOverride) { userEdited = true @@ -125,39 +129,68 @@ fun ReminderDefaultPicker( onClick = { apply(ReminderOverride.None) }, ) Spacer(Modifier.height(24.dp)) - val rowCount = rows.size + 1 // + the custom row - rows.forEachIndexed { index, minute -> - val checked = minute in selectedMinutes - GroupedRow( - title = reminderLeadTimeLabel(minute), - summary = leadTimeSummary?.invoke(minute), - position = positionOf(index, rowCount), - selected = checked, - trailing = { Checkbox(checked = checked, onCheckedChange = { toggle(minute) }) }, - onClick = { toggle(minute) }, - ) - } - CustomExpandRow( - title = stringResource(R.string.event_edit_reminder_custom), - position = positionOf(rows.size, rowCount), - expanded = customExpanded, - onExpandedChange = { customExpanded = it }, - ) { - CustomReminderEditor( - amountText = amountText, - onAmountChange = { amountText = it }, - unit = unit, - onUnitChange = { unit = it }, - onConfirm = { minutes -> - emit(selectedMinutes + minutes) - amountText = "" - customExpanded = false - }, - ) - } + GroupedLeadTimeRows( + minutes = rows, + splitSubDay = splitsSubDay(presets), + row = { minute, position -> + val checked = minute in selectedMinutes + GroupedRow( + title = reminderLeadTimeLabel(minute), + summary = leadTimeSummary?.invoke(minute), + position = position, + selected = checked, + trailing = { Checkbox(checked = checked, onCheckedChange = { toggle(minute) }) }, + onClick = { toggle(minute) }, + ) + }, + trailing = { position -> + CustomExpandRow( + title = stringResource(R.string.event_edit_reminder_custom), + position = position, + expanded = customExpanded, + onExpandedChange = { customExpanded = it }, + ) { + CustomReminderEditor( + amountText = amountText, + onAmountChange = { amountText = it }, + units = units, + unit = unit, + onUnitChange = { pickedUnit = it }, + onConfirm = { minutes -> + emit(selectedMinutes + minutes) + amountText = "" + customExpanded = false + }, + ) + } + }, + ) } } +/** + * Lead-time rows laid out as [groupReminderLeadTimes] groups, each a connected + * card, with [trailing] (the Custom row) closing the last one. + */ +@Composable +internal fun GroupedLeadTimeRows( + minutes: Collection, + splitSubDay: Boolean, + row: @Composable (minute: Int, position: Position) -> Unit, + trailing: @Composable (position: Position) -> Unit, +) { + val groups = groupReminderLeadTimes(minutes, splitSubDay) + groups.forEachIndexed { groupIndex, group -> + val isLast = groupIndex == groups.lastIndex + val rowCount = group.size + if (isLast) 1 else 0 + group.forEachIndexed { index, minute -> + key(minute) { row(minute, positionOf(index, rowCount)) } + } + if (!isLast) Spacer(Modifier.height(12.dp)) + } + trailing(if (groups.isEmpty()) Position.Alone else Position.Bottom) +} + /** * The expanded "Custom" lead-time editor: a tonal card connected to the Custom @@ -170,6 +203,7 @@ fun ReminderDefaultPicker( private fun CustomReminderEditor( amountText: String, onAmountChange: (String) -> Unit, + units: List, unit: ReminderUnit, onUnitChange: (ReminderUnit) -> Unit, onConfirm: (Int) -> Unit, @@ -178,9 +212,10 @@ private fun CustomReminderEditor( CustomAmountEditor( amountText = amountText, onAmountChange = onAmountChange, - unitLabels = ReminderUnit.entries.map { stringResource(reminderUnitLabel(it)) }, - selectedUnit = unit.ordinal, - onUnitChange = { onUnitChange(ReminderUnit.entries[it]) }, + unitLabels = units.map { stringResource(reminderUnitLabel(it)) }, + placeholder = customReminderPlaceholder(unit), + selectedUnit = units.indexOf(unit), + onUnitChange = { onUnitChange(units[it]) }, preview = amount?.let { reminderLeadTimeLabel(it * unit.minutesFactor) } ?: stringResource(R.string.reminder_custom_amount), setLabel = stringResource(R.string.reminder_custom_set), diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/ReminderFormatting.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/ReminderFormatting.kt index 3812dee8..bfddb2ca 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/ReminderFormatting.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/ReminderFormatting.kt @@ -8,8 +8,46 @@ import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.data.calendar.MINUTES_DEFAULT import de.jeanlucmakiola.floret.reminders.ReminderUnit +private val DAY = ReminderUnit.Days.minutesFactor +private val WEEK = ReminderUnit.Weeks.minutesFactor + +private val DAY_SCALE_PRESETS = + listOf(DAY, 2 * DAY, 3 * DAY, 4 * DAY, 5 * DAY, WEEK, 2 * WEEK, 3 * WEEK) + /** Common reminder lead times offered as quick picks in the form and settings. */ -val REMINDER_PRESETS = listOf(0, 10, 30, 60, 1_440) +val REMINDER_PRESETS = listOf(0, 10, 30, 60) + DAY_SCALE_PRESETS + +/** Day-scale lead times for all-day events, all-day defaults and contact special dates. */ +val ALLDAY_REMINDER_PRESETS = listOf(0) + DAY_SCALE_PRESETS + +fun reminderPresets(isAllDay: Boolean): List = + if (isAllDay) ALLDAY_REMINDER_PRESETS else REMINDER_PRESETS + +/** + * Units the Custom step offers. All-day reminders fire on whole days at the + * all-day reminder time, so minutes and hours would be dropped on save. + */ +fun customReminderUnits(isAllDay: Boolean): List = + if (isAllDay) listOf(ReminderUnit.Days, ReminderUnit.Weeks) else ReminderUnit.entries + +/** Placeholder for the Custom amount field: a typical amount in [unit]. */ +fun customReminderPlaceholder(unit: ReminderUnit): String = + if (unit == ReminderUnit.Minutes) "10" else "1" + +/** Whether a picker over [presets] splits its rows into sub-day and day-scale groups. */ +fun splitsSubDay(presets: Collection): Boolean = presets.any { it in 1 until DAY } + +/** + * Sorts lead times and, when [splitSubDay] (see [splitsSubDay]), splits them into a sub-day group and + * a day-scale group so a long picker list reads as two connected sections. + * Empty groups are dropped. + */ +fun groupReminderLeadTimes(minutes: Collection, splitSubDay: Boolean): List> { + val sorted = minutes.sorted() + if (!splitSubDay) return listOfNotNull(sorted.takeIf { it.isNotEmpty() }) + val (subDay, dayScale) = sorted.partition { it < DAY } + return listOf(subDay, dayScale).filter { it.isNotEmpty() } +} @StringRes fun reminderUnitLabel(unit: ReminderUnit): Int = when (unit) { @@ -35,10 +73,10 @@ fun reminderLeadTimeLabel(minutes: Int): String = when { minutes == MINUTES_DEFAULT -> stringResource(R.string.reminder_default) minutes == 0 -> stringResource(R.string.reminder_at_time) minutes < 0 -> stringResource(R.string.reminder_after, durationLabel(-minutes)) - minutes % 10_080 == 0 -> - pluralStringResource(R.plurals.reminder_weeks, minutes / 10_080, minutes / 10_080) - minutes % 1_440 == 0 -> - pluralStringResource(R.plurals.reminder_days, minutes / 1_440, minutes / 1_440) + minutes % WEEK == 0 -> + pluralStringResource(R.plurals.reminder_weeks, minutes / WEEK, minutes / WEEK) + minutes % DAY == 0 -> + pluralStringResource(R.plurals.reminder_days, minutes / DAY, minutes / DAY) minutes % 60 == 0 -> pluralStringResource(R.plurals.reminder_hours, minutes / 60, minutes / 60) else -> pluralStringResource(R.plurals.reminder_minutes, minutes, minutes) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/RescheduleViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/RescheduleViewModel.kt index 5ef83d4a..82c510ae 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/RescheduleViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/RescheduleViewModel.kt @@ -23,9 +23,12 @@ import de.jeanlucmakiola.calendula.domain.resolvedZone import de.jeanlucmakiola.calendula.domain.shiftedByDays import de.jeanlucmakiola.calendula.domain.shiftedTo import de.jeanlucmakiola.calendula.domain.toEditForm +import de.jeanlucmakiola.calendula.domain.withFixedTimeRemindersRead +import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.floret.android.stateWhileSubscribed import de.jeanlucmakiola.floret.di.IoDispatcher import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow @@ -172,6 +175,7 @@ class RescheduleViewModel @Inject constructor( private val repository: CalendarRepository, @IoDispatcher private val io: CoroutineDispatcher, private val zoneSource: ZoneSource, + private val settingsPrefs: SettingsPrefs, ) : ViewModel() { private val _scopePrompt = MutableStateFlow(null) @@ -457,7 +461,9 @@ class RescheduleViewModel @Inject constructor( dropped } + // Read fixed-time reminders out, so the move keeps them on their wall clock (#459). val original = detail.toEditForm(request.beginMillis, request.endMillis, zone) + .withFixedTimeRemindersRead(settingsPrefs.knownFixedTimeReminders.first(), zone) val shifted = when (val target = request.target) { is MoveTarget.Start -> original.shiftedTo(target.instant, zone) is MoveTarget.ByDays -> original.shiftedByDays(target.days, zone) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/ResultSummary.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/ResultSummary.kt new file mode 100644 index 00000000..0c9d5375 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/ResultSummary.kt @@ -0,0 +1,135 @@ +package de.jeanlucmakiola.calendula.ui.common + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.height +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.PriorityHigh +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary +import de.jeanlucmakiola.floret.components.ResultBadge as FloretResultBadge + +/** floret's [FloretResultBadge] as a check on success, or an exclamation mark in the error colours. */ +@Composable +fun ResultBadge(error: Boolean) { + val scheme = MaterialTheme.colorScheme + if (error) { + FloretResultBadge(Icons.Default.PriorityHigh, scheme.errorContainer, scheme.onErrorContainer) + } else { + FloretResultBadge(Icons.Default.Check, scheme.primaryContainer, scheme.onPrimaryContainer) + } +} + +/** A result screen's headline under its badge, then its notes; an error note takes the error colour. */ +@Composable +fun ResultMessage(title: String, notes: List = emptyList()) { + Spacer(Modifier.height(24.dp)) + Text( + title, + style = MaterialTheme.typography.headlineSmall, + color = MaterialTheme.colorScheme.onSurface, + textAlign = TextAlign.Center, + ) + notes.forEach { note -> + Spacer(Modifier.height(8.dp)) + Text( + note.text, + style = MaterialTheme.typography.bodyMedium, + color = if (note.error) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + ) + } +} + +data class ResultNote(val text: String, val error: Boolean = false) + +/** The notes an import summary carries: failures, skipped duplicates, then [stoppedNote] when part was never tried. */ +@Composable +fun importSummaryNotes(summary: IcsImportSummary, stoppedNote: String?): List = buildList { + if (summary.failed > 0) add(ResultNote(stringResource(R.string.import_done_failed_note))) + if (summary.skippedDuplicate > 0) add(ResultNote(stringResource(R.string.import_done_dedup_note))) + if (stoppedNote != null) add(ResultNote(stoppedNote, error = true)) +} + +/** Added / skipped / failed as big-number tiles, the latter two only when non-zero. */ +@Composable +fun ImportSummaryStats(summary: IcsImportSummary, modifier: Modifier = Modifier) { + Row(modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) { + ResultStatCard( + count = summary.imported, + label = stringResource(R.string.import_done_added_label), + contentDescription = pluralStringResource(R.plurals.import_done_imported, summary.imported, summary.imported), + container = MaterialTheme.colorScheme.secondaryContainer, + onContainer = MaterialTheme.colorScheme.onSecondaryContainer, + ) + if (summary.skippedDuplicate > 0) { + ResultStatCard( + count = summary.skippedDuplicate, + label = stringResource(R.string.import_done_skipped_label), + contentDescription = pluralStringResource( + R.plurals.import_done_skipped, + summary.skippedDuplicate, + summary.skippedDuplicate, + ), + container = MaterialTheme.colorScheme.surfaceContainerHighest, + onContainer = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + if (summary.failed > 0) { + ResultStatCard( + count = summary.failed, + label = stringResource(R.string.import_done_failed_label), + contentDescription = pluralStringResource(R.plurals.import_done_failed, summary.failed, summary.failed), + container = MaterialTheme.colorScheme.errorContainer, + onContainer = MaterialTheme.colorScheme.onErrorContainer, + ) + } + } +} + +/** A big-number tonal tile summarising one outcome. */ +@Composable +private fun RowScope.ResultStatCard( + count: Int, + label: String, + contentDescription: String, + container: Color, + onContainer: Color, +) { + Surface( + modifier = Modifier + .weight(1f) + .clearAndSetSemantics { this.contentDescription = contentDescription }, + shape = RoundedCornerShape(24.dp), + color = container, + ) { + Column( + Modifier.padding(vertical = 20.dp, horizontal = 12.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + Text(count.toString(), style = MaterialTheme.typography.displaySmall, color = onContainer) + Text(label, style = MaterialTheme.typography.labelLarge, color = onContainer.copy(alpha = 0.85f)) + } + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SelectionTopBar.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SelectionTopBar.kt index d9d69b71..6d1c6f94 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SelectionTopBar.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SelectionTopBar.kt @@ -18,6 +18,7 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.domain.EventInstance +import de.jeanlucmakiola.floret.locale.capitalizeStart import de.jeanlucmakiola.floret.locale.currentLocale import de.jeanlucmakiola.floret.locale.localizedDateFormatter import java.time.ZoneId @@ -92,5 +93,5 @@ private fun formatSelectionWhen(event: EventInstance, use24Hour: Boolean, locale "${day.format(start)} · ${time.format(start)}–${time.format(end)}" } else { "${day.format(start)}, ${time.format(start)} – ${day.format(end)}, ${time.format(end)}" - } + }.capitalizeStart(locale) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt new file mode 100644 index 00000000..2863d769 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncAccessPicker.kt @@ -0,0 +1,153 @@ +package de.jeanlucmakiola.calendula.ui.common + +import kotlinx.coroutines.flow.combine +import de.jeanlucmakiola.calendula.data.calendar.SyncRequestResult +import androidx.compose.runtime.snapshotFlow +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.MutableState +import android.content.ActivityNotFoundException +import android.util.Log +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.DrawerState +import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi +import androidx.compose.material3.LoadingIndicator +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.DrawerValue +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LifecycleEventEffect +import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.data.calendar.SyncAccount +import de.jeanlucmakiola.calendula.data.calendar.accountAccessIntent +import de.jeanlucmakiola.floret.components.FullScreenPicker +import de.jeanlucmakiola.floret.components.GroupedHint +import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.Position +import de.jeanlucmakiola.floret.components.positionOf + +/** + * Launches the system account picker for an account sync requests can't reach + * yet (#240), one launch at a time. Access is re-read on every resume, which covers + * the picker's return and grants or revokes made in system settings. + */ +@Composable +fun rememberSyncAccessPicker(sync: SyncViewModel): (SyncAccount) -> Unit { + var open by remember { mutableStateOf(false) } + val launcher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { + open = false + } + LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { sync.refreshAccess() } + val description = stringResource(R.string.sync_access_picker_description) + return remember(launcher, description) { + { account -> + if (!open) { + try { + launcher.launch(accountAccessIntent(account, description)) + open = true + } catch (e: ActivityNotFoundException) { + Log.w("SyncAccessPicker", "No account picker", e) + } + } + } + } +} + +/** Re-reads account access whenever [drawerState] opens; the app may stay resumed in multi-window. */ +@Composable +fun RefreshSyncAccessOnOpen(drawerState: DrawerState, sync: SyncViewModel) { + LaunchedEffect(drawerState.targetValue) { + if (drawerState.targetValue == DrawerValue.Open) sync.refreshAccess() + } +} + +/** + * Routes "Sync now"'s outcome (#240): one that lands while the drawer is open + * shows in its row and is dropped when the drawer closes; one that lands while + * it is closed is handed to the returned state, for the chip. + */ +@Composable +fun rememberSyncChipOutcome(drawerState: DrawerState, sync: SyncViewModel): MutableState { + val chip = rememberSaveable { mutableStateOf(null) } + LaunchedEffect(drawerState, sync) { + var shownInRow = false + combine(sync.result, snapshotFlow { drawerState.targetValue == DrawerValue.Closed }) { result, closed -> + result to closed + }.collect { (result, closed) -> + when { + result == null -> shownInRow = false + !closed -> shownInRow = true + else -> { + if (!shownInRow) chip.value = result + shownInRow = false + sync.consumeResult() + } + } + } + } + return chip +} + +/** + * The accounts sync requests can't reach yet (#240), one row each: tapping one + * opens the system picker for just that account, "Don't ask" stops offering it. + * Closes itself once no account is left. + */ +@OptIn(ExperimentalMaterial3ExpressiveApi::class) +@Composable +fun SyncAccessSheet( + accounts: List?, + onGrant: (SyncAccount) -> Unit, + onDismissAccount: (SyncAccount) -> Unit, + onDismiss: () -> Unit, +) { + LaunchedEffect(accounts?.isEmpty()) { if (accounts?.isEmpty() == true) onDismiss() } + FullScreenPicker(title = stringResource(R.string.drawer_sync_access), onDismiss = onDismiss, predictiveBack = true) { + GroupedHint(stringResource(R.string.sync_access_hint), verticalPadding = 8.dp) + if (accounts == null) { + Box(Modifier.fillMaxWidth().padding(24.dp), contentAlignment = Alignment.Center) { LoadingIndicator() } + } + accounts.orEmpty().forEachIndexed { index, account -> + SyncAccountRow( + account = account, + position = positionOf(index, accounts.orEmpty().size), + actionLabel = stringResource(R.string.sync_access_dont_ask), + onAction = { onDismissAccount(account) }, + onClick = { onGrant(account) }, + ) + } + } +} + +/** One synced account with a text action, as the access sheet and the calendar manager list them. */ +@Composable +fun SyncAccountRow( + account: SyncAccount, + position: Position, + actionLabel: String, + onAction: () -> Unit, + onClick: (() -> Unit)? = null, +) { + GroupedRow( + title = account.name, + summary = sourceAppName(account.type), + position = position, + minHeight = 64.dp, + leading = { SourceLogo(account.type) }, + trailing = { TextButton(onClick = onAction) { Text(actionLabel) } }, + onClick = onClick, + ) +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt new file mode 100644 index 00000000..bcb2f9e8 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModel.kt @@ -0,0 +1,107 @@ +package de.jeanlucmakiola.calendula.ui.common + +import android.util.Log +import androidx.annotation.StringRes +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import dagger.hilt.android.lifecycle.HiltViewModel +import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository +import de.jeanlucmakiola.calendula.data.calendar.SyncAccount +import de.jeanlucmakiola.calendula.data.calendar.SyncRequestResult +import de.jeanlucmakiola.calendula.data.calendar.SyncTargets +import de.jeanlucmakiola.calendula.data.calendar.SyncWait +import de.jeanlucmakiola.floret.android.stateWhileSubscribed +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.retryWhen +import kotlinx.coroutines.launch +import javax.inject.Inject + +/** + * The drawer's "Sync now" (#240): asks the sync adapters of every visible synced + * calendar to run now, then follows them through the system's sync state. + * [inFlight] holds until every reached account has synced or the wait gives up; + * [result] then says [SyncRequestResult.Completed] only when that was seen. + */ +@HiltViewModel +class SyncViewModel @Inject constructor( + private val repository: CalendarRepository, +) : ViewModel() { + + /** Who "Sync now" can reach, and who first needs the user's grant; null until first read. */ + val targets: StateFlow = repository.syncTargets + // A failed read hides the rows for now, then reads again rather than for good. + .retryWhen { e, attempt -> + if (e is CancellationException) return@retryWhen false + emit(SyncTargets.None) + delay((RETRY_BASE_MILLIS shl attempt.coerceAtMost(5).toInt()).coerceAtMost(RETRY_MAX_MILLIS)) + true + } + .stateWhileSubscribed(scope = viewModelScope, initialValue = null) + + /** Re-read account access: on resume (which includes the picker returning) and drawer open. */ + fun refreshAccess() = repository.refreshSyncAccess() + + private val _inFlight = MutableStateFlow(false) + val inFlight: StateFlow = _inFlight.asStateFlow() + + private val _result = MutableStateFlow(null) + + /** The last request's outcome, until [consumeResult]. */ + val result: StateFlow = _result.asStateFlow() + + fun requestSync() { + if (_inFlight.value) return + _inFlight.value = true + _result.value = null + viewModelScope.launch { + try { + val request = repository.requestSync() + val waited = if (request.accounts.isEmpty()) null else repository.awaitSyncs(request.accounts) + _result.value = if (waited == SyncWait.Completed && request.result == SyncRequestResult.Requested) { + SyncRequestResult.Completed + } else { + request.result + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Sync now failed", e) + _result.value = SyncRequestResult.Failed + } finally { + _inFlight.value = false + } + } + } + + /** Stop asking for [account]'s access (#240); undone from the calendar manager. */ + fun dismissAccess(account: SyncAccount) { + viewModelScope.launch { repository.setSyncAccessDismissed(account, dismissed = true) } + } + + fun consumeResult() { + _result.value = null + } + + private companion object { + const val RETRY_BASE_MILLIS = 1_000L + const val RETRY_MAX_MILLIS = 30_000L + const val TAG = "SyncViewModel" + } +} + +/** The text for a sync request's outcome, in the drawer row or the chip. */ +@StringRes +fun SyncRequestResult.messageRes(): Int = when (this) { + SyncRequestResult.Requested -> R.string.sync_requested + SyncRequestResult.Completed -> R.string.sync_completed + SyncRequestResult.PartlyFailed -> R.string.sync_request_partly_failed + SyncRequestResult.NeedsAccess -> R.string.sync_request_needs_access + SyncRequestResult.SomeNeedAccess -> R.string.sync_request_some_need_access + SyncRequestResult.NothingToSync -> R.string.sync_nothing_to_sync + SyncRequestResult.Failed -> R.string.sync_request_failed +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/ViewHiddenCalendars.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/ViewHiddenCalendars.kt new file mode 100644 index 00000000..d78e880b --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/ViewHiddenCalendars.kt @@ -0,0 +1,63 @@ +package de.jeanlucmakiola.calendula.ui.common + +import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository +import de.jeanlucmakiola.calendula.domain.EventInstance +import de.jeanlucmakiola.calendula.domain.withoutCalendars +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.retryWhen +import kotlinx.coroutines.flow.shareIn +import java.io.IOException +import kotlin.time.Instant + +/** The calendars hidden in [view] under a per-calendar hidden-views map (#270). */ +fun Map>.calendarsHiddenIn(view: CalendarView): Set = + filterValues { view in it }.keys + +/** + * The calendars hidden in [view], shared by everything one view model shows so + * the setting is read once rather than per page. A failed read hides nothing + * rather than failing the view; the replay expires with the last subscriber, so + * a returning view filters against a fresh read. + */ +fun Flow>>.calendarsHiddenIn( + view: CalendarView, + scope: CoroutineScope, +): Flow> = + hidingNothingOnError() + .map { it.calendarsHiddenIn(view) } + .distinctUntilChanged() + // The grace period outlasts a flatMapLatest swap, so paging doesn't re-read it. + .shareIn(scope, SharingStarted.WhileSubscribed(5_000, replayExpirationMillis = 0), replay = 1) + +/** + * A failed read of the per-view setting hides nothing rather than failing what + * shows it, and keeps reading, so the next change still lands. + */ +fun Flow>>.hidingNothingOnError(): Flow>> = + retryWhen { cause, attempt -> + if (cause !is IOException) return@retryWhen false + emit(emptyMap()) + // Backs off, so a file that keeps failing (corrupt) isn't re-read every second. + delay((RETRY_BASE_DELAY_MS shl attempt.coerceAtMost(6).toInt()).coerceAtMost(RETRY_MAX_DELAY_MS)) + true + } + +private const val RETRY_BASE_DELAY_MS = 1_000L +private const val RETRY_MAX_DELAY_MS = 60_000L + +/** + * [CalendarRepository.instances] as one view shows them: also without the + * [hidden] calendars the user keeps out of it. Display only — reminders, search + * and widgets read the repository directly. + */ +fun CalendarRepository.instancesWithout( + range: ClosedRange, + hidden: Flow>, +): Flow> = + combine(instances(range), hidden) { instances, ids -> instances.withoutCalendars(ids) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailScreen.kt index fc723aca..50592f52 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailScreen.kt @@ -90,6 +90,7 @@ import de.jeanlucmakiola.calendula.domain.timeZoneOptionOf import de.jeanlucmakiola.calendula.domain.zoneDescriptor import de.jeanlucmakiola.calendula.domain.zoneOrNull import de.jeanlucmakiola.calendula.ui.common.orUnnamed +import de.jeanlucmakiola.floret.android.mapsSearchIntents import de.jeanlucmakiola.floret.components.IconInfoCard import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme import de.jeanlucmakiola.floret.identity.predictiveBack @@ -103,11 +104,13 @@ import de.jeanlucmakiola.calendula.ui.common.rememberFieldCopier import de.jeanlucmakiola.calendula.ui.common.icuTimeZoneRegion import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors import de.jeanlucmakiola.calendula.ui.common.eventAccent +import de.jeanlucmakiola.floret.locale.capitalizeStart import de.jeanlucmakiola.floret.locale.currentLocale import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat import de.jeanlucmakiola.calendula.ui.common.timeOfDayFormatter import de.jeanlucmakiola.calendula.ui.common.withRepeatedHourZone import de.jeanlucmakiola.calendula.ui.common.recurrenceText +import de.jeanlucmakiola.calendula.ui.common.fixedTimeReminderLabel import de.jeanlucmakiola.calendula.ui.common.reminderLeadTimeLabel import kotlinx.coroutines.launch import kotlinx.datetime.TimeZone @@ -140,6 +143,7 @@ fun EventDetailScreen( onEdit: () -> Unit, onDuplicate: (EventForm) -> Unit, visible: Boolean = true, + backEnabled: Boolean = true, viewModel: EventDetailViewModel = hiltViewModel(), ) { LaunchedEffect(eventId, beginMillis, endMillis) { @@ -196,7 +200,7 @@ fun EventDetailScreen( } Scaffold( - modifier = Modifier.predictiveBack(onBack = onBack, visible = visible), + modifier = Modifier.predictiveBack(onBack = onBack, enabled = backEnabled, visible = visible), snackbarHost = { SnackbarHost(snackbarHostState) }, topBar = { TopAppBar( @@ -532,7 +536,8 @@ private fun EventDetailContent( .sortedBy { it.minutes } .forEach { reminder -> Text( - text = reminderLeadTimeLabel(reminder.minutes), + text = state.fixedReminders[reminder.minutes]?.let { fixedTimeReminderLabel(it) } + ?: reminderLeadTimeLabel(reminder.minutes), style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(vertical = 2.dp), ) @@ -845,7 +850,7 @@ private fun formatWhen( val startDate = instance.start.toJavaLocalDateTime(utc).toLocalDate() val lastDate = (instance.end - 1.seconds).toJavaLocalDateTime(utc).toLocalDate() return if (startDate == lastDate) { - allDayLabel to dateFull.format(startDate) + allDayLabel to dateFull.format(startDate).capitalizeStart(locale) } else { allDayLabel to "${dateMedium.format(startDate)} – ${dateMedium.format(lastDate)}" } @@ -855,7 +860,7 @@ private fun formatWhen( val startTime = withRepeatedHourZone(timeShort.format(startLdt), instance.start, zone, locale) val endTime = withRepeatedHourZone(timeShort.format(endLdt), instance.end, zone, locale) return if (startLdt.toLocalDate() == endLdt.toLocalDate()) { - dateFull.format(startLdt.toLocalDate()) to "$startTime – $endTime" + dateFull.format(startLdt.toLocalDate()).capitalizeStart(locale) to "$startTime – $endTime" } else { val start = "${dateMedium.format(startLdt.toLocalDate())} $startTime" val end = "${dateMedium.format(endLdt.toLocalDate())} $endTime" @@ -884,9 +889,6 @@ private fun startOrSayNoApp(context: Context, intent: Intent) { /** Open a maps intent for [query]; fall back to a web maps URL if no app handles geo:. */ private fun openInMaps(context: Context, query: String) { - val encoded = Uri.encode(query) - val geo = Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=$encoded")) - if (runCatching { context.startActivity(geo) }.isFailure) { - openWebLink(context, "https://www.google.com/maps/search/?api=1&query=$encoded") - } + val opened = mapsSearchIntents(query).any { runCatching { context.startActivity(it) }.isSuccess } + if (!opened) Toast.makeText(context, R.string.link_open_failed, Toast.LENGTH_SHORT).show() } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailUiState.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailUiState.kt index 18c278cf..6fe0ecd3 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailUiState.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailUiState.kt @@ -3,6 +3,7 @@ package de.jeanlucmakiola.calendula.ui.detail import de.jeanlucmakiola.calendula.domain.EventDetail import de.jeanlucmakiola.calendula.domain.FailureReason import de.jeanlucmakiola.calendula.domain.RichText +import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder /** * UI state for the event-detail screen (spec S4). @@ -26,6 +27,10 @@ sealed interface EventDetailUiState { val phoneLinks: EventPhoneLinks = EventPhoneLinks(), /** The description as drawn — HTML rendered (#271); null when there is none. */ val description: RichText? = null, + /** Reminder offsets that read as "N days before at HH:MM" (#459), by raw minutes. */ + val fixedReminders: Map = emptyMap(), + /** The fixed-time patterns the reminders were read against. */ + val knownFixed: Set = emptySet(), ) : EventDetailUiState } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailViewModel.kt index 066ad4ad..ec0b14eb 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailViewModel.kt @@ -1,5 +1,7 @@ package de.jeanlucmakiola.calendula.ui.detail +import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs +import de.jeanlucmakiola.calendula.domain.reminders.classifyTimedReminder import android.net.Uri import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope @@ -46,6 +48,7 @@ class EventDetailViewModel @Inject constructor( private val icsExporter: IcsExporter, @IoDispatcher private val io: CoroutineDispatcher, private val zoneSource: ZoneSource, + private val settingsPrefs: SettingsPrefs, ) : ViewModel() { private val _target = MutableStateFlow(null) @@ -142,7 +145,7 @@ class EventDetailViewModel @Inject constructor( */ fun duplicateForm(): EventForm? { val loaded = state.value as? EventDetailUiState.Success ?: return null - return loaded.detail.toDuplicateForm(loaded.canModify, zoneSource.current()) + return loaded.detail.toDuplicateForm(zoneSource.current(), loaded.knownFixed) } private suspend fun loadDetail(target: Target): EventDetailUiState = try { @@ -157,6 +160,17 @@ class EventDetailViewModel @Inject constructor( } val calendar = repository.calendars().first() .firstOrNull { it.id == corrected.instance.calendarId } + val knownFixed = settingsPrefs.knownFixedTimeReminders.first() + val fixedReminders = if (corrected.instance.isAllDay) { + emptyMap() + } else { + val zone = zoneSource.current() + corrected.reminders.map { it.minutes }.distinct().mapNotNull { minutes -> + classifyTimedReminder( + minutes, corrected.instance.start, zone, knownFixed, wallClock = corrected.rrule != null, + )?.let { minutes to it } + }.toMap() + } val description = corrected.description ?.let(::descriptionRichText) ?.takeIf { it.text.isNotBlank() } @@ -173,6 +187,8 @@ class EventDetailViewModel @Inject constructor( description = description?.text, ), description = description, + fixedReminders = fixedReminders, + knownFixed = knownFixed, ) } catch (e: CancellationException) { throw e diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/edit/EventEditScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/edit/EventEditScreen.kt index 86e70e55..356e6f68 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/edit/EventEditScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/edit/EventEditScreen.kt @@ -125,6 +125,10 @@ import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.EventAttendee import de.jeanlucmakiola.calendula.domain.EventColorOption import de.jeanlucmakiola.calendula.domain.EventForm +import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder +import de.jeanlucmakiola.calendula.ui.common.DEFAULT_FIXED_TIME_REMINDER +import de.jeanlucmakiola.calendula.ui.common.FixedTimeReminderEditor +import de.jeanlucmakiola.calendula.ui.common.fixedTimeReminderLabel import de.jeanlucmakiola.calendula.domain.startInstant import de.jeanlucmakiola.calendula.domain.endInstant import de.jeanlucmakiola.calendula.domain.resolvedZone @@ -153,6 +157,7 @@ import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors import de.jeanlucmakiola.calendula.ui.common.eventAccent import de.jeanlucmakiola.calendula.ui.common.eventFill import de.jeanlucmakiola.floret.components.DialogAmountField +import de.jeanlucmakiola.floret.components.GroupedHint import de.jeanlucmakiola.floret.components.DialogUnitDropdown import de.jeanlucmakiola.calendula.ui.common.eventFormFieldIcon import de.jeanlucmakiola.calendula.ui.common.eventFormFieldLabel @@ -165,9 +170,12 @@ import de.jeanlucmakiola.floret.components.OptionPicker import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.groupedShape as floretGroupedShape import de.jeanlucmakiola.floret.components.positionOf -import de.jeanlucmakiola.calendula.ui.common.REMINDER_PRESETS +import de.jeanlucmakiola.calendula.ui.common.reminderPresets +import de.jeanlucmakiola.calendula.ui.common.customReminderUnits +import de.jeanlucmakiola.calendula.ui.common.customReminderPlaceholder +import de.jeanlucmakiola.calendula.ui.common.splitsSubDay +import de.jeanlucmakiola.calendula.ui.common.GroupedLeadTimeRows import de.jeanlucmakiola.calendula.ui.common.TimePickerAlert -import de.jeanlucmakiola.floret.reminders.ReminderUnit import de.jeanlucmakiola.floret.locale.currentLocale import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat import de.jeanlucmakiola.calendula.ui.common.formatTimeOfDay @@ -874,8 +882,10 @@ private fun EventEditContent( OptionalFormSection(visible = EventFormField.Reminders in state.visibleFields) { Spacer(Modifier.height(gap)) RemindersSection( - reminders = form.reminders, + reminders = form.firingReminders(), + fixedReminders = if (form.isAllDay) emptyList() else form.fixedReminders, onRemove = viewModel::removeReminder, + onRemoveFixed = viewModel::removeFixedReminder, onAdd = { sheet = EditSheet.Reminder }, ) } @@ -1284,9 +1294,25 @@ private fun LocationCard( * connected corners, the last row being "Add reminder". */ @Composable -private fun RemindersSection(reminders: List, onRemove: (Int) -> Unit, onAdd: () -> Unit) { - val rows = reminders.size + 1 - reminders.forEachIndexed { index, minutes -> +private fun RemindersSection( + reminders: List, + fixedReminders: List, + onRemove: (Int) -> Unit, + onRemoveFixed: (FixedTimeReminder) -> Unit, + onAdd: () -> Unit, +) { + val rows = fixedReminders.size + reminders.size + 1 + fixedReminders.forEachIndexed { index, reminder -> + GroupedItemCard( + position = positionOf(index, rows), + icon = Icons.Default.Notifications, + title = fixedTimeReminderLabel(reminder), + removeContentDescription = stringResource(R.string.event_edit_remove_reminder), + onRemove = { onRemoveFixed(reminder) }, + ) + } + reminders.forEachIndexed { i, minutes -> + val index = fixedReminders.size + i GroupedItemCard( position = positionOf(index, rows), icon = Icons.Default.Notifications, @@ -1297,7 +1323,7 @@ private fun RemindersSection(reminders: List, onRemove: (Int) -> Unit, onAd } AddActionCard( label = stringResource(R.string.event_edit_add_reminder), - position = positionOf(reminders.size, rows), + position = positionOf(rows - 1, rows), onClick = onAdd, ) } @@ -1488,11 +1514,17 @@ private fun EditSheetHost( ) } EditSheet.Reminder -> ReminderPickerDialog( - alreadyChosen = form.reminders, + isAllDay = form.isAllDay, + alreadyChosen = form.firingReminders(), + offerFixedTime = !form.isAllDay, onSelect = { minutes -> viewModel.addReminder(minutes) onClose() }, + onSelectFixed = { reminder -> + viewModel.addFixedReminder(reminder) + onClose() + }, onDismiss = onClose, ) EditSheet.Recurrence -> RecurrencePickerDialog( @@ -1580,13 +1612,20 @@ private fun FieldPickerDialog( @OptIn(ExperimentalMaterial3Api::class) @Composable private fun ReminderPickerDialog( + isAllDay: Boolean, alreadyChosen: List, + offerFixedTime: Boolean, onSelect: (Int) -> Unit, + onSelectFixed: (FixedTimeReminder) -> Unit, onDismiss: () -> Unit, ) { var customMode by rememberSaveable { mutableStateOf(false) } + var fixedMode by rememberSaveable { mutableStateOf(false) } + var pendingFixed by remember { mutableStateOf(null) } var amountText by rememberSaveable { mutableStateOf("") } - var unit by rememberSaveable { mutableStateOf(ReminderUnit.Minutes) } + val units = customReminderUnits(isAllDay) + var pickedUnit by rememberSaveable { mutableStateOf(units.first()) } + val unit = pickedUnit.takeIf { it in units } ?: units.first() val customMinutes = amountText.toIntOrNull() ?.takeIf { it in 1..999 } ?.let { it * unit.minutesFactor } @@ -1595,29 +1634,55 @@ private fun ReminderPickerDialog( title = stringResource(R.string.event_edit_add_reminder), onDismiss = onDismiss, actions = { - // The quick-pick list adds on tap; only the custom step needs Add. + // The quick-pick list adds on tap; only the custom steps need Add. if (customMode) { TextButton( enabled = customMinutes != null && customMinutes !in alreadyChosen, onClick = { customMinutes?.let(onSelect) }, ) { Text(stringResource(R.string.event_edit_add)) } + } else if (fixedMode) { + TextButton( + enabled = pendingFixed != null, + onClick = { pendingFixed?.let(onSelectFixed) }, + ) { Text(stringResource(R.string.event_edit_add)) } } }, ) { - if (!customMode) { - val presets = REMINDER_PRESETS.filterNot { it in alreadyChosen } - val rowCount = presets.size + 1 - presets.forEachIndexed { index, minutes -> - GroupedRow( - title = reminderLeadTimeLabel(minutes), - position = positionOf(index, rowCount), - onClick = { onSelect(minutes) }, - ) - } - GroupedRow( - title = stringResource(R.string.event_edit_reminder_custom), - position = positionOf(rowCount - 1, rowCount), - onClick = { customMode = true }, + if (fixedMode) { + GroupedHint(text = stringResource(R.string.event_edit_reminder_fixed_hint)) + Spacer(Modifier.height(8.dp)) + FixedTimeReminderEditor( + initial = DEFAULT_FIXED_TIME_REMINDER, + onValueChange = { pendingFixed = it }, + connected = false, + ) + } else if (!customMode) { + val presets = reminderPresets(isAllDay) + GroupedLeadTimeRows( + minutes = presets.filterNot { it in alreadyChosen }, + splitSubDay = splitsSubDay(presets), + row = { minutes, position -> + GroupedRow( + title = reminderLeadTimeLabel(minutes), + position = position, + onClick = { onSelect(minutes) }, + ) + }, + trailing = { position -> + if (offerFixedTime) { + GroupedRow( + title = stringResource(R.string.reminder_fixed_at_set_time), + summary = stringResource(R.string.event_edit_reminder_fixed_summary), + position = if (position == Position.Alone) Position.Top else Position.Middle, + onClick = { fixedMode = true }, + ) + } + GroupedRow( + title = stringResource(R.string.event_edit_reminder_custom), + position = if (offerFixedTime) Position.Bottom else position, + onClick = { customMode = true }, + ) + }, ) } else { Row( @@ -1627,13 +1692,13 @@ private fun ReminderPickerDialog( DialogAmountField( value = amountText, onValueChange = { amountText = it }, - placeholder = "10", + placeholder = customReminderPlaceholder(unit), ) Spacer(Modifier.width(12.dp)) DialogUnitDropdown( label = stringResource(reminderUnitLabel(unit)), - entries = ReminderUnit.entries.map { stringResource(reminderUnitLabel(it)) }, - onPick = { unit = ReminderUnit.entries[it] }, + entries = units.map { stringResource(reminderUnitLabel(it)) }, + onPick = { pickedUnit = units[it] }, ) } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/edit/EventEditUiState.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/edit/EventEditUiState.kt index f96ee377..256d9a5c 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/edit/EventEditUiState.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/edit/EventEditUiState.kt @@ -12,7 +12,7 @@ import de.jeanlucmakiola.calendula.domain.RecurringWriteScope * form means the screen hasn't been opened yet. */ data class EventEditUiState( - /** The form with its calendar id resolved (picked > last used > first writable). */ + /** The form with its calendar id resolved, see [de.jeanlucmakiola.calendula.domain.resolveEventCalendar]. */ val form: EventForm, /** Calendars that accept writes — the only valid targets. */ val calendars: List, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/edit/EventEditViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/edit/EventEditViewModel.kt index 5235cb7b..79f487ab 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/edit/EventEditViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/edit/EventEditViewModel.kt @@ -7,13 +7,20 @@ import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository import de.jeanlucmakiola.calendula.data.calendar.NoSuchEventException +import de.jeanlucmakiola.calendula.data.calendar.wholeDayLeadMinutes +import de.jeanlucmakiola.calendula.data.calendar.wholeDayLeadTimes import de.jeanlucmakiola.calendula.data.ics.IcsExporter import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.data.time.ZoneSource import de.jeanlucmakiola.calendula.data.prefs.firstDayOfWeek import de.jeanlucmakiola.calendula.data.prefs.resolveDefaultEventDuration +import de.jeanlucmakiola.calendula.data.prefs.resolveDefaultFixedTimeReminder import de.jeanlucmakiola.calendula.data.prefs.resolveDefaultReminder +import de.jeanlucmakiola.calendula.domain.reminders.FIXED_ORDER +import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder +import de.jeanlucmakiola.calendula.domain.fixedReminderOffsets +import de.jeanlucmakiola.calendula.domain.withFixedTimeRemindersRead import de.jeanlucmakiola.calendula.domain.canSaveApartFromSeries import de.jeanlucmakiola.calendula.domain.AccessLevel import de.jeanlucmakiola.calendula.domain.Availability @@ -33,6 +40,8 @@ import de.jeanlucmakiola.calendula.domain.withStart import de.jeanlucmakiola.calendula.domain.withTimes import de.jeanlucmakiola.calendula.domain.withTimezone import de.jeanlucmakiola.calendula.domain.EventFormField +import de.jeanlucmakiola.calendula.domain.NewEventCalendarHints +import de.jeanlucmakiola.calendula.domain.resolveEventCalendar import de.jeanlucmakiola.calendula.domain.RecurringWriteScope import de.jeanlucmakiola.calendula.domain.atOccurrence import de.jeanlucmakiola.calendula.domain.isEventTarget @@ -139,12 +148,13 @@ enum class ImportSource(internal val ownsDuration: Boolean) { data class ImportReminderPrompt( val currentReminderCount: Int, val defaultReminders: List, + val defaultFixedReminders: List = emptyList(), ) /** - * Holds the event form being composed. The form's calendar id resolves to - * (user pick > last used > first writable); the resolved value is what the UI - * shows and what gets saved. + * Holds the event form being composed. The form's calendar id resolves through + * [resolveEventCalendar] (user pick > requested > default > last used > first + * target); the resolved value is what the UI shows and what gets saved. */ @HiltViewModel class EventEditViewModel @Inject constructor( @@ -181,6 +191,9 @@ class EventEditViewModel @Inject constructor( // A one-time offer, raised when a .ics import opens, to replace the file's // reminders with the settings default (#49). Null while there's nothing to ask. private val _importReminderPrompt = MutableStateFlow(null) + // A calendar named by an insert intent or a duplicate's source (#429); wins + // over the default calendar while it is an event target. + private val _requestedCalendarId = MutableStateFlow(null) // The form as the user received it: the loaded event, or a new form with its // prefill and auto-applied defaults. Anything else is an unsaved change. private val _baseline = MutableStateFlow(null) @@ -208,6 +221,8 @@ class EventEditViewModel @Inject constructor( val zone: TimeZone, /** The event as loaded, on the tapped occurrence's times — what Share exports. */ val detail: EventDetail, + /** The fixed-time patterns its reminders were read against, so a re-read splits alike. */ + val knownFixed: Set, ) { val original: EventForm get() = snapshot.form } @@ -225,7 +240,13 @@ class EventEditViewModel @Inject constructor( val allDay: List, val timedOverrides: Map>, val allDayOverrides: Map>, + val fixed: FixedTimeReminder?, + val fixedOverrides: Map, ) { + /** The fixed-time reminders a new event on [calendarId] gets (#459); none on an all-day one. */ + fun resolveFixedFor(calendarId: Long?, isAllDay: Boolean): List = + if (isAllDay) emptyList() else listOfNotNull(resolveDefaultFixedTimeReminder(fixed, fixedOverrides, calendarId)) + /** The default reminders for an event on [calendarId] of the given kind. */ fun resolveFor(calendarId: Long?, isAllDay: Boolean): List = resolveDefaultReminder( timedGlobal = timed, @@ -239,7 +260,7 @@ class EventEditViewModel @Inject constructor( private data class ExternalInputs( val writable: List, - val lastUsed: Long?, + val hints: NewEventCalendarHints, val defaultFields: Set, val allowColorOnUnsupported: Boolean, val autofocusTitle: Boolean, @@ -252,8 +273,8 @@ class EventEditViewModel @Inject constructor( /** * The calendars a new event can be saved to ([isEventTarget]): writable, * switched on, not a contact-filled mirror, not a non-syncing subscription. - * A last-used preselect landing on an excluded calendar falls back to the - * first remaining one (handled by [resolvedCalendarId] and [state]). + * A preselect landing on an excluded calendar falls back as + * [resolveEventCalendar] describes. * * This is the list of *targets*. An event already living in an excluded * calendar keeps it — [state] adds it back to the picker. @@ -262,16 +283,20 @@ class EventEditViewModel @Inject constructor( calendars.filter { it.isEventTarget } } + private val calendarHints: Flow = combine( + _requestedCalendarId, + settingsPrefs.defaultNewEventCalendar, + prefs.lastUsedCalendarId, + ::NewEventCalendarHints, + ) + /** The target calendar id, resolved exactly as the form shows it. */ private val resolvedCalendarId: Flow = combine( _form.map { it?.calendarId }, - writableCalendars, - prefs.lastUsedCalendarId, - ) { picked, writable, lastUsed -> - picked - ?: lastUsed?.takeIf { id -> writable.any { it.id == id } } - ?: writable.firstOrNull()?.id - }.distinctUntilChanged() + calendarHints, + allCalendars, + ::resolveEventCalendar, + ).distinctUntilChanged() /** The resolved calendar's published event palette, refetched when it changes. */ @OptIn(ExperimentalCoroutinesApi::class) @@ -285,7 +310,7 @@ class EventEditViewModel @Inject constructor( combine(_form, _saveState, _showProblems, _revealed, _editTarget, ::LocalInputs), combine( writableCalendars, - prefs.lastUsedCalendarId, + calendarHints, settingsPrefs.defaultFormFields, settingsPrefs.allowColorOnUnsupportedCalendars, settingsPrefs.autofocusEventTitle, @@ -296,10 +321,14 @@ class EventEditViewModel @Inject constructor( settingsPrefs.recentTimeZones.flowOn(io), ) { local, external, palette, allCalendars, recentTimeZones -> val form = local.form ?: return@combine null - val resolvedId = form.calendarId - ?: external.lastUsed?.takeIf { id -> external.writable.any { it.id == id } } - ?: external.writable.firstOrNull()?.id - val resolved = form.copy(calendarId = resolvedId) + val resolvedId = resolveEventCalendar(form.calendarId, external.hints, allCalendars) + // A colour is scoped to the calendar it came from, so one that came with + // a requested calendar the form couldn't take goes, as on [setCalendar]. + val requestRefused = form.calendarId == null && resolvedId != null && + external.hints.requested.let { it != null && it != resolvedId } + val resolved = form.copy(calendarId = resolvedId).let { + if (requestRefused) it.copy(colorKey = null, color = null) else it + } val resolvedCalendar = allCalendars.firstOrNull { it.id == resolvedId } // Editing an event in a managed calendar locks its synced fields. Keyed // off the calendar's durable marker, not a stored id, so it holds after a @@ -407,8 +436,9 @@ class EventEditViewModel @Inject constructor( * Seed a fresh event from a prefilled [form] — a parsed single-event `.ics` * file ([ImportSource.File]) or an external `ACTION_INSERT` intent (another * app/widget creating an event, e.g. Google Maps' "add to calendar"; - * [ImportSource.Insert]; #30, #49). [EventForm.calendarId] is null so the - * calendar still resolves to the last-used/first-writable one. + * [ImportSource.Insert]; #30, #49). A set [EventForm.calendarId] is the + * calendar the caller asked for: it is preselected while it is an event + * target, and the form otherwise resolves its calendar like a new event (#429). * * Reminders are handled per [source], because the two paths mean different * things by "no reminders": @@ -431,17 +461,18 @@ class EventEditViewModel @Inject constructor( fun openImported(form: EventForm, source: ImportSource) { if (_form.value != null || _editTarget.value != null) return _revealed.value = form.populatedFields() - open(form) + _requestedCalendarId.value = form.calendarId + open(form.copy(calendarId = null)) if (source.ownsDuration) _durationTouched.value = true else applyDefaultDuration() when (source) { ImportSource.Insert, ImportSource.InsertOpenEnded -> - if (form.reminders.isNotEmpty()) _remindersTouched.value = true + if (form.reminders.isNotEmpty() || form.fixedReminders.isNotEmpty()) _remindersTouched.value = true else applyDefaultReminder() ImportSource.File -> { // Respect the file's own reminders; never silently overwrite them. _remindersTouched.value = true - maybePromptImportedReminderDefault(form) + maybePromptImportedReminderDefault() } } } @@ -465,27 +496,35 @@ class EventEditViewModel @Inject constructor( val form = _form.value ?: return@launch if (_editTarget.value != null || _remindersTouched.value) return@launch val reminders = defaults.resolveFor(targetId, form.isAllDay) + val fixed = defaults.resolveFixedFor(targetId, form.isAllDay) // The duration default resolves in parallel, so both must compose // onto the current form, not a pre-suspend copy. - applyDefault { it.copy(reminders = reminders) } + applyDefault { it.copy(reminders = reminders, fixedReminders = fixed) } // Surface the section so an auto-applied default is visible and // removable, even when Reminders isn't a default-shown field. - if (reminders.isNotEmpty()) { + if (reminders.isNotEmpty() || fixed.isNotEmpty()) { _revealed.value = _revealed.value + EventFormField.Reminders } } } - /** Snapshot the four settings-default reminder flows into one value. */ + /** Snapshot the settings-default reminder flows into one value. */ private suspend fun reminderDefaults(): ReminderDefaults = combine( - settingsPrefs.defaultReminderMinutes, - settingsPrefs.defaultAllDayReminderMinutes, - settingsPrefs.perCalendarReminderOverride, - settingsPrefs.perCalendarAllDayReminderOverride, - ) { timed, allDay, timedOv, allDayOv -> - ReminderDefaults(timed, allDay, timedOv, allDayOv) + combine( + settingsPrefs.defaultReminderMinutes, + settingsPrefs.defaultAllDayReminderMinutes, + settingsPrefs.perCalendarReminderOverride, + settingsPrefs.perCalendarAllDayReminderOverride, + ::Quadruple, + ), + settingsPrefs.defaultFixedTimeReminder, + settingsPrefs.perCalendarFixedTimeReminderOverride, + ) { (timed, allDay, timedOv, allDayOv), fixed, fixedOv -> + ReminderDefaults(timed, allDay, timedOv, allDayOv, fixed, fixedOv) }.first() + private data class Quadruple(val a: A, val b: B, val c: C, val d: D) + /** * Stretch a new timed event to the configured default length (#54) — the * resolved calendar's per-calendar duration, otherwise the global default — @@ -527,19 +566,26 @@ class EventEditViewModel @Inject constructor( * settings default — but only when there's a real choice: a default is * configured and it isn't already exactly what the file carried. */ - private fun maybePromptImportedReminderDefault(form: EventForm) { + private fun maybePromptImportedReminderDefault() { val opened = session viewModelScope.launch { val targetId = resolvedCalendarId.first() - val default = reminderDefaults().resolveFor(targetId, form.isAllDay) + val defaults = reminderDefaults() // Bail if the form closed or became an edit while we resolved. if (opened != session) return@launch val current = _form.value ?: return@launch if (_editTarget.value != null) return@launch - if (default.isEmpty() || default == current.reminders) return@launch + // The form may have switched all-day meanwhile; offer that kind's default. + val default = defaults.resolveFor(targetId, current.isAllDay) + val fixed = defaults.resolveFixedFor(targetId, current.isAllDay) + val firing = current.firingReminders() + val firingFixed = if (current.isAllDay) emptyList() else current.fixedReminders + if (default.isEmpty() && fixed.isEmpty()) return@launch + if (default == firing && fixed == firingFixed) return@launch _importReminderPrompt.value = ImportReminderPrompt( - currentReminderCount = current.reminders.size, + currentReminderCount = firing.size + firingFixed.size, defaultReminders = default, + defaultFixedReminders = fixed, ) } } @@ -549,7 +595,7 @@ class EventEditViewModel @Inject constructor( val prompt = _importReminderPrompt.value ?: return _importReminderPrompt.value = null // Already frozen as touched by openImported; this just swaps the values. - edit { it.copy(reminders = prompt.defaultReminders) } + edit { it.copy(reminders = prompt.defaultReminders, fixedReminders = prompt.defaultFixedReminders) } _revealed.value = _revealed.value + EventFormField.Reminders } @@ -579,14 +625,15 @@ class EventEditViewModel @Inject constructor( if (opened == session) _loadFailed.value = true return@launch } + val knownFixed = settingsPrefs.knownFixedTimeReminders.first() if (opened != session) return@launch val zone = zoneSource.current() val begin = beginMillis.takeUnless { it == NO_OCCURRENCE_TIME } ?: detail.instance.start.toEpochMilliseconds() val end = endMillis.takeUnless { it == NO_OCCURRENCE_TIME } ?: detail.instance.end.toEpochMilliseconds() - val snapshot = detail.toEditSnapshot(begin, end, zone) - _editTarget.value = EditTarget(eventId, snapshot, begin, end, zone, detail.atOccurrence(begin, end)) + val snapshot = detail.toEditSnapshot(begin, end, zone).withFixedTimeRemindersRead(knownFixed, zone) + _editTarget.value = EditTarget(eventId, snapshot, begin, end, zone, detail.atOccurrence(begin, end), knownFixed) // Sections holding data must show even when not in the defaults. _revealed.value = snapshot.form.populatedFields() open(snapshot.form) @@ -609,6 +656,7 @@ class EventEditViewModel @Inject constructor( _remindersTouched.value = false _durationTouched.value = false _importReminderPrompt.value = null + _requestedCalendarId.value = null } /** Unfold one optional field, picked in the "more fields" dialog. */ @@ -667,6 +715,11 @@ class EventEditViewModel @Inject constructor( * The event falls back to the new calendar's colour until re-picked. */ fun setCalendar(id: Long) { + // Confirming the calendar the form shows pins it and changes nothing else. + if (id == state.value?.form?.calendarId) { + pinShownCalendar() + return + } edit { it.copy(calendarId = id, colorKey = null, color = null) } // A fresh event re-inherits the new calendar's default reminder and // length unless the user has already hand-edited them (guarded inside). @@ -678,25 +731,79 @@ class EventEditViewModel @Inject constructor( fun setAccessLevel(value: AccessLevel) = edit { it.copy(accessLevel = value) } /** Pick a palette colour (round-trips via its key); [argb] is its swatch. */ - fun setColorKey(key: String, argb: Int) = edit { it.copy(colorKey = key, color = argb) } + fun setColorKey(key: String, argb: Int) { + pinShownCalendar() + edit { it.copy(colorKey = key, color = argb) } + } /** Pick a raw colour (local / opted-in calendars), clearing any palette key. */ - fun setColorRaw(argb: Int) = edit { it.copy(colorKey = null, color = argb) } + fun setColorRaw(argb: Int) { + pinShownCalendar() + edit { it.copy(colorKey = null, color = argb) } + } /** Clear the colour so the event inherits its calendar's. */ - fun clearColor() = edit { it.copy(colorKey = null, color = null) } + fun clearColor() { + pinShownCalendar() + edit { it.copy(colorKey = null, color = null) } + } + + /** + * Fix a still-resolving form to the calendar and colour it shows, so a colour + * picked for that calendar stays with it. Not a change of its own. + */ + private fun pinShownCalendar() { + val shown = state.value?.form ?: return + if (_form.value?.calendarId != null) return + applyDefault { it.copy(calendarId = shown.calendarId, colorKey = shown.colorKey, color = shown.color) } + } /** Bare RRULE value from the recurrence picker; null = does not repeat. */ fun setRecurrence(rrule: String?) = edit { it.copy(rrule = rrule) } fun addReminder(minutes: Int) { _remindersTouched.value = true - edit { it.copy(reminders = (it.reminders + minutes).distinct().sorted()) } + edit { + // A lead firing with a set-time reminder would be one row once saved. + if (minutes in it.fixedReminderOffsets(zoneSource.current())) it + else it.copy(reminders = (it.reminders + minutes).distinct().sorted()) + } } + /** + * On an all-day event a reminder is shown as the whole day it fires on, so + * removing it drops every stored lead time that lands on that day. + */ fun removeReminder(minutes: Int) { _remindersTouched.value = true - edit { it.copy(reminders = it.reminders - minutes) } + edit { form -> + val removed = if (form.isAllDay) { + form.reminders.filter { wholeDayLeadMinutes(it) == wholeDayLeadMinutes(minutes) } + } else { + listOf(minutes) + } + form.copy(reminders = form.reminders - removed.toSet()) + } + } + + /** + * Add an "N days before at HH:MM" reminder (#459); timed events only. A lead + * time landing on the same moment is replaced by it — the two would be one + * row once saved. + */ + fun addFixedReminder(reminder: FixedTimeReminder) { + _remindersTouched.value = true + edit { form -> + if (form.isAllDay) return@edit form + val withFixed = form.copy(fixedReminders = (form.fixedReminders + reminder).distinct().sortedWith(FIXED_ORDER)) + val offsets = withFixed.fixedReminderOffsets(zoneSource.current()).toSet() + withFixed.copy(reminders = form.reminders.filterNot { it in offsets }) + } + } + + fun removeFixedReminder(reminder: FixedTimeReminder) { + _remindersTouched.value = true + edit { it.copy(fixedReminders = it.fixedReminders - reminder) } } /** @@ -815,6 +922,7 @@ class EventEditViewModel @Inject constructor( val fresh = try { repository.eventDetail(target.eventId) .toEditSnapshot(target.beginMillis, target.endMillis, target.zone) + .withFixedTimeRemindersRead(target.knownFixed, target.zone) } catch (e: CancellationException) { throw e } catch (e: NoSuchEventException) { @@ -829,6 +937,17 @@ class EventEditViewModel @Inject constructor( return@launch } } + // Remembered before the write, so the rows read back as these + // reminders from the first re-read on (#459). + if (!form.isAllDay && form.fixedReminders.isNotEmpty()) { + try { + settingsPrefs.rememberFixedTimeReminders(form.fixedReminders) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Could not remember the set-time reminders", e) + } + } val result = try { if (target == null) { repository.createEvent(form) @@ -950,3 +1069,15 @@ class EventEditViewModel @Inject constructor( _form.value = _form.value?.let(block) } } + +/** [EditSnapshot.form] with its timed reminders read back into lead times and fixed-time ones. */ +private fun EditSnapshot.withFixedTimeRemindersRead(known: Set, zone: TimeZone): EditSnapshot = + copy(form = form.withFixedTimeRemindersRead(known, zone)) + +/** + * Reminders as they fire: an all-day event fires on whole days, so a sub-day lead + * time kept from the timed form reads as its day. The form keeps the raw values, + * so switching all-day off again restores any the user did not remove. + */ +internal fun EventForm.firingReminders(): List = + if (isAllDay) wholeDayLeadTimes(reminders) else reminders diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/CalendarFilterList.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/CalendarFilterList.kt index 68191a85..2d78c348 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/CalendarFilterList.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/CalendarFilterList.kt @@ -1,19 +1,33 @@ package de.jeanlucmakiola.calendula.ui.filter import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.wrapContentHeight +import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.FilterList import androidx.compose.material3.Checkbox +import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.state.ToggleableState import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel @@ -22,20 +36,27 @@ import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.domain.FailureReason import de.jeanlucmakiola.calendula.ui.common.CalendarAccountGroup import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip +import de.jeanlucmakiola.calendula.ui.common.CalendarView import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle +import de.jeanlucmakiola.calendula.ui.common.label import de.jeanlucmakiola.calendula.ui.common.orUnnamed import de.jeanlucmakiola.floret.components.GroupedListInset import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.positionOf /** * Calendar-visibility filter (M3), rendered inline in the navigation drawer. * Every calendar grouped by account, each with a colour swatch and a visibility * switch; toggling writes straight to DataStore and every calendar view - * re-filters live. Three states (Loading / Failure / Success). + * re-filters live. Three states (Loading / Failure / Success). A calendar hidden + * in [currentView] through its per-view setting (#270) says so on its row, and + * the entry below the list opens that setting for the view (#517). */ @Composable fun CalendarFilterList( + currentView: CalendarView, + onHideInView: () -> Unit, modifier: Modifier = Modifier, viewModel: FilterViewModel = hiltViewModel(), ) { @@ -43,12 +64,20 @@ fun CalendarFilterList( when (val s = state) { FilterUiState.Loading -> FilterLoading(modifier) is FilterUiState.Failure -> FilterMessage(s.reason, modifier) - is FilterUiState.Success -> FilterList( - groups = s.groups, - hidden = s.hidden, - onSetVisible = viewModel::setVisible, - modifier = modifier, - ) + is FilterUiState.Success -> { + val hiddenInView = remember(s, currentView) { s.hiddenOnlyIn(currentView) } + FilterList( + groups = s.groups, + hidden = s.hidden, + hiddenInView = hiddenInView, + hiddenOnlyHere = hiddenInView.size, + currentView = currentView, + onHideInView = onHideInView, + onToggleCalendar = viewModel::toggleCalendar, + onToggleGroup = viewModel::toggleGroup, + modifier = modifier, + ) + } } } @@ -61,44 +90,97 @@ fun CalendarFilterList( private fun FilterList( groups: List, hidden: Set, - onSetVisible: (Long, Boolean) -> Unit, + hiddenInView: Set, + hiddenOnlyHere: Int, + currentView: CalendarView, + onHideInView: () -> Unit, + onToggleCalendar: (Long) -> Unit, + onToggleGroup: (List) -> Unit, modifier: Modifier = Modifier, ) { + val viewName = currentView.label() Column(modifier = modifier.fillMaxWidth()) { groups.forEach { group -> - Text( - text = accountGroupTitle(group), - style = MaterialTheme.typography.labelMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding( - start = GroupedListInset, - end = GroupedListInset, - top = 12.dp, - bottom = 4.dp, - ), + val ids = group.calendars.map { it.id } + GroupHeader( + title = accountGroupTitle(group), + state = groupVisibility(ids, hidden), + onToggle = { onToggleGroup(ids) }, ) group.calendars.forEachIndexed { index, cal -> val visible = cal.id !in hidden GroupedRow( title = cal.displayName.orUnnamed(), + summary = if (cal.id in hiddenInView) stringResource(R.string.filter_hidden_in_named_view, viewName) else null, position = positionOf(index, group.calendars.size), minHeight = 56.dp, leading = { CalendarColorChip(cal.color) }, trailing = { Checkbox( checked = visible, - onCheckedChange = { onSetVisible(cal.id, it) }, + onCheckedChange = { onToggleCalendar(cal.id) }, ) }, - onClick = { onSetVisible(cal.id, !visible) }, + onClick = { onToggleCalendar(cal.id) }, ) } } + // The per-view hide (#517): the drawer filter above hides everywhere, this only here. + Spacer(Modifier.height(8.dp)) + GroupedRow( + title = stringResource(R.string.view_hide_in_title, viewName), + summary = if (hiddenOnlyHere > 0) { + pluralStringResource(R.plurals.drawer_hidden_in_named_view_count, hiddenOnlyHere, hiddenOnlyHere, viewName) + } else { + stringResource(R.string.drawer_hidden_in_named_view_none, viewName) + }, + position = Position.Alone, + minHeight = 56.dp, + // Tinted, not "selected": it is an entry point, not a chosen option. + container = if (hiddenOnlyHere > 0) MaterialTheme.colorScheme.secondaryContainer else null, + contentColor = if (hiddenOnlyHere > 0) MaterialTheme.colorScheme.onSecondaryContainer else null, + leading = { + Box(Modifier.size(40.dp), contentAlignment = Alignment.Center) { + Icon(Icons.Filled.FilterList, contentDescription = null) + } + }, + onClick = onHideInView, + ) } } +/** + * An account's header doubling as the group's parent checkbox (#143): checked + * when every calendar shows, indeterminate when some do. Tapping it shows all, + * or hides all when the group is fully shown. + */ @Composable -private fun FilterLoading(modifier: Modifier = Modifier) { +private fun GroupHeader( + title: String, + state: ToggleableState, + onToggle: () -> Unit, +) { + val label = stringResource( + if (state.nextGroupVisible()) R.string.filter_group_show_all else R.string.filter_group_hide_all, + ) + // The header itself is the toggle; the rows' checkboxes show the result. + Text( + text = title, + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = GroupedListInset / 2) + .clip(MaterialTheme.shapes.large) + .clickable(onClickLabel = label, role = Role.Button) { onToggle() } + .heightIn(min = 48.dp) + .wrapContentHeight(Alignment.CenterVertically) + .padding(horizontal = GroupedListInset / 2), + ) +} + +@Composable +internal fun FilterLoading(modifier: Modifier = Modifier) { Column( modifier = modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp), @@ -119,7 +201,7 @@ private fun FilterLoading(modifier: Modifier = Modifier) { } @Composable -private fun FilterMessage(reason: FailureReason, modifier: Modifier = Modifier) { +internal fun FilterMessage(reason: FailureReason, modifier: Modifier = Modifier) { val msg = when (reason) { FailureReason.NoCalendarsConfigured -> R.string.state_failure_no_calendars FailureReason.AllCalendarsHidden -> R.string.state_failure_all_hidden diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/FilterUiState.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/FilterUiState.kt index 765d9edf..dbaac633 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/FilterUiState.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/FilterUiState.kt @@ -2,6 +2,8 @@ package de.jeanlucmakiola.calendula.ui.filter import de.jeanlucmakiola.calendula.domain.FailureReason import de.jeanlucmakiola.calendula.ui.common.CalendarAccountGroup +import de.jeanlucmakiola.calendula.ui.common.CalendarView +import de.jeanlucmakiola.calendula.ui.common.calendarsHiddenIn /** * State for the calendar-filter sheet (M3). The user toggles per-calendar @@ -11,9 +13,22 @@ import de.jeanlucmakiola.calendula.ui.common.CalendarAccountGroup sealed interface FilterUiState { data object Loading : FilterUiState data class Failure(val reason: FailureReason) : FilterUiState - /** A calendar shows when its id is *not* in [hidden]. */ + /** + * A calendar shows when its id is *not* in [hidden]; [hiddenViews] are the + * views each calendar is hidden in regardless (#270). + */ data class Success( val groups: List, val hidden: Set, - ) : FilterUiState + val hiddenViews: Map> = emptyMap(), + ) : FilterUiState { + /** + * The listed calendars [view] hides on its own (#517); ones already + * hidden everywhere from the drawer, or not listed, aren't included. + */ + fun hiddenOnlyIn(view: CalendarView): Set { + val listed = groups.flatMapTo(mutableSetOf()) { group -> group.calendars.map { it.id } } + return hiddenViews.calendarsHiddenIn(view).filterTo(mutableSetOf()) { it in listed && it !in hidden } + } + } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/FilterViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/FilterViewModel.kt index fda4c1fb..6528da11 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/FilterViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/FilterViewModel.kt @@ -1,20 +1,24 @@ package de.jeanlucmakiola.calendula.ui.filter +import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs +import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.domain.FailureReason import de.jeanlucmakiola.calendula.domain.calendarListFailure +import de.jeanlucmakiola.calendula.ui.common.CalendarView +import de.jeanlucmakiola.calendula.ui.common.hidingNothingOnError import de.jeanlucmakiola.calendula.ui.common.groupByAccount import de.jeanlucmakiola.floret.android.stateWhileSubscribed import de.jeanlucmakiola.floret.di.IoDispatcher +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.combine -import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.launch import javax.inject.Inject @@ -23,6 +27,7 @@ import javax.inject.Inject class FilterViewModel @Inject constructor( private val repository: CalendarRepository, private val prefs: CalendarPrefs, + private val settingsPrefs: SettingsPrefs, @IoDispatcher private val io: CoroutineDispatcher, ) : ViewModel() { @@ -30,7 +35,9 @@ class FilterViewModel @Inject constructor( combine( repository.calendars(), prefs.hiddenCalendarIds, - ) { calendars, hidden -> + // Only feeds a note on the rows; a failed read leaves it off rather than failing the list. + settingsPrefs.perCalendarHiddenViews.hidingNothingOnError(), + ) { calendars, hidden, hiddenViews -> // Calendars switched off device-wide don't belong in the drawer's // hide/show list; they live only in Settings → Calendars. val enabled = calendars.filter { it.isVisibleInSystem } @@ -38,7 +45,7 @@ class FilterViewModel @Inject constructor( if (failure != null) { FilterUiState.Failure(failure) } else { - FilterUiState.Success(enabled.groupByAccount(), hidden) + FilterUiState.Success(enabled.groupByAccount(), hidden, hiddenViews) } } .catch { emit(FilterUiState.Failure(FailureReason.ProviderUnavailable)) } @@ -48,13 +55,32 @@ class FilterViewModel @Inject constructor( initialValue = FilterUiState.Loading, ) - /** Show or hide a single calendar; persists the new hidden set. */ - fun setVisible(calendarId: Long, visible: Boolean) { + /** Hide or show one calendar in [view] only (#517), the same setting as Settings → Calendars. */ + fun setHiddenIn(calendarId: Long, view: CalendarView, hidden: Boolean) { viewModelScope.launch { - val current = prefs.hiddenCalendarIds.first() - val next = if (visible) current - calendarId else current + calendarId - if (next != current) prefs.setHiddenCalendarIds(next) + try { + settingsPrefs.setCalendarHiddenIn(calendarId, view, hidden) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w("FilterViewModel", "Could not change hidden views of $calendarId", e) + } } } + + /** + * Flip one calendar, or a whole group from its header (#143). Both decide + * against the stored set rather than the last drawn state, so quick repeated + * taps still alternate. + */ + fun toggleCalendar(calendarId: Long) { + viewModelScope.launch { + prefs.updateHiddenCalendarIds { if (calendarId in it) it - calendarId else it + calendarId } + } + } + + fun toggleGroup(calendarIds: List) { + viewModelScope.launch { prefs.updateHiddenCalendarIds { toggledGroup(it, calendarIds) } } + } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/GroupVisibility.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/GroupVisibility.kt new file mode 100644 index 00000000..3994bc9d --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/GroupVisibility.kt @@ -0,0 +1,20 @@ +package de.jeanlucmakiola.calendula.ui.filter + +import androidx.compose.ui.state.ToggleableState + +/** The drawer group header's checkbox state: on, off, or some of [calendarIds] shown. */ +internal fun groupVisibility(calendarIds: Collection, hidden: Set): ToggleableState { + val shown = calendarIds.count { it !in hidden } + return when (shown) { + 0 -> ToggleableState.Off + calendarIds.size -> ToggleableState.On + else -> ToggleableState.Indeterminate + } +} + +/** What tapping the header does: a fully shown group hides, anything else shows all. */ +internal fun ToggleableState.nextGroupVisible(): Boolean = this != ToggleableState.On + +/** [hidden] after tapping the header of the group holding [calendarIds]. */ +internal fun toggledGroup(hidden: Set, calendarIds: Collection): Set = + if (groupVisibility(calendarIds, hidden).nextGroupVisible()) hidden - calendarIds.toSet() else hidden + calendarIds diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/ViewCalendarsPicker.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/ViewCalendarsPicker.kt new file mode 100644 index 00000000..b22f18c5 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/ViewCalendarsPicker.kt @@ -0,0 +1,67 @@ +package de.jeanlucmakiola.calendula.ui.filter + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip +import de.jeanlucmakiola.calendula.ui.common.CalendarView +import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle +import de.jeanlucmakiola.calendula.ui.common.calendarsHiddenIn +import de.jeanlucmakiola.calendula.ui.common.label +import de.jeanlucmakiola.calendula.ui.common.orUnnamed +import de.jeanlucmakiola.floret.components.FullScreenPicker +import de.jeanlucmakiola.floret.components.GroupedHint +import de.jeanlucmakiola.floret.components.GroupedSectionHeader +import de.jeanlucmakiola.floret.components.MultiOptionRows + +/** + * The calendars hidden in [view] (#517), opened from the drawer while on it: the + * per-view setting from Settings → Calendars (#270), seen from the view's side. + * Toggles apply at once. + */ +@Composable +fun ViewCalendarsPicker( + view: CalendarView, + state: FilterUiState, + onSetHidden: (calendarId: Long, hidden: Boolean) -> Unit, + onDismiss: () -> Unit, +) { + val viewName = view.label() + FullScreenPicker( + title = stringResource(R.string.view_hide_in_title, viewName), + onDismiss = onDismiss, + predictiveBack = true, + ) { + when (state) { + FilterUiState.Loading -> FilterLoading() + is FilterUiState.Failure -> FilterMessage(state.reason) + is FilterUiState.Success -> { + // Seeded once, then ahead of the store: the picker is the only + // writer while open, so a quick second tap still flips. + var hidden by remember(view) { mutableStateOf(state.hiddenViews.calendarsHiddenIn(view)) } + GroupedHint(stringResource(R.string.view_calendars_named_hint, viewName), verticalPadding = 8.dp) + state.groups.forEach { group -> + GroupedSectionHeader(accountGroupTitle(group)) + MultiOptionRows( + options = group.calendars, + selected = group.calendars.filterTo(mutableSetOf()) { it.id in hidden }, + label = { it.displayName.orUnnamed() }, + onToggle = { calendar, hide -> + hidden = if (hide) hidden + calendar.id else hidden - calendar.id + onSetHidden(calendar.id, hide) + }, + summary = { calendar -> + if (calendar.id in state.hidden) stringResource(R.string.view_calendars_hidden_everywhere) else null + }, + leading = { CalendarColorChip(it.color) }, + ) + } + } + } + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/imports/ImportScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/imports/ImportScreen.kt index 9fd95c6c..3a957985 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/imports/ImportScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/imports/ImportScreen.kt @@ -1,15 +1,9 @@ package de.jeanlucmakiola.calendula.ui.imports import android.net.Uri -import androidx.compose.animation.core.Animatable -import androidx.compose.animation.core.Spring -import androidx.compose.animation.core.spring -import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth @@ -17,13 +11,9 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Check import androidx.compose.material.icons.filled.Close -import androidx.compose.material.icons.filled.PriorityHigh import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api @@ -31,34 +21,31 @@ import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold -import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.graphicsLayer -import androidx.compose.ui.semantics.clearAndSetSemantics -import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle +import de.jeanlucmakiola.floret.components.OnboardingPrimaryButton import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.ics.IcsParseWarning import de.jeanlucmakiola.calendula.ui.common.CalendarPickerGroups +import de.jeanlucmakiola.calendula.ui.common.ImportSummaryStats +import de.jeanlucmakiola.calendula.ui.common.ResultBadge +import de.jeanlucmakiola.calendula.ui.common.ResultMessage +import de.jeanlucmakiola.calendula.ui.common.importSummaryNotes import de.jeanlucmakiola.floret.identity.predictiveBack /** @@ -211,18 +198,6 @@ private fun ManyContent( @Composable private fun DoneContent(state: ImportUiState.Done, onClose: () -> Unit) { - // A little expressive pop on the success badge — springs in on first show. - val badgeScale = remember { Animatable(0.7f) } - LaunchedEffect(Unit) { - badgeScale.animateTo( - targetValue = 1f, - animationSpec = spring( - dampingRatio = Spring.DampingRatioMediumBouncy, - stiffness = Spring.StiffnessLow, - ), - ) - } - // Part of the file never reached the calendar, so the screen doesn't get to // read as a plain success. val stopped = state.summary.notAttempted > 0 @@ -232,160 +207,28 @@ private fun DoneContent(state: ImportUiState.Done, onClose: () -> Unit) { horizontalAlignment = Alignment.CenterHorizontally, ) { Spacer(Modifier.weight(1f)) - Box( - Modifier - .size(112.dp) - .graphicsLayer { - scaleX = badgeScale.value - scaleY = badgeScale.value - } - .clip(CircleShape) - .background( - if (stopped) { - MaterialTheme.colorScheme.errorContainer - } else { - MaterialTheme.colorScheme.primaryContainer - }, - ), - contentAlignment = Alignment.Center, - ) { - Icon( - if (stopped) Icons.Default.PriorityHigh else Icons.Default.Check, - contentDescription = null, - tint = if (stopped) { - MaterialTheme.colorScheme.onErrorContainer - } else { - MaterialTheme.colorScheme.onPrimaryContainer - }, - modifier = Modifier.size(56.dp), - ) - } - Spacer(Modifier.height(24.dp)) - Text( - stringResource( + ResultBadge(error = stopped) + ResultMessage( + title = stringResource( if (stopped) R.string.import_done_stopped_title else R.string.import_done_title, ), - style = MaterialTheme.typography.headlineSmall, - color = MaterialTheme.colorScheme.onSurface, + // The counts cover the part of the file that was tried, so say how much never was. + notes = importSummaryNotes( + state.summary, + stoppedNote = if (stopped) { + pluralStringResource(R.plurals.import_done_stopped, state.summary.notAttempted, state.summary.notAttempted) + } else { + null + }, + ), ) - if (state.summary.failed > 0) { - Spacer(Modifier.height(8.dp)) - Text( - stringResource(R.string.import_done_failed_note), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center, - ) - } - if (state.summary.skippedDuplicate > 0) { - Spacer(Modifier.height(8.dp)) - Text( - stringResource(R.string.import_done_dedup_note), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center, - ) - } - // The one note that isn't about individual events: the counts below cover - // the part of the file that was tried, so say how much never was. - if (stopped) { - Spacer(Modifier.height(8.dp)) - Text( - pluralStringResource( - R.plurals.import_done_stopped, - state.summary.notAttempted, - state.summary.notAttempted, - ), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.error, - textAlign = TextAlign.Center, - ) - } Spacer(Modifier.height(24.dp)) - Row( - Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - ImportStatCard( - count = state.summary.imported, - label = stringResource(R.string.import_done_added_label), - contentDescription = pluralStringResource( - R.plurals.import_done_imported, - state.summary.imported, - state.summary.imported, - ), - container = MaterialTheme.colorScheme.secondaryContainer, - onContainer = MaterialTheme.colorScheme.onSecondaryContainer, - ) - if (state.summary.skippedDuplicate > 0) { - ImportStatCard( - count = state.summary.skippedDuplicate, - label = stringResource(R.string.import_done_skipped_label), - contentDescription = pluralStringResource( - R.plurals.import_done_skipped, - state.summary.skippedDuplicate, - state.summary.skippedDuplicate, - ), - container = MaterialTheme.colorScheme.surfaceContainerHighest, - onContainer = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - if (state.summary.failed > 0) { - ImportStatCard( - count = state.summary.failed, - label = stringResource(R.string.import_done_failed_label), - contentDescription = pluralStringResource( - R.plurals.import_done_failed, - state.summary.failed, - state.summary.failed, - ), - container = MaterialTheme.colorScheme.errorContainer, - onContainer = MaterialTheme.colorScheme.onErrorContainer, - ) - } - } + ImportSummaryStats(state.summary) Spacer(Modifier.weight(1f)) - Button( + OnboardingPrimaryButton( + text = stringResource(R.string.import_close), onClick = onClose, - modifier = Modifier.fillMaxWidth(), - ) { - Text(stringResource(R.string.import_close)) - } - } -} - -/** A big-number tonal tile summarising one import outcome (added / skipped / failed). */ -@Composable -private fun RowScope.ImportStatCard( - count: Int, - label: String, - contentDescription: String, - container: Color, - onContainer: Color, -) { - Surface( - modifier = Modifier - .weight(1f) - .clearAndSetSemantics { this.contentDescription = contentDescription }, - shape = RoundedCornerShape(24.dp), - color = container, - ) { - Column( - Modifier.padding(vertical = 20.dp, horizontal = 12.dp), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(2.dp), - ) { - Text( - count.toString(), - style = MaterialTheme.typography.displaySmall, - color = onContainer, - ) - Text( - label, - style = MaterialTheme.typography.labelLarge, - color = onContainer.copy(alpha = 0.85f), - ) - } + ) } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthScreen.kt index 46b8a0f1..7a78eb26 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthScreen.kt @@ -31,6 +31,7 @@ import de.jeanlucmakiola.calendula.ui.common.morphEvent import de.jeanlucmakiola.calendula.ui.common.jumpToPage import de.jeanlucmakiola.calendula.ui.common.rememberCalendarPageSpec import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme +import de.jeanlucmakiola.floret.locale.capitalizeStart import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.drop import androidx.compose.animation.ExperimentalSharedTransitionApi @@ -798,7 +799,7 @@ internal fun WeekdayHeader(weekStart: DayOfWeek, showWeekNumbers: Boolean) { val isWeekend = dow == DayOfWeek.SATURDAY || dow == DayOfWeek.SUNDAY val javaDow = dow.toJavaDayOfWeek() Text( - text = javaDow.getDisplayName(JavaTextStyle.SHORT, locale), + text = javaDow.getDisplayName(JavaTextStyle.SHORT, locale).capitalizeStart(locale), style = MaterialTheme.typography.labelMedium, color = if (isWeekend) MaterialTheme.colorScheme.onSurfaceVariant else MaterialTheme.colorScheme.onSurface, @@ -2842,6 +2843,7 @@ private fun shortMonthName(date: LocalDate): String { return remember(date.month, locale) { date.month.toJavaMonth() .getDisplayName(JavaTextStyle.SHORT, locale) + .capitalizeStart(locale) } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthViewModel.kt index 8f83b13f..90caa5dc 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/month/MonthViewModel.kt @@ -19,7 +19,10 @@ import de.jeanlucmakiola.calendula.domain.calendarListFailure import de.jeanlucmakiola.calendula.ui.agenda.AgendaDay import de.jeanlucmakiola.calendula.ui.agenda.anchorTodayIfMissing import de.jeanlucmakiola.calendula.ui.common.CalendarSpan +import de.jeanlucmakiola.calendula.ui.common.CalendarView import de.jeanlucmakiola.calendula.ui.common.PageStateCache +import de.jeanlucmakiola.calendula.ui.common.calendarsHiddenIn +import de.jeanlucmakiola.calendula.ui.common.instancesWithout import de.jeanlucmakiola.calendula.domain.isCrossedOut import de.jeanlucmakiola.calendula.domain.sortedForDisplay import de.jeanlucmakiola.calendula.ui.week.coversDay @@ -68,6 +71,8 @@ class MonthViewModel @Inject constructor( private val zone = TimeZone.currentSystemDefault() + private val hiddenHere = settingsPrefs.perCalendarHiddenViews.calendarsHiddenIn(CalendarView.Month, viewModelScope) + /** First day of the week, from the Settings preference (AUTO → locale). */ val weekStart: StateFlow = settingsPrefs.firstDayOfWeek(viewModelScope) @@ -152,7 +157,7 @@ class MonthViewModel @Inject constructor( ) { (ym, ws) -> combine( repository.calendars(), - repository.instances(monthGridRange(ym, ws, zone)), + repository.instancesWithout(monthGridRange(ym, ws, zone), hiddenHere), today, ) { calendars, instances, today -> buildState(ym, ws, calendars, instances, today) @@ -224,7 +229,7 @@ class MonthViewModel @Inject constructor( val range = dayRange(first, last, zone) combine( repository.calendars(), - repository.instances(range), + repository.instancesWithout(range, hiddenHere), today, ) { calendars, instances, today -> buildContinuousState(window, ws, style, calendars, instances, today) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/CalendarsStep.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/CalendarsStep.kt index ab37d675..01c49d17 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/CalendarsStep.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/CalendarsStep.kt @@ -89,7 +89,7 @@ internal fun CalendarsStep( initialName = "", initialColor = CalendarColorPalette.all.first(), initialDescription = "", - onSave = { name, color, description -> + onSave = { name, color, description, _ -> if (!submitted) { submitted = true onCreateLocal(name, color, description) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/OnboardingViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/OnboardingViewModel.kt index 2a2894d4..7a8709f2 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/OnboardingViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/onboarding/OnboardingViewModel.kt @@ -15,6 +15,7 @@ import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.data.prefs.WeekStartPref import de.jeanlucmakiola.calendula.data.reminders.ReminderScanner import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.domain.backup.isBackedUpByDefault import de.jeanlucmakiola.calendula.domain.hasVisibilitySwitch import de.jeanlucmakiola.calendula.domain.orderedForManager import de.jeanlucmakiola.calendula.ui.common.CalendarView @@ -339,12 +340,7 @@ class OnboardingViewModel @Inject constructor( } prefs.setAutoBackupFolderUri(folder.toString()) prefs.setAutoBackupEnabled(true) - BackupScheduler.apply( - context = context, - enabled = true, - intervalMinutes = prefs.autoBackupIntervalMinutes.first(), - hasFolder = true, - ) + BackupScheduler.reconcile(context, prefs) // Immediate feedback: the first backup lands while onboarding runs. BackupScheduler.runNow(context) prefs.setOnboardingDone(OnboardingStep.Backup) @@ -483,7 +479,7 @@ private fun List.allHidden(): Boolean = * A read-only subscription is not a backup, so it does not count. */ private fun List.backupApplies(): Boolean { - val exportable = any { it.isLocal && it.canModifyContents && !it.isManaged } + val exportable = any { it.isBackedUpByDefault } val syncedTarget = any { !it.isLocal && it.canModifyContents } return exportable && !syncedTarget } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertActivity.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertActivity.kt new file mode 100644 index 00000000..e132b4d3 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertActivity.kt @@ -0,0 +1,181 @@ +package de.jeanlucmakiola.calendula.ui.reminders + +import android.content.Context +import android.content.Intent +import android.os.Bundle +import android.util.Log +import android.view.WindowManager +import androidx.activity.ComponentActivity +import androidx.activity.compose.BackHandler +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.core.net.toUri +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle +import dagger.hilt.android.AndroidEntryPoint +import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource +import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs +import de.jeanlucmakiola.calendula.data.reminders.FullScreenAlerts +import de.jeanlucmakiola.calendula.data.reminders.ReminderActionReceiver +import de.jeanlucmakiola.calendula.data.reminders.ReminderActionReceiver.Companion.putAlert +import de.jeanlucmakiola.calendula.data.reminders.ReminderAlert +import de.jeanlucmakiola.calendula.data.reminders.ReminderNotifier +import de.jeanlucmakiola.calendula.data.reminders.ReminderRingService +import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors +import de.jeanlucmakiola.calendula.ui.theme.CalendulaTheme +import de.jeanlucmakiola.calendula.ui.theme.WindowThemeCache +import de.jeanlucmakiola.floret.di.IoDispatcher +import de.jeanlucmakiola.floret.prefs.ThemeMode +import de.jeanlucmakiola.floret.prefs.isDark +import de.jeanlucmakiola.floret.prefs.isPureBlack +import de.jeanlucmakiola.floret.ring.showOverLockScreen +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import javax.inject.Inject + +/** + * The full-screen reminder alert (#171), opened by the reminder's full-screen + * intent over the lock screen, or, for a ringing one, from its heads-up. + * It stays until the reminder is dismissed or snoozed — here, from the + * notification, or by the ring giving up — and back does not close it. + */ +@AndroidEntryPoint +class ReminderAlertActivity : ComponentActivity() { + + @Inject lateinit var notifier: ReminderNotifier + @Inject lateinit var alerts: FullScreenAlerts + @Inject lateinit var settingsPrefs: SettingsPrefs + @Inject lateinit var calendarDataSource: CalendarDataSource + + @Inject @IoDispatcher + lateinit var io: CoroutineDispatcher + + private var state by mutableStateOf(ReminderAlertUiState.Loading) + private var alert: ReminderAlert? = null + private var loading: Job? = null + private var screenOn: Job? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + showOverLockScreen() + enableEdgeToEdge() + show(intent) + lifecycleScope.launch { + repeatOnLifecycle(Lifecycle.State.CREATED) { + alerts.handled.collect { key -> if (key == alert?.key) finish() } + } + } + val cachedTheme = WindowThemeCache.read(this) ?: ThemeMode.SYSTEM + val cachedDynamicColor = WindowThemeCache.readDynamicColor(this) ?: true + setContent { + val themeMode by settingsPrefs.themeMode.collectAsStateWithLifecycle(cachedTheme) + val dynamicColor by settingsPrefs.dynamicColor.collectAsStateWithLifecycle(cachedDynamicColor) + val soften by settingsPrefs.softenCalendarColors.collectAsStateWithLifecycle(true) + CalendulaTheme( + darkTheme = themeMode.isDark(isSystemInDarkTheme()), + dynamicColor = dynamicColor, + pureBlack = themeMode.isPureBlack, + ) { + CompositionLocalProvider(LocalSoftenColors provides soften) { + BackHandler(enabled = true) { /* Handled by Dismiss or Snooze, not by leaving. */ } + when (val current = state) { + ReminderAlertUiState.Loading -> + Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.surface) {} + is ReminderAlertUiState.Showing -> ReminderAlertScreen( + state = current, + onSnooze = { act(ReminderActionReceiver.ACTION_SNOOZE) }, + onDismiss = { act(ReminderActionReceiver.ACTION_DISMISS) }, + ) + } + } + } + } + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + setIntent(intent) + show(intent) + } + + /** Tapped from a stale notification, or handled while this window was away. */ + override fun onResume() { + super.onResume() + val current = alert + if (current != null && !notifier.isShowing(current)) finish() + } + + private fun show(intent: Intent) { + val next = ReminderActionReceiver.alertFrom(intent) + if (next == null) { + finish() + return + } + alert = next + // A ring still going, this one's or another's, keeps the screen up as long as it rings. + val ringing = alerts.ringing != null + keepScreenOn(if (ringing) ReminderRingService.RING_TIMEOUT_MILLIS else ONCE_SCREEN_ON_MILLIS) + loading?.cancel() + state = ReminderAlertUiState.Loading + loading = lifecycleScope.launch { + val calendar = try { + withContext(io) { calendarDataSource.calendars().firstOrNull { it.id == next.calendarId } } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + // The alert still shows, only without its calendar. + Log.w(TAG, "Could not read the calendar of event ${next.eventId}", e) + null + } + state = ReminderAlertUiState.Showing( + title = next.title, + time = notifier.timeText(next), + location = next.location?.takeIf { it.isNotBlank() }, + calendarName = calendar?.displayName, + calendarColor = calendar?.color, + ) + } + } + + /** An alert nobody answers lets the display sleep again; it stays on the lock screen. */ + private fun keepScreenOn(millis: Long) { + window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + screenOn?.cancel() + screenOn = lifecycleScope.launch { + delay(millis) + window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + } + } + + private fun act(action: String) { + val current = alert ?: return + sendBroadcast(ReminderActionReceiver.intent(this, action, current)) + finish() + } + + companion object { + private const val TAG = "ReminderAlertActivity" + private const val ONCE_SCREEN_ON_MILLIS = 60_000L + + fun intent(context: Context, alert: ReminderAlert): Intent = + Intent(context, ReminderAlertActivity::class.java) + .setData("calendula://reminder-alert/${alert.key}".toUri()) + .putAlert(alert) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_USER_ACTION) + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertScreen.kt new file mode 100644 index 00000000..6cd8de1c --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertScreen.kt @@ -0,0 +1,195 @@ +package de.jeanlucmakiola.calendula.ui.reminders + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Event +import androidx.compose.material.icons.outlined.LocationOn +import androidx.compose.material.icons.outlined.Snooze +import androidx.compose.material.icons.rounded.Close +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi +import androidx.compose.material3.FilledTonalButton +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors +import de.jeanlucmakiola.calendula.ui.common.eventFill +import de.jeanlucmakiola.calendula.ui.common.eventInk +import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme +import de.jeanlucmakiola.floret.ring.RingBadge + +/** + * The alert itself, after the incoming-call screen: the calendar's pulsing + * badge, what and when in the middle, and the two ways out at the bottom, + * large enough to hit half awake. + */ +@Composable +internal fun ReminderAlertScreen( + state: ReminderAlertUiState.Showing, + onSnooze: () -> Unit, + onDismiss: () -> Unit, + modifier: Modifier = Modifier, +) { + Surface(modifier.fillMaxSize(), color = MaterialTheme.colorScheme.surfaceContainer) { + Column( + modifier = Modifier + .fillMaxSize() + .safeDrawingPadding() + .padding(horizontal = 24.dp, vertical = 32.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + // Centred, but scrolls rather than pushing the buttons off a short landscape screen. + BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) { + Column( + modifier = Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .heightIn(min = maxHeight), + verticalArrangement = Arrangement.Center, + horizontalAlignment = Alignment.CenterHorizontally, + ) { + state.calendarName?.let { + Text( + text = it, + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Spacer(Modifier.size(24.dp)) + } + CalendarBadge(state.calendarColor) + Spacer(Modifier.size(32.dp)) + Text( + text = state.title.ifBlank { stringResource(R.string.event_untitled) }, + style = MaterialTheme.typography.displaySmall, + color = MaterialTheme.colorScheme.onSurface, + textAlign = TextAlign.Center, + maxLines = 3, + overflow = TextOverflow.Ellipsis, + ) + Spacer(Modifier.size(12.dp)) + Text( + text = state.time, + style = MaterialTheme.typography.titleLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + ) + state.location?.let { location -> + Spacer(Modifier.size(8.dp)) + Row(verticalAlignment = Alignment.CenterVertically) { + Icon( + imageVector = Icons.Outlined.LocationOn, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(20.dp), + ) + Spacer(Modifier.size(4.dp)) + Text( + text = location, + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + } + } + } + Spacer(Modifier.size(24.dp)) + Column( + modifier = Modifier.widthIn(max = 480.dp).fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + AlertButton( + label = stringResource(R.string.reminder_action_dismiss), + icon = Icons.Rounded.Close, + tonal = false, + onClick = onDismiss, + modifier = Modifier.fillMaxWidth(), + ) + AlertButton( + label = stringResource(R.string.reminder_action_snooze), + icon = Icons.Outlined.Snooze, + tonal = true, + onClick = onSnooze, + modifier = Modifier.fillMaxWidth(), + ) + } + } + } +} + +/** The calendar's colour as the badge fill, or the theme's primary container without one. */ +@Composable +private fun CalendarBadge(color: Int?) { + if (color == null) { + RingBadge(icon = Icons.Outlined.Event, size = 120.dp) + return + } + val fill = eventFill(color, LocalFloretDarkTheme.current, LocalSoftenColors.current) + RingBadge( + icon = Icons.Outlined.Event, + containerColor = fill, + contentColor = eventInk(fill, alpha = 1f), + size = 120.dp, + ) +} + +@OptIn(ExperimentalMaterial3ExpressiveApi::class) +@Composable +private fun AlertButton( + label: String, + icon: ImageVector, + tonal: Boolean, + onClick: () -> Unit, + modifier: Modifier = Modifier, +) { + val height = ButtonDefaults.LargeContainerHeight + val content: @Composable () -> Unit = { + Icon(icon, contentDescription = null, modifier = Modifier.size(ButtonDefaults.iconSizeFor(height))) + Spacer(Modifier.size(ButtonDefaults.iconSpacingFor(height))) + Text(label, style = ButtonDefaults.textStyleFor(height), maxLines = 1, overflow = TextOverflow.Ellipsis) + } + val buttonModifier = modifier.heightIn(min = height) + val padding = ButtonDefaults.contentPaddingFor(height) + if (tonal) { + FilledTonalButton( + onClick = onClick, + modifier = buttonModifier, + shapes = ButtonDefaults.shapesFor(height), + contentPadding = padding, + ) { content() } + } else { + Button( + onClick = onClick, + modifier = buttonModifier, + shapes = ButtonDefaults.shapesFor(height), + contentPadding = padding, + ) { content() } + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertUiState.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertUiState.kt new file mode 100644 index 00000000..8368a571 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertUiState.kt @@ -0,0 +1,16 @@ +package de.jeanlucmakiola.calendula.ui.reminders + +sealed interface ReminderAlertUiState { + /** The calendar is still being read; the surface is already up. */ + data object Loading : ReminderAlertUiState + + data class Showing( + /** Raw title; blank shows as "(no title)". */ + val title: String, + val time: String, + val location: String?, + /** Null when the calendar could not be read. */ + val calendarName: String?, + val calendarColor: Int?, + ) : ReminderAlertUiState +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/search/SearchScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/search/SearchScreen.kt index 018cf5e1..56088eae 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/search/SearchScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/search/SearchScreen.kt @@ -88,6 +88,7 @@ import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.SnackChip import de.jeanlucmakiola.floret.components.SnackChipHeight import de.jeanlucmakiola.floret.components.SnackChipMargin +import de.jeanlucmakiola.floret.locale.capitalizeStart import de.jeanlucmakiola.floret.locale.currentLocale import de.jeanlucmakiola.floret.locale.localizedDateFormatter import de.jeanlucmakiola.calendula.ui.common.EventDimAlpha @@ -470,6 +471,7 @@ private fun monthLabel(month: SearchMonth): String { return remember(month.year, month.monthNumber, locale) { localizedDateFormatter(locale, "LLLLy") .format(java.time.LocalDate.of(month.year, month.monthNumber, 1)) + .capitalizeStart(locale) } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/CalendarReminderSettings.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/CalendarReminderSettings.kt new file mode 100644 index 00000000..bec548ff --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/CalendarReminderSettings.kt @@ -0,0 +1,486 @@ +package de.jeanlucmakiola.calendula.ui.settings + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.LifecycleResumeEffect +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.data.reminders.RING_CHANNEL_ID +import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride +import de.jeanlucmakiola.calendula.data.prefs.fixedTimeOverrideFor +import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle +import de.jeanlucmakiola.calendula.domain.reminders.alertStyleFor +import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip +import de.jeanlucmakiola.calendula.ui.common.FixedTimeReminderPicker +import de.jeanlucmakiola.calendula.ui.common.fixedTimeReminderLabel +import de.jeanlucmakiola.calendula.ui.common.ReminderDefaultPicker +import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle +import de.jeanlucmakiola.calendula.ui.common.groupByAccount +import de.jeanlucmakiola.calendula.ui.common.orUnnamed +import de.jeanlucmakiola.floret.components.CollapsingScaffold +import de.jeanlucmakiola.floret.android.openNotificationSettings +import de.jeanlucmakiola.floret.components.ExpandIcon +import de.jeanlucmakiola.floret.components.GroupedHint +import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.GroupedSectionHeader +import de.jeanlucmakiola.floret.components.GroupedSwitchRow +import de.jeanlucmakiola.floret.components.OptionPicker +import de.jeanlucmakiola.floret.components.Position +import de.jeanlucmakiola.floret.components.positionOf +import de.jeanlucmakiola.floret.identity.collapseExit +import de.jeanlucmakiola.floret.identity.expandEnter +import de.jeanlucmakiola.floret.reminders.ReminderOverride +import de.jeanlucmakiola.floret.reminders.reminderOverrideFor +import de.jeanlucmakiola.floret.ring.canUseFullScreenIntent +import de.jeanlucmakiola.floret.ring.openFullScreenIntentSettings + +/** + * Per-calendar notifications and reminder overrides (#145, #272), reached from + * Settings → Notifications. Calendars are listed by account as connected groups; + * a calendar unfolds its options in place, one tone darker, inside its group. + */ +@Composable +internal fun CalendarRemindersScreen( + state: SettingsUiState, + viewModel: SettingsViewModel, + onBack: () -> Unit, + onOpenSpecialDates: () -> Unit, + visible: Boolean = true, +) { + var expandedCalendars by rememberSaveable { mutableStateOf(emptyList()) } + var overrideDialog by remember { mutableStateOf(null) } + var alertStylePicker by remember { mutableStateOf(null) } + var alertSoundPicker by remember { mutableStateOf(null) } + val canFullScreen = rememberCanUseFullScreenIntent() + val context = LocalContext.current + var fixedOverrideFor by remember { mutableStateOf(null) } + val channelStatus by viewModel.channelStatus.collectAsStateWithLifecycle() + val calendarIds = state.reminderCalendars.map { it.id } + val soundPicker = rememberReminderSoundPicker(viewModel, calendarIds) + LifecycleResumeEffect(calendarIds) { + viewModel.refreshChannelStatus(calendarIds) + onPauseOrDispose { } + } + + CollapsingScaffold( + title = stringResource(R.string.settings_calendar_reminders_title), + onBack = onBack, + predictiveBack = true, + visible = visible, + ) { + GroupedHint(stringResource(R.string.settings_calendar_reminders_hint), style = MaterialTheme.typography.bodySmall) + state.reminderCalendars.groupByAccount().forEachIndexed { groupIndex, group -> + if (groupIndex > 0) Spacer(Modifier.height(8.dp)) + GroupedSectionHeader(accountGroupTitle(group)) + val calendars = group.calendars + calendars.forEachIndexed { index, calendar -> + val expanded = calendar.id in expandedCalendars + val notifying = calendar.id !in state.mutedReminderCalendarIds + val blocked = notifying && calendar.id in channelStatus.blockedCalendarIds + CalendarReminderEntry( + calendar = calendar, + state = state, + position = positionOf(index, calendars.size), + expanded = expanded, + notifying = notifying, + blocked = blocked, + heldBack = fullScreenHeldBack( + style = state.reminderAlertStyles.alertStyleFor(calendar.id), + notifying = notifying, + blocked = blocked, + ringBlocked = channelStatus.ringBlocked, + canFullScreen = canFullScreen, + ), + onToggleExpand = { + expandedCalendars = if (expanded) { + expandedCalendars - calendar.id + } else { + expandedCalendars + calendar.id + } + }, + onSetNotifying = { viewModel.setCalendarRemindersEnabled(calendar.id, it) }, + soundLabel = soundPicker.loadedSounds?.let { soundLabel(it[calendar.id]) }, + onPickSound = { soundPicker.pick(calendar.id) }, + onOpenSettings = { soundPicker.openCalendarSettings(calendar.id) }, + onOpenRingSettings = { context.openNotificationSettings(RING_CHANNEL_ID) }, + onEditAlertStyle = { alertStylePicker = calendar.id }, + onEditAlertSound = { alertSoundPicker = calendar.id }, + onAllowFullScreen = { context.openFullScreenIntentSettings() }, + onOpenSpecialDates = onOpenSpecialDates, + onEditOverride = { overrideDialog = it }, + onEditFixedOverride = { fixedOverrideFor = calendar.id }, + onSetInDigest = { viewModel.setCalendarInDailyDigest(calendar.id, it) }, + ) + } + } + } + + alertStylePicker?.let { calendarId -> + val current = state.reminderAlertStyles.alertStyleFor(calendarId) + OptionPicker( + title = stringResource(R.string.settings_alert_style), + options = listOf(ReminderAlertStyle.Notification, ReminderAlertStyle.FullScreen), + selected = if (current.isFullScreen) ReminderAlertStyle.FullScreen else ReminderAlertStyle.Notification, + label = { alertStyleLabel(it) }, + summary = { + stringResource( + if (it.isFullScreen) { + R.string.settings_alert_style_full_screen_summary + } else { + R.string.settings_alert_style_notification_summary + }, + ) + }, + onSelect = { picked -> + if (picked.isFullScreen != current.isFullScreen) { + viewModel.setCalendarAlertStyle(calendarId, picked) + // Guide the user straight to the switch Android 14+ may hold back. + if (picked.isFullScreen && !canFullScreen) context.openFullScreenIntentSettings() + } + }, + onDismiss = { alertStylePicker = null }, + ) + } + alertSoundPicker?.let { calendarId -> + OptionPicker( + title = stringResource(R.string.settings_alert_sound), + options = listOf(ReminderAlertStyle.FullScreen, ReminderAlertStyle.FullScreenRing), + selected = state.reminderAlertStyles.alertStyleFor(calendarId), + label = { alertSoundLabel(it) }, + summary = { + stringResource( + if (it == ReminderAlertStyle.FullScreenRing) { + R.string.settings_alert_sound_ring_summary + } else { + R.string.settings_alert_sound_once_summary + }, + ) + }, + onSelect = { viewModel.setCalendarAlertStyle(calendarId, it) }, + onDismiss = { alertSoundPicker = null }, + ) + } + fixedOverrideFor?.let { calendarId -> + FixedTimeReminderPicker( + title = stringResource(R.string.settings_fixed_reminder), + selected = state.perCalendarFixedTimeReminderOverride.fixedTimeOverrideFor(calendarId), + onSelect = { viewModel.setCalendarFixedTimeReminderOverride(calendarId, it) }, + onDismiss = { fixedOverrideFor = null }, + inheritedLabel = fixedReminderChoiceLabel(state.defaultFixedTimeReminder), + inherited = state.defaultFixedTimeReminder, + ) + } + overrideDialog?.let { target -> + val map = if (target.isAllDay) { + state.perCalendarAllDayReminderOverride + } else { + state.perCalendarReminderOverride + } + ReminderDefaultPicker( + title = stringResource( + if (target.isAllDay) { + R.string.settings_default_reminder_allday + } else { + R.string.settings_default_reminder + }, + ), + isAllDay = target.isAllDay, + selected = map.reminderOverrideFor(target.calendarId), + allowInherit = true, + onSelect = { + if (target.isAllDay) { + viewModel.setCalendarAllDayReminderOverride(target.calendarId, it) + } else { + viewModel.setCalendarReminderOverride(target.calendarId, it) + } + }, + onDismiss = { overrideDialog = null }, + leadTimeSummary = if (target.isAllDay) { + allDayFiringTimeSummary(state.allDayReminderTimeMinutes) + } else { + null + }, + ) + } +} + +/** + * One calendar in its account group, with its options unfolding beneath it: + * the notification switch and channel deep-link for every calendar, then the + * default-reminder overrides where it takes them — or, for a special-dates + * calendar, a link to the section that owns them. + */ +@Composable +private fun CalendarReminderEntry( + calendar: CalendarSource, + state: SettingsUiState, + position: Position, + expanded: Boolean, + notifying: Boolean, + blocked: Boolean, + heldBack: FullScreenHeldBack, + onToggleExpand: () -> Unit, + onSetNotifying: (Boolean) -> Unit, + soundLabel: String?, + onPickSound: () -> Unit, + onOpenSettings: () -> Unit, + onOpenRingSettings: () -> Unit, + onEditAlertStyle: () -> Unit, + onEditAlertSound: () -> Unit, + onAllowFullScreen: () -> Unit, + onOpenSpecialDates: () -> Unit, + onEditOverride: (OverrideTarget) -> Unit, + onEditFixedOverride: () -> Unit, + onSetInDigest: (Boolean) -> Unit, +) { + val opensGroup = position == Position.Top || position == Position.Alone + val closesGroup = position == Position.Bottom || position == Position.Alone + GroupedRow( + title = calendar.displayName.orUnnamed(), + summary = when { + // Still in the summary, so only its reminders are off. + !notifying && state.dailyDigest.enabled && calendar.id !in state.dailyDigest.excludedCalendarIds -> + stringResource(R.string.settings_calendar_reminders_off) + !notifying -> stringResource(R.string.settings_calendar_notifications_off) + blocked -> stringResource(R.string.settings_notifications_blocked) + heldBack.any -> stringResource(R.string.settings_full_screen_held_back) + else -> null + }, + position = when { + !expanded -> position + opensGroup -> Position.Top + else -> Position.Middle + }, + leading = { CalendarColorChip(calendar.color) }, + trailing = { ExpandIcon(expanded) }, + onClick = onToggleExpand, + ) + AnimatedVisibility( + visible = expanded, + enter = expandEnter(), + exit = collapseExit(), + ) { + val managed = calendar.id in state.managedCalendarIds + val takesOverrides = calendar.canModifyContents && !managed + val alertStyle = state.reminderAlertStyles.alertStyleFor(calendar.id) + val digestOn = state.dailyDigest.enabled + val nested = MaterialTheme.colorScheme.surfaceContainerHighest + // The options round off their calendar; mid-group they keep the row gap. + Column(if (closesGroup) Modifier else Modifier.padding(bottom = 2.dp)) { + GroupedSwitchRow( + title = stringResource(R.string.settings_calendar_notifications), + checked = notifying, + onCheckedChange = onSetNotifying, + summary = stringResource(R.string.settings_calendar_notifications_hint), + position = Position.Middle, + container = nested, + ) + GroupedRow( + title = stringResource(R.string.settings_notification_sound), + summary = soundLabel, + position = Position.Middle, + container = nested, + onClick = onPickSound, + ) + GroupedRow( + title = stringResource(R.string.settings_notification_more), + summary = if (blocked) { + stringResource(R.string.settings_notifications_blocked_hint) + } else { + stringResource(R.string.settings_calendar_notification_sound_hint) + }, + position = Position.Middle, + container = nested, + trailing = { ExternalLinkIcon() }, + onClick = onOpenSettings, + ) + val lastAlertRow = !(managed || takesOverrides || digestOn) + GroupedRow( + title = stringResource(R.string.settings_alert_style), + summary = alertStyleLabel(alertStyle), + position = if (lastAlertRow && !alertStyle.isFullScreen) Position.Bottom else Position.Middle, + container = nested, + onClick = onEditAlertStyle, + ) + if (alertStyle.isFullScreen) { + GroupedRow( + title = stringResource(R.string.settings_alert_sound), + summary = alertSoundLabel(alertStyle), + position = if (lastAlertRow && !heldBack.any) Position.Bottom else Position.Middle, + container = nested, + onClick = onEditAlertSound, + ) + } + if (heldBack.ring) { + GroupedRow( + title = stringResource(R.string.reminder_ring_channel_name), + summary = stringResource(R.string.settings_ring_blocked_hint), + position = if (lastAlertRow && !heldBack.permission) Position.Bottom else Position.Middle, + container = nested, + trailing = { ExternalLinkIcon() }, + onClick = onOpenRingSettings, + ) + } + if (heldBack.permission) { + GroupedRow( + title = stringResource(R.string.settings_full_screen_permission), + summary = stringResource(R.string.settings_full_screen_permission_hint), + position = if (lastAlertRow) Position.Bottom else Position.Middle, + container = nested, + trailing = { ExternalLinkIcon() }, + onClick = onAllowFullScreen, + ) + } + if (digestOn) { + GroupedSwitchRow( + title = stringResource(R.string.settings_calendar_in_digest), + checked = calendar.id !in state.dailyDigest.excludedCalendarIds, + onCheckedChange = onSetInDigest, + summary = stringResource(R.string.settings_calendar_in_digest_hint), + position = if (managed || takesOverrides) Position.Middle else Position.Bottom, + container = nested, + ) + } + if (managed) { + GroupedRow( + title = stringResource(R.string.settings_default_reminder_allday), + summary = stringResource(R.string.settings_calendar_reminders_managed_hint), + position = Position.Bottom, + container = nested, + trailing = { ChevronIcon() }, + onClick = onOpenSpecialDates, + ) + } else if (takesOverrides) { + OverrideRow( + calendarId = calendar.id, + isAllDay = false, + choice = state.perCalendarReminderOverride.reminderOverrideFor(calendar.id), + globalDefault = state.defaultReminderMinutes, + position = Position.Middle, + container = nested, + onEditOverride = onEditOverride, + ) + GroupedRow( + title = stringResource(R.string.settings_fixed_reminder), + summary = when (val fixed = state.perCalendarFixedTimeReminderOverride.fixedTimeOverrideFor(calendar.id)) { + FixedTimeOverride.Inherit -> stringResource( + R.string.settings_calendar_reminder_inherits, + fixedReminderChoiceLabel(state.defaultFixedTimeReminder), + ) + FixedTimeOverride.Off -> stringResource(R.string.reminder_none) + is FixedTimeOverride.At -> fixedTimeReminderLabel(fixed.reminder) + }, + position = Position.Middle, + container = nested, + onClick = onEditFixedOverride, + ) + OverrideRow( + calendarId = calendar.id, + isAllDay = true, + choice = state.perCalendarAllDayReminderOverride.reminderOverrideFor(calendar.id), + globalDefault = state.defaultAllDayReminderMinutes, + position = Position.Bottom, + container = nested, + onEditOverride = onEditOverride, + ) + } + } + } +} + +@Composable +private fun OverrideRow( + calendarId: Long, + isAllDay: Boolean, + choice: ReminderOverride, + globalDefault: List, + position: Position, + container: Color, + onEditOverride: (OverrideTarget) -> Unit, +) { + GroupedRow( + title = stringResource( + if (isAllDay) R.string.settings_default_reminder_allday else R.string.settings_default_reminder, + ), + summary = calendarOverrideSummary(choice, globalDefault), + position = position, + container = container, + onClick = { onEditOverride(OverrideTarget(calendarId, isAllDay)) }, + ) +} + +@Composable +private fun ChevronIcon() { + Icon( + imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) +} + +/** Which calendar + event kind a per-calendar reminder-override dialog targets. */ +private data class OverrideTarget(val calendarId: Long, val isAllDay: Boolean) + +/** Row summary for a calendar: its override, or the inherited global default. */ +@Composable +private fun calendarOverrideSummary( + choice: ReminderOverride, + globalDefault: List, +): String = when (choice) { + ReminderOverride.Inherit -> + stringResource(R.string.settings_calendar_reminder_inherits, reminderChoiceLabel(globalDefault)) + ReminderOverride.None -> stringResource(R.string.reminder_none) + is ReminderOverride.Minutes -> reminderChoiceLabel(choice.minutes) +} + +/** What keeps a full-screen calendar from alerting as chosen: the missing permission, or the blocked ring channel. */ +private data class FullScreenHeldBack(val permission: Boolean, val ring: Boolean) { + val any: Boolean get() = permission || ring +} + +private fun fullScreenHeldBack( + style: ReminderAlertStyle, + notifying: Boolean, + blocked: Boolean, + ringBlocked: Boolean, + canFullScreen: Boolean, +): FullScreenHeldBack { + val live = notifying && !blocked + return FullScreenHeldBack( + permission = live && style.isFullScreen && !canFullScreen, + ring = live && style == ReminderAlertStyle.FullScreenRing && ringBlocked, + ) +} + +@Composable +private fun alertStyleLabel(style: ReminderAlertStyle): String = stringResource( + if (style.isFullScreen) R.string.settings_alert_style_full_screen else R.string.settings_alert_style_notification, +) + +@Composable +private fun alertSoundLabel(style: ReminderAlertStyle): String = stringResource( + if (style == ReminderAlertStyle.FullScreenRing) R.string.settings_alert_sound_ring else R.string.settings_alert_sound_once, +) + +/** Whether Android lets full-screen alerts open, re-read on every `ON_RESUME`. */ +@Composable +private fun rememberCanUseFullScreenIntent(): Boolean = rememberOnResume { it.canUseFullScreenIntent() } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/EventFormSettings.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/EventFormSettings.kt index 590a0085..0f1f0668 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/EventFormSettings.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/EventFormSettings.kt @@ -5,6 +5,8 @@ import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.AutoMode +import androidx.compose.material.icons.filled.Event import androidx.compose.material.icons.filled.Keyboard import androidx.compose.material.icons.filled.Schedule import androidx.compose.material3.Icon @@ -19,7 +21,10 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs +import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.EventFormField +import de.jeanlucmakiola.calendula.ui.common.CalendarPickerGroups +import de.jeanlucmakiola.calendula.ui.common.LeadingAvatar import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip import de.jeanlucmakiola.calendula.ui.common.DurationPicker import de.jeanlucmakiola.calendula.ui.common.durationLabel @@ -28,6 +33,7 @@ import de.jeanlucmakiola.calendula.ui.common.eventFormFieldLabel import de.jeanlucmakiola.calendula.ui.common.orUnnamed import de.jeanlucmakiola.floret.components.CollapsingScaffold import de.jeanlucmakiola.floret.components.ExpandIcon +import de.jeanlucmakiola.floret.components.FullScreenPicker import de.jeanlucmakiola.floret.components.GroupedHint import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.GroupedSwitchRow @@ -45,6 +51,7 @@ internal fun EventFormScreen( visible: Boolean = true, ) { var showDefaultDuration by remember { mutableStateOf(false) } + var showDefaultCalendar by remember { mutableStateOf(false) } // The calendar whose duration-override picker is open, if any. var durationTarget by remember { mutableStateOf(null) } var durationSectionExpanded by remember { mutableStateOf(false) } @@ -78,6 +85,26 @@ internal fun EventFormScreen( ) } + // The calendar a new event opens in (#429). + Spacer(Modifier.height(24.dp)) + GroupedRow( + title = stringResource(R.string.settings_default_calendar), + summary = state.defaultNewEventCalendar?.displayName?.orUnnamed() + ?: state.unavailableDefaultCalendar?.let { + stringResource(R.string.settings_default_calendar_unavailable, it.displayName.orUnnamed()) + } + ?: stringResource(R.string.settings_default_calendar_automatic), + position = Position.Alone, + leading = { + Icon( + imageVector = Icons.Default.Event, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + }, + onClick = { showDefaultCalendar = true }, + ) + // Auto-focus the title on a new event (#10), on by default. Spacer(Modifier.height(24.dp)) GroupedSwitchRow( @@ -159,6 +186,17 @@ internal fun EventFormScreen( ) } + if (showDefaultCalendar) { + DefaultCalendarPicker( + calendars = state.eventTargetCalendars, + selectedId = state.defaultNewEventCalendar?.id, + onSelect = { id -> + viewModel.setDefaultNewEventCalendar(state.eventTargetCalendars.firstOrNull { it.id == id }) + showDefaultCalendar = false + }, + onDismiss = { showDefaultCalendar = false }, + ) + } if (showDefaultDuration) { DurationPicker( title = stringResource(R.string.settings_event_duration), @@ -189,5 +227,34 @@ internal fun EventFormScreen( } } +/** "Automatic" above every calendar a new event can go into, grouped by account. */ +@Composable +private fun DefaultCalendarPicker( + calendars: List, + selectedId: Long?, + onSelect: (Long?) -> Unit, + onDismiss: () -> Unit, +) { + FullScreenPicker( + title = stringResource(R.string.settings_default_calendar), + onDismiss = onDismiss, + ) { + GroupedRow( + title = stringResource(R.string.settings_default_calendar_automatic), + summary = stringResource(R.string.settings_default_calendar_automatic_hint), + position = Position.Alone, + checked = selectedId == null, + leading = { LeadingAvatar(Icons.Default.AutoMode) }, + onClick = { onSelect(null) }, + ) + if (calendars.isNotEmpty()) Spacer(Modifier.height(16.dp)) + CalendarPickerGroups( + calendars = calendars, + selectedId = selectedId, + onSelect = onSelect, + ) + } +} + /** Lengths offered for a new timed event, in minutes — up to a full work day. */ private val EVENT_DURATION_PRESETS = listOf(15, 30, 45, 60, 90, 120, 240, 480) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt index b6fd7b28..80f841ed 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt @@ -1,55 +1,78 @@ package de.jeanlucmakiola.calendula.ui.settings +import de.jeanlucmakiola.floret.identity.collapseExit +import de.jeanlucmakiola.floret.identity.expandEnter +import androidx.compose.foundation.layout.Column +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.EnterExitState import android.Manifest import android.content.Context import android.content.Intent import android.os.Build import android.os.PowerManager import android.provider.Settings +import android.provider.Settings.System.DEFAULT_NOTIFICATION_URI +import android.widget.Toast import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts -import androidx.compose.animation.AnimatedVisibility -import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height +import androidx.compose.foundation.relocation.BringIntoViewRequester +import androidx.compose.foundation.relocation.bringIntoViewRequester import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight +import androidx.compose.material.icons.automirrored.filled.OpenInNew +import androidx.compose.material.icons.outlined.Info +import androidx.compose.material.icons.outlined.NotificationsActive import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.core.net.toUri -import androidx.lifecycle.Lifecycle -import androidx.lifecycle.LifecycleEventObserver -import androidx.lifecycle.compose.LocalLifecycleOwner +import androidx.lifecycle.compose.LifecycleResumeEffect +import androidx.lifecycle.compose.collectAsStateWithLifecycle import de.jeanlucmakiola.calendula.R -import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip +import de.jeanlucmakiola.calendula.domain.reminders.DailyDigestSettings +import de.jeanlucmakiola.calendula.domain.reminders.DigestDay +import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride +import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder +import de.jeanlucmakiola.calendula.ui.common.FixedTimeReminderPicker +import de.jeanlucmakiola.calendula.ui.common.fixedTimeReminderLabel import de.jeanlucmakiola.calendula.ui.common.DurationPicker -import de.jeanlucmakiola.calendula.ui.common.REMINDER_PRESETS import de.jeanlucmakiola.calendula.ui.common.ReminderDefaultPicker import de.jeanlucmakiola.calendula.ui.common.TimePickerAlert import de.jeanlucmakiola.calendula.ui.common.durationLabel -import de.jeanlucmakiola.calendula.ui.common.orUnnamed import de.jeanlucmakiola.floret.android.hasPermission +import de.jeanlucmakiola.floret.android.notificationSoundPickerIntent +import de.jeanlucmakiola.floret.android.openNotificationSettings +import de.jeanlucmakiola.floret.android.pickedSound import de.jeanlucmakiola.floret.components.CollapsingScaffold -import de.jeanlucmakiola.floret.components.ExpandIcon import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.GroupedSwitchRow +import de.jeanlucmakiola.floret.components.IconInfoCard +import de.jeanlucmakiola.floret.components.OptionPicker import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.SelectedCheck -import de.jeanlucmakiola.floret.identity.collapseExit -import de.jeanlucmakiola.floret.identity.expandEnter import de.jeanlucmakiola.floret.reminders.ReminderOverride import de.jeanlucmakiola.floret.reminders.minutesOrEmpty -import de.jeanlucmakiola.floret.reminders.reminderOverrideFor +import kotlinx.coroutines.launch import kotlinx.datetime.LocalTime /** @@ -62,15 +85,16 @@ internal fun NotificationsScreen( state: SettingsUiState, viewModel: SettingsViewModel, onBack: () -> Unit, - onOpenSpecialDates: () -> Unit, + onOpenCalendarReminders: () -> Unit, visible: Boolean = true, ) { val context = LocalContext.current val launcher = rememberLauncherForActivityResult( contract = ActivityResultContracts.RequestPermission(), ) { /* The pref is already on; a denial just leaves the OS gate shut. */ } - val toggleReminders: (Boolean) -> Unit = { enabled -> - viewModel.setRemindersEnabled(enabled) + // Turning either kind of notification on asks for the permission if missing. + fun askingPermission(set: (Boolean) -> Unit): (Boolean) -> Unit = { enabled -> + set(enabled) val needsPermission = enabled && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && !context.hasPermission(Manifest.permission.POST_NOTIFICATIONS) @@ -78,14 +102,29 @@ internal fun NotificationsScreen( launcher.launch(Manifest.permission.POST_NOTIFICATIONS) } } + val toggleReminders = askingPermission(viewModel::setRemindersEnabled) + val toggleDigest = askingPermission(viewModel::setDailyDigestEnabled) var showDefaultReminder by remember { mutableStateOf(false) } var showAllDayReminder by remember { mutableStateOf(false) } var showAllDayReminderTime by remember { mutableStateOf(false) } var showSnooze by remember { mutableStateOf(false) } - var overrideDialog by remember { mutableStateOf(null) } - var calendarSectionExpanded by remember { mutableStateOf(false) } - var expandedCalendars by remember { mutableStateOf(emptySet()) } + var showFixedDefault by remember { mutableStateOf(false) } + var showDigestDay by remember { mutableStateOf(false) } + var showDigestTime by remember { mutableStateOf(false) } + var revealDigest by rememberSaveable { mutableStateOf(false) } + val scope = rememberCoroutineScope() + val channelStatus by viewModel.channelStatus.collectAsStateWithLifecycle() + val digestBlocked by viewModel.digestBlocked.collectAsStateWithLifecycle() + val calendarIds = state.reminderCalendars.map { it.id } + LifecycleResumeEffect(calendarIds) { + viewModel.refreshChannelStatus(calendarIds) + onPauseOrDispose { } + } + val soundPicker = rememberReminderSoundPicker(viewModel, calendarIds) + val openAppSettings = soundPicker.openAppSettings + val loadedSounds = soundPicker.loadedSounds + val pickSound = soundPicker.pick CollapsingScaffold( title = stringResource(R.string.settings_section_notifications), @@ -93,6 +132,16 @@ internal fun NotificationsScreen( predictiveBack = true, visible = visible, ) { + if (IS_SAMSUNG && !state.notificationCategoryHintDismissed) { + NotificationCategoryHint( + onOpen = { + viewModel.dismissNotificationCategoryHint() + openAppSettings() + }, + onDismiss = viewModel::dismissNotificationCategoryHint, + ) + Spacer(Modifier.height(16.dp)) + } GroupedSwitchRow( title = stringResource(R.string.settings_reminders), checked = state.remindersEnabled, @@ -100,12 +149,37 @@ internal fun NotificationsScreen( summary = stringResource(R.string.settings_reminders_hint), position = Position.Top, ) + if (calendarIds.isNotEmpty()) { + GroupedRow( + title = stringResource(R.string.settings_notification_sound), + summary = loadedSounds?.let { globalSoundLabel(it, calendarIds) }, + position = Position.Middle, + onClick = { pickSound(ALL_CALENDARS) }, + ) + } + GroupedRow( + title = stringResource(R.string.settings_notification_more), + summary = if (channelStatus.appBlocked) { + stringResource(R.string.settings_notifications_blocked_hint) + } else { + stringResource(R.string.settings_notification_sound_hint) + }, + position = Position.Middle, + trailing = { ExternalLinkIcon() }, + onClick = openAppSettings, + ) GroupedRow( title = stringResource(R.string.settings_default_reminder), summary = reminderChoiceLabel(state.defaultReminderMinutes), position = Position.Middle, onClick = { showDefaultReminder = true }, ) + GroupedRow( + title = stringResource(R.string.settings_fixed_reminder), + summary = fixedReminderChoiceLabel(state.defaultFixedTimeReminder), + position = Position.Middle, + onClick = { showFixedDefault = true }, + ) GroupedRow( title = stringResource(R.string.settings_default_reminder_allday), summary = reminderChoiceLabel(state.defaultAllDayReminderMinutes), @@ -122,6 +196,26 @@ internal fun NotificationsScreen( onClick = { showAllDayReminderTime = true }, ) + Spacer(Modifier.height(24.dp)) + DailyDigestRows( + reveal = revealDigest, + onRevealed = { revealDigest = false }, + digest = state.dailyDigest, + blocked = channelStatus.appBlocked || digestBlocked, + onEnable = { + revealDigest = false + toggleDigest(it) + }, + onPickDay = { showDigestDay = true }, + onPickTime = { showDigestTime = true }, + onOpenSound = { + // The app's own page while the app is blocked: the channel's would be greyed out. + scope.launch { + context.openNotificationSettings(viewModel.digestChannel().takeUnless { channelStatus.appBlocked }) + } + }, + ) + // Reliability is a soft, optional battery-optimisation exemption via // a system-settings deep-link, shown as live status. Spacer(Modifier.height(24.dp)) @@ -149,87 +243,75 @@ internal fun NotificationsScreen( onClick = { showSnooze = true }, ) - // Per-calendar overrides, folded behind one header. Each writable - // calendar may keep, drop or replace the global default, separately for - // timed and all-day events. - if (state.writableCalendars.isNotEmpty()) { + if (state.reminderCalendars.isNotEmpty()) { Spacer(Modifier.height(24.dp)) GroupedRow( title = stringResource(R.string.settings_calendar_reminders_title), - summary = stringResource(R.string.settings_calendar_reminders_hint), + summary = stringResource(R.string.settings_calendar_reminders_subtitle), position = Position.Alone, - trailing = { ExpandIcon(calendarSectionExpanded) }, - onClick = { calendarSectionExpanded = !calendarSectionExpanded }, + trailing = { + Icon( + imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + }, + onClick = onOpenCalendarReminders, ) - AnimatedVisibility( - visible = calendarSectionExpanded, - enter = expandEnter(), - exit = collapseExit(), - ) { - Column { - state.writableCalendars.forEach { calendar -> - Spacer(Modifier.height(16.dp)) - // Special-dates calendars own their reminders in their - // own section — link there instead. - if (calendar.id in state.managedCalendarIds) { - GroupedRow( - title = calendar.displayName.orUnnamed(), - summary = stringResource(R.string.settings_calendar_reminders_managed_hint), - position = Position.Alone, - leading = { CalendarColorChip(calendar.color) }, - trailing = { - Icon( - imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - ) - }, - onClick = onOpenSpecialDates, - ) - return@forEach - } - val expanded = calendar.id in expandedCalendars - GroupedRow( - title = calendar.displayName.orUnnamed(), - position = if (expanded) Position.Top else Position.Alone, - leading = { CalendarColorChip(calendar.color) }, - trailing = { ExpandIcon(expanded) }, - onClick = { - expandedCalendars = if (expanded) { - expandedCalendars - calendar.id - } else { - expandedCalendars + calendar.id - } - }, - ) - AnimatedVisibility( - visible = expanded, - enter = expandEnter(), - exit = collapseExit(), - ) { - Column { - val timed = state.perCalendarReminderOverride.reminderOverrideFor(calendar.id) - GroupedRow( - title = stringResource(R.string.settings_default_reminder), - summary = calendarOverrideSummary(timed, state.defaultReminderMinutes), - position = Position.Middle, - onClick = { overrideDialog = OverrideTarget(calendar.id, isAllDay = false) }, - ) - val allDay = state.perCalendarAllDayReminderOverride.reminderOverrideFor(calendar.id) - GroupedRow( - title = stringResource(R.string.settings_default_reminder_allday), - summary = calendarOverrideSummary(allDay, state.defaultAllDayReminderMinutes), - position = Position.Bottom, - onClick = { overrideDialog = OverrideTarget(calendar.id, isAllDay = true) }, - ) - } - } - } - } - } } } + if (showFixedDefault) { + FixedTimeReminderPicker( + title = stringResource(R.string.settings_fixed_reminder), + selected = state.defaultFixedTimeReminder?.let { FixedTimeOverride.At(it) } ?: FixedTimeOverride.Off, + onSelect = { viewModel.setDefaultFixedTimeReminder((it as? FixedTimeOverride.At)?.reminder) }, + onDismiss = { showFixedDefault = false }, + footer = { dismiss -> + // For those after one list of the day's events (#459). + if (!state.dailyDigest.enabled) { + Spacer(Modifier.height(24.dp)) + GroupedRow( + title = stringResource(R.string.settings_digest_turn_on), + summary = stringResource(R.string.settings_digest_hint), + position = Position.Alone, + leading = { + Icon( + imageVector = Icons.Outlined.NotificationsActive, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + }, + onClick = { + revealDigest = true + toggleDigest(true) + dismiss() + }, + ) + } + }, + ) + } + if (showDigestDay) { + OptionPicker( + title = stringResource(R.string.settings_digest_day), + options = DigestDay.entries, + selected = state.dailyDigest.day, + label = { stringResource(digestDayLabel(it)) }, + onSelect = viewModel::setDailyDigestDay, + onDismiss = { showDigestDay = false }, + ) + } + if (showDigestTime) { + TimePickerAlert( + initial = LocalTime(state.dailyDigest.timeMinutes / 60, state.dailyDigest.timeMinutes % 60), + onConfirm = { + viewModel.setDailyDigestTimeMinutes(it.hour * 60 + it.minute) + showDigestTime = false + }, + onDismiss = { showDigestTime = false }, + ) + } if (showSnooze) { DurationPicker( title = stringResource(R.string.settings_snooze_duration), @@ -244,7 +326,7 @@ internal fun NotificationsScreen( if (showDefaultReminder) { ReminderDefaultPicker( title = stringResource(R.string.settings_default_reminder), - presets = REMINDER_PRESETS, + isAllDay = false, selected = state.defaultReminderMinutes.toReminderChoice(), allowInherit = false, onSelect = { viewModel.setDefaultReminderMinutes(it.minutesOrEmpty()) }, @@ -254,7 +336,7 @@ internal fun NotificationsScreen( if (showAllDayReminder) { ReminderDefaultPicker( title = stringResource(R.string.settings_default_reminder_allday), - presets = ALLDAY_REMINDER_PRESETS, + isAllDay = true, selected = state.defaultAllDayReminderMinutes.toReminderChoice(), allowInherit = false, onSelect = { viewModel.setDefaultAllDayReminderMinutes(it.minutesOrEmpty()) }, @@ -275,59 +357,160 @@ internal fun NotificationsScreen( onDismiss = { showAllDayReminderTime = false }, ) } - overrideDialog?.let { target -> - val map = if (target.isAllDay) { - state.perCalendarAllDayReminderOverride - } else { - state.perCalendarReminderOverride - } - ReminderDefaultPicker( - title = stringResource( - if (target.isAllDay) { - R.string.settings_default_reminder_allday - } else { - R.string.settings_default_reminder - }, - ), - presets = if (target.isAllDay) ALLDAY_REMINDER_PRESETS else REMINDER_PRESETS, - selected = map.reminderOverrideFor(target.calendarId), - allowInherit = true, - onSelect = { - if (target.isAllDay) { - viewModel.setCalendarAllDayReminderOverride(target.calendarId, it) - } else { - viewModel.setCalendarReminderOverride(target.calendarId, it) - } - }, - onDismiss = { overrideDialog = null }, - leadTimeSummary = if (target.isAllDay) { - allDayFiringTimeSummary(state.allDayReminderTimeMinutes) +} + +/** + * The daily summary (#459): its switch, and once on, which day it lists, when, + * and its channel's system settings. With [reveal], the block scrolls into view + * once those rows have expanded, then reports [onRevealed]. + */ +@Composable +private fun DailyDigestRows( + digest: DailyDigestSettings, + blocked: Boolean, + onEnable: (Boolean) -> Unit, + onPickDay: () -> Unit, + onPickTime: () -> Unit, + onOpenSound: () -> Unit, + reveal: Boolean, + onRevealed: () -> Unit, +) { + val requester = remember { BringIntoViewRequester() } + Column(Modifier.bringIntoViewRequester(requester)) { + GroupedSwitchRow( + title = stringResource(R.string.settings_digest), + checked = digest.enabled, + onCheckedChange = onEnable, + summary = if (digest.enabled) { + stringResource( + R.string.settings_digest_summary, + stringResource(digestDayLabel(digest.day)), + settingsTimeOfDay(digest.timeMinutes), + ) } else { - null + stringResource(R.string.settings_digest_hint) }, + position = if (digest.enabled) Position.Top else Position.Alone, ) + AnimatedVisibility(visible = digest.enabled, enter = expandEnter(), exit = collapseExit()) { + val settled = !transition.isRunning && transition.currentState == EnterExitState.Visible + LaunchedEffect(settled, reveal) { + if (settled && reveal) { + requester.bringIntoView() + onRevealed() + } + } + Column { + GroupedRow( + title = stringResource(R.string.settings_digest_day), + summary = stringResource(digestDayLabel(digest.day)), + position = Position.Middle, + onClick = onPickDay, + ) + GroupedRow( + title = stringResource(R.string.settings_digest_time), + summary = settingsTimeOfDay(digest.timeMinutes), + position = Position.Middle, + onClick = onPickTime, + ) + GroupedRow( + title = stringResource(R.string.settings_notification_sound), + summary = if (blocked) { + stringResource(R.string.settings_notifications_blocked_hint) + } else { + stringResource(R.string.settings_digest_sound_hint) + }, + position = Position.Bottom, + trailing = { ExternalLinkIcon() }, + onClick = onOpenSound, + ) + } + } } } -/** Which calendar + event kind a per-calendar reminder-override dialog targets. */ -private data class OverrideTarget(val calendarId: Long, val isAllDay: Boolean) +/** [soundTarget] meaning every calendar at once. */ +internal const val ALL_CALENDARS = Long.MIN_VALUE + +/** What the calendars that have a channel share, sound-wise. */ +private sealed interface SharedSound { + data object None : SharedSound + data object Mixed : SharedSound + data class Same(val sound: ReminderSound) : SharedSound +} + +private fun sharedSound(sounds: Map, calendarIds: List): SharedSound { + val distinct = calendarIds.mapNotNull { sounds[it] }.distinctBy { it.uri } + return when (distinct.size) { + 0 -> SharedSound.None + 1 -> SharedSound.Same(distinct.single()) + else -> SharedSound.Mixed + } +} + +@Composable +internal fun soundLabel(sound: ReminderSound?): String = when { + sound == null -> stringResource(R.string.settings_notification_sound_default) + sound.uri == null -> stringResource(R.string.settings_notification_sound_silent) + sound.uri == DEFAULT_NOTIFICATION_URI -> sound.title + ?.let { stringResource(R.string.settings_notification_sound_default_named, it) } + ?: stringResource(R.string.settings_notification_sound_default) + else -> sound.title ?: stringResource(R.string.settings_notification_sound_custom) +} + +@Composable +private fun globalSoundLabel(sounds: Map, calendarIds: List): String = + when (val shared = sharedSound(sounds, calendarIds)) { + SharedSound.None -> soundLabel(null) + SharedSound.Mixed -> stringResource(R.string.settings_notification_sound_mixed) + is SharedSound.Same -> soundLabel(shared.sound) + } + +/** Samsung's One UI can start a new notification category switched off (#145). */ +private val IS_SAMSUNG = Build.MANUFACTURER.equals("samsung", ignoreCase = true) + +/** The one-time Samsung note, with a way into the app's notification settings. */ +@Composable +private fun NotificationCategoryHint(onOpen: () -> Unit, onDismiss: () -> Unit) { + IconInfoCard( + icon = Icons.Outlined.Info, + iconContentDescription = null, + iconAlignment = Alignment.Top, + ) { + Text( + text = stringResource(R.string.settings_notification_category_hint), + style = MaterialTheme.typography.bodyMedium, + ) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + TextButton(onClick = onDismiss) { Text(stringResource(R.string.reminder_action_dismiss)) } + TextButton(onClick = onOpen) { Text(stringResource(R.string.settings_notification_category_hint_open)) } + } + } +} + +private fun digestDayLabel(day: DigestDay): Int = when (day) { + DigestDay.Today -> R.string.settings_digest_day_today + DigestDay.Tomorrow -> R.string.settings_digest_day_tomorrow +} + +/** A fixed-time default's label, or "None". */ +@Composable +internal fun fixedReminderChoiceLabel(reminder: FixedTimeReminder?): String = + reminder?.let { fixedTimeReminderLabel(it) } ?: stringResource(R.string.reminder_none) + +@Composable +internal fun ExternalLinkIcon() { + Icon( + imageVector = Icons.AutoMirrored.Filled.OpenInNew, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) +} /** A global default (empty = none) as a picker choice for selection highlighting. */ private fun List.toReminderChoice(): ReminderOverride = if (isEmpty()) ReminderOverride.None else ReminderOverride.Minutes(this) -/** Row summary for a calendar: its override, or the inherited global default. */ -@Composable -private fun calendarOverrideSummary( - choice: ReminderOverride, - globalDefault: List, -): String = when (choice) { - ReminderOverride.Inherit -> - stringResource(R.string.settings_calendar_reminder_inherits, reminderChoiceLabel(globalDefault)) - ReminderOverride.None -> stringResource(R.string.reminder_none) - is ReminderOverride.Minutes -> reminderChoiceLabel(choice.minutes) -} - /** Snooze delays offered for the notification "Snooze" action, in minutes. */ private val SNOOZE_PRESETS = listOf(5, 10, 15, 30, 60) @@ -336,20 +519,18 @@ private val SNOOZE_PRESETS = listOf(5, 10, 15, 30, 60) * `ON_RESUME` so a change made in system settings shows up at once. */ @Composable -private fun rememberBatteryOptimizationExempt(): Boolean { +private fun rememberBatteryOptimizationExempt(): Boolean = rememberOnResume(::isIgnoringBatteryOptimizations) + +/** [read], re-read on every `ON_RESUME` so a change made in system settings shows up at once. */ +@Composable +internal fun rememberOnResume(read: (Context) -> Boolean): Boolean { val context = LocalContext.current - var exempt by remember { mutableStateOf(isIgnoringBatteryOptimizations(context)) } - val lifecycleOwner = LocalLifecycleOwner.current - DisposableEffect(lifecycleOwner) { - val observer = LifecycleEventObserver { _, event -> - if (event == Lifecycle.Event.ON_RESUME) { - exempt = isIgnoringBatteryOptimizations(context) - } - } - lifecycleOwner.lifecycle.addObserver(observer) - onDispose { lifecycleOwner.lifecycle.removeObserver(observer) } + var value by remember { mutableStateOf(read(context)) } + LifecycleResumeEffect(context) { + value = read(context) + onPauseOrDispose {} } - return exempt + return value } private fun isIgnoringBatteryOptimizations(context: Context): Boolean { @@ -372,3 +553,68 @@ private fun openBatteryOptimizationSettings(context: Context) { } } } + +/** The reminder-sound picker (#518) shared by Notifications (all calendars) and the per-calendar page. */ +internal class ReminderSoundPicker( + val loadedSounds: Map?, + val pick: (Long) -> Unit, + val openAppSettings: () -> Unit, + val openCalendarSettings: (Long) -> Unit, +) + +@Composable +internal fun rememberReminderSoundPicker(viewModel: SettingsViewModel, calendarIds: List): ReminderSoundPicker { + val context = LocalContext.current + val scope = rememberCoroutineScope() + val openCalendarSettings: (Long) -> Unit = { calendarId -> + scope.launch { context.openNotificationSettings(viewModel.soundSettingsChannel(calendarId)) } + } + val openAppSettings: () -> Unit = { + scope.launch { + viewModel.syncReminderChannels() + context.openNotificationSettings() + } + } + val loadedSounds by viewModel.channelSounds.collectAsStateWithLifecycle() + val sounds = loadedSounds.orEmpty() + val soundFailedMessage = stringResource(R.string.settings_notification_sound_failed) + val soundUnreadableMessage = stringResource(R.string.settings_notification_sound_unreadable) + LaunchedEffect(Unit) { + viewModel.soundFailed.collect { failure -> + val message = if (failure == SoundFailure.Unreadable) soundUnreadableMessage else soundFailedMessage + Toast.makeText(context, message, Toast.LENGTH_LONG).show() + } + } + // ALL_CALENDARS, a calendar id, or null when no pick is pending. + var soundTarget by rememberSaveable { mutableStateOf(null) } + val soundPicker = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> + val target = soundTarget + soundTarget = null + val picked = pickedSound(result.resultCode, result.data) ?: return@rememberLauncherForActivityResult + when (target) { + null -> Unit + ALL_CALENDARS -> viewModel.setReminderSoundForAll(picked.uri) + else -> viewModel.setReminderSound(target, picked.uri) + } + } + val pickSoundTitle = stringResource(R.string.settings_notification_sound) + val pickSound: (Long) -> Unit = pick@{ target -> + if (soundTarget != null) return@pick + val current = if (target == ALL_CALENDARS) { + (sharedSound(sounds, calendarIds) as? SharedSound.Same)?.sound + } else { + sounds[target] + } + soundTarget = target + try { + // A missing or mixed sound preselects Default; a silent one, Silent. + val preselect = if (current == null) DEFAULT_NOTIFICATION_URI else current.uri + soundPicker.launch(notificationSoundPickerIntent(preselect, pickSoundTitle)) + } catch (e: RuntimeException) { + // No picker, or one that refuses to start: the system screen still has the sound. + soundTarget = null + if (target == ALL_CALENDARS) openAppSettings() else openCalendarSettings(target) + } + } + return ReminderSoundPicker(loadedSounds, pickSound, openAppSettings, openCalendarSettings) +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsCommon.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsCommon.kt index 746ff28d..e484c99d 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsCommon.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsCommon.kt @@ -72,9 +72,6 @@ internal fun reminderChoiceLabel(minutes: List): String { return minutes.map { reminderLeadTimeLabel(it) }.joinToString(", ") } -/** Day-scale lead times for all-day defaults and contact special dates. */ -internal val ALLDAY_REMINDER_PRESETS = listOf(0, 1_440, 2_880, 10_080) - /** A minute-of-day in the app's own 12/24-hour convention ([LocalUse24HourFormat]). */ @Composable internal fun settingsTimeOfDay(minutesOfDay: Int): String = diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsScreen.kt index 3bab7449..e3ba551c 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsScreen.kt @@ -73,7 +73,7 @@ import de.jeanlucmakiola.floret.identity.predictiveBackExit /** The settings sub-screens reached from the hub's category rows. */ private enum class SettingsSection { - Appearance, Views, EventForm, Notifications, SpecialDates, Widgets, Licences + Appearance, Views, EventForm, Notifications, CalendarReminders, SpecialDates, Widgets, Licences } /** @@ -131,8 +131,9 @@ fun SettingsScreen( ) { EventFormScreen(state = state, viewModel = viewModel, onBack = { section = null }, visible = section == SettingsSection.EventForm) } + // Stays up beneath its per-calendar subpage, so backing out reveals it. AnimatedVisibility( - visible = section == SettingsSection.Notifications, + visible = section == SettingsSection.Notifications || section == SettingsSection.CalendarReminders, enter = slideInHorizontally(slideSpec) { it } + fadeIn(), exit = overlayExit, ) { @@ -140,10 +141,23 @@ fun SettingsScreen( state = state, viewModel = viewModel, onBack = { section = null }, - onOpenSpecialDates = { section = SettingsSection.SpecialDates }, + onOpenCalendarReminders = { section = SettingsSection.CalendarReminders }, visible = section == SettingsSection.Notifications, ) } + AnimatedVisibility( + visible = section == SettingsSection.CalendarReminders, + enter = slideInHorizontally(slideSpec) { it } + fadeIn(), + exit = overlayExit, + ) { + CalendarRemindersScreen( + state = state, + viewModel = viewModel, + onBack = { section = SettingsSection.Notifications }, + onOpenSpecialDates = { section = SettingsSection.SpecialDates }, + visible = section == SettingsSection.CalendarReminders, + ) + } AnimatedVisibility( visible = section == SettingsSection.SpecialDates, enter = slideInHorizontally(slideSpec) { it } + fadeIn(), diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt index d97e7a00..a296674f 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt @@ -1,5 +1,9 @@ package de.jeanlucmakiola.calendula.ui.settings +import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle +import de.jeanlucmakiola.calendula.domain.reminders.DailyDigestSettings +import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder +import android.net.Uri import de.jeanlucmakiola.floret.reminders.ReminderOverride import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs @@ -96,8 +100,28 @@ data class SettingsUiState( val perCalendarReminderOverride: Map> = emptyMap(), /** Per-calendar overrides of [defaultAllDayReminderMinutes] for all-day events. */ val perCalendarAllDayReminderOverride: Map> = emptyMap(), - /** Writable calendars, shown as per-calendar reminder-override rows. */ + /** The "N days before at HH:MM" default for new timed events (#459); null = none. */ + val defaultFixedTimeReminder: FixedTimeReminder? = null, + /** Per-calendar overrides of [defaultFixedTimeReminder]: absent inherits, null turns it off. */ + val perCalendarFixedTimeReminderOverride: Map = emptyMap(), + /** The daily summary notification (#459). */ + val dailyDigest: DailyDigestSettings = DailyDigestSettings(), + /** Switched-on calendars you can edit: the per-calendar event-duration rows. */ val writableCalendars: List = emptyList(), + /** Switched-on calendars, each with its own notification switch and channel (#145, #272). */ + val reminderCalendars: List = emptyList(), + /** Calendars whose reminders Calendula doesn't post (#272). */ + val mutedReminderCalendarIds: Set = emptySet(), + /** Per-calendar alert styles (#171); absent means a plain notification. */ + val reminderAlertStyles: Map = emptyMap(), + /** Whether the Samsung notification-category hint has been dismissed (#145); hidden until prefs load. */ + val notificationCategoryHintDismissed: Boolean = true, + /** Calendars a new event can go into: the default calendar picker's choices. */ + val eventTargetCalendars: List = emptyList(), + /** The default calendar for new events (#429); null is Automatic, also when the stored one fell out. */ + val defaultNewEventCalendar: CalendarSource? = null, + /** The stored default while it exists but takes no new events, named on the Automatic row. */ + val unavailableDefaultCalendar: CalendarSource? = null, /** * Whether the event-colour picker is offered on calendars that publish no * colour palette (the colour may then not survive their next sync). @@ -130,3 +154,9 @@ data class SpecialDatesUiState( /** Epoch millis of the last sync, or 0 if it has never run. */ val lastRun: Long = 0L, ) + +/** A reminder channel's sound: null [uri] is silent; [title] is null when it can't be resolved. */ +data class ReminderSound(val uri: Uri?, val title: String?) + +/** Why a picked reminder sound wasn't applied. */ +enum class SoundFailure { NotApplied, Unreadable } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt index 812910d8..49915cc5 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt @@ -3,6 +3,8 @@ package de.jeanlucmakiola.calendula.ui.settings import android.content.Context import android.net.Uri import android.os.Build +import android.provider.Settings +import android.util.Log import androidx.datastore.preferences.core.Preferences import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope @@ -16,10 +18,18 @@ import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesScheduler import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesSyncEngine import de.jeanlucmakiola.calendula.data.contacts.resolveTitleTemplate import de.jeanlucmakiola.calendula.data.fonts.CustomFontStore +import de.jeanlucmakiola.floret.android.ringtoneTitle import de.jeanlucmakiola.floret.android.stateWhileSubscribed import de.jeanlucmakiola.floret.di.IoDispatcher +import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride +import de.jeanlucmakiola.calendula.data.prefs.dailyDigest +import de.jeanlucmakiola.calendula.data.prefs.ReminderStatePrefs +import de.jeanlucmakiola.calendula.data.reminders.DailyDigestNotifier +import de.jeanlucmakiola.calendula.domain.reminders.DigestDay +import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder import de.jeanlucmakiola.floret.reminders.ReminderOverride import de.jeanlucmakiola.floret.reminders.reminderOverrideFor +import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs @@ -33,10 +43,18 @@ import de.jeanlucmakiola.calendula.data.prefs.SpecialDatesStalledReason import de.jeanlucmakiola.floret.prefs.ThemeMode import de.jeanlucmakiola.calendula.data.prefs.TimeFormatPref import de.jeanlucmakiola.calendula.data.prefs.WeekStartPref +import de.jeanlucmakiola.calendula.data.reminders.ReminderChannelStatus +import de.jeanlucmakiola.calendula.data.reminders.ReminderChannels +import de.jeanlucmakiola.calendula.data.reminders.ReminderNotifier +import de.jeanlucmakiola.calendula.data.reminders.RingMatch import de.jeanlucmakiola.calendula.data.reminders.ReminderScanner import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle import de.jeanlucmakiola.calendula.domain.EventFormField +import de.jeanlucmakiola.calendula.domain.DefaultCalendarRef +import de.jeanlucmakiola.calendula.domain.effectiveDefaultCalendar import de.jeanlucmakiola.calendula.domain.FontRole +import de.jeanlucmakiola.calendula.domain.isEventTarget import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType import de.jeanlucmakiola.calendula.ui.agenda.AgendaRange import de.jeanlucmakiola.calendula.ui.common.CalendarView @@ -45,7 +63,12 @@ import de.jeanlucmakiola.calendula.ui.common.TimelineScale import de.jeanlucmakiola.calendula.ui.month.MonthViewStyle import de.jeanlucmakiola.calendula.ui.theme.AppFontSettings import de.jeanlucmakiola.calendula.ui.theme.FONT_CUSTOM_TOKEN +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow @@ -54,6 +77,7 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -62,11 +86,16 @@ import javax.inject.Inject @HiltViewModel class SettingsViewModel @Inject constructor( private val prefs: SettingsPrefs, + calendarPrefs: CalendarPrefs, repository: CalendarRepository, private val specialDatesEngine: SpecialDatesSyncEngine, specialDatesSpec: SpecialDatesCalendarSpec, private val launcherNameManager: LauncherNameManager, private val reminderScanner: ReminderScanner, + private val reminderChannels: ReminderChannels, + private val reminderNotifier: ReminderNotifier, + private val digestNotifier: DailyDigestNotifier, + private val reminderState: ReminderStatePrefs, @IoDispatcher private val io: CoroutineDispatcher, @ApplicationContext private val appContext: Context, ) : ViewModel() { @@ -74,61 +103,84 @@ class SettingsViewModel @Inject constructor( private val dynamicColorAvailable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S /** - * Writable calendars that are switched on — the only ones that take a - * per-calendar reminder override, since a switched-off one plans no - * reminders at all (#75). + * Every calendar, for the default calendar picker (#429); the settings + * that only apply to switched-on calendars filter it with [switchedOn]. */ - private val writableCalendars: Flow> = repository.calendars() - .map { calendars -> calendars.filter { it.canModifyContents && it.isVisibleInSystem } } + private val calendars: Flow> = repository.calendars() .catch { emit(emptyList()) } + /** + * Calendars that are switched on — the only ones that plan reminders at + * all (#75), so the only ones with notification settings. + */ + private val visibleCalendars: Flow> = + combine(calendars, calendarPrefs.pendingDisabledCalendarIds, ::switchedOn) + + private fun switchedOn(calendars: List, pending: Set) = + calendars.filter { it.isVisibleInSystem && it.id !in pending } + val state: StateFlow = - combine(prefs.data, writableCalendars) { stored, calendars -> stored.toUiState(calendars) } + combine(prefs.data, calendars, calendarPrefs.pendingDisabledCalendarIds) { stored, calendars, pending -> + stored.toUiState(calendars, switchedOn(calendars, pending)) + } .stateWhileSubscribed( scope = viewModelScope, initialValue = SettingsUiState(dynamicColorAvailable = dynamicColorAvailable), ) - private fun Preferences.toUiState(calendars: List) = SettingsUiState( - themeMode = this[SettingsKeys.themeMode], - dynamicColor = this[SettingsKeys.dynamicColor] && dynamicColorAvailable, - dynamicColorAvailable = dynamicColorAvailable, - softenColors = this[SettingsKeys.softenCalendarColors], - weekStart = this[SettingsKeys.weekStart], - timeFormat = this[SettingsKeys.timeFormat], - showHourGrid = this[SettingsKeys.showHourGrid], - multiDayCount = this[SettingsKeys.multiDayCount], - pastEventDisplay = this[SettingsKeys.pastEventDisplay], - dimCompletedEvents = this[SettingsKeys.dimCompletedEvents], - showWeekNumbers = this[SettingsKeys.showWeekNumbers], - monthShowStartTimes = this[SettingsKeys.monthShowStartTimes], - todayButtonInToolbar = this[SettingsKeys.todayButtonInToolbar], - dragToReschedule = this[SettingsKeys.dragToReschedule], - tapOpensEditor = this[SettingsKeys.tapOpensEditor], - agendaScreenRange = this[SettingsKeys.agendaScreenRange], - agendaShowToday = this[SettingsKeys.agendaShowToday], - agendaShowRangeBar = this[SettingsKeys.agendaShowRangeBar], - defaultView = this[SettingsKeys.defaultView], - quickSwitchConfig = this[SettingsKeys.quickSwitchConfig], - monthViewStyle = this[SettingsKeys.monthViewStyle], - timelineScale = this[SettingsKeys.timelineScale], - timelineHours = timelineHours, - drawerViewOrder = this[SettingsKeys.drawerViewOrder], - defaultFormFields = this[SettingsKeys.defaultFormFields], - autofocusEventTitle = this[SettingsKeys.autofocusEventTitle], - defaultEventDurationMinutes = this[SettingsKeys.defaultEventDurationMinutes], - perCalendarEventDuration = this[SettingsKeys.perCalendarEventDuration], - remindersEnabled = this[SettingsKeys.remindersEnabled], - defaultReminderMinutes = this[SettingsKeys.defaultReminderMinutes], - defaultAllDayReminderMinutes = this[SettingsKeys.defaultAllDayReminderMinutes], - allDayReminderTimeMinutes = this[SettingsKeys.allDayReminderTimeMinutes], - snoozeMinutes = this[SettingsKeys.snoozeMinutes], - perCalendarReminderOverride = this[SettingsKeys.perCalendarReminderOverride], - perCalendarAllDayReminderOverride = this[SettingsKeys.perCalendarAllDayReminderOverride], - writableCalendars = calendars, - allowColorOnUnsupportedCalendars = this[SettingsKeys.allowColorOnUnsupportedCalendars], - managedCalendarIds = specialDatesCalendars.values.toSet(), - ) + private fun Preferences.toUiState(calendars: List, visible: List): SettingsUiState { + val storedDefault = this[SettingsKeys.defaultNewEventCalendar] + return SettingsUiState( + themeMode = this[SettingsKeys.themeMode], + dynamicColor = this[SettingsKeys.dynamicColor] && dynamicColorAvailable, + dynamicColorAvailable = dynamicColorAvailable, + softenColors = this[SettingsKeys.softenCalendarColors], + weekStart = this[SettingsKeys.weekStart], + timeFormat = this[SettingsKeys.timeFormat], + showHourGrid = this[SettingsKeys.showHourGrid], + multiDayCount = this[SettingsKeys.multiDayCount], + pastEventDisplay = this[SettingsKeys.pastEventDisplay], + dimCompletedEvents = this[SettingsKeys.dimCompletedEvents], + showWeekNumbers = this[SettingsKeys.showWeekNumbers], + monthShowStartTimes = this[SettingsKeys.monthShowStartTimes], + todayButtonInToolbar = this[SettingsKeys.todayButtonInToolbar], + dragToReschedule = this[SettingsKeys.dragToReschedule], + tapOpensEditor = this[SettingsKeys.tapOpensEditor], + agendaScreenRange = this[SettingsKeys.agendaScreenRange], + agendaShowToday = this[SettingsKeys.agendaShowToday], + agendaShowRangeBar = this[SettingsKeys.agendaShowRangeBar], + defaultView = this[SettingsKeys.defaultView], + quickSwitchConfig = this[SettingsKeys.quickSwitchConfig], + monthViewStyle = this[SettingsKeys.monthViewStyle], + timelineScale = this[SettingsKeys.timelineScale], + timelineHours = timelineHours, + drawerViewOrder = this[SettingsKeys.drawerViewOrder], + defaultFormFields = this[SettingsKeys.defaultFormFields], + autofocusEventTitle = this[SettingsKeys.autofocusEventTitle], + defaultEventDurationMinutes = this[SettingsKeys.defaultEventDurationMinutes], + perCalendarEventDuration = this[SettingsKeys.perCalendarEventDuration], + remindersEnabled = this[SettingsKeys.remindersEnabled], + defaultReminderMinutes = this[SettingsKeys.defaultReminderMinutes], + defaultAllDayReminderMinutes = this[SettingsKeys.defaultAllDayReminderMinutes], + allDayReminderTimeMinutes = this[SettingsKeys.allDayReminderTimeMinutes], + snoozeMinutes = this[SettingsKeys.snoozeMinutes], + perCalendarReminderOverride = this[SettingsKeys.perCalendarReminderOverride], + perCalendarAllDayReminderOverride = this[SettingsKeys.perCalendarAllDayReminderOverride], + defaultFixedTimeReminder = this[SettingsKeys.defaultFixedTimeReminder], + perCalendarFixedTimeReminderOverride = this[SettingsKeys.perCalendarFixedTimeReminderOverride], + dailyDigest = dailyDigest, + writableCalendars = visible.filter { it.canModifyContents }, + reminderCalendars = visible, + mutedReminderCalendarIds = this[SettingsKeys.mutedReminderCalendarIds], + reminderAlertStyles = this[SettingsKeys.reminderAlertStyles], + notificationCategoryHintDismissed = this[SettingsKeys.notificationCategoryHintDismissed], + eventTargetCalendars = calendars.filter { it.isEventTarget }, + defaultNewEventCalendar = effectiveDefaultCalendar(storedDefault, calendars), + unavailableDefaultCalendar = storedDefault?.find(calendars)?.takeUnless { it.isEventTarget }, + allowColorOnUnsupportedCalendars = this[SettingsKeys.allowColorOnUnsupportedCalendars], + managedCalendarIds = specialDatesCalendars.values.toSet(), + ) + } /** * The app-wide custom-font choice (issue #19). Its own flow — both this @@ -353,12 +405,174 @@ class SettingsViewModel @Inject constructor( fun setRemindersEnabled(enabled: Boolean) { viewModelScope.launch { prefs.setRemindersEnabled(enabled) + if (!enabled) reminderNotifier.stopRing(RingMatch.Any) reminderScanner.scan() } } + /** + * Re-plans, since a muted calendar armed no wake-up for its next reminder. + * Unmuting scans once more before the write, so the watermark starts at the + * unmute and nothing that came due while muted is replayed. + */ + fun setCalendarRemindersEnabled(calendarId: Long, enabled: Boolean) { + viewModelScope.launch { + if (enabled) reminderScanner.scan() + prefs.setCalendarRemindersEnabled(calendarId, enabled) + if (!enabled) reminderNotifier.stopRing(RingMatch.Calendar(calendarId)) + reminderScanner.scan() + } + } + + fun setCalendarAlertStyle(calendarId: Long, style: ReminderAlertStyle) { + viewModelScope.launch { + prefs.setCalendarAlertStyle(calendarId, style) + // Up front, so it can be checked in system settings before the first ring. + if (style == ReminderAlertStyle.FullScreenRing) { + onChannels { ensureRingChannel() } + refreshChannelStatus(state.value.reminderCalendars.map { it.id }) + } + // A ring for it goes quiet but stays in the shade. + if (style != ReminderAlertStyle.FullScreenRing) { + reminderNotifier.stopRing(RingMatch.Calendar(calendarId), handBack = true) + } + } + } + + private val _channelStatus = MutableStateFlow(ReminderChannelStatus()) + + /** What the system blocks of the reminders; re-read with [refreshChannelStatus] (#145). */ + val channelStatus: StateFlow = _channelStatus.asStateFlow() + + private var channelStatusJob: Job? = null + + private val _channelSounds = MutableStateFlow?>(null) + + /** Each calendar's reminder sound (#518), null until first read; a calendar without a channel yet is absent. */ + val channelSounds: StateFlow?> = _channelSounds.asStateFlow() + + private val _soundFailed = Channel(Channel.CONFLATED) + + /** Emits when a picked sound couldn't be applied; kept until the screen collects it. */ + val soundFailed: Flow = _soundFailed.receiveAsFlow() + + private val soundTitles = mutableMapOf() + + fun refreshChannelStatus(calendarIds: Collection) { + channelStatusJob?.cancel() + channelStatusJob = viewModelScope.launch { + onChannels { status(calendarIds) }?.let { _channelStatus.value = it } + _digestBlocked.value = withContext(io) { runCatching { digestNotifier.isChannelOff() }.getOrDefault(false) } + val sounds = onChannels { sounds(calendarIds) } ?: return@launch + _channelSounds.value = withContext(io) { + sounds.mapValues { (_, uri) -> + ReminderSound(uri, uri?.let(::soundTitle)) + } + } + } + } + + /** A sound's title, cached unless it is a "default" alias whose target can change. */ + private fun soundTitle(uri: Uri): String? { + if (uri.authority == Settings.AUTHORITY) return appContext.ringtoneTitle(uri) + return synchronized(soundTitles) { soundTitles.getOrPut(uri) { appContext.ringtoneTitle(uri) } } + } + + /** Give [calendarId]'s reminders [sound] (null = silent), on a fresh channel (#518). */ + fun setReminderSound(calendarId: Long, sound: Uri?) = applySound(sound) { + setSound(listOf(calendarId), sound, createMissing = true) + } + + /** + * Give every switched-on calendar's reminders [sound]. Reads the calendars + * itself, so a pick returning after process death still finds them; those + * that only get a channel when something posts are left alone. + */ + fun setReminderSoundForAll(sound: Uri?) = applySound(sound) { + try { + sync() + } catch (e: Exception) { + Log.w("SettingsViewModel", "Channel sync before a sound pick failed", e) + } + val ids = visibleCalendars.first().map { it.id } + ids.isNotEmpty() && setSound(ids, sound, createMissing = false) + } + + private fun canRead(uri: Uri): Boolean = uri.authority == Settings.AUTHORITY || + runCatching { appContext.contentResolver.openAssetFileDescriptor(uri, "r")?.close() != null }.getOrDefault(false) + + /** Runs to completion even if the screen closes meanwhile, so a pick is never half-applied. */ + private fun applySound(sound: Uri?, block: suspend ReminderChannels.() -> Boolean) { + viewModelScope.launch { + val failure = withContext(io + NonCancellable) { + try { + // The system plays the sound but checks that Calendula could read it. + when { + sound != null && !canRead(sound) -> SoundFailure.Unreadable + reminderChannels.block() -> null + else -> SoundFailure.NotApplied + } + } catch (e: Exception) { + Log.w("SettingsViewModel", "Could not set the reminder sound", e) + SoundFailure.NotApplied + } + } + failure?.let(_soundFailed::trySend) + refreshChannelStatus(visibleCalendars.first().map { it.id }) + } + } + + private val _digestBlocked = MutableStateFlow(false) + + /** + * Whether the daily summary's own channel is switched off (#459); the app-wide + * block is [channelStatus]'s. Refreshed with [refreshChannelStatus]. + */ + val digestBlocked: StateFlow = _digestBlocked.asStateFlow() + + fun dismissNotificationCategoryHint() = save { dismissNotificationCategoryHint() } + + /** + * The channel whose system screen to open for [calendarId] (#340), created + * if needed; null when only the app's own screen can help — the app or the + * calendar's account group is blocked there, or the channel couldn't be made. + */ + suspend fun soundSettingsChannel(calendarId: Long): String? = onChannels { + val channelId = channelFor(calendarId) ?: return@onChannels null + val status = status(listOf(calendarId)) + channelId.takeUnless { status.appBlocked || calendarId in status.groupBlockedCalendarIds } + } + + /** + * Create the per-calendar channels before showing the app's channel list, even with reminders off, + * plus the ring and daily summary ones in use, so they are on the list to check. + */ + suspend fun syncReminderChannels() { + val ringing = state.value.reminderAlertStyles.containsValue(ReminderAlertStyle.FullScreenRing) + onChannels { + sync() + if (ringing) ensureRingChannel() + } + if (state.value.dailyDigest.enabled) digestChannel() + } + + private suspend fun onChannels(block: ReminderChannels.() -> T): T? = withContext(io) { + try { + reminderChannels.block() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w("SettingsViewModel", "Reminder channel update failed", e) + null + } + } + fun setAutofocusEventTitle(enabled: Boolean) = save { setAutofocusEventTitle(enabled) } + /** [calendar] null goes back to Automatic. */ + fun setDefaultNewEventCalendar(calendar: CalendarSource?) = + save { setDefaultNewEventCalendar(calendar?.let(DefaultCalendarRef::of)) } + fun setDefaultEventDuration(minutes: Int) = save { setDefaultEventDurationMinutes(minutes) } /** [minutes] null clears the override, so the calendar inherits the default. */ @@ -369,12 +583,7 @@ class SettingsViewModel @Inject constructor( fun setDefaultAllDayReminderMinutes(minutes: List) = save { setDefaultAllDayReminderMinutes(minutes) } /** The armed alarm was planned for the old hour, so re-plan against the new one. */ - fun setAllDayReminderTimeMinutes(minutesOfDay: Int) { - viewModelScope.launch { - prefs.setAllDayReminderTimeMinutes(minutesOfDay) - reminderScanner.scan() - } - } + fun setAllDayReminderTimeMinutes(minutesOfDay: Int) = saveAndScan { setAllDayReminderTimeMinutes(minutesOfDay) } fun setSnoozeMinutes(minutes: Int) = save { setSnoozeMinutes(minutes) } @@ -384,6 +593,53 @@ class SettingsViewModel @Inject constructor( fun setAllowColorOnUnsupportedCalendars(enabled: Boolean) = save { setAllowColorOnUnsupportedCalendars(enabled) } + fun setDefaultFixedTimeReminder(reminder: FixedTimeReminder?) = save { setDefaultFixedTimeReminder(reminder) } + + fun setCalendarFixedTimeReminderOverride(calendarId: Long, override: FixedTimeOverride) = + save { setCalendarFixedTimeReminderOverride(calendarId, override) } + + /** Every summary change re-plans, so the next one is armed for its new moment (#459). */ + fun setDailyDigestEnabled(enabled: Boolean) { + viewModelScope.launch { + prefs.setDailyDigestEnabled(enabled) + // Created now, so a phone that starts new categories switched off + // shows it blocked here rather than dropping the first summary. + if (enabled) { + digestChannel() + _digestBlocked.value = withContext(io) { runCatching { digestNotifier.isChannelOff() }.getOrDefault(false) } + } + // After the scan, so one already under way can't post past the cancel; + // a summary left showing would go stale with nothing to replace it. + reminderScanner.scan() + if (!enabled) digestNotifier.cancel() + } + } + + fun setDailyDigestTimeMinutes(minutesOfDay: Int) = saveAndScan { setDailyDigestTimeMinutes(minutesOfDay) } + + /** A new mode lists afresh: from "tomorrow" to "today", the day just listed comes again. */ + fun setDailyDigestDay(day: DigestDay) { + viewModelScope.launch { + prefs.setDailyDigestDay(day) + reminderState.clearLastDigestDay() + reminderScanner.scan() + } + } + + fun setCalendarInDailyDigest(calendarId: Long, included: Boolean) = save { setCalendarInDailyDigest(calendarId, included) } + + /** The summary's channel, created if needed so its system settings can open. */ + suspend fun digestChannel(): String? = withContext(io) { + runCatching { digestNotifier.channelId() }.getOrNull() + } + + private fun saveAndScan(write: suspend SettingsPrefs.() -> Unit) { + viewModelScope.launch { + prefs.write() + reminderScanner.scan() + } + } + private fun save(write: suspend SettingsPrefs.() -> Unit) { viewModelScope.launch { prefs.write() } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SpecialDatesSettings.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SpecialDatesSettings.kt index 2f20e9ac..33f96d92 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SpecialDatesSettings.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SpecialDatesSettings.kt @@ -196,7 +196,7 @@ internal fun SpecialDatesScreen( reminderPickerType?.let { type -> ReminderDefaultPicker( title = stringResource(R.string.settings_special_dates_reminders), - presets = ALLDAY_REMINDER_PRESETS, + isAllDay = true, selected = state.reminderChoices[type] ?: ReminderOverride.None, // Managed calendars own their reminders outright — no "inherit global". allowInherit = false, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/ViewsSettings.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/ViewsSettings.kt index d6b8eab6..772b21aa 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/ViewsSettings.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/ViewsSettings.kt @@ -53,6 +53,7 @@ import de.jeanlucmakiola.floret.components.OptionPicker import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.ReorderableColumn import de.jeanlucmakiola.floret.components.ReorderableRowHeight +import de.jeanlucmakiola.floret.locale.capitalizeStart import de.jeanlucmakiola.floret.locale.currentLocale import kotlinx.datetime.DayOfWeek import java.time.format.TextStyle as JavaTextStyle @@ -104,7 +105,7 @@ internal fun ViewsScreen( ) GroupedRow( title = stringResource(R.string.settings_week_start), - summary = weekStartLabel(state.weekStart), + summary = weekStartLabel(state.weekStart).capitalizeStart(currentLocale()), position = Position.Middle, onClick = { showWeekStart = true }, ) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/WeekStartPicker.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/WeekStartPicker.kt index 0f1888c3..fa23868f 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/WeekStartPicker.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/WeekStartPicker.kt @@ -14,6 +14,7 @@ import de.jeanlucmakiola.floret.components.FullScreenPicker import de.jeanlucmakiola.floret.components.GroupedHint import de.jeanlucmakiola.floret.components.OptionRows import de.jeanlucmakiola.floret.components.ViewPreviewFrame +import de.jeanlucmakiola.floret.locale.capitalizeStart import de.jeanlucmakiola.floret.locale.currentLocale /** @@ -55,7 +56,7 @@ internal fun WeekStartPicker( OptionRows( options = options, selected = selected, - label = { weekStartLabel(it) }, + label = { weekStartLabel(it).capitalizeStart(currentLocale()) }, onSelect = onSelect, summary = { option -> if (option == WeekStartPref.Auto) { diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekScreen.kt index cb6607fa..0f00f711 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekScreen.kt @@ -21,6 +21,7 @@ import de.jeanlucmakiola.calendula.ui.common.rememberViewSwitchSpec import de.jeanlucmakiola.calendula.ui.common.jumpToPage import de.jeanlucmakiola.calendula.ui.common.pagedHeight import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme +import de.jeanlucmakiola.floret.locale.capitalizeStart import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.drop import androidx.compose.foundation.background @@ -1106,7 +1107,7 @@ private fun WeekDayHeader( ) { // One line, as the gutter cell beside it assumes (see WeekNumberCell). Text( - text = javaDow.getDisplayName(JavaTextStyle.SHORT, locale), + text = javaDow.getDisplayName(JavaTextStyle.SHORT, locale).capitalizeStart(locale), style = MaterialTheme.typography.labelSmall, maxLines = 1, overflow = TextOverflow.Clip, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekViewModel.kt index 9a34d71c..db4c04a5 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/week/WeekViewModel.kt @@ -19,7 +19,10 @@ import de.jeanlucmakiola.calendula.domain.displayPriority import de.jeanlucmakiola.calendula.domain.displayStart import de.jeanlucmakiola.calendula.domain.FailureReason import de.jeanlucmakiola.calendula.domain.calendarListFailure +import de.jeanlucmakiola.calendula.ui.common.CalendarView import de.jeanlucmakiola.calendula.ui.common.PageStateCache +import de.jeanlucmakiola.calendula.ui.common.calendarsHiddenIn +import de.jeanlucmakiola.calendula.ui.common.instancesWithout import de.jeanlucmakiola.floret.android.stateWhileSubscribed import de.jeanlucmakiola.floret.di.IoDispatcher import kotlinx.coroutines.CoroutineDispatcher @@ -89,8 +92,11 @@ abstract class PagedTimelineViewModel( private val io: CoroutineDispatcher, gridRule: Flow<(LocalDate) -> DaysGrid>, initialRule: (LocalDate) -> DaysGrid, + view: CalendarView, ) : ViewModel() { + private val hiddenHere = settingsPrefs.perCalendarHiddenViews.calendarsHiddenIn(view, viewModelScope) + /** * The zone every page is laid out in; drags and drops resolve in it too, and * pages lay out again when the device moves zones (#387). @@ -167,7 +173,7 @@ abstract class PagedTimelineViewModel( zone.flatMapLatest { zone -> combine( repository.calendars(), - repository.instances(spanRange(span.start, span.count, zone)), + repository.instancesWithout(spanRange(span.start, span.count, zone), hiddenHere), today, ) { calendars, instances, today -> buildState(span, calendars, instances, today, zone) @@ -240,6 +246,7 @@ class WeekViewModel @Inject constructor( rule }, initialRule = { DaysGrid.weeks(DayOfWeek.MONDAY) }, + view = CalendarView.Week, ) /** @@ -264,6 +271,7 @@ class MultiDayViewModel @Inject constructor( { anchor: LocalDate -> DaysGrid.startingAt(anchor, count) } }, initialRule = { DaysGrid.startingAt(it, SettingsPrefs.DEFAULT_MULTI_DAY_COUNT) }, + view = CalendarView.MultiDay, ) /** The day view: the timeline one day at a time. */ @@ -282,6 +290,7 @@ class DayViewModel @Inject constructor( io = io, gridRule = flowOf { _: LocalDate -> DaysGrid.days }, initialRule = { DaysGrid.days }, + view = CalendarView.Day, ) /** diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/widget/WidgetConfig.kt b/app/src/main/java/de/jeanlucmakiola/calendula/widget/WidgetConfig.kt index 4340e426..b4624682 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/widget/WidgetConfig.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/widget/WidgetConfig.kt @@ -11,7 +11,6 @@ import androidx.glance.GlanceId import androidx.glance.appwidget.state.getAppWidgetState import androidx.glance.state.PreferencesGlanceStateDefinition import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay -import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.ui.agenda.AgendaRange import de.jeanlucmakiola.calendula.ui.agenda.parseAgendaRange import de.jeanlucmakiola.calendula.ui.agenda.storageValue @@ -116,8 +115,5 @@ internal fun MutablePreferences.putHiddenCalendars(ids: Set) { this[HiddenCalendarsKey] = ids.map(Long::toString).toSet() } -internal fun List.withoutCalendars(hidden: Set): List = - if (hidden.isEmpty()) this else filterNot { it.calendarId in hidden } - internal suspend fun Context.widgetState(id: GlanceId): Preferences = getAppWidgetState(this, PreferencesGlanceStateDefinition, id) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/widget/WidgetData.kt b/app/src/main/java/de/jeanlucmakiola/calendula/widget/WidgetData.kt index 2d91c32b..302c72b1 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/widget/WidgetData.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/widget/WidgetData.kt @@ -14,6 +14,7 @@ import de.jeanlucmakiola.calendula.data.prefs.WeekStartPref import de.jeanlucmakiola.calendula.data.prefs.is24Hour import de.jeanlucmakiola.calendula.data.prefs.resolveFirstDay import de.jeanlucmakiola.calendula.domain.EventInstance +import de.jeanlucmakiola.calendula.domain.withoutCalendars import de.jeanlucmakiola.calendula.ui.agenda.AgendaDay import de.jeanlucmakiola.calendula.ui.agenda.AgendaRange import de.jeanlucmakiola.calendula.ui.agenda.agendaRange diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/widget/WidgetParts.kt b/app/src/main/java/de/jeanlucmakiola/calendula/widget/WidgetParts.kt index a894c46d..aaa76183 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/widget/WidgetParts.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/widget/WidgetParts.kt @@ -11,6 +11,7 @@ import de.jeanlucmakiola.calendula.ui.agenda.agendaTimeLabel import de.jeanlucmakiola.calendula.ui.common.formatTimeOfDay import de.jeanlucmakiola.floret.glance.LocalWidgetBackground import de.jeanlucmakiola.floret.glance.WidgetBackground +import de.jeanlucmakiola.floret.locale.capitalizeStart import de.jeanlucmakiola.floret.locale.localizedDateFormatter import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.LocalDate @@ -39,9 +40,9 @@ internal fun EventInstance.openIntent(context: Context, source: CalendarView) = source = source, ) -/** Opens [date] in the app's agenda. */ +/** Opens [date]'s day view. */ internal fun openDayAction(context: Context, date: LocalDate) = - actionStartActivity(MainActivity.openDateIntent(context, date, CalendarView.Agenda)) + actionStartActivity(MainActivity.openDateIntent(context, date)) /** An event's time on [day]: "All day", "Starts 14:00", "Ends 9:00" or "14:00 – 15:30". */ internal fun widgetTimeLabel(context: Context, event: EventInstance, day: LocalDate, is24Hour: Boolean): String = diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/widget/agenda/AgendaWidget.kt b/app/src/main/java/de/jeanlucmakiola/calendula/widget/agenda/AgendaWidget.kt index bee99ebb..4d018977 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/widget/agenda/AgendaWidget.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/widget/agenda/AgendaWidget.kt @@ -55,6 +55,7 @@ import de.jeanlucmakiola.calendula.domain.hasEnded import de.jeanlucmakiola.calendula.ui.agenda.anchorTodayIfMissing import de.jeanlucmakiola.calendula.ui.common.CalendarView import de.jeanlucmakiola.calendula.ui.common.formatCalendarTitle +import de.jeanlucmakiola.floret.locale.capitalizeStart import de.jeanlucmakiola.floret.locale.localizedDateFormatter import de.jeanlucmakiola.calendula.widget.widgetEventFill import de.jeanlucmakiola.calendula.ui.common.eventAccent @@ -669,7 +670,7 @@ private fun agendaDayLabel(context: Context, date: LocalDate, today: LocalDate): val java = java.time.LocalDate.of(date.year, date.month.ordinal + 1, date.day) // Weekday + date in the locale's own field order (compact: no year), rather // than a hardcoded day-month layout. - val formatted = localizedDateFormatter(locale, if (date.year == today.year) "EEEdMMM" else "EEEdMMMy").format(java) + val formatted = localizedDateFormatter(locale, if (date.year == today.year) "EEEdMMM" else "EEEdMMMy").format(java).capitalizeStart(locale) return if (relative != null) "$relative · $formatted" else formatted } @@ -680,8 +681,10 @@ private fun monthName(date: LocalDate, today: LocalDate): String = formatCalenda skeleton = "LLLL", ) -private fun weekdayShort(date: LocalDate): String = - date.dayOfWeek.toJavaDayOfWeek().getDisplayName(java.time.format.TextStyle.SHORT, widgetLocale()) +private fun weekdayShort(date: LocalDate): String { + val locale = widgetLocale() + return date.dayOfWeek.toJavaDayOfWeek().getDisplayName(java.time.format.TextStyle.SHORT, locale).capitalizeStart(locale) +} private fun eventTimeSummary( context: Context, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/widget/config/CountdownOptionsSection.kt b/app/src/main/java/de/jeanlucmakiola/calendula/widget/config/CountdownOptionsSection.kt index c11d7b77..6b6f84a3 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/widget/config/CountdownOptionsSection.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/widget/config/CountdownOptionsSection.kt @@ -38,6 +38,7 @@ import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.GroupedSectionHeader import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.positionOf +import de.jeanlucmakiola.floret.locale.capitalizeStart import de.jeanlucmakiola.floret.locale.currentLocale import de.jeanlucmakiola.floret.locale.localizedDateFormatter import kotlinx.datetime.TimeZone @@ -149,7 +150,7 @@ private fun CountdownEventPicker( val formatter = remember(locale) { localizedDateFormatter(locale, "EEEdMMMy") } LazyColumn(contentPadding = PaddingValues(top = 8.dp, bottom = 24.dp)) { itemsIndexed(matches, key = { _, it -> it.event.eventId }) { index, candidate -> - val date = formatter.format(candidate.event.start.toLocalDateTime(candidate.event.dateZone(zone)).date.toJavaLocalDate()) + val date = formatter.format(candidate.event.start.toLocalDateTime(candidate.event.dateZone(zone)).date.toJavaLocalDate()).capitalizeStart(locale) GroupedRow( title = candidate.event.title.ifBlank { stringResource(R.string.event_untitled) }, summary = if (candidate.repeats) stringResource(R.string.widget_config_countdown_repeats, date) else date, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/widget/countdown/CountdownData.kt b/app/src/main/java/de/jeanlucmakiola/calendula/widget/countdown/CountdownData.kt index db9ac1d7..462a187a 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/widget/countdown/CountdownData.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/widget/countdown/CountdownData.kt @@ -12,6 +12,7 @@ import de.jeanlucmakiola.floret.glance.updateWithRefresh import kotlinx.coroutines.CancellationException import de.jeanlucmakiola.calendula.data.prefs.is24Hour import de.jeanlucmakiola.calendula.domain.EventInstance +import de.jeanlucmakiola.calendula.domain.withoutCalendars import de.jeanlucmakiola.calendula.widget.Themed import de.jeanlucmakiola.calendula.widget.WidgetKind import de.jeanlucmakiola.calendula.widget.WidgetLoadContext @@ -22,7 +23,6 @@ import de.jeanlucmakiola.calendula.widget.today import de.jeanlucmakiola.calendula.widget.widgetEntryPoint import de.jeanlucmakiola.calendula.widget.widgetLoadContext import de.jeanlucmakiola.calendula.widget.widgetState -import de.jeanlucmakiola.calendula.widget.withoutCalendars import de.jeanlucmakiola.floret.prefs.toEnum import kotlinx.coroutines.flow.first import kotlinx.datetime.LocalDate diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/widget/countdown/CountdownWidget.kt b/app/src/main/java/de/jeanlucmakiola/calendula/widget/countdown/CountdownWidget.kt index df620dee..a7c1772f 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/widget/countdown/CountdownWidget.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/widget/countdown/CountdownWidget.kt @@ -52,12 +52,14 @@ import de.jeanlucmakiola.calendula.widget.formatWidgetTime import de.jeanlucmakiola.calendula.widget.relativeDayLabel import de.jeanlucmakiola.calendula.widget.systemZone import de.jeanlucmakiola.calendula.widget.widgetAppearance +import de.jeanlucmakiola.calendula.widget.widgetLocale import de.jeanlucmakiola.floret.glance.wallpaperBacking import de.jeanlucmakiola.floret.glance.WidgetData import de.jeanlucmakiola.floret.glance.WidgetMessage import de.jeanlucmakiola.floret.glance.currentRefreshStamp import de.jeanlucmakiola.floret.glance.refreshStamp import de.jeanlucmakiola.floret.glance.themedColor +import de.jeanlucmakiola.floret.locale.capitalizeStart import de.jeanlucmakiola.floret.prefs.ThemeMode import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.minus @@ -206,14 +208,15 @@ private fun whenText(context: Context, event: EventInstance, data: CountdownData val at = if (running) counted.end else counted.start val date = at.toLocalDateTime(systemZone()).date val day = relativeDayLabel(context, date, data.today) + val locale = widgetLocale() val wholeDays = event.coversWholeDays(systemZone()) return when { wholeDays && running -> context.getString( R.string.widget_countdown_until, relativeDayLabel(context, date.minus(1, DateTimeUnit.DAY), data.today), ) - wholeDays -> "$day · ${context.getString(R.string.event_detail_all_day)}" + wholeDays -> "${day.capitalizeStart(locale)} · ${context.getString(R.string.event_detail_all_day)}" running -> context.getString(R.string.agenda_span_ends, "$day · ${formatWidgetTime(at, data.is24Hour)}") - else -> "$day · ${formatWidgetTime(at, data.is24Hour)}" + else -> "${day.capitalizeStart(locale)} · ${formatWidgetTime(at, data.is24Hour)}" } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/widget/date/DateWidget.kt b/app/src/main/java/de/jeanlucmakiola/calendula/widget/date/DateWidget.kt index aa78587e..e5c45f6a 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/widget/date/DateWidget.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/widget/date/DateWidget.kt @@ -33,7 +33,6 @@ import androidx.glance.text.Text import androidx.glance.text.TextAlign import androidx.glance.text.TextStyle import de.jeanlucmakiola.calendula.MainActivity -import de.jeanlucmakiola.calendula.ui.common.CalendarView import de.jeanlucmakiola.calendula.widget.CalendulaWidgetReceiver import de.jeanlucmakiola.calendula.widget.CalendulaWidgetRoot import de.jeanlucmakiola.calendula.widget.WidgetAppearance @@ -46,6 +45,7 @@ import de.jeanlucmakiola.floret.glance.WidgetShapedBox import de.jeanlucmakiola.floret.glance.currentRefreshStamp import de.jeanlucmakiola.floret.glance.refreshStamp import de.jeanlucmakiola.floret.glance.wallpaperBacking +import de.jeanlucmakiola.floret.locale.capitalizeStart import de.jeanlucmakiola.floret.locale.localizedDateFormatter import de.jeanlucmakiola.floret.prefs.ThemeMode import kotlinx.datetime.LocalDate @@ -99,7 +99,7 @@ internal fun DateWidgetContent(today: LocalDate, appearance: WidgetAppearance, a Column( modifier = GlanceModifier .fillMaxSize() - .clickable(actionStartActivity(MainActivity.openDateIntent(context, today, CalendarView.Day))) + .clickable(actionStartActivity(MainActivity.openDateIntent(context, today))) .semantics { contentDescription = label }, horizontalAlignment = Alignment.CenterHorizontally, verticalAlignment = Alignment.CenterVertically, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/widget/month/MonthGridViews.kt b/app/src/main/java/de/jeanlucmakiola/calendula/widget/month/MonthGridViews.kt index c7df3985..a1ae8808 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/widget/month/MonthGridViews.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/widget/month/MonthGridViews.kt @@ -14,7 +14,6 @@ import de.jeanlucmakiola.calendula.MainActivity import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.domain.isCrossedOut -import de.jeanlucmakiola.calendula.ui.common.CalendarView import de.jeanlucmakiola.calendula.ui.common.eventFill import de.jeanlucmakiola.calendula.ui.common.eventInk import de.jeanlucmakiola.floret.glance.RemoteColor @@ -161,7 +160,7 @@ private fun span(text: String, span: Any): CharSequence = private fun openDayIntent(context: Context, date: LocalDate): PendingIntent = PendingIntent.getActivity( context, date.toEpochDays().toInt(), - MainActivity.openDateIntent(context, date, CalendarView.Month), + MainActivity.openDateIntent(context, date), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, ) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/widget/split/MonthDayWidget.kt b/app/src/main/java/de/jeanlucmakiola/calendula/widget/split/MonthDayWidget.kt index d7e377c3..5a208d7e 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/widget/split/MonthDayWidget.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/widget/split/MonthDayWidget.kt @@ -83,6 +83,7 @@ import de.jeanlucmakiola.calendula.widget.widgetCardColor import de.jeanlucmakiola.calendula.widget.widgetEntryPoint import de.jeanlucmakiola.calendula.widget.widgetSettings import de.jeanlucmakiola.calendula.widget.widgetState +import de.jeanlucmakiola.floret.locale.capitalizeStart import de.jeanlucmakiola.floret.locale.localizedDateFormatter import kotlinx.datetime.toJavaLocalDate import de.jeanlucmakiola.calendula.widget.widgetTimeLabel @@ -415,9 +416,9 @@ private fun DayList(day: LocalDate, data: MonthDayData.Ready, preview: Boolean) val events = groupAgendaDays(day, day, source.instances, zone).firstOrNull()?.events.orEmpty() .let { all -> if (data.options.pastDisplay == PastEventDisplay.HIDE) all.filterNot { it.hasEnded(data.now) } else all } val metrics = compactRowMetrics(data.options.textSize, context.resources.configuration.fontScale) - val openDay = actionStartActivity(MainActivity.openDateIntent(context, day, CalendarView.Month)) + val openDay = actionStartActivity(MainActivity.openDateIntent(context, day)) Column(modifier = GlanceModifier.fillMaxSize()) { - val date = localizedDateFormatter(widgetLocale(), "EEEdMMM").format(day.toJavaLocalDate()) + val date = widgetLocale().let { localizedDateFormatter(it, "EEEdMMM").format(day.toJavaLocalDate()).capitalizeStart(it) } val label = when (day) { source.today, source.today.plus(1, DateTimeUnit.DAY) -> "${relativeDayLabel(context, day, source.today)} · $date" else -> date diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/widget/today/TodayWidget.kt b/app/src/main/java/de/jeanlucmakiola/calendula/widget/today/TodayWidget.kt index 584db6c7..6220158d 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/widget/today/TodayWidget.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/widget/today/TodayWidget.kt @@ -73,6 +73,7 @@ import de.jeanlucmakiola.floret.glance.WidgetMessage import de.jeanlucmakiola.floret.glance.currentRefreshStamp import de.jeanlucmakiola.floret.glance.refreshStamp import de.jeanlucmakiola.floret.glance.wallpaperBacking +import de.jeanlucmakiola.floret.locale.capitalizeStart import de.jeanlucmakiola.floret.locale.localizedDateFormatter import de.jeanlucmakiola.floret.prefs.ThemeMode import kotlinx.datetime.DateTimeUnit @@ -245,13 +246,13 @@ private fun TodayPill(today: LocalDate) { .fillMaxHeight() .cornerRadius(PillWidth / 2) .background(GlanceTheme.colors.primary) - .clickable(actionStartActivity(MainActivity.openDateIntent(context, today, CalendarView.Day))) + .clickable(actionStartActivity(MainActivity.openDateIntent(context, today))) .semantics { contentDescription = localizedDateFormatter(locale, "EEEEdMMMM").format(today.toJavaLocalDate()) }, horizontalAlignment = Alignment.CenterHorizontally, verticalAlignment = Alignment.CenterVertically, ) { Text( - text = today.dayOfWeek.toJavaDayOfWeek().getDisplayName(JavaTextStyle.SHORT, locale), + text = today.dayOfWeek.toJavaDayOfWeek().getDisplayName(JavaTextStyle.SHORT, locale).capitalizeStart(locale), maxLines = 1, style = TextStyle(color = GlanceTheme.colors.onPrimary, fontSize = 11.sp, textAlign = TextAlign.Center), ) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/widget/upcoming/UpcomingWidget.kt b/app/src/main/java/de/jeanlucmakiola/calendula/widget/upcoming/UpcomingWidget.kt index 3687e774..530bb746 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/widget/upcoming/UpcomingWidget.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/widget/upcoming/UpcomingWidget.kt @@ -60,6 +60,7 @@ import de.jeanlucmakiola.floret.glance.WidgetMessage import de.jeanlucmakiola.floret.glance.currentRefreshStamp import de.jeanlucmakiola.floret.glance.refreshStamp import de.jeanlucmakiola.floret.glance.wallpaperBacking +import de.jeanlucmakiola.floret.locale.capitalizeStart import de.jeanlucmakiola.floret.prefs.ThemeMode import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.LocalDate @@ -137,7 +138,7 @@ internal fun UpcomingWidgetContent(data: DaysWidgetData, appearance: WidgetAppea val time = widgetTimeLabel(context, event, day, data.is24Hour) WidgetEventRow( event = event, - secondary = if (day == data.today) time else "${relativeDayLabel(context, day, data.today)} · $time", + secondary = if (day == data.today) time else "${relativeDayLabel(context, day, data.today).capitalizeStart(widgetLocale())} · $time", soften = data.soften, metrics = metrics, position = positionOf(index, events.size), @@ -170,12 +171,12 @@ private fun DateHeader(today: LocalDate, height: Dp) { Spacer(GlanceModifier.width(8.dp)) Column { Text( - text = today.dayOfWeek.toJavaDayOfWeek().getDisplayName(JavaTextStyle.FULL, locale), + text = today.dayOfWeek.toJavaDayOfWeek().getDisplayName(JavaTextStyle.FULL, locale).capitalizeStart(locale), maxLines = 1, style = TextStyle(color = GlanceTheme.colors.onSurface, fontSize = 13.sp, fontWeight = FontWeight.Medium), ) Text( - text = java.time.Month.of(today.month.ordinal + 1).getDisplayName(JavaTextStyle.FULL_STANDALONE, locale), + text = java.time.Month.of(today.month.ordinal + 1).getDisplayName(JavaTextStyle.FULL_STANDALONE, locale).capitalizeStart(locale), maxLines = 1, style = TextStyle(color = GlanceTheme.colors.onSurfaceVariant, fontSize = 12.sp), ) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/widget/week/WeekStripWidget.kt b/app/src/main/java/de/jeanlucmakiola/calendula/widget/week/WeekStripWidget.kt index cf856ca3..99935adb 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/widget/week/WeekStripWidget.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/widget/week/WeekStripWidget.kt @@ -46,7 +46,6 @@ import androidx.glance.text.TextStyle import androidx.glance.unit.ColorProvider import de.jeanlucmakiola.calendula.MainActivity import de.jeanlucmakiola.calendula.R -import de.jeanlucmakiola.calendula.ui.common.CalendarView import de.jeanlucmakiola.calendula.ui.common.eventAccent import de.jeanlucmakiola.calendula.ui.common.eventFill import de.jeanlucmakiola.calendula.widget.CalendulaWidgetReceiver @@ -64,6 +63,7 @@ import de.jeanlucmakiola.floret.glance.WidgetMessage import de.jeanlucmakiola.floret.glance.currentRefreshStamp import de.jeanlucmakiola.floret.glance.refreshStamp import de.jeanlucmakiola.floret.glance.themedColor +import de.jeanlucmakiola.floret.locale.capitalizeStart import de.jeanlucmakiola.floret.locale.localizedDateFormatter import de.jeanlucmakiola.floret.prefs.ThemeMode import kotlinx.datetime.DateTimeUnit @@ -155,7 +155,7 @@ private fun DayTile(date: LocalDate, data: DaysWidgetData.Ready) { .fillMaxSize() .cornerRadius(14.dp) .background(container) - .clickable(actionStartActivity(MainActivity.openDateIntent(context, date, CalendarView.Week))) + .clickable(actionStartActivity(MainActivity.openDateIntent(context, date))) .semantics { contentDescription = if (colors.isEmpty()) label else context.resources.getQuantityString( R.plurals.widget_day_with_events, events.size, label, events.size, @@ -165,7 +165,7 @@ private fun DayTile(date: LocalDate, data: DaysWidgetData.Ready) { verticalAlignment = Alignment.CenterVertically, ) { Text( - text = date.dayOfWeek.toJavaDayOfWeek().getDisplayName(JavaTextStyle.SHORT, locale), + text = date.dayOfWeek.toJavaDayOfWeek().getDisplayName(JavaTextStyle.SHORT, locale).capitalizeStart(locale), maxLines = 1, style = TextStyle(color = ink, fontSize = 11.sp, textAlign = TextAlign.Center), ) diff --git a/app/src/main/res/drawable/ic_notification_link.xml b/app/src/main/res/drawable/ic_notification_link.xml new file mode 100644 index 00000000..19b21a7b --- /dev/null +++ b/app/src/main/res/drawable/ic_notification_link.xml @@ -0,0 +1,12 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_notification_map.xml b/app/src/main/res/drawable/ic_notification_map.xml new file mode 100644 index 00000000..3963fe2c --- /dev/null +++ b/app/src/main/res/drawable/ic_notification_map.xml @@ -0,0 +1,12 @@ + + + + + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 278cc7ca..eb53ffa0 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -231,6 +231,8 @@ Title Location Open in maps + + Open link No app can open this link Description Attendees @@ -376,6 +378,8 @@ Not now Snooze Dismiss + Ringing reminders + Full-screen reminders that ring until you dismiss them. Calendula plays their sound itself. Today Tomorrow @@ -395,6 +399,23 @@ Jump to date + Sync now + Allow sync requests + Pick each account Calendula may ask to sync + Android only lets Calendula ask an account to sync once you pick it here. Tap an account to allow it, or choose Don\'t ask to stop offering it. + Don\'t ask + Not asked for sync access + Calendula won\'t offer to request syncs for these accounts. Ask again to bring them back to Allow sync requests in the menu. + Ask again + Choose an account Calendula may ask to sync your calendars + Sync requested + Syncing… + Sync completed + Couldn\'t request a sync + Sync requested. Allow sync requests in the menu for the other accounts + Allow sync requests in the menu first + Sync requested, but not for every account + No synced calendars to sync Today @@ -550,6 +571,9 @@ Calendars + + Show all calendars in this group + Hide all calendars in this group Settings @@ -705,6 +729,10 @@ Drag to reorder New event form Fields shown by default — everything else sits behind \"More fields\" + Default calendar + Automatic + Automatic while %1$s can’t take new events + The calendar you last added or moved an event to Focus title on new event When you start a new event, place the cursor in the title field and open the keyboard right away. Default duration @@ -731,8 +759,81 @@ Amount Set Per-calendar reminders - Override the default per calendar — separately for timed and all-day events. A calendar can keep the default, drop it, or set its own. + Notifications, sound and default reminders per calendar + Turn notifications off or pick a sound per calendar, and override the default reminder for calendars you can edit. + Notifications + Notify at this calendar\'s reminder times + Notifications off + Reminders off + Notification sound + Silent + Default + + Default (%1$s) + Custom sound + Couldn\'t change the notification sound + Calendula can\'t play this sound. Pick another one. + Differs per calendar + More notification settings + Vibration, pop-ups and more for each calendar, in system settings + Blocked in system settings + Blocked in system settings — tap to allow + On Samsung phones, new notification categories can start switched off. If a calendar\'s reminders don\'t arrive, check that its category is on. + Open settings + Vibration, pop-ups and more for this calendar, in system settings + Alert style + Notification + A notification that pops up and waits in the shade + Full-screen alert + Fills the screen, even on the lock screen, until you dismiss or snooze it + Full-screen sound + Play sound once + This calendar\'s notification sound, once + Ring until dismissed + Your alarm sound and vibration, like an alarm, also in Do Not Disturb when alarms may sound + Full-screen alerts held back + Blocked in system settings, so this calendar\'s reminders only sound once — tap to allow + Allow full-screen alerts + Android blocks Calendula\'s full-screen alerts, so they only pop up as notifications. Tap to allow them. Default (%1$s) + + %1$s at %2$s + At a set time + + days before, at + Pick 1 to %1$d days + Reminder at a set time + E.g. the evening before + Fires at this time however early or late the event starts, and moves along when you change the event\'s time. + Added to new timed events, e.g. the evening before. It follows the event when you move it to another time. + + Daily summary + Turn on daily summary + One notification listing a day\'s events + + %1$s at %2$s + Lists + Today\'s events + Tomorrow\'s events + Time + Sound and pop-up for the summary, in system settings + In daily summary + List this calendar\'s events in the daily summary + Daily summary + One notification listing a day\'s events + + + %1$s: %2$d event + %1$s: %2$d events + + + %1$s, %2$s + + %1$s · %2$s + + +%d more + +%d more + Reliable delivery Android may delay reminders to save battery. Exempt Calendula so they arrive on time. Exempt from battery optimisation — reminders arrive on time. @@ -849,7 +950,7 @@ Filled from your contacts This calendar is filled from your contacts, so Calendula would create it again on the next sync. Turn special dates off under Settings → Special dates to delete it. Synced calendars - These come from accounts on your device. Create and edit them in their own app. + These come from accounts on your device. Create and edit them in their own app; tap one here to hide it in some views. Manage in app %1$s (%2$s) @@ -863,6 +964,24 @@ Color Description Add a description + Hide in views + Events from “%1$s” stay out of the views checked here. Reminders, search and widgets still include them. + Shown in every view + Hidden in %1$s + + Hidden in “%1$s” view + + Hide in “%1$s” view + + + %1$d calendar hidden in “%2$s” view + %1$d calendars hidden in “%2$s” view + + + Leave calendars out of the “%1$s” view only + + Checked calendars stay out of the “%1$s” view only. Reminders, search and widgets still include them. + Hidden in every view from the menu Mauve Red Orange @@ -880,7 +999,7 @@ Couldn\'t save the change. Backup - Local calendars aren\'t synced anywhere, so export them to an .ics file to keep a copy. + Export calendars to an .ics file to keep a copy. Local calendars aren\'t synced anywhere, so they need it most. Export as .ics file Export calendars Choose which calendars to include in the .ics file. @@ -889,13 +1008,59 @@ Restore from .ics file Import events from a backup or another calendar app. No calendar can take the imported events yet. + Copy events + Copy one calendar\'s events into another, for example to move off Google. + The original calendar stays as it is. Guests and invitations you declined are left out. + From + To + Choose a calendar + Copy from + Copy into + Copy + Copy more + Reading events… + + %1$d of %2$d event + %1$d of %2$d events + + Copy complete + Copy stopped + Copy finished, some events couldn\'t be added + No calendar can be copied into another one right now. + Copy cancelled. Run it again to finish: events that were already copied are skipped. + Couldn\'t copy the events. + + The target calendar stopped accepting events part way through. %d event was never copied. + The target calendar stopped accepting events part way through. %d events were never copied. + Automatic backup - Periodically export your local calendars to a folder as an .ics file. + Periodically export your calendars to a folder as .ics files. Backup folder Tap to choose a folder Interval Every %1$s Minimum 30 minutes. + Off, only after changes + Also back up after changes + Updates the undated copy a few minutes after events change. Dated backups stay on the interval. + Updates the undated copy a few minutes after events change. No dated backups. + Calendars + + %d calendar + %d calendars + + No calendar selected + No calendar is selected, so nothing is backed up. + Local calendars are backed up unless you turn them off. Synced calendars already live on their server, so add them here only if you want a copy in the backup folder too. + Single file + All calendars in one file + One file per calendar, named after it + Backups to keep + + Only the latest + The latest %d + + Counted per file: with one file per calendar, each calendar keeps this many dated copies, plus one undated copy of the latest backup unless a file of yours already has that name. Older backups Calendula wrote are deleted after each run; a calendar you stop backing up keeps its last files, and nothing else in the folder is touched. No automatic backup yet Last backup: %1$s Last backup failed: %1$s @@ -910,6 +1075,41 @@ Weeks Couldn\'t export the backup. + Settings + Save Calendula\'s settings to a file and restore them after reinstalling or on a new phone. Events aren\'t part of it. + Export settings + Save every setting to a .json file + Import settings + Replace the current settings with a saved file + Settings exported. + Couldn\'t export the settings. + Replace your settings? + Every setting is replaced with the one in the file. Your events and calendars stay as they are, apart from contact special dates, which follow the imported setting. + Replace + That file isn\'t a Calendula settings backup. + That backup is from a newer Calendula. Update the app to import it. + That settings backup is damaged and wasn\'t imported. + That file is too large to be a settings backup. + Couldn\'t read that file. + Couldn\'t import the settings. + Settings imported + Your settings now match the ones in the file. + + Calendar settings were applied to %d calendar. + Calendar settings were applied to %d calendars. + + Not imported + + %1$s (%2$s): no matching calendar on this phone + + %1$s (%2$s): more than one calendar on this phone has that name + Calendar settings: Calendula can\'t read your calendars, so they were left as they are + Custom headings font: choose the font file again + Custom body font: choose the font file again + Contact special dates: turn them on again to allow access to contacts + Automatic backup: choose the backup folder again + + %1$s isn\'t available in this version Exported %d event. Exported %d events. diff --git a/app/src/main/res/xml/locales_config.xml b/app/src/main/res/xml/locales_config.xml index 8bd7cdf1..1feec3d9 100644 --- a/app/src/main/res/xml/locales_config.xml +++ b/app/src/main/res/xml/locales_config.xml @@ -16,6 +16,7 @@ + diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt b/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt index 51de87a3..ff668ab0 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/TestRepositories.kt @@ -5,12 +5,17 @@ import androidx.datastore.preferences.core.PreferenceDataStoreFactory import androidx.datastore.preferences.core.Preferences import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource import de.jeanlucmakiola.calendula.data.calendar.CalendarRepositoryImpl +import de.jeanlucmakiola.calendula.data.calendar.SyncAccount +import de.jeanlucmakiola.calendula.data.calendar.SyncActivity +import de.jeanlucmakiola.calendula.data.calendar.SyncRequester import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.test.TestDispatcher import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain @@ -43,7 +48,58 @@ fun testRepository( io: CoroutineDispatcher, prefs: CalendarPrefs = testPrefs(dir), settings: SettingsPrefs = testSettings(dir), -): CalendarRepositoryImpl = CalendarRepositoryImpl(source, prefs, settings, io) + syncRequester: SyncRequester = RecordingSyncRequester(), +): CalendarRepositoryImpl = CalendarRepositoryImpl(source, prefs, settings, io, syncRequester) + +/** + * Records every sync request; [accepts] false models the system refusing all, + * [refusedTypes] refusing those account types, [adapterTypes] the installed + * calendar sync adapters (null: a fixed set covering the test accounts), + * [hiddenTypes] account types the app can't address by name. + */ +class RecordingSyncRequester( + var accepts: Boolean = true, + var adapterTypes: Set? = null, + var refusedTypes: Set = emptySet(), + var hiddenTypes: Set = emptySet(), +) : SyncRequester { + data class Request(val account: SyncAccount, val userInitiated: Boolean) + + val requests = mutableListOf() + + override fun adapterAccountTypes(): Set = + adapterTypes ?: setOf("bitfire.at.davdroid", "com.google", "LOCAL") + + override fun addressableAccounts(types: Set): Set? { + visibilityError?.let { throw it } + return if (hiddenTypes.isEmpty()) { + null + } else { + knownAccounts.filterTo(mutableSetOf()) { it.type in types && it.type !in hiddenTypes } + } + } + + /** Thrown by [addressableAccounts] when set. */ + var visibilityError: Exception? = null + + /** The accounts on the "device", for [addressableAccounts]. */ + var knownAccounts: Set = emptySet() + + override fun requestSync(account: SyncAccount, userInitiated: Boolean) { + if (!accepts || account.type in refusedTypes) throw SecurityException("refused") + requests += Request(account, userInitiated) + } + + /** Each account's sync state; null stands for a system that won't say. */ + var activity: (SyncAccount) -> SyncActivity? = { SyncActivity.Idle } + + /** Emit to tell waiters the sync state changed. */ + val activityChanges = MutableSharedFlow(extraBufferCapacity = 8) + + override fun syncActivity(account: SyncAccount): SyncActivity? = activity(account) + + override fun syncActivityChanges(): Flow = activityChanges +} /** Installs [dispatcher] as `Dispatchers.Main` around each test. */ @OptIn(ExperimentalCoroutinesApi::class) diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/backup/ChangeRunPolicyTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/backup/ChangeRunPolicyTest.kt new file mode 100644 index 00000000..523608c7 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/backup/ChangeRunPolicyTest.kt @@ -0,0 +1,30 @@ +package de.jeanlucmakiola.calendula.data.backup + +import androidx.work.ExistingWorkPolicy +import androidx.work.WorkInfo.State.BLOCKED +import androidx.work.WorkInfo.State.CANCELLED +import androidx.work.WorkInfo.State.ENQUEUED +import androidx.work.WorkInfo.State.RUNNING +import androidx.work.WorkInfo.State.SUCCEEDED +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class ChangeRunPolicyTest { + + @Test + fun `a run that hasn't started yet covers the change`() { + assertThat(changeRunPolicy(listOf(ENQUEUED))).isNull() + assertThat(changeRunPolicy(listOf(RUNNING, BLOCKED))).isNull() + } + + @Test + fun `a run already going gets the next one queued behind it`() { + assertThat(changeRunPolicy(listOf(RUNNING))).isEqualTo(ExistingWorkPolicy.APPEND_OR_REPLACE) + } + + @Test + fun `with nothing pending a fresh run starts`() { + assertThat(changeRunPolicy(emptyList())).isEqualTo(ExistingWorkPolicy.REPLACE) + assertThat(changeRunPolicy(listOf(SUCCEEDED, CANCELLED))).isEqualTo(ExistingWorkPolicy.REPLACE) + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/backup/SettingsBackupSchemaTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/backup/SettingsBackupSchemaTest.kt new file mode 100644 index 00000000..6813b72b --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/backup/SettingsBackupSchemaTest.kt @@ -0,0 +1,45 @@ +package de.jeanlucmakiola.calendula.data.backup + +import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefKeys +import de.jeanlucmakiola.calendula.data.prefs.ReminderStateKeys +import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys +import de.jeanlucmakiola.floret.prefs.Pref +import org.junit.jupiter.api.Test + +/** + * Every key of the settings store is either backed up or deliberately left + * out. A new key fails here until [SettingsBackupSchema] says which. + */ +class SettingsBackupSchemaTest { + + private val schema = SettingsBackupSchema + + private fun keysOf(holder: Any): List = holder.javaClass.declaredFields + .filter { java.lang.reflect.Modifier.isStatic(it.modifiers) && it.name != "INSTANCE" } + .flatMap { field -> + field.isAccessible = true + when (val value = field.get(null)) { + is Pref<*> -> listOf(value.name) + is Map<*, *> -> value.values.filterIsInstance>().map { it.name } + else -> emptyList() + } + } + + @Test + fun `every stored key is classified`() { + val stored = (keysOf(SettingsKeys) + keysOf(CalendarPrefKeys) + keysOf(ReminderStateKeys)).toSet() + val classified = (schema.plain + schema.perCalendar + schema.excluded).map { it.name } + + assertThat(stored).isNotEmpty() + assertThat(classified).containsAtLeastElementsIn(stored) + assertThat(stored).containsAtLeastElementsIn(classified) + } + + @Test + fun `no key is classified twice`() { + val classified = (schema.plain + schema.perCalendar + schema.excluded).map { it.name } + + assertThat(classified).containsNoDuplicates() + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/backup/SettingsBackupTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/backup/SettingsBackupTest.kt new file mode 100644 index 00000000..959f1003 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/backup/SettingsBackupTest.kt @@ -0,0 +1,441 @@ +package de.jeanlucmakiola.calendula.data.backup + +import androidx.datastore.preferences.core.MutablePreferences +import androidx.datastore.preferences.core.mutablePreferencesOf +import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.data.appname.LauncherName +import de.jeanlucmakiola.calendula.data.calendar.ManagedCalendarRow +import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefKeys +import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride +import de.jeanlucmakiola.calendula.data.prefs.SettingsKeys +import de.jeanlucmakiola.calendula.data.prefs.fixedTimeOverrideFor +import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.domain.FontRole +import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType +import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder +import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle +import de.jeanlucmakiola.calendula.ui.common.CalendarView +import de.jeanlucmakiola.calendula.ui.theme.FONT_CUSTOM_TOKEN +import de.jeanlucmakiola.floret.backup.BackupProblem +import de.jeanlucmakiola.floret.backup.BackupResult +import de.jeanlucmakiola.floret.prefs.ThemeMode +import de.jeanlucmakiola.floret.prefs.get +import de.jeanlucmakiola.floret.prefs.set +import org.junit.jupiter.api.Test + +class SettingsBackupTest { + + private fun calendar(id: Long, name: String, account: String = "me@example.org", managed: Boolean = false) = + CalendarSource( + id = id, + displayName = name, + accountName = account, + accountType = "com.google", + color = 0, + isVisibleInSystem = true, + isManaged = managed, + ) + + private val work = calendar(1, "Work") + private val home = calendar(2, "Home") + private val birthdays = calendar(3, "Birthdays", account = "Calendula", managed = true) + + private fun environment( + calendars: List? = listOf(work, home, birthdays), + managed: List = listOf(ManagedCalendarRow(3, SpecialDateType.Birthday)), + contacts: Boolean = true, + fonts: Set = emptySet(), + folder: Boolean = false, + languages: List = listOf("de", "en-US", "fr"), + ) = ImportEnvironment(calendars, managed, contacts, fonts, folder, languages) + + private fun roundTrip(source: MutablePreferences, calendars: List = listOf(work, home, birthdays)): SettingsBackup { + val backup = buildSettingsBackup( + snapshot = source, + calendars = calendars, + managed = listOf(ManagedCalendarRow(3, SpecialDateType.Birthday)), + language = LanguageChoice("de"), + launcherName = LauncherName.CALENDAR, + ) + val decoded = decodeSettingsBackup(encodeSettingsBackup(backup, 1_700_000_000_000, "2.25.0")) + return (decoded as BackupResult.Success).value + } + + private fun import(backup: SettingsBackup, current: MutablePreferences, env: ImportEnvironment = environment()) = + planSettingsImport(backup, current, env).also { it.applyTo(current) } + + @Test + fun `plain settings survive the round trip`() { + val source = mutablePreferencesOf() + source[SettingsKeys.themeMode] = ThemeMode.BLACK + source[SettingsKeys.multiDayCount] = 5 + source[SettingsKeys.defaultView] = CalendarView.Month + source[SettingsKeys.defaultReminderMinutes] = listOf(10, 60) + + val target = mutablePreferencesOf() + import(roundTrip(source), target) + + assertThat(target[SettingsKeys.themeMode]).isEqualTo(ThemeMode.BLACK) + assertThat(target[SettingsKeys.multiDayCount]).isEqualTo(5) + assertThat(target[SettingsKeys.defaultView]).isEqualTo(CalendarView.Month) + assertThat(target[SettingsKeys.defaultReminderMinutes]).containsExactly(10, 60).inOrder() + } + + @Test + fun `a setting the file leaves at its default resets here`() { + val target = mutablePreferencesOf() + target[SettingsKeys.showWeekNumbers] = true + + import(roundTrip(mutablePreferencesOf()), target) + + assertThat(target[SettingsKeys.showWeekNumbers]).isFalse() + } + + @Test + fun `device state is neither exported nor touched`() { + val source = mutablePreferencesOf() + source[SettingsKeys.autoBackupFolderUri] = "content://tree/backup" + source[SettingsKeys.recentTimeZones] = listOf("Europe/Berlin") + val target = mutablePreferencesOf() + target[SettingsKeys.autoBackupLastRun] = 42L + + val backup = roundTrip(source) + import(backup, target) + + assertThat(backup.prefs.keys.map { it.name }).doesNotContain("auto_backup_folder_uri") + assertThat(target[SettingsKeys.autoBackupFolderUri]).isNull() + assertThat(target[SettingsKeys.autoBackupLastRun]).isEqualTo(42L) + } + + @Test + fun `per-calendar settings follow the calendar to its new id`() { + val source = mutablePreferencesOf() + source[CalendarPrefKeys.hiddenCalendarIds] = setOf(1L) + source[CalendarPrefKeys.lastUsedCalendarId] = 2L + source[SettingsKeys.perCalendarEventDuration] = mapOf(1L to 30) + source[SettingsKeys.perCalendarReminderOverride] = mapOf(2L to emptyList()) + val moved = listOf(calendar(11, "Work"), calendar(12, "Home")) + + val target = mutablePreferencesOf() + val plan = import(roundTrip(source), target, environment(calendars = moved, managed = emptyList())) + + assertThat(target[CalendarPrefKeys.hiddenCalendarIds]).containsExactly(11L) + assertThat(target[CalendarPrefKeys.lastUsedCalendarId]).isEqualTo(12L) + assertThat(target[SettingsKeys.perCalendarEventDuration]).containsExactly(11L, 30) + assertThat(target[SettingsKeys.perCalendarReminderOverride]).containsExactly(12L, emptyList()) + assertThat(plan.calendars).hasSize(2) + } + + @Test + fun `a calendar missing here is reported, and its old id is not reused`() { + val source = mutablePreferencesOf() + source[SettingsKeys.perCalendarEventDuration] = mapOf(1L to 30) + val target = mutablePreferencesOf() + target[SettingsKeys.perCalendarEventDuration] = mapOf(1L to 45) + + val plan = import(roundTrip(source), target, environment(calendars = listOf(calendar(1, "Other")))) + + assertThat(target[SettingsKeys.perCalendarEventDuration]).isEmpty() + assertThat(plan.skipped).containsExactly(SkippedSetting.Calendar("Work", "me@example.org")) + } + + @Test + fun `two calendars with the same name and account match neither`() { + val source = mutablePreferencesOf() + source[CalendarPrefKeys.hiddenCalendarIds] = setOf(1L) + + val target = mutablePreferencesOf() + val plan = import(roundTrip(source), target, environment(calendars = listOf(calendar(5, "Work"), calendar(6, "Work")))) + + assertThat(target[CalendarPrefKeys.hiddenCalendarIds]).isEmpty() + assertThat(plan.skipped).containsExactly(SkippedSetting.Calendar("Work", "me@example.org", ambiguous = true)) + } + + @Test + fun `every per-calendar key travels with its calendar`() { + val source = mutablePreferencesOf() + source[CalendarPrefKeys.hiddenCalendarIds] = setOf(1L) + source[CalendarPrefKeys.lastUsedCalendarId] = 1L + source[SettingsKeys.perCalendarEventDuration] = mapOf(1L to 30) + source[SettingsKeys.perCalendarReminderOverride] = mapOf(1L to listOf(5)) + source[SettingsKeys.perCalendarAllDayReminderOverride] = mapOf(1L to listOf(0)) + source[SettingsKeys.perCalendarHiddenViews] = mapOf(1L to setOf(CalendarView.Month, CalendarView.Week)) + source[SettingsKeys.mutedReminderCalendarIds] = setOf(1L) + source[SettingsKeys.reminderAlertStyles] = mapOf(1L to ReminderAlertStyle.FullScreenRing) + source[SettingsKeys.perCalendarFixedTimeReminderOverride] = mapOf(1L to FixedTimeReminder(2, 1_200)) + source[SettingsKeys.digestExcludedCalendarIds] = setOf(1L) + source[SettingsKeys.autoBackupIncluded] = setOf(1L) + source[SettingsKeys.autoBackupExcluded] = setOf(1L) + + val target = mutablePreferencesOf() + import(roundTrip(source), target, environment(calendars = listOf(calendar(9, "Work")), managed = emptyList())) + + // One assertion per key in the schema: a new per-calendar key fails here until it is carried. + // Both auto-backup keys are set at the source so each is checked; one calendar sits in only one. + SettingsBackupSchema.perCalendar.filter { it != SettingsKeys.autoBackupExcluded }.forEach { pref -> + assertThat(target.asMap().keys.map { it.name }).contains(pref.name) + } + assertThat(target[SettingsKeys.perCalendarAllDayReminderOverride]).containsExactly(9L, listOf(0)) + assertThat(target[SettingsKeys.perCalendarHiddenViews]).containsExactly(9L, setOf(CalendarView.Month, CalendarView.Week)) + assertThat(target[SettingsKeys.mutedReminderCalendarIds]).containsExactly(9L) + assertThat(target[SettingsKeys.reminderAlertStyles]).containsExactly(9L, ReminderAlertStyle.FullScreenRing) + assertThat(target[SettingsKeys.perCalendarFixedTimeReminderOverride]).containsExactly(9L, FixedTimeReminder(2, 1_200)) + assertThat(target[SettingsKeys.digestExcludedCalendarIds]).containsExactly(9L) + assertThat(target[SettingsKeys.autoBackupIncluded]).containsExactly(9L) + } + + @Test + fun `an off set-time override and an excluded backup calendar survive the round trip`() { + val source = mutablePreferencesOf() + source[SettingsKeys.perCalendarFixedTimeReminderOverride] = mapOf(1L to null) + source[SettingsKeys.autoBackupExcluded] = setOf(1L) + + val target = mutablePreferencesOf() + import(roundTrip(source), target, environment(calendars = listOf(calendar(9, "Work")), managed = emptyList())) + + assertThat(target[SettingsKeys.perCalendarFixedTimeReminderOverride].fixedTimeOverrideFor(9L)) + .isEqualTo(FixedTimeOverride.Off) + assertThat(target[SettingsKeys.autoBackupExcluded]).containsExactly(9L) + assertThat(target[SettingsKeys.autoBackupIncluded]).isEmpty() + } + + @Test + fun `a mirror type the import switches off is left out`() { + val source = mutablePreferencesOf() + source[SettingsKeys.specialDatesEnabled] = true + source[SettingsKeys.specialDateTypeEnabled.getValue(SpecialDateType.Birthday)] = false + source[CalendarPrefKeys.hiddenCalendarIds] = setOf(3L) + + val target = mutablePreferencesOf() + val plan = import(roundTrip(source), target) + + assertThat(target[CalendarPrefKeys.hiddenCalendarIds]).isEmpty() + assertThat(plan.pendingSpecialDates).isEmpty() + assertThat(plan.skipped).isEmpty() + } + + @Test + fun `an out-of-range calendar length is clamped, not refused`() { + val text = """{"format":"calendula-settings","version":1,"exportedAt":1,"settings":{},"calendars":[ + {"account_name":"me@example.org","account_type":"com.google","display_name":"Work","event_duration_minutes":5000}]}""" + val backup = (decodeSettingsBackup(text) as BackupResult.Success).value + + val target = mutablePreferencesOf() + import(backup, target) + + assertThat(target[SettingsKeys.perCalendarEventDuration]).containsExactly(1L, 1440) + } + + @Test + fun `unreadable calendars leave the per-calendar settings alone`() { + val source = mutablePreferencesOf() + source[CalendarPrefKeys.hiddenCalendarIds] = setOf(1L) + val target = mutablePreferencesOf() + target[SettingsKeys.perCalendarEventDuration] = mapOf(4L to 45) + + val plan = import(roundTrip(source), target, environment(calendars = null)) + + assertThat(target[SettingsKeys.perCalendarEventDuration]).containsExactly(4L, 45) + assertThat(plan.skipped).containsExactly(SkippedSetting.CalendarsUnavailable) + } + + @Test + fun `mirror calendars are left out when the import turns the mirror off`() { + val source = mutablePreferencesOf() + source[CalendarPrefKeys.hiddenCalendarIds] = setOf(3L) + + val target = mutablePreferencesOf() + val plan = import(roundTrip(source), target) + + assertThat(target[CalendarPrefKeys.hiddenCalendarIds]).isEmpty() + assertThat(plan.pendingSpecialDates).isEmpty() + assertThat(plan.skipped).isEmpty() + } + + @Test + fun `a stale id in the prefs is dropped on export`() { + val source = mutablePreferencesOf() + source[CalendarPrefKeys.hiddenCalendarIds] = setOf(1L, 99L) + + assertThat(roundTrip(source).calendars.map { it.calendar.displayName }).containsExactly("Work") + } + + @Test + fun `a mirror calendar is matched by its date type`() { + val source = mutablePreferencesOf() + source[SettingsKeys.specialDatesEnabled] = true + source[SettingsKeys.perCalendarAllDayReminderOverride] = mapOf(3L to listOf(0, 10080)) + + val target = mutablePreferencesOf() + val renamed = listOf(calendar(7, "Geburtstage", account = "Calendula", managed = true)) + import(roundTrip(source), target, environment(calendars = renamed, managed = listOf(ManagedCalendarRow(7, SpecialDateType.Birthday)))) + + assertThat(target[SettingsKeys.perCalendarAllDayReminderOverride]).containsExactly(7L, listOf(0, 10080)) + } + + @Test + fun `a mirror calendar that doesn't exist yet waits for the sync`() { + val source = mutablePreferencesOf() + source[SettingsKeys.specialDatesEnabled] = true + source[SettingsKeys.perCalendarAllDayReminderOverride] = mapOf(3L to listOf(0)) + + val target = mutablePreferencesOf() + val plan = import(roundTrip(source), target, environment(managed = emptyList())) + plan.pendingSpecialDates.forEach { target.addCalendarSettings(8L, it) } + + assertThat(plan.skipped).isEmpty() + assertThat(target[SettingsKeys.perCalendarAllDayReminderOverride]).containsExactly(8L, listOf(0)) + } + + @Test + fun `a custom font without its file keeps the current font`() { + val source = mutablePreferencesOf() + source[SettingsKeys.brandFont] = FONT_CUSTOM_TOKEN + source[SettingsKeys.plainFont] = FONT_CUSTOM_TOKEN + val target = mutablePreferencesOf() + target[SettingsKeys.brandFont] = "lora" + + val plan = import(roundTrip(source), target, environment(fonts = setOf(FontRole.PLAIN))) + + assertThat(target[SettingsKeys.brandFont]).isEqualTo("lora") + assertThat(target[SettingsKeys.plainFont]).isEqualTo(FONT_CUSTOM_TOKEN) + assertThat(plan.skipped).containsExactly(SkippedSetting.CustomFont(FontRole.BRAND)) + } + + @Test + fun `contact dates without the permission stay as they are`() { + val source = mutablePreferencesOf() + source[SettingsKeys.specialDatesEnabled] = true + val target = mutablePreferencesOf() + + val plan = import(roundTrip(source), target, environment(contacts = false)) + + assertThat(target[SettingsKeys.specialDatesEnabled]).isFalse() + assertThat(plan.skipped).contains(SkippedSetting.SpecialDates) + } + + @Test + fun `automatic backup without a folder here stays off, its interval comes along`() { + val source = mutablePreferencesOf() + source[SettingsKeys.autoBackupEnabled] = true + source[SettingsKeys.autoBackupIntervalMinutes] = 120L + val target = mutablePreferencesOf() + + val plan = import(roundTrip(source), target) + + assertThat(target[SettingsKeys.autoBackupEnabled]).isFalse() + assertThat(target[SettingsKeys.autoBackupIntervalMinutes]).isEqualTo(120L) + assertThat(plan.skipped).contains(SkippedSetting.AutoBackupFolder) + } + + @Test + fun `automatic backup keeps going where a folder is already set`() { + val source = mutablePreferencesOf() + source[SettingsKeys.autoBackupEnabled] = true + val target = mutablePreferencesOf() + + import(roundTrip(source), target, environment(folder = true)) + + assertThat(target[SettingsKeys.autoBackupEnabled]).isTrue() + } + + @Test + fun `the language resolves against what this build ships`() { + val backup = roundTrip(mutablePreferencesOf()) + + assertThat(planSettingsImport(backup.copy(language = LanguageChoice("en-US")), mutablePreferencesOf(), environment()).language) + .isEqualTo(LanguageChoice("en-US")) + assertThat(planSettingsImport(backup.copy(language = LanguageChoice(null)), mutablePreferencesOf(), environment()).language) + .isEqualTo(LanguageChoice(null)) + val missing = planSettingsImport(backup.copy(language = LanguageChoice("ja")), mutablePreferencesOf(), environment()) + assertThat(missing.language).isNull() + assertThat(missing.skipped).containsExactly(SkippedSetting.Language("ja")) + } + + @Test + fun `app-level choices travel along`() { + val backup = roundTrip(mutablePreferencesOf()) + + assertThat(backup.language).isEqualTo(LanguageChoice("de")) + assertThat(backup.launcherName).isEqualTo(LauncherName.CALENDAR) + } + + @Test + fun `unknown fields from a later build are ignored`() { + val text = """ + {"format":"calendula-settings","version":1,"exportedAt":1,"future":{"x":1}, + "settings":{"multi_day_count":4,"some_new_key":true}, + "calendars":[{"account_name":"a","account_type":"t","display_name":"d","colour":"red"}], + "app":{"launcher_name":"SOMETHING_NEW"}} + """.trimIndent() + + val backup = (decodeSettingsBackup(text) as BackupResult.Success).value + + assertThat(backup.prefs.values).containsExactly(4) + assertThat(backup.calendars).hasSize(1) + assertThat(backup.launcherName).isNull() + assertThat(backup.language).isNull() + } + + @Test + fun `a malformed known field rejects the whole file`() { + listOf( + """{"format":"calendula-settings","version":1,"exportedAt":1,"settings":{"multi_day_count":"4"}}""", + """{"format":"calendula-settings","version":1,"exportedAt":1,"calendars":[{"account_name":"a"}]}""", + """{"format":"calendula-settings","version":1,"exportedAt":1,"calendars":[{"account_name":"a","account_type":"t","display_name":"d","reminders":["x"]}]}""", + ).forEach { text -> + val result = decodeSettingsBackup(text) as BackupResult.Failure + assertThat(result.problem).isEqualTo(BackupProblem.INVALID_DATA) + } + } + + @Test + fun `a file without its settings section is refused`() { + val result = decodeSettingsBackup("""{"format":"calendula-settings","version":1,"exportedAt":1,"calendars":[]}""") + + assertThat((result as BackupResult.Failure).problem).isEqualTo(BackupProblem.INVALID_DATA) + } + + @Test + fun `an import without per-calendar settings leaves no empty keys behind`() { + val target = mutablePreferencesOf() + target[SettingsKeys.perCalendarEventDuration] = mapOf(1L to 30) + + import(roundTrip(mutablePreferencesOf()), target) + + SettingsBackupSchema.perCalendar.forEach { pref -> + assertThat(target.asMap().keys.map { it.name }).doesNotContain(pref.name) + } + } + + @Test + fun `two file entries naming the same calendar are both skipped`() { + val text = """{"format":"calendula-settings","version":1,"exportedAt":1,"settings":{},"calendars":[ + {"account_name":"me@example.org","account_type":"com.google","display_name":"Work","hidden":true}, + {"account_name":"me@example.org","account_type":"com.google","display_name":"Work","event_duration_minutes":90}]}""" + val backup = (decodeSettingsBackup(text) as BackupResult.Success).value + + val target = mutablePreferencesOf() + val plan = import(backup, target) + + assertThat(target[CalendarPrefKeys.hiddenCalendarIds]).isEmpty() + assertThat(plan.skipped).containsExactly(SkippedSetting.Calendar("Work", "me@example.org", ambiguous = true)) + } + + @Test + fun `reminder lists are cleaned the way the setters store them`() { + val text = """{"format":"calendula-settings","version":1,"exportedAt":1,"settings":{},"calendars":[ + {"account_name":"a","account_type":"t","display_name":"d","reminders":[60,-5,30,30]}]}""" + + val backup = (decodeSettingsBackup(text) as BackupResult.Success).value + + assertThat(backup.calendars.single().reminders).containsExactly(30, 60).inOrder() + } + + @Test + fun `a newer schema is refused`() { + val result = decodeSettingsBackup("""{"format":"calendula-settings","version":2,"exportedAt":1}""") + + assertThat((result as BackupResult.Failure).problem).isEqualTo(BackupProblem.NEWER_VERSION) + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/AllDayReminderEncodingTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/AllDayReminderEncodingTest.kt index 75da13de..ae380c05 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/AllDayReminderEncodingTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/AllDayReminderEncodingTest.kt @@ -48,11 +48,29 @@ class AllDayReminderEncodingTest { assertThat(actualFire(raw, summer)).isEqualTo(intendedFire(summer, 0, nineAm)) } + @Test + fun `whole-day lead times match the encoder and keep the default sentinel`() { + assertThat(wholeDayLeadTimes(listOf(2_880, 10, 1_500, 0, MINUTES_DEFAULT))) + .containsExactly(MINUTES_DEFAULT, 0, 1_440, 2_880).inOrder() + for (minutes in listOf(10, 1_500, -30)) { + assertThat(toProviderAllDayMinutes(minutes, summer, berlin, nineAm)) + .isEqualTo(toProviderAllDayMinutes(wholeDayLeadMinutes(minutes), summer, berlin, nineAm)) + } + } + + @Test + fun `three weeks before fires at 9am local across a DST change`() { + val afterDst = LocalDate.of(2026, 4, 10) // CEST; three weeks earlier is CET + val raw = toProviderAllDayMinutes(3 * 10_080, afterDst, berlin, nineAm) + assertThat(actualFire(raw, afterDst)).isEqualTo(intendedFire(afterDst, 21, nineAm)) + assertThat(fromProviderAllDayMinutes(raw, afterDst, berlin, nineAm)).isEqualTo(3 * 10_080) + } + @Test fun `round-trips for whole-day lead times across both seasons`() { for (date in listOf(summer, winter)) { for (time in listOf(0, nineAm, 20 * 60)) { - for (semantic in listOf(0, 1_440, 2_880, 10_080)) { + for (semantic in listOf(0, 1_440, 2_880, 4_320, 5_760, 7_200, 10_080, 20_160, 30_240)) { val raw = toProviderAllDayMinutes(semantic, date, berlin, time) assertThat(fromProviderAllDayMinutes(raw, date, berlin, time)) .isEqualTo(semantic) diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt index fcf402c6..a951a2a4 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt @@ -8,6 +8,13 @@ import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.domain.FormTime import de.jeanlucmakiola.calendula.domain.SearchCandidate +import de.jeanlucmakiola.calendula.domain.EventStatus +import de.jeanlucmakiola.calendula.domain.ics.CalendarRows +import de.jeanlucmakiola.calendula.domain.ics.IcsEvent +import de.jeanlucmakiola.calendula.domain.ics.IcsParser +import de.jeanlucmakiola.calendula.domain.ics.IcsWriter +import de.jeanlucmakiola.calendula.domain.ics.OverrideRow +import de.jeanlucmakiola.calendula.domain.ics.MasterRow import de.jeanlucmakiola.calendula.testEvent import de.jeanlucmakiola.calendula.testPrefs import de.jeanlucmakiola.calendula.testRepository @@ -946,19 +953,153 @@ class CalendarRepositoryImplTest { repo.exportEvents(calendarIds = setOf(1L, 4L)) - assertThat(fake.lastExportableEventsCalendarIds).containsExactly(1L, 4L) + assertThat(fake.lastCalendarRowsIds).containsExactly(1L, 4L) } @Test - fun `exportEvents defaults to null so every eligible calendar is exported`( + fun `exportEvents reads synced calendars when asked for them`( @TempDir tempDir: Path, ) = runTest { val fake = FakeCalendarDataSource() val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) - repo.exportEvents() + repo.exportEvents(calendarIds = setOf(2L)) - assertThat(fake.lastExportableEventsCalendarIds).isNull() + assertThat(fake.lastCalendarRowsIds).containsExactly(2L) + } + + @Test + fun `copyEvents reports progress and skips what an earlier run copied`( + @TempDir tempDir: Path, + ) = runTest { + fun icsEvent(uid: String) = IcsEvent( + uid = uid, + summary = uid, + start = Instant.fromEpochMilliseconds(1_000_000_000L), + end = Instant.fromEpochMilliseconds(1_000_003_600L), + isAllDay = false, + zoneId = "UTC", + ) + val fake = FakeCalendarDataSource().apply { + existingUidsResult = setOf("a") + calendarRowsResult = CalendarRows( + series = listOf(MasterRow(1, 1, null, icsEvent("a")), MasterRow(2, 1, null, icsEvent("b"))), + overrides = emptyList(), + ) + } + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) + val progress = mutableListOf>() + + val summary = repo.copyEvents(sourceCalendarId = 1L, targetCalendarId = 3L) { done, total -> + progress += done to total + } + + assertThat(summary.imported).isEqualTo(1) + assertThat(summary.skippedDuplicate).isEqualTo(1) + assertThat(fake.importedEvents.map { it.first.uid to it.second }).containsExactly("b" to 3L) + assertThat(progress.first()).isEqualTo(0 to 2) + assertThat(progress.last()).isEqualTo(2 to 2) + } + + @Test + fun `a backup restores a series' moved and deleted occurrences, and skips them where the series is`( + @TempDir tempDir: Path, + ) = runTest { + val start = Instant.parse("2026-01-05T09:00:00Z") + fun at(week: Int) = Instant.fromEpochMilliseconds(start.toEpochMilliseconds() + week * 7 * 86_400_000L) + fun event(at: Instant, status: EventStatus = EventStatus.Confirmed, rrule: String? = null) = IcsEvent( + uid = "s@x", + summary = "Standup", + start = at, + end = Instant.fromEpochMilliseconds(at.toEpochMilliseconds() + 3_600_000L), + isAllDay = false, + zoneId = "Europe/Berlin", + recurrenceRule = rrule, + status = status, + ) + val moved = Instant.fromEpochMilliseconds(at(1).toEpochMilliseconds() + 3_600_000L) + val source = FakeCalendarDataSource().apply { + calendarRowsResult = CalendarRows( + series = listOf(MasterRow(1, 1, "sync-1", event(start, rrule = "FREQ=WEEKLY"))), + overrides = listOf( + OverrideRow(1, null, "sync-1", at(1), event(moved)), + OverrideRow(1, null, "sync-1", at(2), event(at(2), EventStatus.Cancelled)), + ), + ) + } + val file = IcsWriter().writeCalendar( + testRepository(source, tempDir.resolve("a"), Dispatchers.Unconfined).exportEvents(setOf(1L)), + start, + ) + val parsed = IcsParser().parse(file).events + + val empty = FakeCalendarDataSource() + testRepository(empty, tempDir.resolve("b"), Dispatchers.Unconfined).importEvents(3L, parsed) + val (detached, series) = empty.importedEvents.map { it.first } + assertThat(detached.start).isEqualTo(moved) + assertThat(detached.recurrenceRule).isNull() + assertThat(series.exDates).containsExactly("20260112T090000Z", "20260119T090000Z") + + val original = FakeCalendarDataSource().apply { existingUidsResult = setOf("s@x") } + val summary = testRepository(original, tempDir.resolve("c"), Dispatchers.Unconfined).importEvents(3L, parsed) + assertThat(original.importedEvents).isEmpty() + assertThat(summary.skippedDuplicate).isEqualTo(2) + } + + @Test + fun `a series keeps an occurrence whose standalone copy didn't land`( + @TempDir tempDir: Path, + ) = runTest { + val fake = FakeCalendarDataSource().apply { failingImportSummaries += "moved" } + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) + val at = Instant.parse("2026-01-12T09:00:00Z") + + val summary = repo.importEvents( + 3L, + listOf( + parsedEvent("1-s", summary = "moved").copy(overrideOf = "s", overrideAt = at), + parsedEvent("s").copy(recurrenceRule = "FREQ=WEEKLY", exDates = listOf("20260112T090000Z", "20260119T090000Z")), + ), + ) + + assertThat(summary.failed).isEqualTo(1) + assertThat(fake.importedEvents.single().first.exDates).containsExactly("20260119T090000Z") + } + + @Test + fun `a standalone occurrence listed after its series still goes first`( + @TempDir tempDir: Path, + ) = runTest { + val fake = FakeCalendarDataSource() + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) + + repo.importEvents(3L, listOf(parsedEvent("s"), parsedEvent("1-s").copy(overrideOf = "s"))) + + assertThat(fake.importedEvents.map { it.first.uid }).containsExactly("1-s", "s").inOrder() + } + + @Test + fun `a backup keeps an RDATE-only series and its exceptions`( + @TempDir tempDir: Path, + ) = runTest { + val start = Instant.parse("2026-01-05T09:00:00Z") + val other = Instant.parse("2026-01-12T09:00:00Z") + val event = IcsEvent( + "s", "S", start, Instant.parse("2026-01-05T10:00:00Z"), false, "UTC", + recurrenceDates = listOf("20260112T090000Z", "20260119T090000Z"), + ) + val fake = FakeCalendarDataSource().apply { + calendarRowsResult = CalendarRows( + listOf(MasterRow(1, 1, null, event)), + listOf(OverrideRow(1, 1, null, other, event.copy(recurrenceDates = emptyList(), status = EventStatus.Cancelled))), + ) + } + + val exported = testRepository(fake, tempDir, Dispatchers.Unconfined).exportEvents(setOf(1L)) + val restored = IcsParser().parse(IcsWriter().writeCalendar(exported, start)).events.single() + + assertThat(restored.recurrenceDates).containsExactly("20260112T090000Z", "20260119T090000Z") + assertThat(restored.exDates).containsExactly("20260112T090000Z") } private fun parsedEvent(uid: String?, summary: String = "E") = diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapperTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapperTest.kt index a783bafe..bbfe7355 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapperTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapperTest.kt @@ -13,6 +13,7 @@ import kotlinx.datetime.LocalDateTime import kotlinx.datetime.LocalTime import kotlinx.datetime.UtcOffset import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows import java.time.ZoneId import kotlin.time.Instant @@ -33,6 +34,14 @@ class EventWriteMapperTest { timezone = timezone, ) + @Test + fun `reminders are rewritten when they change or the all-day flag flips`() { + val timed = form().copy(reminders = listOf(10)) + assertThat(remindersNeedRewrite(timed, timed.copy(title = "Renamed"))).isFalse() + assertThat(remindersNeedRewrite(timed, timed.copy(reminders = listOf(10, 30)))).isTrue() + assertThat(remindersNeedRewrite(timed, timed.copy(isAllDay = true))).isTrue() + } + @Test fun `timed event resolves wall clock in the given zone`() { val times = form().toWriteTimes(berlin) @@ -492,6 +501,58 @@ class EventWriteMapperTest { .isEqualTo(CalendarContract.Events.STATUS_CANCELED) } + // --- seriesDuration (#502) --- + + @Test + fun `series duration prefers the expanded occurrence over dtend`() { + // DTEND as the end of the whole series must not stretch every occurrence. + assertThat(seriesDuration(1_000_000L, 9_000_000_000L, 3_600_000L, isAllDay = false)).isEqualTo("P3600S") + } + + @Test + fun `series duration falls back to dtend when it lies after dtstart`() { + assertThat(seriesDuration(1_000_000L, 8_200_000L, null, isAllDay = false)).isEqualTo("P7200S") + } + + @Test + fun `series duration ignores a zero dtend and uses the occurrence span`() { + assertThat(seriesDuration(1_790_852_400_000L, 0L, 7_200_000L, isAllDay = false)).isEqualTo("P7200S") + } + + @Test + fun `series duration gives up rather than guessing`() { + assertThat(seriesDuration(1_000L, 0L, null, isAllDay = false)).isNull() + assertThat(seriesDuration(1_000L, null, null, isAllDay = true)).isNull() + } + + @Test + fun `all-day series duration rounds to whole days`() { + // 47 h: a two-day occurrence read across a DST change. + assertThat(seriesDuration(0L, null, 47L * 3_600_000L, isAllDay = true)).isEqualTo("P2D") + } + + @Test + fun `series duration keeps a zero length the provider already shows`() { + assertThat(seriesDuration(1_000L, 0L, 0L, isAllDay = false)).isEqualTo("P0S") + assertThat(seriesDuration(1_000L, 1_000L, null, isAllDay = true)).isEqualTo("P1D") + } + + @Test + fun `exdate drop clears a stray dtend on the series`() { + val values = buildOccurrenceExdateValues( + existingExdate = null, + occurrenceMillis = 1_784_102_400_000L, + dtStartMillis = 1_783_929_600_000L, + rrule = "FREQ=DAILY;COUNT=5", + rdate = null, + duration = "PT1H", + timezone = "Europe/Berlin", + allDay = 0, + ) + assertThat(values).containsKey(CalendarContract.Events.DTEND) + assertThat(values[CalendarContract.Events.DTEND]).isNull() + } + // --- buildOccurrenceExdateValues ("delete only this event", no _sync_id) --- @Test @@ -1186,6 +1247,14 @@ class EventWriteMapperTest { description = "", ) + @Test + fun `moved series with a zero dtend and no duration is refused, not copied broken`() { + val snapshot = masterSnapshot(dtEndMillis = 0L, rrule = "FREQ=WEEKLY;BYDAY=TH") + assertThrows { + buildMovedMasterValues(snapshot, targetCalendarId = 9L, uid = "u@calendula") + } + } + @Test fun `moved one-off carries target calendar, uid and DTEND but no recurrence`() { val values = buildMovedMasterValues(masterSnapshot(), targetCalendarId = 9L, uid = "u@calendula") diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/FakeCalendarDataSource.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/FakeCalendarDataSource.kt index e22ec492..4fb9dff0 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/FakeCalendarDataSource.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/FakeCalendarDataSource.kt @@ -8,6 +8,7 @@ import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.domain.SearchCandidate import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType +import de.jeanlucmakiola.calendula.domain.ics.CalendarRows import de.jeanlucmakiola.calendula.domain.ics.IcsEvent import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent import java.time.ZoneId @@ -23,9 +24,9 @@ internal class FakeCalendarDataSource : CalendarDataSource { var searchResult: (String) -> List = { _ -> emptyList() } var eventDetailResult: (Long) -> EventDetail? = { null } var publishedEventColorsResult: (Long) -> List = { emptyList() } - var exportableEventsResult: List = emptyList() - /** The [calendarIds] the last [exportableEvents] call received (null = all). */ - var lastExportableEventsCalendarIds: Set? = null + var calendarRowsResult: CalendarRows = CalendarRows(emptyList(), emptyList()) + /** The [calendarIds] the last [calendarRows] call received. */ + var lastCalendarRowsIds: Set? = null /** UIDs the target calendar already holds, for import dedup. */ var existingUidsResult: Set = emptySet() /** Set to make the next write call throw. */ @@ -64,14 +65,27 @@ internal class FakeCalendarDataSource : CalendarDataSource { val updatedCalendars = mutableListOf() val deletedCalendarIds = mutableListOf() + /** eventId → calendarId, for [eventCalendarId]. */ + val eventCalendars = mutableMapOf() + + override fun calendarAccount(calendarId: Long): SyncAccount? = + calendarsResult.firstOrNull { it.id == calendarId } + ?.let { SyncAccount(it.accountName, it.accountType) } + + override fun eventCalendarId(eventId: Long): Long? = eventCalendars[eventId] + private val listeners = mutableListOf<() -> Unit>() /** How often [calendars] was queried — the repository shares one read per tick. */ var calendarQueries = 0 private set + /** Set to make [calendars] throw until cleared. */ + var calendarsError: Exception? = null + override fun calendars(): List { calendarQueries++ + calendarsError?.let { throw it } return calendarsResult } override fun instances(beginMillis: Long, endMillis: Long): List = @@ -81,12 +95,9 @@ internal class FakeCalendarDataSource : CalendarDataSource { eventDetailResult(eventId) override fun publishedEventColors(calendarId: Long): List = publishedEventColorsResult(calendarId) - override fun exportableEvents( - calendarIds: Set?, - allDayReminderTimeMinutes: Int, - ): List { - lastExportableEventsCalendarIds = calendarIds - return exportableEventsResult + override fun calendarRows(calendarIds: Set, allDayReminderTimeMinutes: Int): CalendarRows { + lastCalendarRowsIds = calendarIds + return calendarRowsResult } override fun existingUids(calendarId: Long): Set = existingUidsResult diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapperTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapperTest.kt index 6045ef4d..a6096aa3 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapperTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapperTest.kt @@ -294,4 +294,39 @@ class IcsExportMapperTest { assertThat(event.exDates).isEmpty() } + + @Test + fun `a zoned RDATE list is written as UTC stamps, a period by its start`() { + assertThat(exportRecurrenceDates("Europe/Berlin;20260110T100000,20260111T100000/PT1H", isAllDay = false)) + .containsExactly("20260110T090000Z", "20260111T090000Z").inOrder() + } + + @Test + fun `an all-day RDATE keeps its days, junk is dropped`() { + assertThat(exportRecurrenceDates("20260110T000000Z,20260111,garbage", isAllDay = true)) + .containsExactly("20260110", "20260111").inOrder() + } + + @Test + fun `an RDATE stored over several lines keeps every line's dates`() { + assertThat(exportRecurrenceDates("Europe/Berlin;20260110T100000\nAmerica/New_York;20260112T090000", isAllDay = false)) + .containsExactly("20260110T090000Z", "20260112T140000Z").inOrder() + } + + @Test + fun `an EXDATE stored over several lines keeps every line, unreadable stamps go`() { + assertThat(exportExDates("Europe/Berlin;20260110T100000\nEurope/Berlin;20260117T100000,junk", isAllDay = false)) + .containsExactly("20260110T090000Z", "20260117T090000Z").inOrder() + } + + @Test + fun `a bare day on a timed series is read at the series' time of day`() { + val tenBerlin = java.time.ZonedDateTime.of(2026, 1, 5, 10, 0, 0, 0, java.time.ZoneId.of("Europe/Berlin")) + .toInstant().toEpochMilli() + + assertThat(exportExDates("20260112", isAllDay = false, "Europe/Berlin", tenBerlin)) + .containsExactly("20260112T090000Z") + assertThat(exportRecurrenceDates("20260712", isAllDay = false, "Europe/Berlin", tenBerlin)) + .containsExactly("20260712T080000Z") + } } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/ImportedEventValuesTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/ImportedEventValuesTest.kt index e84e6580..49b39cf8 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/ImportedEventValuesTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/ImportedEventValuesTest.kt @@ -2,6 +2,7 @@ package de.jeanlucmakiola.calendula.data.calendar import android.provider.CalendarContract import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.domain.AccessLevel import de.jeanlucmakiola.calendula.domain.EventColorOption import de.jeanlucmakiola.calendula.domain.EventStatus import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent @@ -123,4 +124,21 @@ class ImportedEventValuesTest { assertThat(v[CalendarContract.Events.DURATION]).isEqualTo("P900S") assertThat(v[CalendarContract.Events.ALL_DAY]).isEqualTo(0) } + + @Test + fun `a copied RDATE-only series recurs by its dates`() { + val v = values(allDay().copy(recurrenceDates = listOf("20260820"), exDates = listOf("20260820"))) + assertThat(v).doesNotContainKey(CalendarContract.Events.DTEND) + assertThat(v).doesNotContainKey(CalendarContract.Events.RRULE) + assertThat(v[CalendarContract.Events.RDATE]).isEqualTo("20260820") + assertThat(v[CalendarContract.Events.EXDATE]).isEqualTo("20260820") + assertThat(v[CalendarContract.Events.DURATION]).isEqualTo("P1D") + } + + @Test + fun `a private event stays private, a default one leaves the calendar's say`() { + assertThat(values(allDay().copy(accessLevel = AccessLevel.Private))[CalendarContract.Events.ACCESS_LEVEL]) + .isEqualTo(CalendarContract.Events.ACCESS_PRIVATE) + assertThat(values(allDay())).doesNotContainKey(CalendarContract.Events.ACCESS_LEVEL) + } } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt new file mode 100644 index 00000000..abb8f9de --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/SyncNudgeTest.kt @@ -0,0 +1,314 @@ +package de.jeanlucmakiola.calendula.data.calendar + +import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.RecordingSyncRequester +import de.jeanlucmakiola.calendula.RecordingSyncRequester.Request +import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.domain.EventForm +import de.jeanlucmakiola.calendula.domain.FormTime +import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent +import de.jeanlucmakiola.calendula.testRepository +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.test.runTest +import kotlinx.datetime.LocalDate +import kotlinx.datetime.LocalDateTime +import kotlinx.datetime.LocalTime +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Path +import kotlin.time.Instant + +class SyncNudgeTest { + + private val dav = SyncAccount("me@dav", "bitfire.at.davdroid") + private val google = SyncAccount("me@gmail.com", "com.google") + + private fun cal(id: Long, account: SyncAccount, visible: Boolean = true) = CalendarSource( + id = id, + displayName = "Cal $id", + accountName = account.name, + accountType = account.type, + color = 0, + isVisibleInSystem = visible, + isLocal = account.type == "LOCAL", + ) + + private val local = SyncAccount("Calendula", "LOCAL") + + private fun fake() = FakeCalendarDataSource().apply { + calendarsResult = listOf(cal(1L, dav), cal(2L, dav), cal(3L, google), cal(4L, local)) + eventCalendars += mapOf(10L to 1L, 30L to 3L, 40L to 4L) + } + + private fun form(calendarId: Long) = EventForm( + calendarId = calendarId, + title = "Stand-up", + start = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 0))), + end = FormTime(LocalDateTime(LocalDate(2026, 6, 12), LocalTime(9, 15))), + ) + + private fun auto(account: SyncAccount) = Request(account, userInitiated = false) + + @Test + fun `a write to a synced calendar nudges its account once, not manually`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester() + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + repo.createEvent(form(1L)) + + assertThat(sync.requests).containsExactly(auto(dav)) + } + + @Test + fun `a write to a local calendar asks for no sync`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester() + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + repo.createEvent(form(4L)) + repo.deleteEvent(40L) + + assertThat(sync.requests).isEmpty() + } + + @Test + fun `event writes resolve the account from the event's calendar`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester() + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + repo.updateEventFromOccurrence(10L, 0L, form(1L), form(1L)) + repo.deleteOccurrence(30L, 0L) + + assertThat(sync.requests).containsExactly(auto(dav), auto(google)).inOrder() + } + + @Test + fun `a move between accounts nudges both, each once`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester() + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + repo.moveEvent(10L, 3L, form(1L), form(3L)) + + assertThat(sync.requests).containsExactly(auto(dav), auto(google)) + } + + @Test + fun `a move between calendars of one account nudges it once`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester() + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + repo.moveEvent(10L, 2L, form(1L), form(2L)) + + assertThat(sync.requests).containsExactly(auto(dav)) + } + + @Test + fun `an import nudges once at the end, however many events`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester() + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + val events = (1..5).map { + ParsedIcsEvent( + uid = "u$it", + summary = "E$it", + start = Instant.fromEpochMilliseconds(1_000_000_000L), + end = Instant.fromEpochMilliseconds(1_000_003_600L), + isAllDay = false, + zoneId = "UTC", + ) + } + + repo.importEvents(3L, events) + + assertThat(sync.requests).containsExactly(auto(google)) + } + + @Test + fun `a failed write still nudges, since part of it may have landed`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester() + val source = fake().apply { writeError = IllegalStateException("boom") } + val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = sync) + + assertThrows { repo.deleteEvent(10L) } + + assertThat(sync.requests).containsExactly(auto(dav)) + } + + @Test + fun `a throwing requester never fails the save`(@TempDir dir: Path) = runTest { + val throwing = RecordingSyncRequester(accepts = false) + val source = fake().apply { nextInsertId = 77L } + val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = throwing) + + assertThat(repo.createEvent(form(1L))).isEqualTo(77L) + } + + @Test + fun `manual sync asks each visible synced account once, as manual`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester() + val source = fake().apply { + calendarsResult = calendarsResult + cal(5L, SyncAccount("hidden@dav", "bitfire.at.davdroid"), visible = false) + } + val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = sync) + + assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.Requested) + assertThat(sync.requests).containsExactly(Request(dav, true), Request(google, true)) + } + + @Test + fun `manual sync with only local calendars has nothing to sync`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester() + val source = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(4L, local)) } + val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = sync) + + assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.NothingToSync) + assertThat(sync.requests).isEmpty() + } + + @Test + fun `manual sync the system refuses reports a failure`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester(accepts = false) + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.Failed) + } + + @Test + fun `syncAccounts skips local, invisible and blank accounts`() { + val calendars = listOf( + cal(1L, dav), + cal(2L, dav), + cal(3L, google, visible = false), + cal(4L, local), + cal(5L, SyncAccount("", "com.google")), + ) + + assertThat(calendars.syncAccounts()).containsExactly(dav) + } + + @Test + fun `accounts without a calendar sync adapter are never asked`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester(adapterTypes = setOf(dav.type)) + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + repo.createEvent(form(3L)) + assertThat(sync.requests).isEmpty() + + assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.Requested) + assertThat(sync.requests).containsExactly(Request(dav, true)) + } + + @Test + fun `syncTargets needs a visible calendar with an adapter`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester(adapterTypes = setOf(google.type)) + val source = fake().apply { + calendarsResult = listOf(cal(1L, dav), cal(3L, google, visible = false), cal(4L, local)) + } + val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = sync) + + assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets.None) + + sync.adapterTypes = setOf(dav.type) + assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav), emptySet())) + } + + @Test + fun `manual sync refused for some accounts says so`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester(refusedTypes = setOf(google.type)) + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.PartlyFailed) + assertThat(sync.requests).containsExactly(Request(dav, true)) + } + + @Test + fun `accounts the app can't see wait for access instead of being asked`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester(hiddenTypes = setOf(google.type)) + sync.knownAccounts = setOf(dav, google) + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + repo.moveEvent(10L, 3L, form(1L), form(3L)) + assertThat(sync.requests).containsExactly(auto(dav)) + + assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav), setOf(google))) + + sync.requests.clear() + assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.SomeNeedAccess) + assertThat(sync.requests).containsExactly(Request(dav, true)) + } + + @Test + fun `once access is granted the account is asked by name`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester(hiddenTypes = setOf(google.type)) + sync.knownAccounts = setOf(dav, google) + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + sync.hiddenTypes = setOf("other") + + assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav, google), emptySet())) + assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.Requested) + assertThat(sync.requests).containsExactly(Request(dav, true), Request(google, true)) + } + + @Test + fun `only hidden accounts make manual sync ask for access, asking no one`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester(hiddenTypes = setOf(dav.type, google.type)) + sync.knownAccounts = setOf(dav, google) + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.NeedsAccess) + repo.createEvent(form(1L)) + assertThat(sync.requests).isEmpty() + } + + @Test + fun `unreadable account visibility counts as reachable`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester(hiddenTypes = setOf("other")) + sync.visibilityError = SecurityException("no") + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + repo.createEvent(form(1L)) + + assertThat(sync.requests).containsExactly(auto(dav)) + } + + @Test + fun `a dismissed hidden account no longer needs access`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester(hiddenTypes = setOf(google.type)) + sync.knownAccounts = setOf(dav, google) + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + repo.setSyncAccessDismissed(google, dismissed = true) + + assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav), emptySet(), dismissed = setOf(google))) + assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.Requested) + + repo.setSyncAccessDismissed(google, dismissed = false) + assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav), setOf(google))) + } + + @Test + fun `with every hidden account dismissed there is nothing to sync or grant`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester(hiddenTypes = setOf(dav.type, google.type)) + sync.knownAccounts = setOf(dav, google) + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + repo.setSyncAccessDismissed(dav, dismissed = true) + repo.setSyncAccessDismissed(google, dismissed = true) + + assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(emptySet(), emptySet(), dismissed = setOf(dav, google))) + assertThat(repo.requestSync().result).isEqualTo(SyncRequestResult.NothingToSync) + } + + @Test + fun `a dismissed account that becomes visible is still asked`(@TempDir dir: Path) = runTest { + val sync = RecordingSyncRequester() + val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync) + + repo.setSyncAccessDismissed(dav, dismissed = true) + repo.createEvent(form(1L)) + + assertThat(sync.requests).containsExactly(auto(dav)) + assertThat(repo.syncTargets.first().dismissed).isEmpty() + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/CalendarPrefsTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/CalendarPrefsTest.kt index 9f0fb46b..5a95a37d 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/CalendarPrefsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/CalendarPrefsTest.kt @@ -2,6 +2,7 @@ package de.jeanlucmakiola.calendula.data.prefs import androidx.datastore.preferences.core.stringPreferencesKey import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.data.calendar.SyncAccount import de.jeanlucmakiola.calendula.testDataStore import de.jeanlucmakiola.calendula.testPrefs import kotlinx.coroutines.flow.first @@ -34,6 +35,16 @@ class CalendarPrefsTest { assertThat(prefs.hiddenCalendarIds.first()).isEmpty() } + @Test + fun `updateHiddenCalendarIds transforms the stored set`(@TempDir tempDir: Path) = runTest { + val prefs = testPrefs(tempDir) + prefs.setHiddenCalendarIds(setOf(9L)) + prefs.updateHiddenCalendarIds { it + listOf(1L, 2L) } + assertThat(prefs.hiddenCalendarIds.first()).isEqualTo(setOf(1L, 2L, 9L)) + prefs.updateHiddenCalendarIds { emptySet() } + assertThat(prefs.hiddenCalendarIds.first()).isEmpty() + } + @Test fun `garbage stored string is parsed defensively`(@TempDir tempDir: Path) = runTest { val store = testDataStore(tempDir, "test_prefs") @@ -108,4 +119,18 @@ class CalendarPrefsTest { prefs.setVisibilityNoticePending(false) assertThat(prefs.visibilityNoticePending.first()).isFalse() } + + @Test + fun `sync access dismissals round-trip per account, names with any characters`(@TempDir tempDir: Path) = runTest { + val prefs = testPrefs(tempDir) + val dav = SyncAccount("me@dav.example/cal, 1", "bitfire.at.davdroid") + val google = SyncAccount("me@dav.example/cal, 1", "com.google") + + prefs.setSyncAccessDismissed(dav, dismissed = true) + prefs.setSyncAccessDismissed(google, dismissed = true) + assertThat(prefs.syncAccessDismissed.first()).containsExactly(dav, google) + + prefs.setSyncAccessDismissed(dav, dismissed = false) + assertThat(prefs.syncAccessDismissed.first()).containsExactly(google) + } } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt index d2fb8e65..1ca51f74 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt @@ -5,11 +5,17 @@ import de.jeanlucmakiola.calendula.testSettings import de.jeanlucmakiola.floret.reminders.ReminderOverride import androidx.compose.ui.unit.dp +import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.EventFormField import de.jeanlucmakiola.calendula.domain.FontRole import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType +import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle +import de.jeanlucmakiola.calendula.domain.reminders.DailyDigestSettings +import de.jeanlucmakiola.calendula.domain.reminders.DigestDay +import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder import de.jeanlucmakiola.calendula.ui.agenda.AgendaRange import de.jeanlucmakiola.calendula.ui.common.CalendarView import de.jeanlucmakiola.calendula.ui.common.IMPLEMENTED_VIEWS @@ -501,6 +507,18 @@ class SettingsPrefsTest { assertThat(prefs.defaultAllDayReminderMinutes.first()).isEmpty() } + @Test + fun `sub-day all-day defaults read as the day they fire on`(@TempDir tempDir: Path) = runTest { + val prefs = testSettings(tempDir) + prefs.setDefaultAllDayReminderMinutes(listOf(120, 0, 1_500)) + assertThat(prefs.defaultAllDayReminderMinutes.first()).containsExactly(0, 1_440).inOrder() + prefs.setCalendarAllDayReminderOverride(7L, ReminderOverride.Minutes(listOf(30, 2_880))) + assertThat(prefs.perCalendarAllDayReminderOverride.first()).containsExactly(7L, listOf(0, 2_880)) + // The timed default keeps sub-day lead times. + prefs.setDefaultReminderMinutes(listOf(120)) + assertThat(prefs.defaultReminderMinutes.first()).containsExactly(120) + } + @Test fun `per-calendar all-day override round-trips independently of the timed one`(@TempDir tempDir: Path) = runTest { val prefs = testSettings(tempDir) @@ -601,6 +619,42 @@ class SettingsPrefsTest { assertThat(prefs.perCalendarEventDuration.first()).containsExactly(9L, 30) } + @Test + fun `calendar notifications default on and toggle per calendar`( + @TempDir tempDir: Path, + ) = runTest { + val prefs = testSettings(tempDir) + assertThat(prefs.mutedReminderCalendarIds.first()).isEmpty() + prefs.setCalendarRemindersEnabled(7L, false) + prefs.setCalendarRemindersEnabled(9L, false) + assertThat(prefs.mutedReminderCalendarIds.first()).containsExactly(7L, 9L) + prefs.setCalendarRemindersEnabled(7L, true) + assertThat(prefs.mutedReminderCalendarIds.first()).containsExactly(9L) + } + + @Test + fun `calendar alert styles default to notifications and persist per calendar`( + @TempDir tempDir: Path, + ) = runTest { + val prefs = testSettings(tempDir) + assertThat(prefs.reminderAlertStyles.first()).isEmpty() + prefs.setCalendarAlertStyle(7L, ReminderAlertStyle.FullScreenRing) + prefs.setCalendarAlertStyle(9L, ReminderAlertStyle.FullScreen) + prefs.setCalendarAlertStyle(9L, ReminderAlertStyle.Notification) + assertThat(prefs.reminderAlertStyles.first()).containsExactly(7L, ReminderAlertStyle.FullScreenRing) + } + + @Test + fun `reminder channel versions only grow`( + @TempDir tempDir: Path, + ) = runTest { + val prefs = testSettings(tempDir) + assertThat(prefs.reminderChannelVersions.first()).isEmpty() + assertThat(prefs.reserveReminderChannelVersions(mapOf(7L to 1))).containsExactly(7L, 1) + assertThat(prefs.reserveReminderChannelVersions(mapOf(7L to 1, 9L to 5))).containsExactly(7L, 2, 9L, 5) + assertThat(prefs.reminderChannelVersions.first()).containsExactly(7L, 2, 9L, 5) + } + @Test fun `garbage per-calendar duration entries are dropped, the rest survive`( @TempDir tempDir: Path, @@ -616,6 +670,66 @@ class SettingsPrefsTest { assertThat(prefs.perCalendarEventDuration.first()).containsExactly(9L, 45) } + @Test + fun `per-calendar hidden views round-trip and clear back to every view`( + @TempDir tempDir: Path, + ) = runTest { + val prefs = testSettings(tempDir) + assertThat(prefs.perCalendarHiddenViews.first()).isEmpty() + prefs.applyCalendarHiddenChanges(7L, listOf(CalendarView.Month, CalendarView.Agenda).associateWith { true }) + prefs.applyCalendarHiddenChanges(9L, listOf(CalendarView.MultiDay).associateWith { true }) + assertThat(prefs.perCalendarHiddenViews.first()).containsExactly( + 7L, setOf(CalendarView.Month, CalendarView.Agenda), + 9L, setOf(CalendarView.MultiDay), + ) + prefs.clearCalendarHiddenViews(7L) + assertThat(prefs.perCalendarHiddenViews.first()).containsExactly(9L, setOf(CalendarView.MultiDay)) + // One write can hide some views and show others, leaving the rest alone. + prefs.applyCalendarHiddenChanges(9L, mapOf(CalendarView.MultiDay to false, CalendarView.Day to true)) + assertThat(prefs.perCalendarHiddenViews.first()).containsExactly(9L, setOf(CalendarView.Day)) + } + + @Test + fun `toggling one hidden view keeps the others and clears the entry when empty`( + @TempDir tempDir: Path, + ) = runTest { + val prefs = testSettings(tempDir) + prefs.setCalendarHiddenIn(7L, CalendarView.Month, hidden = true) + prefs.setCalendarHiddenIn(7L, CalendarView.Week, hidden = true) + assertThat(prefs.perCalendarHiddenViews.first()) + .containsExactly(7L, setOf(CalendarView.Month, CalendarView.Week)) + prefs.setCalendarHiddenIn(7L, CalendarView.Month, hidden = false) + prefs.setCalendarHiddenIn(7L, CalendarView.Week, hidden = false) + assertThat(prefs.perCalendarHiddenViews.first()).isEmpty() + } + + @Test + fun `garbage hidden-views entries are dropped, the rest survive`( + @TempDir tempDir: Path, + ) = runTest { + val store = testDataStore(tempDir, "test_settings") + val prefs = SettingsPrefs(store) + store.updateData { p -> + val m = p.toMutablePreferences() + // A bad id, only an unknown view, no separator, and a good entry with one unknown view. + m[stringPreferencesKey("per_calendar_hidden_views")] = "x=Month;7=Year;8;9=Month,Year,Agenda" + m + } + assertThat(prefs.perCalendarHiddenViews.first()) + .containsExactly(9L, setOf(CalendarView.Month, CalendarView.Agenda)) + } + + @Test + fun `hidden views serialise in view order and drop empty entries`() { + val stored = mapOf( + 3L to setOf(CalendarView.Agenda, CalendarView.Month), + 1L to emptySet(), + ).toStoredHiddenViews() + assertThat(stored).isEqualTo("3=Month,Agenda") + assertThat(emptyMap>().toStoredHiddenViews()).isNull() + assertThat(parseHiddenViews(stored)).containsExactly(3L, setOf(CalendarView.Month, CalendarView.Agenda)) + } + @Test fun `resolveDefaultEventDuration prefers the calendar's own length`() { val overrides = mapOf(7L to 480) @@ -705,4 +819,208 @@ class SettingsPrefsTest { prefs.recordSpecialDatesRun(2000L, null) assertThat(prefs.specialDatesStatus.first()).isEqualTo(SpecialDatesStatus(2000L, null)) } + + @Test + fun `fixed-time reminder defaults to off and round-trips`(@TempDir tempDir: Path) = runTest { + val prefs = testSettings(tempDir) + assertThat(prefs.defaultFixedTimeReminder.first()).isNull() + val evening = FixedTimeReminder(1, 1_200) + prefs.setDefaultFixedTimeReminder(evening) + assertThat(prefs.defaultFixedTimeReminder.first()).isEqualTo(evening) + prefs.setDefaultFixedTimeReminder(null) + assertThat(prefs.defaultFixedTimeReminder.first()).isNull() + } + + @Test + fun `per-calendar fixed-time overrides keep inherit, off and a value apart`(@TempDir tempDir: Path) = runTest { + val prefs = testSettings(tempDir) + val morning = FixedTimeReminder(2, 480) + prefs.setDefaultFixedTimeReminder(FixedTimeReminder(1, 1_200)) + prefs.setCalendarFixedTimeReminderOverride(1L, FixedTimeOverride.Off) + prefs.setCalendarFixedTimeReminderOverride(2L, FixedTimeOverride.At(morning)) + val overrides = prefs.perCalendarFixedTimeReminderOverride.first() + assertThat(overrides.fixedTimeOverrideFor(1L)).isEqualTo(FixedTimeOverride.Off) + assertThat(overrides.fixedTimeOverrideFor(2L)).isEqualTo(FixedTimeOverride.At(morning)) + assertThat(overrides.fixedTimeOverrideFor(3L)).isEqualTo(FixedTimeOverride.Inherit) + assertThat(resolveDefaultFixedTimeReminder(FixedTimeReminder(1, 1_200), overrides, 1L)).isNull() + assertThat(resolveDefaultFixedTimeReminder(FixedTimeReminder(1, 1_200), overrides, 3L)) + .isEqualTo(FixedTimeReminder(1, 1_200)) + assertThat(prefs.knownFixedTimeReminders.first()).containsExactly(FixedTimeReminder(1, 1_200), morning) + val picked = FixedTimeReminder(3, 600) + prefs.rememberFixedTimeReminders(listOf(picked, morning)) + assertThat(prefs.knownFixedTimeReminders.first()).contains(picked) + // A default already known takes no recents slot. + assertThat(prefs.knownFixedTimeReminders.first()).hasSize(3) + + // A replaced default stays known. + prefs.setDefaultFixedTimeReminder(FixedTimeReminder(1, 1_140)) + assertThat(prefs.knownFixedTimeReminders.first()).contains(FixedTimeReminder(1, 1_200)) + + prefs.setCalendarFixedTimeReminderOverride(2L, FixedTimeOverride.Inherit) + assertThat(prefs.perCalendarFixedTimeReminderOverride.first().containsKey(2L)).isFalse() + } + + @Test + fun `daily summary is off by default and its settings round-trip`(@TempDir tempDir: Path) = runTest { + val prefs = testSettings(tempDir) + assertThat(prefs.dailyDigest.first()).isEqualTo(DailyDigestSettings()) + prefs.setDailyDigestEnabled(true) + prefs.setDailyDigestTimeMinutes(420) + prefs.setDailyDigestDay(DigestDay.Today) + prefs.setCalendarInDailyDigest(5L, included = false) + val digest = prefs.dailyDigest.first() + assertThat(digest.copy(armedAtMillis = 0L)).isEqualTo( + DailyDigestSettings(enabled = true, timeMinutes = 420, day = DigestDay.Today, excludedCalendarIds = setOf(5L)), + ) + assertThat(digest.armedAtMillis).isGreaterThan(0L) + prefs.setCalendarInDailyDigest(5L, included = true) + assertThat(prefs.dailyDigest.first().excludedCalendarIds).isEmpty() + } + + @Test + fun `a fresh install backs up one file per calendar, keeping three`(@TempDir tempDir: Path) = runTest { + val prefs = testSettings(tempDir) + prefs.setAutoBackupFolderUri("content://tree/a") + assertThat(prefs.autoBackupCombined.first()).isFalse() + assertThat(prefs.autoBackupKeep.first()).isEqualTo(3) + } + + @Test + fun `an install that had a backup folder before 411 keeps its single file`(@TempDir tempDir: Path) = runTest { + val store = testDataStore(tempDir, "test_settings") + val prefs = SettingsPrefs(store) + store.updateData { p -> + val m = p.toMutablePreferences() + m[stringPreferencesKey("auto_backup_folder_uri")] = "content://tree/old" + m + } + assertThat(prefs.autoBackupCombined.first()).isTrue() + + + // Picking another folder pins the layout instead of flipping it, and + // keeps the old file recognised as this install's own. + prefs.setAutoBackupFolderUri("content://tree/new") + assertThat(prefs.autoBackupCombined.first()).isTrue() + // A new folder starts a new ledger: the old file there isn't known to be ours. + assertThat(prefs.autoBackupLedger.first()).isEmpty() + + prefs.setAutoBackupCombined(false) + assertThat(prefs.autoBackupCombined.first()).isFalse() + } + + @Test + fun `backup calendar choices are stored as deviations from the default`(@TempDir tempDir: Path) = runTest { + val prefs = testSettings(tempDir) + val local = backupCalendar(1L, local = true) + val synced = backupCalendar(2L, local = false) + + prefs.setAutoBackupCalendar(synced, true) + prefs.setAutoBackupCalendar(local, false) + val selection = prefs.autoBackupSelection.first() + assertThat(selection.included).containsExactly(2L) + assertThat(selection.excluded).containsExactly(1L) + + prefs.setAutoBackupCalendar(local, true) + assertThat(prefs.autoBackupSelection.first().excluded).isEmpty() + } + + @Test + fun `a stray retention count snaps to an offered one`(@TempDir tempDir: Path) = runTest { + val prefs = testSettings(tempDir) + prefs.setAutoBackupKeep(4) + assertThat(prefs.autoBackupKeep.first()).isIn(listOf(3, 5)) + prefs.setAutoBackupKeep(99) + assertThat(prefs.autoBackupKeep.first()).isEqualTo(10) + } + + @Test + fun `the backup interval is on by default and can only go off alongside after-change backups`(@TempDir tempDir: Path) = runTest { + val prefs = testSettings(tempDir) + assertThat(prefs.autoBackupScheduled.first()).isTrue() + + prefs.setAutoBackupScheduled(false) + assertThat(prefs.autoBackupScheduled.first()).isTrue() + + prefs.setAutoBackupOnChange(true) + prefs.setAutoBackupScheduled(false) + assertThat(prefs.autoBackupScheduled.first()).isFalse() + prefs.setAutoBackupScheduled(true) + assertThat(prefs.autoBackupScheduled.first()).isTrue() + } + + @Test + fun `turning after-change backups off brings the interval back for good`(@TempDir tempDir: Path) = runTest { + val prefs = testSettings(tempDir) + prefs.setAutoBackupIntervalMinutes(6 * 60L) + prefs.setAutoBackupOnChange(true) + prefs.setAutoBackupScheduled(false) + + prefs.setAutoBackupOnChange(false) + assertThat(prefs.autoBackupScheduled.first()).isTrue() + assertThat(prefs.autoBackupIntervalMinutes.first()).isEqualTo(6 * 60L) + + prefs.setAutoBackupOnChange(true) + assertThat(prefs.autoBackupScheduled.first()).isTrue() + } + + @Test + fun `the interval setters report whether they switched it`(@TempDir tempDir: Path) = runTest { + val prefs = testSettings(tempDir) + assertThat(prefs.setAutoBackupScheduled(false)).isFalse() + assertThat(prefs.setAutoBackupOnChange(true)).isFalse() + assertThat(prefs.setAutoBackupScheduled(false)).isTrue() + assertThat(prefs.setAutoBackupScheduled(false)).isFalse() + assertThat(prefs.setAutoBackupOnChange(false)).isTrue() + assertThat(prefs.autoBackupOnChangeAndScheduled.first()).isEqualTo(false to true) + } + + @Test + fun `switching the interval off without after-change backups leaves nothing behind`(@TempDir tempDir: Path) = runTest { + val prefs = testSettings(tempDir) + prefs.setAutoBackupScheduled(false) + + prefs.setAutoBackupOnChange(true) + assertThat(prefs.autoBackupScheduled.first()).isTrue() + } + + @Test + fun `an interval-off stored without after-change backups doesn't stick once they go on`(@TempDir tempDir: Path) = runTest { + val store = testDataStore(tempDir, "test_settings") + val prefs = SettingsPrefs(store) + store.updateData { p -> + val m = p.toMutablePreferences() + m[booleanPreferencesKey("auto_backup_scheduled")] = false + m + } + assertThat(prefs.autoBackupScheduled.first()).isTrue() + + assertThat(prefs.setAutoBackupOnChange(true)).isFalse() + assertThat(prefs.autoBackupScheduled.first()).isTrue() + } + + @Test + fun `a pre-411 install adopts its old file when the layout is pinned in place`(@TempDir tempDir: Path) = runTest { + val store = testDataStore(tempDir, "test_settings") + val prefs = SettingsPrefs(store) + store.updateData { p -> + val m = p.toMutablePreferences() + m[stringPreferencesKey("auto_backup_folder_uri")] = "content://tree/old" + m + } + prefs.setAutoBackupCombined(false) + assertThat(prefs.autoBackupLedger.first()) + .containsExactly("latest-combined", listOf("calendula-backup.ics")) + } + + private fun backupCalendar(id: Long, local: Boolean) = CalendarSource( + id = id, + displayName = "C$id", + accountName = "a", + accountType = if (local) "LOCAL" else "com.google", + color = 0, + isVisibleInSystem = true, + canModifyContents = true, + isLocal = local, + ) } + diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlanTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlanTest.kt new file mode 100644 index 00000000..e1f3ad93 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlanTest.kt @@ -0,0 +1,208 @@ +package de.jeanlucmakiola.calendula.data.reminders + +import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.domain.CalendarSource +import org.junit.jupiter.api.Test + +class ReminderChannelPlanTest { + + private fun calendar(id: Long, account: String, type: String, local: Boolean = false) = CalendarSource( + id = id, + displayName = "Cal $id", + accountName = account, + accountType = type, + color = 0, + isVisibleInSystem = true, + isLocal = local, + ) + + @Test + fun `one channel per calendar, grouped by account`() { + val plan = planReminderChannels( + calendars = listOf( + calendar(1, "me@example.org", "com.google"), + calendar(2, "me@example.org", "com.google"), + calendar(3, "dav", "bitfire.at.davdroid"), + ), + existing = emptyList(), + existingGroupIds = emptyList(), + unnamed = "Unnamed", + description = DESC, + ) + assertThat(plan.groups).hasSize(2) + assertThat(plan.channels.map { it.id }) + .containsExactly(reminderChannelId(1), reminderChannelId(2), reminderChannelId(3)) + assertThat(plan.channels[0].groupId).isEqualTo(plan.channels[1].groupId) + assertThat(plan.channels[2].groupId).isNotEqualTo(plan.channels[0].groupId) + assertThat(plan.staleChannelIds).isEmpty() + } + + @Test + fun `device calendars share one group`() { + val plan = planReminderChannels( + calendars = listOf( + calendar(1, "Calendula", "LOCAL", local = true), + calendar(2, "Other", "LOCAL", local = true), + ), + existing = emptyList(), + existingGroupIds = emptyList(), + unnamed = "Unnamed", + description = DESC, + ) + assertThat(plan.groups).hasSize(1) + assertThat(plan.groups.single().isLocal).isTrue() + } + + @Test + fun `same account name under two types is ambiguous`() { + val plan = planReminderChannels( + calendars = listOf( + calendar(1, "me@example.org", "com.google"), + calendar(2, "me@example.org", "bitfire.at.davdroid"), + calendar(3, "work", "bitfire.at.davdroid"), + ), + existing = emptyList(), + existingGroupIds = emptyList(), + unnamed = "Unnamed", + description = DESC, + ) + assertThat(plan.groups.filter { it.ambiguous }.map { it.accountType }) + .containsExactly("com.google", "bitfire.at.davdroid") + assertThat(plan.groups.single { it.label == "work" }.ambiguous).isFalse() + } + + @Test + fun `stale reminder channels and groups go, foreign ones stay`() { + val current = calendar(1, "me@example.org", "com.google") + fun plan(calendars: List, existing: List = emptyList(), groups: List = emptyList()) = + planReminderChannels(calendars, existing.map { ExistingReminderChannel(it, "Cal ${it.last()}", DESC, null) }, groups, "Unnamed", DESC) + val keptGroup = plan(listOf(current)).groups.single().id + val goneGroup = plan(listOf(calendar(9, "old", "com.google"))).groups.single().id + val result = plan( + calendars = listOf(current), + existing = listOf(reminderChannelId(1), reminderChannelId(9), LEGACY_REMINDER_CHANNEL_ID, "backup"), + groups = listOf(keptGroup, goneGroup, "other"), + ) + assertThat(result.staleChannelIds).containsExactly(reminderChannelId(9)) + assertThat(result.staleGroupIds).containsExactly(goneGroup) + } + + @Test + fun `only missing or renamed channels are written`() { + val plan = planReminderChannels( + calendars = listOf( + calendar(1, "a", "com.google"), + calendar(2, "a", "com.google"), + calendar(3, "a", "com.google").copy(displayName = ""), + calendar(4, "a", "com.google"), + ), + existing = listOf( + ExistingReminderChannel(reminderChannelId(1), "Cal 1", DESC, "g"), + ExistingReminderChannel(reminderChannelId(4), "Cal 4", "Old description", "g"), + ExistingReminderChannel(reminderChannelId(2), "Old name", DESC, "g"), + ), + existingGroupIds = emptyList(), + unnamed = "Unnamed", + description = DESC, + ) + assertThat(plan.channelsToWrite.map { it.calendarId }).containsExactly(2L, 3L, 4L) + assertThat(plan.channelsToWrite.single { it.calendarId == 3L }.name).isEqualTo("Unnamed") + } + + @Test + fun `non-syncing calendars keep a channel but get none up front`() { + val quiet = calendar(2, "a", "com.google").copy(syncsEvents = false) + val fresh = planReminderChannels(listOf(quiet), emptyList(), emptyList(), "Unnamed", DESC) + assertThat(fresh.channelsToWrite).isEmpty() + assertThat(fresh.groupsInUse).isEmpty() + val posted = planReminderChannels( + calendars = listOf(quiet), + existing = listOf(ExistingReminderChannel(reminderChannelId(2), "Cal 2", DESC, null)), + existingGroupIds = emptyList(), + unnamed = "Unnamed", + description = DESC, + ) + assertThat(posted.staleChannelIds).isEmpty() + assertThat(posted.channelsToWrite.map { it.calendarId }).containsExactly(2L) + assertThat(posted.groupsInUse).hasSize(1) + } + + @Test + fun `blocked calendars follow app, channel and group`() { + val channels = mapOf( + reminderChannelId(1) to ReminderChannelState(blocked = true, groupId = "g1"), + reminderChannelId(2) to ReminderChannelState(blocked = false, groupId = "g2"), + reminderChannelId(3) to ReminderChannelState(blocked = false, groupId = "g1"), + ) + val ids = listOf(1L, 2L, 3L, 4L) + val groupOff = reminderChannelStatus(ids, appEnabled = true, channels, blockedGroupIds = setOf("g2")) + assertThat(groupOff.blockedCalendarIds).containsExactly(1L, 2L) + assertThat(groupOff.groupBlockedCalendarIds).containsExactly(2L) + assertThat(reminderChannelStatus(ids, appEnabled = true, channels, blockedGroupIds = emptySet()).blockedCalendarIds) + .containsExactly(1L) + val appOff = reminderChannelStatus(ids, appEnabled = false, channels, blockedGroupIds = emptySet()) + assertThat(appOff.appBlocked).isTrue() + assertThat(appOff.blockedCalendarIds).containsExactly(1L, 2L, 3L, 4L) + } + + @Test + fun `a switched-off ring channel is reported while the app may notify`() { + val ringOff = mapOf(RING_CHANNEL_ID to ReminderChannelState(blocked = true, groupId = null)) + assertThat(reminderChannelStatus(listOf(1L), appEnabled = true, ringOff, emptySet()).ringBlocked).isTrue() + assertThat(reminderChannelStatus(listOf(1L), appEnabled = false, ringOff, emptySet()).ringBlocked).isFalse() + assertThat(reminderChannelStatus(listOf(1L), appEnabled = true, emptyMap(), emptySet()).ringBlocked).isFalse() + } + + @Test + fun `channel ids round-trip with versions`() { + assertThat(parseReminderChannelId(reminderChannelId(7))).isEqualTo(7L to 0) + assertThat(parseReminderChannelId(reminderChannelId(7, 3))).isEqualTo(7L to 3) + assertThat(parseReminderChannelId("reminders.calendar.7.v0")).isNull() + assertThat(parseReminderChannelId("reminders.calendar.x")).isNull() + assertThat(parseReminderChannelId(LEGACY_REMINDER_CHANNEL_ID)).isNull() + } + + @Test + fun `a version bump retires the old channel unless it is showing`() { + val existing = listOf( + ExistingReminderChannel(reminderChannelId(1), "Cal 1", DESC, "g"), + ExistingReminderChannel(reminderChannelId(2), "Cal 2", DESC, "g"), + ) + val plan = planReminderChannels( + calendars = listOf(calendar(1, "a", "com.google"), calendar(2, "a", "com.google")), + existing = existing, + existingGroupIds = emptyList(), + unnamed = "Unnamed", + description = DESC, + versions = mapOf(1L to 2, 2L to 1), + showingChannelIds = setOf(reminderChannelId(2)), + ) + assertThat(plan.channels.map { it.id }).containsExactly(reminderChannelId(1, 2), reminderChannelId(2, 1)) + assertThat(plan.staleChannelIds).containsExactly(reminderChannelId(1)) + assertThat(plan.keptChannelIds).containsExactly(reminderChannelId(2)) + } + + @Test + fun `the current version is the highest that exists, else the high-water mark`() { + val versions = currentReminderChannelVersions( + existingChannelIds = listOf(reminderChannelId(1), reminderChannelId(1, 2), reminderChannelId(3), "backup"), + highWater = mapOf(1L to 5, 2L to 4), + ) + // Calendar 1 reserved v5 but never wrote it, so v2 stays current. + assertThat(versions).containsExactly(1L, 2, 2L, 4, 3L, 0) + } + + @Test + fun `status reads the current channel version`() { + val channels = mapOf( + reminderChannelId(1) to ReminderChannelState(blocked = true, groupId = null), + reminderChannelId(1, 2) to ReminderChannelState(blocked = false, groupId = null), + ) + val status = reminderChannelStatus(listOf(1L), true, channels, emptySet(), versions = mapOf(1L to 2)) + assertThat(status.blockedCalendarIds).isEmpty() + } + + private companion object { + const val DESC = "Reminders" + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/EventFormTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/EventFormTest.kt index 83cce332..6ee95aa2 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/domain/EventFormTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/EventFormTest.kt @@ -583,9 +583,16 @@ class EventFormTest { @Test fun `a copy of a cancelled event starts confirmed, a tentative one stays tentative`() { val zone = TimeZone.of("Europe/Berlin") - assertThat(testDetail(status = EventStatus.Cancelled).toDuplicateForm(canModify = true, zone).status) + assertThat(testDetail(status = EventStatus.Cancelled).toDuplicateForm(zone).status) .isEqualTo(EventStatus.Confirmed) - assertThat(testDetail(status = EventStatus.Tentative).toDuplicateForm(canModify = true, zone).status) + assertThat(testDetail(status = EventStatus.Tentative).toDuplicateForm(zone).status) .isEqualTo(EventStatus.Tentative) } + + @Test + fun `a copy requests its source calendar and keeps its colour`() { + val form = testDetail(eventColor = 7, eventColorKey = "3").toDuplicateForm(TimeZone.of("Europe/Berlin")) + assertThat(form.calendarId).isEqualTo(testEvent().calendarId) + assertThat(form.colorKey).isEqualTo("3") + } } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/FixedTimeReminderFormTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/FixedTimeReminderFormTest.kt new file mode 100644 index 00000000..6046e87d --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/FixedTimeReminderFormTest.kt @@ -0,0 +1,47 @@ +package de.jeanlucmakiola.calendula.domain + +import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder +import kotlinx.datetime.LocalDateTime +import kotlinx.datetime.TimeZone +import org.junit.jupiter.api.Test + +class FixedTimeReminderFormTest { + + private val zone = TimeZone.of("Europe/Berlin") + private val evening = FixedTimeReminder(1, 20 * 60) + + private fun form(start: String, reminders: List = emptyList(), allDay: Boolean = false) = EventForm( + calendarId = 1, + isAllDay = allDay, + start = FormTime(LocalDateTime.parse(start)), + end = FormTime(LocalDateTime.parse(start)), + reminders = reminders, + ) + + @Test + fun `a moved start re-derives the offset so the wall clock stays`() { + val loaded = form("2026-06-10T10:00", reminders = listOf(10, 840)) + .withFixedTimeRemindersRead(known = setOf(evening), deviceZone = zone) + assertThat(loaded.reminders).containsExactly(10) + assertThat(loaded.fixedReminders).containsExactly(evening) + assertThat(loaded.fixedReminderOffsets(zone)).containsExactly(840) + + val moved = loaded.copy(start = FormTime(LocalDateTime.parse("2026-06-10T15:30"))) + assertThat(moved.fixedReminderOffsets(zone)).containsExactly(19 * 60 + 30) + } + + @Test + fun `all-day forms keep their reminders and store no fixed ones`() { + val allDay = form("2026-06-10T00:00", reminders = listOf(840), allDay = true) + assertThat(allDay.withFixedTimeRemindersRead(setOf(evening), zone)).isEqualTo(allDay) + assertThat(allDay.copy(fixedReminders = listOf(evening)).fixedReminderOffsets(zone)).isEmpty() + } + + @Test + fun `fixed reminders count as a populated reminders section on a timed event only`() { + val withFixed = form("2026-06-10T10:00").copy(fixedReminders = listOf(evening)) + assertThat(withFixed.populatedFields()).contains(EventFormField.Reminders) + assertThat(withFixed.copy(isAllDay = true).populatedFields()).doesNotContain(EventFormField.Reminders) + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/InsertEventFormTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/InsertEventFormTest.kt index d6f9e667..d16b6c1b 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/domain/InsertEventFormTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/InsertEventFormTest.kt @@ -24,6 +24,7 @@ class InsertEventFormTest { description: String? = null, location: String? = null, rrule: String? = null, + calendarId: Long? = null, ): EventForm = buildInsertEventForm( beginMillis = beginMillis, endMillis = endMillis, @@ -32,6 +33,7 @@ class InsertEventFormTest { description = description, location = location, rrule = rrule, + calendarId = calendarId, zone = zone, now = now, ) @@ -50,7 +52,7 @@ class InsertEventFormTest { location = "Room 1", rrule = "FREQ=DAILY", ) - assertThat(form.calendarId).isNull() // resolves to last-used / first-writable + assertThat(form.calendarId).isNull() // resolved by the editor assertThat(form.isAllDay).isFalse() assertThat(form.start.dateTime).isEqualTo(start) assertThat(form.end.dateTime).isEqualTo(end) @@ -60,6 +62,11 @@ class InsertEventFormTest { assertThat(form.rrule).isEqualTo("FREQ=DAILY") } + @Test + fun `a named calendar is carried over`() { + assertThat(build(calendarId = 7L).calendarId).isEqualTo(7L) + } + @Test fun `missing times default to the next full hour and a one-hour duration`() { val form = build(title = "Quick note") diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/NewEventCalendarTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/NewEventCalendarTest.kt new file mode 100644 index 00000000..c2881ab0 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/NewEventCalendarTest.kt @@ -0,0 +1,102 @@ +package de.jeanlucmakiola.calendula.domain + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class NewEventCalendarTest { + + private fun cal( + id: Long, + writable: Boolean = true, + visible: Boolean = true, + managed: Boolean = false, + ) = CalendarSource( + id = id, + displayName = "Cal $id", + accountName = "account", + accountType = "com.google", + color = 0, + isVisibleInSystem = visible, + canModifyContents = writable, + isManaged = managed, + ) + + private fun ref(id: Long) = DefaultCalendarRef.of(cal(id)) + + private val calendars = listOf( + cal(1L), + cal(2L), + cal(3L), + cal(4L, writable = false), + cal(5L, visible = false), + cal(6L, managed = true), + ) + + @Test + fun `a user pick always wins`() { + val hints = NewEventCalendarHints(requested = 2L, default = ref(3L), lastUsed = 1L) + assertThat(resolveEventCalendar(4L, hints, calendars)).isEqualTo(4L) + } + + @Test + fun `a requested calendar beats the default`() { + val hints = NewEventCalendarHints(requested = 2L, default = ref(3L)) + assertThat(resolveEventCalendar(null, hints, calendars)).isEqualTo(2L) + } + + @Test + fun `a requested calendar that is no target falls back to the default`() { + listOf(4L, 5L, 6L, 99L).forEach { requested -> + val hints = NewEventCalendarHints(requested = requested, default = ref(3L)) + assertThat(resolveEventCalendar(null, hints, calendars)).isEqualTo(3L) + } + } + + @Test + fun `the default beats the last used calendar`() { + val hints = NewEventCalendarHints(default = ref(3L), lastUsed = 2L) + assertThat(resolveEventCalendar(null, hints, calendars)).isEqualTo(3L) + } + + @Test + fun `a default that is no target falls back to the last used calendar`() { + listOf(4L, 5L, 6L).forEach { id -> + val default = DefaultCalendarRef.of(calendars.single { it.id == id }) + val hints = NewEventCalendarHints(default = default, lastUsed = 2L) + assertThat(resolveEventCalendar(null, hints, calendars)).isEqualTo(2L) + assertThat(effectiveDefaultCalendar(default, calendars)).isNull() + } + assertThat(effectiveDefaultCalendar(ref(99L), calendars)).isNull() + } + + @Test + fun `without hints the first target is used`() { + val withoutFirst = listOf(cal(4L, writable = false), cal(5L, visible = false), cal(2L)) + assertThat(resolveEventCalendar(null, NewEventCalendarHints(lastUsed = 5L), withoutFirst)).isEqualTo(2L) + assertThat(resolveEventCalendar(null, NewEventCalendarHints(), emptyList())).isNull() + } + + @Test + fun `the effective default is the stored calendar while it is a target`() { + assertThat(effectiveDefaultCalendar(ref(3L), calendars)?.id).isEqualTo(3L) + assertThat(effectiveDefaultCalendar(null, calendars)).isNull() + } + + @Test + fun `the default survives a rename and a new id, but not another account`() { + assertThat(effectiveDefaultCalendar(ref(3L).copy(displayName = "Old name"), calendars)?.id).isEqualTo(3L) + assertThat(effectiveDefaultCalendar(ref(3L).copy(id = 99L), calendars)?.id).isEqualTo(3L) + // The id was handed to another calendar of the account; the name decides. + assertThat(effectiveDefaultCalendar(ref(3L).copy(id = 2L), calendars)?.id).isEqualTo(3L) + assertThat(effectiveDefaultCalendar(ref(3L).copy(accountName = "other"), calendars)).isNull() + } + + @Test + fun `the stored reference round-trips`() { + val stored = DefaultCalendarRef(12L, "com.google", "me@example.com", "Work | Team") + assertThat(DefaultCalendarRef.decode(stored.encode())).isEqualTo(stored) + assertThat(DefaultCalendarRef.decode(null)).isNull() + assertThat(DefaultCalendarRef.decode("12")).isNull() + assertThat(DefaultCalendarRef.decode("x\u001Fa\u001Fb\u001Fc")).isNull() + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/backup/BackupPlanTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/backup/BackupPlanTest.kt new file mode 100644 index 00000000..1cf4b383 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/backup/BackupPlanTest.kt @@ -0,0 +1,451 @@ +package de.jeanlucmakiola.calendula.domain.backup + +import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.domain.ics.IcsEvent +import de.jeanlucmakiola.calendula.domain.ics.IcsWriter +import org.junit.jupiter.api.Test +import java.time.LocalDateTime +import kotlin.time.Instant + +class BackupPlanTest { + + private fun cal( + id: Long, + name: String = "Calendar $id", + local: Boolean = false, + writable: Boolean = true, + managed: Boolean = false, + syncs: Boolean = true, + ) = CalendarSource( + id = id, + displayName = name, + accountName = "acc", + accountType = if (local) "LOCAL" else "bitfire.at.davdroid", + color = 0, + isVisibleInSystem = true, + canModifyContents = writable, + isLocal = local, + isManaged = managed, + syncsEvents = syncs, + ) + + private val at = LocalDateTime.of(2026, 11, 13, 14, 30, 5) + + @Test + fun `local calendars are selected by default, synced ones are opt-in`() { + val selection = BackupSelection() + assertThat(selection.selects(cal(1L, local = true))).isTrue() + assertThat(selection.selects(cal(2L))).isFalse() + assertThat(selection.selects(cal(3L, writable = false))).isFalse() + } + + @Test + fun `managed and unsynced calendars are never backed up`() { + val selection = BackupSelection(included = setOf(1L, 2L)) + assertThat(selection.selects(cal(1L, local = true, managed = true))).isFalse() + assertThat(selection.selects(cal(2L, syncs = false))).isFalse() + } + + @Test + fun `toggling back to the default leaves no trace`() { + val synced = cal(2L) + val local = cal(1L, local = true) + val chosen = BackupSelection().with(synced, true).with(local, false) + assertThat(chosen).isEqualTo(BackupSelection(included = setOf(2L), excluded = setOf(1L))) + assertThat(chosen.with(synced, false).with(local, true)).isEqualTo(BackupSelection()) + } + + @Test + fun `one target per calendar, with no owner the lowest id keeps a clashing name`() { + val targets = backupTargets( + listOf(cal(2L, "personal"), cal(1L, "Personal", local = true), cal(3L, "Work")), + combined = false, + ) + assertThat(targets.map { it.baseName }).containsExactly("personal-2", "Personal", "Work").inOrder() + assertThat(targets.map { it.calendarName }).containsExactly("personal", "Personal", "Work").inOrder() + } + + @Test + fun `the calendar already owning a name keeps it when a new one shares it`() { + val calendars = listOf(cal(9L, "Fitness"), cal(20L, "Fitness"), cal(4L, "Fitness")) + val byStable = backupTargets(calendars, combined = false, mapOf(latestLedgerKey("9") to listOf("Fitness.ics"))) + assertThat(byStable.map { it.baseName }).containsExactly("Fitness", "Fitness-20", "Fitness-4").inOrder() + // A dated file counts too, for a series whose stable copy was blocked by the user's own file. + val byDated = backupTargets(calendars, combined = false, mapOf("20" to listOf("Fitness_2026-11-13_14-30-05.ics"))) + assertThat(byDated.map { it.baseName }).containsExactly("Fitness-9", "Fitness", "Fitness-4").inOrder() + } + + @Test + fun `series already writing under their id suffix keep it`() { + val ledger = mapOf( + latestLedgerKey("9") to listOf("Fitness-9.ics"), + latestLedgerKey("20") to listOf("Fitness-20.ics"), + ) + val targets = backupTargets(listOf(cal(20L, "Fitness"), cal(9L, "Fitness")), combined = false, ledger) + assertThat(targets.map { it.baseName }).containsExactly("Fitness-20", "Fitness-9").inOrder() + } + + @Test + fun `the stable copy's owner beats a series with only old dated files under the name`() { + val ledger = mapOf( + "9" to listOf("Fitness_2026-11-01_10-00-00.ics"), + latestLedgerKey("20") to listOf("Fitness.ics"), + ) + val targets = backupTargets(listOf(cal(9L, "Fitness"), cal(20L, "Fitness")), combined = false, ledger) + assertThat(targets.map { it.baseName }).containsExactly("Fitness-9", "Fitness").inOrder() + } + + @Test + fun `a provider-renamed dated file still claims the name, a file gone from the folder doesn't`() { + val calendars = listOf(cal(9L, "Fitness"), cal(20L, "Fitness")) + val renamed = mapOf("20" to listOf("Fitness_2026-11-13_14-30-05 (1).ics")) + assertThat(backupTargets(calendars, combined = false, renamed).map { it.baseName }) + .containsExactly("Fitness-9", "Fitness").inOrder() + val gone = mapOf(latestLedgerKey("20") to listOf("Fitness.ics")) + assertThat(backupTargets(calendars, combined = false, gone, existing = emptySet()).map { it.baseName }) + .containsExactly("Fitness", "Fitness-20").inOrder() + } + + @Test + fun `a stable copy kept for a calendar out of the backup isn't taken over or left blocking`() { + val ledger = mapOf(latestLedgerKey("9") to listOf("Fitness.ics")) + val target = backupTargets(listOf(cal(20L, "Fitness")), combined = false, ledger, setOf("Fitness.ics")).single() + assertThat(target.baseName).isEqualTo("Fitness-20") + val plan = planBackupFiles(listOf(target), ledger, setOf("Fitness.ics"), at, keep = 3).single() + assertThat(plan.backedUp(intervalOn = false)).isTrue() + + val gone = backupTargets(listOf(cal(20L, "Fitness")), combined = false, ledger, existing = emptySet()).single() + assertThat(gone.baseName).isEqualTo("Fitness") + } + + @Test + fun `a series writing under its id suffix keeps it once the clash is gone`() { + val ledger = mapOf(latestLedgerKey("20") to listOf("Fitness-20.ics")) + val target = backupTargets(listOf(cal(20L, "Fitness")), combined = false, ledger, setOf("Fitness.ics", "Fitness-20.ics")) + .single() + assertThat(target.baseName).isEqualTo("Fitness-20") + } + + @Test + fun `a calendar named like the combined file doesn't share its series`() { + val target = backupTargets(listOf(cal(4L, COMBINED_BACKUP_BASE)), combined = false).single() + assertThat(target.baseName).isEqualTo("$COMBINED_BACKUP_BASE-4") + } + + @Test + fun `combined mode is one target holding every calendar`() { + val target = backupTargets(listOf(cal(1L), cal(2L)), combined = true).single() + assertThat(target.key).isEqualTo(COMBINED_SERIES) + assertThat(target.calendarIds).containsExactly(1L, 2L) + assertThat(target.baseName).isEqualTo(COMBINED_BACKUP_BASE) + assertThat(target.calendarName).isNull() + assertThat(backupTargets(emptyList(), combined = true)).isEmpty() + } + + @Test + fun `the new file carries the date and time of the run`() { + assertThat(backupFileName("Work", at)).isEqualTo("Work_2026-11-13_14-30-05.ics") + } + + private val work = BackupTarget("1", setOf(1L), "Work", "Work") + + @Test + fun `pruning keeps the newest recorded files and nothing else`() { + val ledger = mapOf("1" to listOf("Work_a.ics", "Work_b.ics", "Work_c.ics")) + val existing = setOf("Work_a.ics", "Work_b.ics", "Work_c.ics", "Work_2026-11-01_09-00-00.ics", "Work notes.ics") + val plan = planBackupFiles(listOf(work), ledger, existing, at, keep = 3).single() + assertThat(plan.fileName).isEqualTo("Work_2026-11-13_14-30-05.ics") + assertThat(plan.keep).containsExactly("Work_b.ics", "Work_c.ics").inOrder() + assertThat(plan.prune).containsExactly("Work_a.ics") + } + + @Test + fun `keeping one replaces every earlier file`() { + val ledger = mapOf("1" to listOf("Work_a.ics", "Work_b.ics")) + val plan = planBackupFiles(listOf(work), ledger, setOf("Work_a.ics", "Work_b.ics"), at, keep = 1).single() + assertThat(plan.keep).isEmpty() + assertThat(plan.prune).containsExactly("Work_a.ics", "Work_b.ics").inOrder() + } + + @Test + fun `files gone from the folder are forgotten, not counted`() { + val ledger = mapOf("1" to listOf("Work_a.ics", "Work_b.ics")) + val plan = planBackupFiles(listOf(work), ledger, setOf("Work_b.ics"), at, keep = 2).single() + assertThat(plan.keep).containsExactly("Work_b.ics") + assertThat(plan.prune).isEmpty() + } + + @Test + fun `a same-named calendar never prunes another calendar's files`() { + // Local "Work" (id 1) was backed up; the user now backs up a synced "Work" (id 9) instead. + val ledger = mapOf("1" to listOf("Work_a.ics")) + val synced = backupTargets(listOf(cal(9L, "Work")), combined = false).single() + val plan = planBackupFiles(listOf(synced), ledger, setOf("Work_a.ics"), at, keep = 1).single() + assertThat(plan.prune).isEmpty() + } + + @Test + fun `a rerun in the same second never prunes the file it writes`() { + val name = "Work_2026-11-13_14-30-05.ics" + val plan = planBackupFiles(listOf(work), mapOf("1" to listOf(name)), setOf(name), at, keep = 1).single() + assertThat(plan.prune).isEmpty() + } + + private val combined = BackupTarget(COMBINED_SERIES, setOf(1L, 2L), COMBINED_BACKUP_BASE, null) + + @Test + fun `the pre-411 file is the combined stable copy only for the install that wrote it`() { + val adopted = mapOf(latestLedgerKey(COMBINED_SERIES) to listOf(LEGACY_BACKUP_FILE)) + val owned = planBackupFiles(listOf(combined), adopted, setOf(LEGACY_BACKUP_FILE), at, 1) + assertThat(owned.single().latestName).isEqualTo(LEGACY_BACKUP_FILE) + assertThat(owned.single().prune).isEmpty() + + val foreign = planBackupFiles(listOf(combined), emptyMap(), setOf(LEGACY_BACKUP_FILE), at, 1) + assertThat(foreign.single().latestName).isNull() + } + + @Test + fun `a stable name recorded as a dated file by an earlier build is never pruned`() { + val ledger = mapOf(COMBINED_SERIES to listOf(LEGACY_BACKUP_FILE, "calendula-backup_a.ics")) + val plan = planBackupFiles( + listOf(combined), ledger, setOf(LEGACY_BACKUP_FILE, "calendula-backup_a.ics"), at, 1, + ).single() + assertThat(plan.prune).containsExactly("calendula-backup_a.ics") + } + + @Test + fun `per-calendar series leave the legacy combined file alone`() { + val plan = planBackupFiles(listOf(work), emptyMap(), setOf(LEGACY_BACKUP_FILE), at, keep = 1).single() + assertThat(plan.prune).isEmpty() + assertThat(plan.staleLatest).isEmpty() + assertThat(plan.latestName).isEqualTo("Work.ics") + } + + @Test + fun `the stable copy is never pruned and never overwrites the user's own file`() { + val ours = planBackupFiles( + listOf(work), + mapOf("1" to listOf("Work_a.ics"), latestLedgerKey("1") to listOf("Work.ics")), + setOf("Work_a.ics", "Work.ics"), + at, + keep = 1, + ).single() + assertThat(ours.latestName).isEqualTo("Work.ics") + assertThat(ours.prune).containsExactly("Work_a.ics") + + val foreign = planBackupFiles(listOf(work), emptyMap(), setOf("Work.ics"), at, keep = 1).single() + assertThat(foreign.latestName).isNull() + } + + @Test + fun `a renamed calendar replaces its old stable copy`() { + val job = BackupTarget("1", setOf(1L), "Job", "Job") + val plan = planBackupFiles( + listOf(job), + mapOf(latestLedgerKey("1") to listOf("Work.ics")), + setOf("Work.ics"), + at, + keep = 3, + ).single() + assertThat(plan.latestName).isEqualTo("Job.ics") + assertThat(plan.staleLatest).containsExactly("Work.ics") + } + + @Test + fun `a stable copy is handed over to the calendar that takes its name in the same run`() { + // Calendar 1 was "Work", is now "Job"; calendar 2 is now called "Work". + val ledger = mapOf(latestLedgerKey("1") to listOf("Work.ics")) + val plans = planBackupFiles( + listOf(BackupTarget("1", setOf(1L), "Job", "Job"), BackupTarget("2", setOf(2L), "Work", "Work")), + ledger, + setOf("Work.ics"), + at, + keep = 1, + ) + assertThat(plans[0].staleLatest).isEmpty() + assertThat(plans[0].handOff).containsExactly("Work.ics") + assertThat(plans[1].latestName).isEqualTo("Work.ics") + } + + @Test + fun `a deselected calendar's stable copy is not taken over by a same-named one`() { + // Calendar 3 "Personal" is out of the backup; calendar 9, also "Personal", is in. + val ledger = mapOf(latestLedgerKey("3") to listOf("Personal.ics")) + val plan = planBackupFiles( + listOf(BackupTarget("9", setOf(9L), "Personal", "Personal")), ledger, setOf("Personal.ics"), at, 1, + ).single() + assertThat(plan.latestName).isNull() + } + + @Test + fun `a layout switch replaces the other layout's stable copies, a deselected calendar keeps its own`() { + val ledger = mapOf( + latestLedgerKey("1") to listOf("Work.ics"), + latestLedgerKey("5") to listOf("Old.ics"), + latestLedgerKey(COMBINED_SERIES) to listOf(LEGACY_BACKUP_FILE), + ) + val existing = setOf("Work.ics", "Old.ics", LEGACY_BACKUP_FILE) + assertThat(replacedLatestCopies(listOf(combined), ledger, existing)) + .containsExactly("1", listOf("Work.ics")) + assertThat(replacedLatestCopies(listOf(work), ledger, existing)) + .containsExactly(COMBINED_SERIES, listOf(LEGACY_BACKUP_FILE)) + } + + @Test + fun `a ledger entry is set, emptied away, and dropped with its calendar`() { + val previous = mapOf( + "1" to listOf("Work_a.ics"), + latestLedgerKey("7") to listOf("Gone.ics"), + latestLedgerKey(COMBINED_SERIES) to listOf(LEGACY_BACKUP_FILE), + ) + val next = withLedgerEntry(previous, "1", listOf("Work_a.ics", "Work_b.ics", "Work_b.ics"), setOf("1")) + assertThat(next).containsExactly( + "1", listOf("Work_a.ics", "Work_b.ics"), + latestLedgerKey(COMBINED_SERIES), listOf(LEGACY_BACKUP_FILE), + ) + assertThat(withLedgerEntry(next, "1", emptyList(), setOf("1")).keys) + .containsExactly(latestLedgerKey(COMBINED_SERIES)) + } + + @Test + fun `the ledger round-trips through storage`() { + val ledger = mapOf("3" to listOf("Work_b.ics", "Work_a (1).ics"), COMBINED_SERIES to listOf("calendula-backup_x.ics")) + assertThat(parseBackupLedger(persistBackupLedger(ledger))).isEqualTo(ledger) + assertThat(persistBackupLedger(emptyMap())).isNull() + assertThat(parseBackupLedger("garbage|/x|4/")).isEmpty() + } + + @Test + fun `retention snaps to the offered choices`() { + assertThat(normalizeBackupKeep(0)).isEqualTo(1) + assertThat(normalizeBackupKeep(3)).isEqualTo(3) + assertThat(normalizeBackupKeep(50)).isEqualTo(10) + } + + @Test + fun `a suffixed name that meets a real one is told apart again`() { + val targets = backupTargets( + listOf(cal(5L, "Work"), cal(6L, "Work"), cal(9L, "Work-6")), + combined = false, + ) + assertThat(targets.map { it.baseName }).containsExactly("Work", "Work-6", "Work-6-9").inOrder() + } + + @Test + fun `claiming a stable copy takes it off its previous owner`() { + val previous = mapOf(latestLedgerKey("1") to listOf("Work.ics", "Job.ics")) + val next = withLedgerEntry(previous, latestLedgerKey("2"), listOf("Work.ics"), setOf("1", "2")) + assertThat(next).containsExactly( + latestLedgerKey("1"), listOf("Job.ics"), + latestLedgerKey("2"), listOf("Work.ics"), + ) + } + + @Test + fun `a claimed hand-off shows as held elsewhere`() { + val ledger = mapOf(latestLedgerKey("1") to listOf("Job.ics"), latestLedgerKey("2") to listOf("Work.ics"), "2" to listOf("Work_a.ics")) + assertThat(ledger.latestHeldElsewhere("1")).containsExactly("Work.ics") + assertThat(ledger.latestHeldElsewhere("2")).containsExactly("Job.ics") + } + + @Test + fun `fingerprints survive storage and drop deleted calendars`() { + val stored = persistBackupFingerprints(mapOf("1" to "ab", COMBINED_SERIES to "cd")) + assertThat(parseBackupFingerprints(stored)).containsExactly("1", "ab", COMBINED_SERIES, "cd") + assertThat(persistBackupFingerprints(emptyMap())).isNull() + assertThat(parseBackupFingerprints(null)).isEmpty() + val next = withFingerprint(mapOf("1" to "ab", "9" to "ef", COMBINED_SERIES to "cd"), "2", "gh", setOf("1", "2")) + assertThat(next).containsExactly("1", "ab", COMBINED_SERIES, "cd", "2", "gh") + } + + @Test + fun `a fingerprint follows the content`() { + val first = "BEGIN:VEVENT\r\nDTSTAMP:20261113T143005Z\r\nSUMMARY:A\r\nEND:VEVENT\r\n" + val later = first.replace("20261113T143005Z", "20261114T090000Z") + assertThat(backupFingerprint(later, "Work.ics")).isEqualTo(backupFingerprint(first, "Work.ics")) + assertThat(backupFingerprint(first.replace("SUMMARY:A", "SUMMARY:B"), "Work.ics")).isNotEqualTo(backupFingerprint(first, "Work.ics")) + assertThat(backupFingerprint(first, "Work.ics")).hasLength(32) + assertThat(backupFingerprint(first, "Job.ics")).isNotEqualTo(backupFingerprint(first, "Work.ics")) + } + + @Test + fun `the writer's output hashes the same at any stamp`() { + val event = IcsEvent( + uid = "u1", summary = "A", start = Instant.fromEpochSeconds(0), end = Instant.fromEpochSeconds(3600), + isAllDay = false, zoneId = "UTC", + ) + val early = IcsWriter().writeCalendar(listOf(event), Instant.fromEpochSeconds(0), "Work") + val late = IcsWriter().writeCalendar(listOf(event), Instant.fromEpochSeconds(1_800_000_000), "Work") + assertThat(early).isNotEqualTo(late) + assertThat(backupFingerprint(late, "Work.ics")).isEqualTo(backupFingerprint(early, "Work.ics")) + } + + @Test + fun `a change run refreshes only a changed or missing stable copy`() { + val target = backupTargets(listOf(cal(1L, "Work")), combined = false).single() + val ledger = mapOf(latestLedgerKey("1") to listOf("Work.ics")) + val plan = planBackupFiles(listOf(target), ledger, setOf("Work.ics"), at, keep = 3).single() + val stored = mapOf("1" to "h1") + val listed = setOf("Work.ics") + assertThat(plan.needsRefresh("h1", stored, listed, complete = true)).isFalse() + assertThat(plan.needsRefresh("h2", stored, listed, complete = true)).isTrue() + assertThat(plan.needsRefresh("h1", emptyMap(), listed, complete = true)).isTrue() + assertThat(plan.needsRefresh("h1", stored, emptySet(), complete = true)).isTrue() + } + + @Test + fun `a change run leaves a copy a loading listing doesn't show to the schedule`() { + val target = backupTargets(listOf(cal(1L, "Work")), combined = false).single() + val ledger = mapOf(latestLedgerKey("1") to listOf("Work.ics")) + val plan = planBackupFiles(listOf(target), ledger, setOf("Work.ics"), at, keep = 3).single() + assertThat(plan.needsRefresh("h2", mapOf("1" to "h1"), emptySet(), complete = false)).isFalse() + assertThat(plan.needsRefresh("h2", mapOf("1" to "h1"), setOf("Work.ics"), complete = false)).isTrue() + } + + @Test + fun `a change run never writes over a file of the user's`() { + val target = backupTargets(listOf(cal(1L, "Work")), combined = false).single() + val plan = planBackupFiles(listOf(target), emptyMap(), setOf("Work.ics"), at, keep = 3).single() + assertThat(plan.latestName).isNull() + assertThat(plan.needsRefresh("h1", emptyMap(), setOf("Work.ics"), complete = true)).isFalse() + } + + @Test + fun `backup order doesn't depend on the provider's`() { + fun event(uid: String, reminders: List) = IcsEvent( + uid = uid, summary = uid, start = Instant.fromEpochSeconds(0), end = Instant.fromEpochSeconds(3600), + isAllDay = false, zoneId = "UTC", reminderMinutes = reminders, + ) + val one = listOf(event("b", listOf(15, 10)), event("a", listOf(5))) + val other = listOf(event("a", listOf(5)), event("b", listOf(10, 15))) + assertThat(one.inBackupOrder()).isEqualTo(other.inBackupOrder()) + assertThat(one.inBackupOrder().map { it.uid }).containsExactly("a", "b").inOrder() + } + + @Test + fun `the interval stays on unless after-change backups cover for it`() { + assertThat(backupIntervalOn(stored = true, onChange = false)).isTrue() + assertThat(backupIntervalOn(stored = false, onChange = false)).isTrue() + assertThat(backupIntervalOn(stored = true, onChange = true)).isTrue() + assertThat(backupIntervalOn(stored = false, onChange = true)).isFalse() + } + + @Test + fun `only a run with the interval on writes dated files`() { + assertThat(backupRunLatestOnly(changeRun = false, intervalOn = true)).isFalse() + assertThat(backupRunLatestOnly(changeRun = true, intervalOn = true)).isTrue() + assertThat(backupRunLatestOnly(changeRun = false, intervalOn = false)).isTrue() + assertThat(backupRunLatestOnly(changeRun = true, intervalOn = false)).isTrue() + } + + @Test + fun `without the interval a series whose stable name is the user's goes unbacked`() { + val free = planBackupFiles(listOf(work), emptyMap(), emptySet(), at, keep = 3).single() + val blocked = planBackupFiles(listOf(work), emptyMap(), setOf("Work.ics"), at, keep = 3).single() + + assertThat(free.backedUp(intervalOn = false)).isTrue() + assertThat(blocked.backedUp(intervalOn = false)).isFalse() + assertThat(blocked.backedUp(intervalOn = true)).isTrue() + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt new file mode 100644 index 00000000..4c763dbc --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt @@ -0,0 +1,287 @@ +package de.jeanlucmakiola.calendula.domain.ics + +import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.data.calendar.formatExdateStamp +import de.jeanlucmakiola.calendula.domain.EventStatus +import org.junit.jupiter.api.Test +import kotlin.time.Instant + +/** How a calendar's exception rows are written out for a backup (#147) or a copy (#325). */ +class CalendarRowsTest { + + private val start = Instant.parse("2026-01-05T09:00:00Z") + private val week = 7 * 24 * 3_600_000L + + private fun event( + uid: String, + rrule: String? = null, + allDay: Boolean = false, + at: Instant = start, + status: EventStatus = EventStatus.Confirmed, + exDates: List = emptyList(), + reminders: List = emptyList(), + color: Int? = null, + ) = IcsEvent( + uid = uid, + summary = uid, + start = at, + end = Instant.fromEpochMilliseconds(at.toEpochMilliseconds() + 3_600_000L), + isAllDay = allDay, + zoneId = "Europe/Berlin", + recurrenceRule = rrule, + exDates = exDates, + reminderMinutes = reminders, + status = status, + color = color, + calendarName = "Work", + ) + + private fun occurrence(n: Int) = Instant.fromEpochMilliseconds(start.toEpochMilliseconds() + n * week) + + private fun series(uid: String, rrule: String? = "FREQ=WEEKLY", id: Long = 1, calendar: Long = 1, syncId: String? = null, status: EventStatus = EventStatus.Confirmed) = + MasterRow(id, calendar, syncId, event(uid, rrule = rrule, status = status)) + + private fun flatten(series: List, overrides: List) = + flattenOverrides(CalendarRows(series, overrides), ::formatExdateStamp) + + @Test + fun `a cancelled occurrence becomes an EXDATE on the series`() { + val flat = flatten( + listOf(MasterRow(1, 1, "sync-1", event("s", rrule = "FREQ=WEEKLY", exDates = listOf("20260112T080000Z")))), + listOf(OverrideRow(1, null, "sync-1", occurrence(2), event("s", at = occurrence(2), status = EventStatus.Cancelled))), + ) + + assertThat(flat.single().exDates).containsExactly("20260112T080000Z", "20260119T090000Z").inOrder() + } + + @Test + fun `a modified occurrence is excluded from the series and written on its own, first`() { + val moved = Instant.fromEpochMilliseconds(occurrence(1).toEpochMilliseconds() + 3_600_000L) + val flat = flatten( + listOf(series("s")), + listOf(OverrideRow(1, 1, null, occurrence(1), event("s", rrule = "FREQ=WEEKLY", at = moved))), + ) + + assertThat(flat).hasSize(2) + val detached = flat[0] + assertThat(detached.uid).isEqualTo("${occurrence(1).toEpochMilliseconds()}-s") + assertThat(detached.overrideOf).isEqualTo("s") + assertThat(detached.recurrenceRule).isNull() + assertThat(detached.start).isEqualTo(moved) + assertThat(detached.calendarName).isEqualTo("Work") + assertThat(flat[1].exDates).containsExactly("20260112T090000Z") + } + + @Test + fun `an all-day series excludes the occurrence by its day`() { + val day = Instant.parse("2026-01-05T00:00:00Z") + val flat = flatten( + listOf(MasterRow(1, 1, null, event("s", rrule = "FREQ=DAILY", allDay = true, at = day))), + listOf(OverrideRow(1, 1, null, Instant.parse("2026-01-07T00:00:00Z"), event("s", allDay = true, status = EventStatus.Cancelled))), + ) + + assertThat(flat.single().exDates).containsExactly("20260107") + } + + @Test + fun `exceptions without their series are left out`() { + val flat = flatten( + emptyList(), + listOf( + OverrideRow(1, 5, null, occurrence(1), event("x")), + OverrideRow(1, 5, null, occurrence(2), event("y", status = EventStatus.Cancelled)), + ), + ) + + assertThat(flat).isEmpty() + } + + @Test + fun `a sync id links an exception only within its own calendar`() { + val flat = flatten( + listOf(series("a", calendar = 1, syncId = "same"), series("b", id = 2, calendar = 2, syncId = "same")), + listOf(OverrideRow(2, null, "same", occurrence(1), event("x", status = EventStatus.Cancelled))), + ) + + assertThat(flat.first { it.uid == "a" }.exDates).isEmpty() + assertThat(flat.first { it.uid == "b" }.exDates).containsExactly("20260112T090000Z") + } + + @Test + fun `an exception to a one-off is ignored`() { + val flat = flatten( + listOf(series("o", rrule = null)), + listOf(OverrideRow(1, 1, null, occurrence(0), event("x"))), + ) + + assertThat(flat.map { it.uid }).containsExactly("o") + } + + @Test + fun `an RDATE-only series keeps its dates and takes its exceptions`() { + val flat = flatten( + listOf(MasterRow(1, 1, null, event("s").copy(recurrenceDates = listOf("20260112T090000Z")))), + listOf(OverrideRow(1, 1, null, occurrence(1), event("s", status = EventStatus.Cancelled))), + ) + + assertThat(flat.single().recurrenceDates).containsExactly("20260112T090000Z") + assertThat(flat.single().exDates).containsExactly("20260112T090000Z") + } + + @Test + fun `two exception rows for one occurrence are written once`() { + val flat = flatten( + listOf(series("s")), + listOf(OverrideRow(1, 1, null, occurrence(1), event("x")), OverrideRow(1, 1, null, occurrence(1), event("y"))), + ) + + assertThat(flat.map { it.summary }).containsExactly("x", "s").inOrder() + } + + @Test + fun `the output is stable, so a re-run dedups every event`() { + val rows = CalendarRows(listOf(series("s")), listOf(OverrideRow(1, 1, null, occurrence(1), event("x")))) + + assertThat(flattenOverrides(rows, ::formatExdateStamp).map { it.uid }) + .isEqualTo(flattenOverrides(rows, ::formatExdateStamp).map { it.uid }) + } + + @Test + fun `a backup keeps a cancelled series, a copy leaves it out with its exceptions`() { + val rows = CalendarRows( + listOf(series("s", status = EventStatus.Cancelled)), + listOf(OverrideRow(1, 1, null, occurrence(1), event("x"))), + ) + + assertThat(flattenOverrides(rows, ::formatExdateStamp).map { it.uid }).contains("s") + assertThat(planCalendarCopy(rows, ::formatExdateStamp)).isEmpty() + } + + @Test + fun `a copy keeps the zone, colour and override link`() { + val rows = CalendarRows( + listOf(MasterRow(1, 1, null, event("s", rrule = "FREQ=WEEKLY", reminders = listOf(10, -5, 10), color = 0xFF112233.toInt()))), + listOf(OverrideRow(1, 1, null, occurrence(1), event("x"))), + ) + + val (detached, copied) = planCalendarCopy(rows, ::formatExdateStamp) + assertThat(detached.overrideOf).isEqualTo("s") + assertThat(copied.zoneId).isEqualTo("Europe/Berlin") + assertThat(copied.color).isEqualTo(0xFF112233.toInt()) + assertThat(copied.reminderMinutes).containsExactly(10) + } + + @Test + fun `a zero-length all-day event lasts its day`() { + val day = Instant.parse("2026-01-05T00:00:00Z") + val parsed = event("a", allDay = true, at = day).copy(end = day).toParsedIcsEvent() + + assertThat(parsed.end).isEqualTo(Instant.parse("2026-01-06T00:00:00Z")) + } + + @Test + fun `the override link survives the file`() { + val text = IcsWriter().writeCalendar(listOf(event("d").copy(overrideOf = "s;1", overrideAt = occurrence(1))), start) + + val parsed = IcsParser().parse(text).events.single() + assertThat(parsed.overrideOf).isEqualTo("s;1") + assertThat(parsed.overrideAt).isEqualTo(occurrence(1)) + } + + @Test + fun `a cancelled series' moved occurrence isn't brought back`() { + val flat = flatten( + listOf(series("s", status = EventStatus.Cancelled)), + listOf(OverrideRow(1, 1, null, occurrence(1), event("x"))), + ) + + assertThat(flat.map { it.uid }).containsExactly("s") + } + + @Test + fun `the same series in two calendars keeps each calendar's moved occurrence`() { + val flat = flatten( + listOf(series("s", id = 1, calendar = 1), series("s", id = 2, calendar = 2)), + listOf( + OverrideRow(1, 1, null, occurrence(1), event("x")), + OverrideRow(2, 2, null, occurrence(1), event("x")), + ), + ) + + assertThat(flat.count { it.overrideOf == "s" }).isEqualTo(2) + } + + @Test + fun `a copy leaves declined invitations out but keeps an occurrence accepted on its own`() { + val rows = CalendarRows( + listOf(series("d").copy(declined = true), series("k", id = 2)), + listOf( + OverrideRow(1, 1, null, occurrence(1), event("accepted"), accepted = true), + OverrideRow(1, 1, null, occurrence(2), event("moved by the organizer")), + ), + ) + + val plan = planCalendarCopy(rows, ::formatExdateStamp) + assertThat(plan.map { it.summary }).containsExactly("accepted", "k") + } + + @Test + fun `a copy treats a declined occurrence as deleted`() { + val rows = CalendarRows( + listOf(series("s")), + listOf(OverrideRow(1, 1, null, occurrence(1), event("x"), declined = true)), + ) + + val plan = planCalendarCopy(rows, ::formatExdateStamp) + assertThat(plan.map { it.uid }).containsExactly("s") + assertThat(plan.single().exDates).containsExactly("20260112T090000Z") + } + + @Test + fun `RDATE and its exclusions survive the file`() { + val timed = event("t").copy( + recurrenceDates = listOf("20260112T090000Z", "20260120T090000Z"), + exDates = listOf("20260112T090000Z"), + ) + val day = Instant.parse("2026-01-05T00:00:00Z") + val allDay = event("a", allDay = true, at = day).copy( + end = Instant.parse("2026-01-06T00:00:00Z"), + recurrenceDates = listOf("20260110"), + exDates = listOf("20260110"), + ) + val text = IcsWriter().writeCalendar(listOf(timed, allDay), start) + + assertThat(text).contains("RDATE;VALUE=DATE:20260110") + assertThat(text).contains("DTSTART;TZID=Europe/Berlin:20260105T100000") + val (t, a) = IcsParser().parse(text).events + assertThat(t.recurrenceDates).containsExactly("20260112T090000Z", "20260120T090000Z") + assertThat(t.exDates).containsExactly("20260112T090000Z") + assertThat(a.recurrenceDates).containsExactly("20260110") + assertThat(a.exDates).containsExactly("20260110") + } + + @Test + fun `a foreign RDATE is read in its own zone, a period by its start`() { + val text = """ + BEGIN:VCALENDAR + BEGIN:VEVENT + UID:f + DTSTART;TZID=Europe/Berlin:20260105T100000 + DTEND;TZID=Europe/Berlin:20260105T110000 + RDATE;TZID=America/New_York:20260110T090000 + RDATE;VALUE=PERIOD:20260111T090000Z/PT1H + END:VEVENT + END:VCALENDAR + """.trimIndent().replace("\n", "\r\n") + + assertThat(IcsParser().parse(text).events.single().recurrenceDates) + .containsExactly("20260110T140000Z", "20260111T090000Z") + } + + @Test + fun `a declined row takes no other row with its UID along`() { + val rows = CalendarRows(listOf(series("u").copy(declined = true), series("u", id = 2)), emptyList()) + + assertThat(planCalendarCopy(rows, ::formatExdateStamp)).hasSize(1) + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/reminders/DailyDigestTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/reminders/DailyDigestTest.kt new file mode 100644 index 00000000..c562407a --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/reminders/DailyDigestTest.kt @@ -0,0 +1,89 @@ +package de.jeanlucmakiola.calendula.domain.reminders + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.ZoneId +import java.time.ZoneOffset + +class DailyDigestTest { + + private val zone = ZoneId.of("Europe/Berlin") + private val minute = 60_000L + private val eight = 20 * 60 + + private fun millis(text: String): Long = LocalDateTime.parse(text).atZone(zone).toInstant().toEpochMilli() + + @Test + fun `due once the moment passes the watermark`() { + val schedule = scheduleDigest(eight, DigestDay.Tomorrow, zone, millis("2026-06-10T19:59"), millis("2026-06-10T20:00")) + assertThat(schedule.dueDay).isEqualTo(LocalDate.of(2026, 6, 11)) + assertThat(schedule.nextAlarmMillis).isEqualTo(millis("2026-06-11T20:00")) + } + + @Test + fun `a second scan does not post again`() { + val schedule = scheduleDigest(eight, DigestDay.Tomorrow, zone, millis("2026-06-10T20:00"), millis("2026-06-10T20:05")) + assertThat(schedule.dueDay).isNull() + } + + @Test + fun `a day already listed is not listed again`() { + // Posted at 20:00, then the time moved to 21:00 the same evening. + val schedule = scheduleDigest( + 21 * 60, DigestDay.Tomorrow, zone, millis("2026-06-10T20:30"), millis("2026-06-10T21:00"), + lastListedDay = LocalDate.of(2026, 6, 11), + ) + assertThat(schedule.dueDay).isNull() + } + + @Test + fun `before the moment it only arms the alarm`() { + val schedule = scheduleDigest(eight, DigestDay.Tomorrow, zone, millis("2026-06-10T08:00"), millis("2026-06-10T09:00")) + assertThat(schedule.dueDay).isNull() + assertThat(schedule.nextAlarmMillis).isEqualTo(millis("2026-06-10T20:00")) + } + + @Test + fun `a late catch-up still lists a day that has not passed`() { + // Off overnight: last scan before 20:00, back on the next morning. + val schedule = scheduleDigest(eight, DigestDay.Tomorrow, zone, millis("2026-06-10T18:00"), millis("2026-06-11T07:00")) + assertThat(schedule.dueDay).isEqualTo(LocalDate.of(2026, 6, 11)) + } + + @Test + fun `a today summary missed until the next day is dropped`() { + val seven = 7 * 60 + val schedule = scheduleDigest(seven, DigestDay.Today, zone, millis("2026-06-10T06:00"), millis("2026-06-11T06:30")) + assertThat(schedule.dueDay).isNull() + assertThat(schedule.nextAlarmMillis).isEqualTo(millis("2026-06-11T07:00")) + } + + @Test + fun `entries list all-day first, keep the day's own, and skip excluded calendars`() { + val day = LocalDate.of(2026, 6, 11) + val utcMidnight = day.atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli() + val allDay = instance(1, utcMidnight, utcMidnight + 24 * 60 * minute, isAllDay = true) + val previousAllDay = instance(2, utcMidnight - 24 * 60 * minute, utcMidnight, isAllDay = true) + val morning = instance(3, millis("2026-06-11T09:00"), millis("2026-06-11T10:00")) + val early = instance(4, millis("2026-06-11T07:00"), millis("2026-06-11T08:00")) + val nextDay = instance(5, millis("2026-06-12T00:00"), millis("2026-06-12T01:00")) + val excluded = instance(6, millis("2026-06-11T12:00"), millis("2026-06-11T13:00"), calendarId = 9) + val entries = digestEntries( + listOf(morning, previousAllDay, nextDay, early, allDay, excluded), + day, + zone, + excludedCalendarIds = setOf(9), + ) + assertThat(entries.map { it.eventId }).containsExactly(1L, 4L, 3L).inOrder() + } + + private fun instance( + eventId: Long, + begin: Long, + end: Long, + isAllDay: Boolean = false, + calendarId: Long = 1, + ) = ReminderEventInstance(eventId, calendarId, begin, end, "Event $eventId", null, isAllDay) +} diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/reminders/FixedTimeReminderTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/reminders/FixedTimeReminderTest.kt new file mode 100644 index 00000000..75ed5783 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/reminders/FixedTimeReminderTest.kt @@ -0,0 +1,100 @@ +package de.jeanlucmakiola.calendula.domain.reminders + +import com.google.common.truth.Truth.assertThat +import kotlinx.datetime.LocalDateTime +import kotlinx.datetime.TimeZone +import kotlinx.datetime.toInstant +import org.junit.jupiter.api.Test +import kotlin.time.Instant + +class FixedTimeReminderTest { + + private val berlin = TimeZone.of("Europe/Berlin") + private val eveningBefore = FixedTimeReminder(daysBefore = 1, minuteOfDay = 20 * 60) + + private fun at(text: String, zone: TimeZone = berlin): Instant = LocalDateTime.parse(text).toInstant(zone) + + @Test + fun `offset is the distance from the named wall clock to the start`() { + assertThat(eveningBefore.offsetMinutes(at("2026-06-10T10:00"), berlin)).isEqualTo(14 * 60) + assertThat(eveningBefore.offsetMinutes(at("2026-06-10T21:30"), berlin)).isEqualTo(25 * 60 + 30) + } + + @Test + fun `offset spans a DST change in real minutes`() { + // Clocks go forward on 29 March 2026: 20:00 on the 28th to 10:00 on the 29th is 13 hours. + assertThat(eveningBefore.offsetMinutes(at("2026-03-29T10:00"), berlin)).isEqualTo(13 * 60) + } + + @Test + fun `a series offset counts clock minutes, so a DST-side occurrence bakes in no hour`() { + // Opened on the Sunday clocks go back: the real span is 15 hours, the clock face says 14. + val start = at("2026-10-25T10:00") + assertThat(eveningBefore.offsetMinutes(start, berlin)).isEqualTo(15 * 60) + val offset = eveningBefore.offsetMinutes(start, berlin, wallClock = true) + assertThat(offset).isEqualTo(14 * 60) + // Read back the same way on any occurrence of the series. + assertThat(fixedTimeReminderAt(offset, at("2026-11-01T10:00"), berlin, wallClock = true)).isEqualTo(eveningBefore) + assertThat(fixedTimeReminderAt(offset, start, berlin, wallClock = true)).isEqualTo(eveningBefore) + } + + @Test + fun `an offset reads back as the pattern it was written from`() { + val start = at("2026-03-29T10:00") + val offset = eveningBefore.offsetMinutes(start, berlin) + assertThat(fixedTimeReminderAt(offset, start, berlin)).isEqualTo(eveningBefore) + } + + @Test + fun `a reminder on the start's own day or after it is no pattern`() { + val start = at("2026-06-10T10:00") + assertThat(fixedTimeReminderAt(60, start, berlin)).isNull() + assertThat(fixedTimeReminderAt(0, start, berlin)).isNull() + assertThat(fixedTimeReminderAt(-30, start, berlin)).isNull() + } + + @Test + fun `only known patterns read as fixed-time`() { + val start = at("2026-06-10T10:00") + // 840 is "1 day before at 20:00" here, but also a plain "14 hours before". + val unknown = splitTimedReminders(listOf(10, 1_440, 840), start, berlin, known = emptySet()) + assertThat(unknown.leadMinutes).containsExactly(10, 840, 1_440).inOrder() + assertThat(unknown.fixed).isEmpty() + + val known = splitTimedReminders(listOf(10, 1_440, 840), start, berlin, known = setOf(eveningBefore)) + assertThat(known.leadMinutes).containsExactly(10, 1_440).inOrder() + assertThat(known.fixed).containsExactly(eveningBefore) + } + + @Test + fun `a whole-day offset landing on a known pattern is fixed-time`() { + // An event at 20:00 with "1 day before at 20:00" stores exactly a day. + val start = at("2026-06-10T20:00") + assertThat(splitTimedReminders(listOf(1_440), start, berlin, known = emptySet()).fixed).isEmpty() + val split = splitTimedReminders(listOf(1_440), start, berlin, known = setOf(eveningBefore)) + assertThat(split.fixed).containsExactly(eveningBefore) + assertThat(split.leadMinutes).isEmpty() + } + + @Test + fun `fixed reminders sort by when they fire`() { + val start = at("2026-06-10T10:00") + val twoDays = FixedTimeReminder(2, 9 * 60) + val split = splitTimedReminders( + listOf(eveningBefore.offsetMinutes(start, berlin), twoDays.offsetMinutes(start, berlin)), + start, + berlin, + known = setOf(eveningBefore, twoDays), + ) + assertThat(split.fixed).containsExactly(twoDays, eveningBefore).inOrder() + } + + @Test + fun `token round-trips and rejects garbage`() { + assertThat(FixedTimeReminder.parse(eveningBefore.toToken())).isEqualTo(eveningBefore) + assertThat(FixedTimeReminder.parse("0@600")).isNull() + assertThat(FixedTimeReminder.parse("1@1440")).isNull() + assertThat(FixedTimeReminder.parse("x")).isNull() + assertThat(FixedTimeReminder.parse(null)).isNull() + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderAlertStyleTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderAlertStyleTest.kt new file mode 100644 index 00000000..17e9b0ec --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderAlertStyleTest.kt @@ -0,0 +1,38 @@ +package de.jeanlucmakiola.calendula.domain.reminders + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class ReminderAlertStyleTest { + + @Test + fun `styles round-trip through their stored form`() { + val styles = mapOf(9L to ReminderAlertStyle.FullScreenRing, 3L to ReminderAlertStyle.FullScreen) + + assertThat(parseAlertStyles(styles.toStoredAlertStyles())).isEqualTo(styles) + } + + @Test + fun `plain notifications are not stored`() { + val stored = mapOf(1L to ReminderAlertStyle.Notification, 2L to ReminderAlertStyle.FullScreen).toStoredAlertStyles() + + assertThat(stored).isEqualTo("2=full_screen") + } + + @Test + fun `garbled entries are dropped, the rest survive`() { + assertThat(parseAlertStyles("x=full_screen;4=loud;5;6=full_screen_ring")) + .containsExactly(6L, ReminderAlertStyle.FullScreenRing) + assertThat(parseAlertStyles(null)).isEmpty() + } + + @Test + fun `a calendar without a style uses notifications`() { + val styles = mapOf(1L to ReminderAlertStyle.FullScreen) + + assertThat(styles.alertStyleFor(1L)).isEqualTo(ReminderAlertStyle.FullScreen) + assertThat(styles.alertStyleFor(2L)).isEqualTo(ReminderAlertStyle.Notification) + assertThat(ReminderAlertStyle.Notification.isFullScreen).isFalse() + assertThat(ReminderAlertStyle.FullScreenRing.isFullScreen).isTrue() + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderMapQueryTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderMapQueryTest.kt new file mode 100644 index 00000000..7368969c --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderMapQueryTest.kt @@ -0,0 +1,51 @@ +package de.jeanlucmakiola.calendula.domain.reminders + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class ReminderMapQueryTest { + + @Test + fun `an address is looked up as written`() { + assertThat(reminderMapQuery(" Main St 1, Berlin ")).isEqualTo("Main St 1, Berlin") + } + + @Test + fun `no location means no lookup`() { + assertThat(reminderMapQuery(null)).isNull() + assertThat(reminderMapQuery(" ")).isNull() + } + + @Test + fun `a bare meeting link is not a place`() { + assertThat(reminderMapQuery("https://meet.google.com/abc-defg-hij")).isNull() + assertThat(reminderMapQuery("HTTP://example.com")).isNull() + assertThat(reminderMapQuery("")).isNull() + assertThat(reminderMapQuery("https://a.example\nhttps://b.example")).isNull() + } + + @Test + fun `dotted place names are still places`() { + assertThat(reminderMapQuery("Hauptstr. 12/3, Wien")).isEqualTo("Hauptstr. 12/3, Wien") + assertThat(reminderMapQuery("St.Gallen/Zentrum")).isEqualTo("St.Gallen/Zentrum") + } + + @Test + fun `a place with a link beside it is still looked up`() { + assertThat(reminderMapQuery("Room 4, https://example.com/map")).isEqualTo("Room 4, https://example.com/map") + } + + @Test + fun `the first web link is the reminder's link`() { + assertThat(reminderLink("https://meet.google.com/abc-defg-hij")).isEqualTo("https://meet.google.com/abc-defg-hij") + assertThat(reminderLink("")).isEqualTo("https://teams.microsoft.com/l/meetup-join/x") + assertThat(reminderLink("Room 4, https://example.com/map.")).isEqualTo("https://example.com/map") + assertThat(reminderLink("https://a.example\nhttps://b.example")).isEqualTo("https://a.example") + } + + @Test + fun `no link without one`() { + assertThat(reminderLink(null)).isNull() + assertThat(reminderLink("Hauptstr. 12/3, Wien")).isNull() + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/ui/WidgetNavRequestTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/ui/WidgetNavRequestTest.kt new file mode 100644 index 00000000..c705cf14 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/ui/WidgetNavRequestTest.kt @@ -0,0 +1,48 @@ +package de.jeanlucmakiola.calendula.ui + +import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.ui.common.CalendarView +import org.junit.jupiter.api.Test + +class WidgetNavRequestTest { + + private val detail = LeaveTarget.Detail(1, 2, 3) + + @Test + fun `a widget's day or event is what back leaves from`() { + assertThat(WidgetNavRequest.OpenDate("2026-11-25", fromWidget = true).leaveTarget).isEqualTo(LeaveTarget.View) + assertThat(WidgetNavRequest.OpenDate("2026-11-25", fromWidget = false).leaveTarget).isNull() + assertThat(WidgetNavRequest.OpenEvent(1, 2, 3, CalendarView.Agenda).leaveTarget).isEqualTo(detail) + assertThat(WidgetNavRequest.OpenEvent(1, 2, 3, CalendarView.Day).leaveTarget).isEqualTo(detail) + assertThat(WidgetNavRequest.OpenView(CalendarView.Month).leaveTarget).isNull() + assertThat(WidgetNavRequest.Create(null).leaveTarget).isNull() + } + + @Test + fun `the target stays only while the views stay put`() { + val day = listOf(CalendarView.Week, CalendarView.Day) + assertThat(LeaveTarget.View.afterMove(day, day.toList())).isEqualTo(LeaveTarget.View) + assertThat(LeaveTarget.View.afterMove(day, listOf(CalendarView.Week))).isNull() + assertThat(detail.afterMove(day, day + CalendarView.Month)).isNull() + assertThat(null.afterMove(day, day)).isNull() + } + + @Test + fun `a widget's detail is dropped once it closes or another opens`() { + assertThat(detail.afterDetail(longArrayOf(1, 2, 3))).isEqualTo(detail) + assertThat(detail.afterDetail(null)).isNull() + assertThat(detail.afterDetail(longArrayOf(4, 5, 6))).isNull() + // A widget's day keeps its target under an in-app detail. + assertThat(LeaveTarget.View.afterDetail(longArrayOf(4, 5, 6))).isEqualTo(LeaveTarget.View) + } + + @Test + fun `back leaves only from the widget's own day or detail`() { + assertThat(LeaveTarget.View.leaves(detail = null, overlayVisible = false)).isTrue() + assertThat(LeaveTarget.View.leaves(detail = longArrayOf(4, 5, 6), overlayVisible = true)).isFalse() + assertThat(detail.leaves(detail = longArrayOf(1, 2, 3), overlayVisible = true)).isTrue() + assertThat(detail.leaves(detail = longArrayOf(4, 5, 6), overlayVisible = true)).isFalse() + assertThat(detail.leaves(detail = null, overlayVisible = false)).isFalse() + assertThat(null.leaves(detail = null, overlayVisible = false)).isFalse() + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiStateTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiStateTest.kt index 6206ea34..c2e8f031 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiStateTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiStateTest.kt @@ -45,10 +45,10 @@ class BackupUiStateTest { } @Test - fun `a synced writable calendar can receive a restore`() { + fun `a synced writable calendar can receive a restore and be backed up`() { val state = ready(backupUiState(listOf(cal(1L)))) assertThat(state.canImport).isTrue() - assertThat(state.exportable).isEmpty() + assertThat(state.exportable.map { it.id }).containsExactly(1L) } @Test @@ -62,16 +62,18 @@ class BackupUiStateTest { } @Test - fun `a read-only subscription is no import target either`() { - assertThat(failure(backupUiState(listOf(cal(1L, writable = false))))) - .isEqualTo(FailureReason.NoImportTarget) + fun `a read-only subscription is no import target but can be backed up`() { + // #147: export only reads, so a subscription is fair game. + val state = ready(backupUiState(listOf(cal(1L, writable = false)))) + assertThat(state.canImport).isFalse() + assertThat(state.exportable).hasSize(1) } @Test - fun `everything switched off is reported as hidden, not as a missing target`() { - // The remedy differs: a visibility switch fixes this one. - assertThat(failure(backupUiState(listOf(cal(1L, visible = false))))) - .isEqualTo(FailureReason.AllCalendarsHidden) + fun `a switched-off synced calendar still backs up`() { + val state = ready(backupUiState(listOf(cal(1L, visible = false)))) + assertThat(state.canImport).isFalse() + assertThat(state.exportable).hasSize(1) } @Test @@ -92,7 +94,51 @@ class BackupUiStateTest { @Test fun `a local calendar alongside a synced one offers both halves`() { val state = ready(backupUiState(listOf(cal(1L, local = true), cal(2L)))) - assertThat(state.exportable.map { it.id }).containsExactly(1L) + assertThat(state.exportable.map { it.id }).containsExactly(1L, 2L) assertThat(state.canImport).isTrue() } + + @Test + fun `a read-only calendar can be copied into a writable one`() { + val readOnly = cal(1, writable = false) + val local = cal(2, local = true) + + val state = ready(backupUiState(listOf(readOnly, local))) + + assertThat(state.canCopy).isTrue() + assertThat(copySources(listOf(readOnly, local)).map { it.id }).containsExactly(1L) + assertThat(copyTargets(listOf(readOnly, local), 1L).map { it.id }).containsExactly(2L) + } + + @Test + fun `a single writable calendar has nothing to copy into`() { + val only = cal(1, local = true) + + assertThat(ready(backupUiState(listOf(only))).canCopy).isFalse() + assertThat(copyTargets(listOf(only), 1L)).isEmpty() + } + + @Test + fun `the only writable calendar is not offered as a source`() { + val local = cal(1, local = true) + val holidays = cal(2, writable = false) + + assertThat(copySources(listOf(local, holidays)).map { it.id }).containsExactly(2L) + } + + @Test + fun `a copy never targets a managed or switched-off calendar`() { + val source = cal(1) + val calendars = listOf(source, cal(2, managed = true), cal(3, visible = false)) + + assertThat(copyTargets(calendars, source.id)).isEmpty() + } + + @Test + fun `choosing the target as source drops it`() { + assertThat(CopySelection(sourceId = 1, targetId = 2).withSource(2)) + .isEqualTo(CopySelection(sourceId = 2, targetId = null)) + assertThat(CopySelection(sourceId = 1, targetId = 2).withSource(3)) + .isEqualTo(CopySelection(sourceId = 3, targetId = 2)) + } } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/ReminderPresetsTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/ReminderPresetsTest.kt new file mode 100644 index 00000000..f3a2363f --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/ReminderPresetsTest.kt @@ -0,0 +1,67 @@ +package de.jeanlucmakiola.calendula.ui.common + +import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.floret.reminders.ReminderUnit +import org.junit.jupiter.api.Test + +class ReminderPresetsTest { + + @Test + fun `presets are sorted and unique`() { + for (presets in listOf(REMINDER_PRESETS, ALLDAY_REMINDER_PRESETS)) { + assertThat(presets).isInStrictOrder() + } + } + + @Test + fun `all-day presets are whole days`() { + assertThat(ALLDAY_REMINDER_PRESETS.all { it % 1_440 == 0 }).isTrue() + } + + @Test + fun `offers two to five days and two and three weeks`() { + val extra = listOf(2_880, 4_320, 5_760, 7_200, 20_160, 30_240) + assertThat(REMINDER_PRESETS).containsAtLeastElementsIn(extra) + assertThat(ALLDAY_REMINDER_PRESETS).containsAtLeastElementsIn(extra) + } + + @Test + fun `groups split sub-day from day-scale lead times, sorted`() { + assertThat(groupReminderLeadTimes(listOf(2_880, 10, 0, 1_440, 45), splitSubDay = true)) + .containsExactly(listOf(0, 10, 45), listOf(1_440, 2_880)).inOrder() + } + + @Test + fun `all-day custom offers whole-day units only`() { + assertThat(customReminderUnits(isAllDay = true)) + .containsExactly(ReminderUnit.Days, ReminderUnit.Weeks).inOrder() + assertThat(customReminderUnits(isAllDay = false)).containsExactlyElementsIn(ReminderUnit.entries) + } + + @Test + fun `custom placeholder fits the selected unit`() { + assertThat(customReminderPlaceholder(ReminderUnit.Minutes)).isEqualTo("10") + assertThat(customReminderPlaceholder(ReminderUnit.Days)).isEqualTo("1") + } + + @Test + fun `only the timed list splits`() { + assertThat(splitsSubDay(REMINDER_PRESETS)).isTrue() + assertThat(splitsSubDay(ALLDAY_REMINDER_PRESETS)).isFalse() + } + + @Test + fun `unsplit list is one sorted group`() { + assertThat(groupReminderLeadTimes(listOf(2_880, 0, 30), splitSubDay = false)) + .containsExactly(listOf(0, 30, 2_880)) + } + + @Test + fun `empty groups are dropped`() { + assertThat(groupReminderLeadTimes(listOf(0, 1_440), splitSubDay = true)) + .containsExactly(listOf(0), listOf(1_440)).inOrder() + assertThat(groupReminderLeadTimes(listOf(2_880), splitSubDay = true)).containsExactly(listOf(2_880)) + assertThat(groupReminderLeadTimes(emptyList(), splitSubDay = true)).isEmpty() + assertThat(groupReminderLeadTimes(emptyList(), splitSubDay = false)).isEmpty() + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/RescheduleViewModelTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/RescheduleViewModelTest.kt index 86215696..41c8c6c2 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/RescheduleViewModelTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/RescheduleViewModelTest.kt @@ -92,12 +92,13 @@ class RescheduleViewModelTest { io: CoroutineDispatcher = dispatcher, ): RescheduleViewModel { fake.occurrencesAt(present) + val settings = testSettings(tempDir, CoroutineScope(dispatcher)) val repo = testRepository( fake, tempDir, io, prefs = testPrefs(tempDir, CoroutineScope(dispatcher)), - settings = testSettings(tempDir, CoroutineScope(dispatcher)), + settings = settings, ) - return RescheduleViewModel(repo, io, FakeZoneSource()) + return RescheduleViewModel(repo, io, FakeZoneSource(), settings) } private fun slowViewModel(tempDir: Path, fake: FakeCalendarDataSource): RescheduleViewModel = diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt new file mode 100644 index 00000000..1d525b00 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/SyncViewModelTest.kt @@ -0,0 +1,209 @@ +package de.jeanlucmakiola.calendula.ui.common + +import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.MainDispatcherExtension +import de.jeanlucmakiola.calendula.RecordingSyncRequester +import de.jeanlucmakiola.calendula.data.calendar.FakeCalendarDataSource +import de.jeanlucmakiola.calendula.data.calendar.SyncAccount +import de.jeanlucmakiola.calendula.data.calendar.SyncActivity +import de.jeanlucmakiola.calendula.data.calendar.SyncRequestResult +import de.jeanlucmakiola.calendula.data.calendar.SyncTargets +import kotlinx.coroutines.launch +import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.testPrefs +import de.jeanlucmakiola.calendula.testRepository +import de.jeanlucmakiola.calendula.testSettings +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.RegisterExtension +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Path + +@OptIn(ExperimentalCoroutinesApi::class) +class SyncViewModelTest { + + @JvmField @RegisterExtension + val mainDispatcher = MainDispatcherExtension(StandardTestDispatcher()) + private val dispatcher = mainDispatcher.dispatcher + + private val synced = CalendarSource(1L, "Work", "me@dav", "bitfire.at.davdroid", 0, true) + private val davAccount = SyncAccount("me@dav", "bitfire.at.davdroid") + + private fun viewModel(dir: Path, sync: RecordingSyncRequester = RecordingSyncRequester()): + Pair { + val source = FakeCalendarDataSource().apply { calendarsResult = listOf(synced) } + val repo = testRepository( + source, dir, dispatcher, + prefs = testPrefs(dir, CoroutineScope(dispatcher)), + settings = testSettings(dir, CoroutineScope(dispatcher)), + syncRequester = sync, + ) + return SyncViewModel(repo) to source + } + + @Test + fun `completed once the reached account has synced`(@TempDir dir: Path) = runTest(dispatcher) { + val sync = RecordingSyncRequester() + var state = SyncActivity.Pending + sync.activity = { state } + val (vm, _) = viewModel(dir, sync) + + vm.requestSync() + runCurrent() + assertThat(vm.inFlight.value).isTrue() + assertThat(vm.result.value).isNull() + + state = SyncActivity.Active + sync.activityChanges.tryEmit(Unit) + runCurrent() + assertThat(vm.inFlight.value).isTrue() + + state = SyncActivity.Idle + sync.activityChanges.tryEmit(Unit) + runCurrent() + + assertThat(vm.inFlight.value).isFalse() + assertThat(vm.result.value).isEqualTo(SyncRequestResult.Completed) + } + + @Test + fun `a sync already running when asked has to finish and the asked one run`(@TempDir dir: Path) = runTest(dispatcher) { + val sync = RecordingSyncRequester() + var state = SyncActivity.Active + sync.activity = { state } + val (vm, _) = viewModel(dir, sync) + + vm.requestSync() + runCurrent() + state = SyncActivity.Pending + sync.activityChanges.tryEmit(Unit) + runCurrent() + assertThat(vm.inFlight.value).isTrue() + + state = SyncActivity.Idle + sync.activityChanges.tryEmit(Unit) + runCurrent() + + assertThat(vm.inFlight.value).isFalse() + assertThat(vm.result.value).isEqualTo(SyncRequestResult.Completed) + } + + @Test + fun `a sync that never shows up counts as done after the grace`(@TempDir dir: Path) = runTest(dispatcher) { + val (vm, _) = viewModel(dir) + + vm.requestSync() + advanceTimeBy(4_000L) + assertThat(vm.inFlight.value).isTrue() + + advanceTimeBy(1_500L) + assertThat(vm.inFlight.value).isFalse() + assertThat(vm.result.value).isEqualTo(SyncRequestResult.Completed) + } + + @Test + fun `a sync still running after a minute stays unconfirmed`(@TempDir dir: Path) = runTest(dispatcher) { + val sync = RecordingSyncRequester().apply { activity = { SyncActivity.Active } } + val (vm, _) = viewModel(dir, sync) + + vm.requestSync() + advanceTimeBy(59_000L) + assertThat(vm.inFlight.value).isTrue() + + advanceTimeBy(1_500L) + assertThat(vm.inFlight.value).isFalse() + assertThat(vm.result.value).isEqualTo(SyncRequestResult.Requested) + } + + @Test + fun `unreadable sync state says requested at once`(@TempDir dir: Path) = runTest(dispatcher) { + val sync = RecordingSyncRequester().apply { activity = { null } } + val (vm, _) = viewModel(dir, sync) + + vm.requestSync() + runCurrent() + + assertThat(vm.inFlight.value).isFalse() + assertThat(vm.result.value).isEqualTo(SyncRequestResult.Requested) + } + + @Test + fun `a tap while in flight asks only once`(@TempDir dir: Path) = runTest(dispatcher) { + val sync = RecordingSyncRequester() + val (vm, _) = viewModel(dir, sync) + + vm.requestSync() + runCurrent() + vm.requestSync() + runCurrent() + + assertThat(sync.requests).hasSize(1) + } + + @Test + fun `a refused request stops at once and says so`(@TempDir dir: Path) = runTest(dispatcher) { + val (vm, _) = viewModel(dir, RecordingSyncRequester(accepts = false)) + + vm.requestSync() + runCurrent() + + assertThat(vm.inFlight.value).isFalse() + assertThat(vm.result.value).isEqualTo(SyncRequestResult.Failed) + + vm.consumeResult() + assertThat(vm.result.value).isNull() + } + + @Test + fun `refreshAccess picks up a grant`(@TempDir dir: Path) = runTest(dispatcher) { + val sync = RecordingSyncRequester(hiddenTypes = setOf(davAccount.type)) + sync.knownAccounts = setOf(davAccount) + val (vm, _) = viewModel(dir, sync) + backgroundScope.launch { vm.targets.collect {} } + runCurrent() + + assertThat(vm.targets.value).isEqualTo(SyncTargets(emptySet(), setOf(davAccount))) + + sync.hiddenTypes = setOf("other") + vm.refreshAccess() + runCurrent() + + assertThat(vm.targets.value).isEqualTo(SyncTargets(setOf(davAccount), emptySet())) + } + + @Test + fun `dismissing a hidden account takes it out of the grant list`(@TempDir dir: Path) = runTest(dispatcher) { + val sync = RecordingSyncRequester(hiddenTypes = setOf(davAccount.type)) + sync.knownAccounts = setOf(davAccount) + val (vm, _) = viewModel(dir, sync) + backgroundScope.launch { vm.targets.collect {} } + runCurrent() + assertThat(vm.targets.value?.needsAccess).containsExactly(davAccount) + + vm.dismissAccess(davAccount) + runCurrent() + + assertThat(vm.targets.value).isEqualTo(SyncTargets(emptySet(), emptySet(), dismissed = setOf(davAccount))) + } + + @Test + fun `a failed read of the targets is retried rather than hiding Sync now for good`(@TempDir dir: Path) = + runTest(dispatcher) { + val (vm, source) = viewModel(dir) + source.calendarsError = IllegalStateException("provider gone") + backgroundScope.launch { vm.targets.collect {} } + runCurrent() + assertThat(vm.targets.value?.reachable.orEmpty()).isEmpty() + + source.calendarsError = null + advanceTimeBy(31_000) + runCurrent() + + assertThat(vm.targets.value?.reachable).containsExactly(davAccount) + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/ViewBackStackTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/ViewBackStackTest.kt index aae8d28d..9d830249 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/ViewBackStackTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/ViewBackStackTest.kt @@ -6,8 +6,8 @@ import org.junit.jupiter.api.Test /** * The pure back-stack rules behind [CalendarHost]'s top-level navigation: * the home view is always the bottom, a lateral move keeps the stack one deep, - * and a date tap drills the day view on top. Verifies the back sequences the - * widget-UX fix promises (e.g. agenda widget → day → back → agenda → back → home). + * and a date tap drills the day view on top. Verifies the back sequences, e.g. + * agenda → day → back → agenda → back → home. */ class ViewBackStackTest { @@ -74,8 +74,8 @@ class ViewBackStackTest { } @Test - fun `agenda widget date tap backs out agenda then home`() { - // openDate(source = Agenda): root in Agenda over the Week home, then drill. + fun `a day tapped in a widget event's view backs out to it, then home`() { + // Agenda widget event tap roots [Week, Agenda]; a day tapped there drills on top. val stack = viewBaseStack(CalendarView.Week, CalendarView.Agenda).drillToDay() assertThat(stack) .containsExactly(CalendarView.Week, CalendarView.Agenda, CalendarView.Day) @@ -86,11 +86,11 @@ class ViewBackStackTest { } @Test - fun `month widget date tap backs out month then home`() { - val stack = viewBaseStack(CalendarView.Week, CalendarView.Month).drillToDay() - assertThat(stack.last()).isEqualTo(CalendarView.Day) - assertThat(stack.dropLast(1).last()).isEqualTo(CalendarView.Month) - assertThat(stack.first()).isEqualTo(CalendarView.Week) + fun `a date launch drills the day over the home view only`() { + assertThat(listOf(CalendarView.Week).drillToDay()) + .containsExactly(CalendarView.Week, CalendarView.Day) + .inOrder() + assertThat(listOf(CalendarView.Day).drillToDay()).containsExactly(CalendarView.Day) } @Test diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/ViewHiddenCalendarsTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/ViewHiddenCalendarsTest.kt new file mode 100644 index 00000000..c561c6fa --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/ui/common/ViewHiddenCalendarsTest.kt @@ -0,0 +1,100 @@ +package de.jeanlucmakiola.calendula.ui.common + +import app.cash.turbine.test +import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.data.calendar.FakeCalendarDataSource +import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.testEvent +import de.jeanlucmakiola.calendula.testRepository +import de.jeanlucmakiola.calendula.testSettings +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.runTest +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Path +import kotlin.time.Instant + +@OptIn(ExperimentalCoroutinesApi::class) +class ViewHiddenCalendarsTest { + + private val range = Instant.fromEpochMilliseconds(0)..Instant.fromEpochMilliseconds(10_000_000_000L) + + private fun event(id: Long, calendarId: Long) = testEvent( + id = id, + calendarId = calendarId, + title = "E $id", + start = Instant.fromEpochMilliseconds(1_000_000_000L), + end = Instant.fromEpochMilliseconds(1_000_003_600L), + color = 0, + ) + + private fun calendar(id: Long) = CalendarSource(id, "Cal $id", "x@y", "LOCAL", 0, true) + + @Test + fun `calendarsHiddenIn picks only the calendars hidden in that view`() { + val map = mapOf( + 1L to setOf(CalendarView.Month), + 2L to setOf(CalendarView.Month, CalendarView.Agenda), + 3L to setOf(CalendarView.Week), + ) + assertThat(map.calendarsHiddenIn(CalendarView.Month)).containsExactly(1L, 2L) + assertThat(map.calendarsHiddenIn(CalendarView.Agenda)).containsExactly(2L) + assertThat(map.calendarsHiddenIn(CalendarView.Day)).isEmpty() + } + + @Test + fun `instancesWithout drops a calendar only in the views it is hidden in`(@TempDir tempDir: Path) = runTest { + val fake = FakeCalendarDataSource().apply { + calendarsResult = listOf(calendar(1L), calendar(2L)) + instancesResult = { _, _ -> listOf(event(10L, 1L), event(20L, 2L)) } + } + val settings = testSettings(tempDir) + val repo = testRepository(fake, tempDir, UnconfinedTestDispatcher(testScheduler), settings = settings) + settings.applyCalendarHiddenChanges(2L, listOf(CalendarView.Month).associateWith { true }) + val hidden = settings.perCalendarHiddenViews + + assertThat(repo.instancesWithout(range, hidden.calendarsHiddenIn(CalendarView.Month, backgroundScope)).first().map { it.eventId }) + .containsExactly(10L) + assertThat(repo.instancesWithout(range, hidden.calendarsHiddenIn(CalendarView.Week, backgroundScope)).first().map { it.eventId }) + .containsExactly(10L, 20L) + // The repository itself, which reminders and search build on, is untouched. + assertThat(repo.instances(range).first().map { it.eventId }).containsExactly(10L, 20L) + } + + @Test + fun `instancesWithout re-filters live when the setting changes`(@TempDir tempDir: Path) = runTest { + val fake = FakeCalendarDataSource().apply { + calendarsResult = listOf(calendar(1L), calendar(2L)) + instancesResult = { _, _ -> listOf(event(10L, 1L), event(20L, 2L)) } + } + val settings = testSettings(tempDir) + val repo = testRepository(fake, tempDir, UnconfinedTestDispatcher(testScheduler), settings = settings) + + val hidden = settings.perCalendarHiddenViews.calendarsHiddenIn(CalendarView.Agenda, backgroundScope) + repo.instancesWithout(range, hidden).test { + assertThat(awaitItem().map { it.eventId }).containsExactly(10L, 20L) + settings.setCalendarHiddenIn(1L, CalendarView.Agenda, hidden = true) + assertThat(awaitItem().map { it.eventId }).containsExactly(20L) + settings.setCalendarHiddenIn(1L, CalendarView.Agenda, hidden = false) + assertThat(awaitItem().map { it.eventId }).containsExactly(10L, 20L) + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `a failed read hides nothing and keeps reading`() = runTest { + var reads = 0 + val source = kotlinx.coroutines.flow.flow { + reads++ + if (reads == 1) throw java.io.IOException("disk") + emit(mapOf(1L to setOf(CalendarView.Month))) + } + source.hidingNothingOnError().test { + assertThat(awaitItem()).isEmpty() + assertThat(awaitItem()).containsExactly(1L, setOf(CalendarView.Month)) + awaitComplete() + } + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailViewModelTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailViewModelTest.kt index 4513eca5..7ec4a6f9 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailViewModelTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailViewModelTest.kt @@ -51,13 +51,14 @@ class EventDetailViewModelTest { ) private fun viewModel(tempDir: Path, fake: FakeCalendarDataSource): EventDetailViewModel { + val settings = testSettings(tempDir, CoroutineScope(dispatcher)) val repo = testRepository( fake, tempDir, dispatcher, prefs = testPrefs(tempDir, CoroutineScope(dispatcher)), - settings = testSettings(tempDir, CoroutineScope(dispatcher)), + settings = settings, ) // Only `shareUri()` touches the exporter, and nothing here shares. - return EventDetailViewModel(repo, IcsExporter(ContextWrapper(null)), dispatcher, FakeZoneSource()) + return EventDetailViewModel(repo, IcsExporter(ContextWrapper(null)), dispatcher, FakeZoneSource(), settings) } private fun fakeSource(description: () -> String?) = FakeCalendarDataSource().apply { diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/ui/edit/EventEditViewModelTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/ui/edit/EventEditViewModelTest.kt index c763b5db..8854295a 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/ui/edit/EventEditViewModelTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/ui/edit/EventEditViewModelTest.kt @@ -9,7 +9,12 @@ import de.jeanlucmakiola.calendula.data.ics.IcsExporter import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.data.time.FakeZoneSource +import de.jeanlucmakiola.calendula.data.prefs.FixedTimeOverride import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.domain.Reminder +import de.jeanlucmakiola.calendula.domain.ReminderMethod +import de.jeanlucmakiola.calendula.domain.reminders.FixedTimeReminder +import de.jeanlucmakiola.calendula.domain.DefaultCalendarRef import de.jeanlucmakiola.calendula.domain.EventDetail import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.FormTime @@ -21,6 +26,7 @@ import de.jeanlucmakiola.calendula.testEvent import de.jeanlucmakiola.calendula.testPrefs import de.jeanlucmakiola.calendula.testRepository import de.jeanlucmakiola.calendula.testSettings +import de.jeanlucmakiola.floret.reminders.ReminderOverride import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi @@ -305,6 +311,31 @@ class EventEditViewModelTest { end = FormTime(end), ) + @Test + fun `switching to all-day keeps sub-day reminders, removing one drops its whole day`( + @TempDir tempDir: Path, + ) = runTest(dispatcher) { + val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L)) } + val vm = viewModel(tempDir, fake) + val job = activate(vm) + + vm.openNew(LocalDate(2030, 1, 15), startMinutes = 9 * 60) + advanceUntilIdle() + vm.addReminder(10) + vm.addReminder(1_440) + vm.setAllDay(true) + vm.setAllDay(false) + advanceUntilIdle() + // Toggling all-day is lossless. + assertThat(vm.state.value?.form?.reminders).containsExactly(10, 1_440).inOrder() + + vm.addReminder(0) + vm.setAllDay(true) + vm.removeReminder(0) + assertThat(vm.state.value?.form?.reminders).containsExactly(1_440) + job.cancel() + } + @Test fun `an all-day event ignores the default duration`( @TempDir tempDir: Path, @@ -719,4 +750,267 @@ class EventEditViewModelTest { assertThat(vm.state.value?.saveState).isEqualTo(SaveUiState.Idle) job.cancel() } + + @Test + fun `a new timed event gets the fixed-time default, and a calendar can turn it off`( + @TempDir tempDir: Path, + ) = runTest(dispatcher) { + val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L)) } + val s = settings(tempDir) + val evening = FixedTimeReminder(1, 1_200) + s.setDefaultFixedTimeReminder(evening) + s.setCalendarFixedTimeReminderOverride(2L, FixedTimeOverride.Off) + val vm = viewModel(tempDir, fake, s) + val job = activate(vm) + + vm.openNew(LocalDate(2030, 1, 15), startMinutes = 600) + advanceUntilIdle() + assertThat(vm.state.value!!.form!!.fixedReminders).containsExactly(evening) + + vm.setCalendar(2L) + advanceUntilIdle() + assertThat(vm.state.value!!.form!!.fixedReminders).isEmpty() + job.cancel() + } + + @Test + fun `an event's set-time reminder opens as one and saves without a conflict`( + @TempDir tempDir: Path, + ) = runTest(dispatcher) { + val zone = FakeZoneSource().current() + val start = Instant.fromEpochMilliseconds(beginMillis) + val evening = FixedTimeReminder(1, 1_200) + val offset = evening.offsetMinutes(start, zone) + val fake = FakeCalendarDataSource().apply { + calendarsResult = listOf(cal(1L)) + eventDetailResult = { + detail(calendarId = 1L).copy(reminders = listOf(Reminder(offset, ReminderMethod.Alert))) + } + } + val s = settings(tempDir) + s.setDefaultFixedTimeReminder(evening) + val vm = viewModel(tempDir, fake, s) + val job = activate(vm) + + vm.openForEdit(eventId = 42L, beginMillis = beginMillis, endMillis = endMillis) + advanceUntilIdle() + val form = vm.state.value!!.form!! + assertThat(form.fixedReminders).containsExactly(evening) + assertThat(form.reminders).isEmpty() + assertThat(vm.hasUnsavedChanges.value).isFalse() + + vm.setTitle("Renamed") + vm.save() + advanceUntilIdle() + assertThat(vm.state.value?.saveState).isEqualTo(SaveUiState.Saved) + assertThat(fake.updatedEvents.single().third.fixedReminders).containsExactly(evening) + job.cancel() + } + + @Test + fun `a new event opens in the default calendar with its reminders`( + @TempDir tempDir: Path, + ) = runTest(dispatcher) { + val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L)) } + val s = settings(tempDir) + s.setDefaultNewEventCalendar(DefaultCalendarRef.of(cal(2L))) + s.setCalendarReminderOverride(2L, ReminderOverride.Minutes(listOf(5))) + val p = prefs(tempDir) + p.setLastUsedCalendarId(1L) + val repo = testRepository(fake, tempDir, dispatcher, p, s) + val vm = EventEditViewModel(repo, p, s, IcsExporter(ContextWrapper(null)), dispatcher, FakeZoneSource()) + val job = activate(vm) + + vm.openNew(LocalDate(2030, 1, 15), startMinutes = 9 * 60) + advanceUntilIdle() + + assertThat(vm.state.value?.form?.calendarId).isEqualTo(2L) + assertThat(vm.state.value?.form?.reminders).containsExactly(5) + job.cancel() + } + + @Test + fun `a switched-off default calendar falls back to the first target`( + @TempDir tempDir: Path, + ) = runTest(dispatcher) { + val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L, visible = false)) } + val s = settings(tempDir) + s.setDefaultNewEventCalendar(DefaultCalendarRef.of(cal(2L))) + val vm = viewModel(tempDir, fake, s) + val job = activate(vm) + + vm.openNew(LocalDate(2030, 1, 15)) + advanceUntilIdle() + + assertThat(vm.state.value?.form?.calendarId).isEqualTo(1L) + job.cancel() + } + + @Test + fun `an insert naming a calendar wins over the default`( + @TempDir tempDir: Path, + ) = runTest(dispatcher) { + val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L), cal(3L)) } + val s = settings(tempDir) + s.setDefaultNewEventCalendar(DefaultCalendarRef.of(cal(2L))) + val vm = viewModel(tempDir, fake, s) + val job = activate(vm) + + vm.openImported( + importedForm(end = LocalDateTime(2030, 1, 15, 10, 0)).copy(calendarId = 3L), + ImportSource.Insert, + ) + advanceUntilIdle() + + assertThat(vm.state.value?.form?.calendarId).isEqualTo(3L) + assertThat(vm.hasUnsavedChanges.value).isFalse() + job.cancel() + } + + @Test + fun `an insert naming an unknown calendar falls back to the default`( + @TempDir tempDir: Path, + ) = runTest(dispatcher) { + val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L)) } + val s = settings(tempDir) + s.setDefaultNewEventCalendar(DefaultCalendarRef.of(cal(2L))) + val vm = viewModel(tempDir, fake, s) + val job = activate(vm) + + vm.openImported( + importedForm(end = LocalDateTime(2030, 1, 15, 10, 0)).copy(calendarId = 77L), + ImportSource.Insert, + ) + advanceUntilIdle() + + assertThat(vm.state.value?.form?.calendarId).isEqualTo(2L) + job.cancel() + } + + @Test + fun `a duplicate in its own calendar keeps its colour`( + @TempDir tempDir: Path, + ) = runTest(dispatcher) { + val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L)) } + val vm = viewModel(tempDir, fake) + val job = activate(vm) + + vm.openImported( + importedForm(end = LocalDateTime(2030, 1, 15, 10, 0)).copy(calendarId = 2L, colorKey = "3", color = 7), + ImportSource.Insert, + ) + advanceUntilIdle() + + assertThat(vm.state.value?.form?.calendarId).isEqualTo(2L) + assertThat(vm.state.value?.form?.colorKey).isEqualTo("3") + job.cancel() + } + + @Test + fun `re-picking the shown calendar is no change`( + @TempDir tempDir: Path, + ) = runTest(dispatcher) { + val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L)) } + val vm = viewModel(tempDir, fake) + val job = activate(vm) + + vm.openImported( + importedForm(end = LocalDateTime(2030, 1, 15, 10, 0)).copy(calendarId = 2L, colorKey = "3", color = 7), + ImportSource.Insert, + ) + advanceUntilIdle() + vm.setCalendar(2L) + advanceUntilIdle() + + assertThat(vm.state.value?.form?.colorKey).isEqualTo("3") + assertThat(vm.hasUnsavedChanges.value).isFalse() + job.cancel() + } + + @Test + fun `a round trip through all-day keeps set-time reminders`( + @TempDir tempDir: Path, + ) = runTest(dispatcher) { + val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L)) } + val s = settings(tempDir) + s.setDefaultFixedTimeReminder(FixedTimeReminder(1, 1_200)) + val vm = viewModel(tempDir, fake, s) + val job = activate(vm) + + vm.openNew(LocalDate(2030, 1, 15), startMinutes = 600) + advanceUntilIdle() + vm.addFixedReminder(FixedTimeReminder(2, 480)) + vm.setAllDay(true) + vm.setAllDay(false) + advanceUntilIdle() + assertThat(vm.state.value!!.form!!.fixedReminders) + .containsExactly(FixedTimeReminder(2, 480), FixedTimeReminder(1, 1_200)) + job.cancel() + } + + @Test + fun `a set-time reminder replaces a lead firing at the same moment`( + @TempDir tempDir: Path, + ) = runTest(dispatcher) { + val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L)) } + val s = settings(tempDir) + s.setDefaultReminderMinutes(listOf(1_440, 10)) + val vm = viewModel(tempDir, fake, s, zones = FakeZoneSource(berlin)) + val job = activate(vm) + + vm.openNew(LocalDate(2030, 1, 15), startMinutes = 20 * 60) + advanceUntilIdle() + vm.addFixedReminder(FixedTimeReminder(1, 20 * 60)) + val form = vm.state.value!!.form!! + assertThat(form.reminders).containsExactly(10) + assertThat(form.fixedReminders).containsExactly(FixedTimeReminder(1, 20 * 60)) + job.cancel() + } + + @Test + fun `a copy carrying only set-time reminders keeps them`( + @TempDir tempDir: Path, + ) = runTest(dispatcher) { + val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L)) } + val s = settings(tempDir) + s.setDefaultReminderMinutes(listOf(15)) + val vm = viewModel(tempDir, fake, s) + val job = activate(vm) + + val copy = importedForm(end = LocalDateTime(2030, 1, 15, 10, 0)) + .copy(reminders = emptyList(), fixedReminders = listOf(FixedTimeReminder(1, 1_200))) + vm.openImported(copy, ImportSource.Insert) + advanceUntilIdle() + val form = vm.state.value!!.form!! + assertThat(form.fixedReminders).containsExactly(FixedTimeReminder(1, 1_200)) + assertThat(form.reminders).isEmpty() + job.cancel() + } + + @Test + fun `a duplicate that can't stay in its calendar drops its colour`( + @TempDir tempDir: Path, + ) = runTest(dispatcher) { + val fake = FakeCalendarDataSource().apply { calendarsResult = listOf(cal(1L), cal(2L, visible = false)) } + val vm = viewModel(tempDir, fake) + val job = activate(vm) + + vm.openImported( + importedForm(end = LocalDateTime(2030, 1, 15, 10, 0)).copy(calendarId = 2L, colorKey = "3", color = 7), + ImportSource.Insert, + ) + advanceUntilIdle() + + assertThat(vm.state.value?.form?.calendarId).isEqualTo(1L) + assertThat(vm.state.value?.form?.colorKey).isNull() + assertThat(vm.state.value?.form?.color).isNull() + + vm.setColorRaw(9) + advanceUntilIdle() + + assertThat(vm.state.value?.form?.calendarId).isEqualTo(1L) + assertThat(vm.state.value?.form?.color).isEqualTo(9) + job.cancel() + } } + diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/ui/filter/FilterUiStateTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/ui/filter/FilterUiStateTest.kt new file mode 100644 index 00000000..fe7eb97f --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/ui/filter/FilterUiStateTest.kt @@ -0,0 +1,31 @@ +package de.jeanlucmakiola.calendula.ui.filter + +import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.ui.common.CalendarView +import de.jeanlucmakiola.calendula.ui.common.groupByAccount +import org.junit.jupiter.api.Test + +class FilterUiStateTest { + + private fun calendar(id: Long) = CalendarSource(id, "Cal $id", "x@y", "LOCAL", 0, true) + + @Test + fun `hiddenOnlyIn lists the calendars the view hides on its own`() { + val state = FilterUiState.Success( + groups = listOf(calendar(1L), calendar(2L), calendar(3L)).groupByAccount(), + // 3 is hidden everywhere from the drawer already. + hidden = setOf(3L), + hiddenViews = mapOf( + 1L to setOf(CalendarView.Month), + 2L to setOf(CalendarView.Month, CalendarView.Week), + 3L to setOf(CalendarView.Month), + // Not listed (switched off device-wide). + 9L to setOf(CalendarView.Month), + ), + ) + assertThat(state.hiddenOnlyIn(CalendarView.Month)).containsExactly(1L, 2L) + assertThat(state.hiddenOnlyIn(CalendarView.Week)).containsExactly(2L) + assertThat(state.hiddenOnlyIn(CalendarView.Agenda)).isEmpty() + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/ui/filter/GroupVisibilityTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/ui/filter/GroupVisibilityTest.kt new file mode 100644 index 00000000..6e0cd4f6 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/ui/filter/GroupVisibilityTest.kt @@ -0,0 +1,49 @@ +package de.jeanlucmakiola.calendula.ui.filter + +import androidx.compose.ui.state.ToggleableState +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class GroupVisibilityTest { + + private val group = listOf(1L, 2L, 3L) + + @Test + fun `all shown is on and hides on tap`() { + val state = groupVisibility(group, hidden = setOf(9L)) + assertThat(state).isEqualTo(ToggleableState.On) + assertThat(state.nextGroupVisible()).isFalse() + } + + @Test + fun `none shown is off and shows on tap`() { + val state = groupVisibility(group, hidden = setOf(1L, 2L, 3L)) + assertThat(state).isEqualTo(ToggleableState.Off) + assertThat(state.nextGroupVisible()).isTrue() + } + + @Test + fun `some shown is indeterminate and shows all on tap`() { + val state = groupVisibility(group, hidden = setOf(2L)) + assertThat(state).isEqualTo(ToggleableState.Indeterminate) + assertThat(state.nextGroupVisible()).isTrue() + } + + @Test + fun `empty group is off`() { + assertThat(groupVisibility(emptyList(), hidden = emptySet())).isEqualTo(ToggleableState.Off) + } + + @Test + fun `toggling twice from the stored set alternates`() { + val hidden = setOf(9L) + val once = toggledGroup(hidden, group) + assertThat(once).isEqualTo(setOf(1L, 2L, 3L, 9L)) + assertThat(toggledGroup(once, group)).isEqualTo(setOf(9L)) + } + + @Test + fun `toggling a partly shown group shows all`() { + assertThat(toggledGroup(setOf(2L, 9L), group)).isEqualTo(setOf(9L)) + } +} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 771d9bd7..327a8120 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -10,6 +10,32 @@ the package list (recurring writes, save conflicts, reminder delivery). 1. **`CalendarContract` is the single source of truth.** No app database, no caching layer, no sync code. Reads query the provider; writes go straight back to it. Sync is DAVx5's / Google's / the system's job. + The app only *asks* for one through `ContentResolver.requestSync`: an + expedited nudge for the account after each of its own writes to a synced + calendar (#303, once per write, so a multi-row save or an import asks once + per account, and never `MANUAL`, which would override master-sync-off), and + a manual request from the drawer's "Sync now" (#240), which like the + system's own "Sync now" also runs for accounts whose auto-sync is off. Both + go through `SyncRequester` and only ask account types with a calendar sync + adapter (visible to the app via a `` entry). From Android 13 a + request naming an account the app can't see is silently dropped, and + without `GET_ACCOUNTS` that is most of them. Such accounts are not asked at + all (an account-less request would sync every account on the device); the + drawer offers "Allow sync requests" instead, which opens the system account + picker (`AccountManager.newChooseAccountIntent`) — the picked account + becomes visible to the app. Access is re-read on every request and on + every resume and drawer open, so a revoke simply puts the account back behind the + grant row. Per account the user can choose "Don't ask" instead + (`CalendarPrefs.syncAccessDismissed`); such accounts drop out of the grant + row and the receipts, and the calendar manager lists them to ask again. Whether and when the adapter syncs stays its call. + "Sync now" then follows what it asked for through the system's sync state + (`READ_SYNC_STATS`: `isSyncPending` / `isSyncActive` plus a status-change + listener, see `awaitSyncs`): it reports "Sync completed" once every reached + account was seen pending or running and is idle again (or, never seen, is + still idle after a short grace), and only "Sync requested" when that isn't + seen within a minute or the state can't be read. The outcome shows in the + drawer row while the drawer is open; one that lands with the drawer closed + gets the chip. 2. **Observer-driven UI.** A `ContentObserver` on the provider triggers re-queries; every screen recomposes from fresh provider state. After a write, nothing is patched by hand — the views refresh from the provider. @@ -62,7 +88,8 @@ flowchart TD of `data/calendar/` because the receiver needs neither the repository nor its flows. - **`data/prefs/`** — DataStore-backed settings (theme, week start, form - field defaults, reminders toggle) and small state (last-used calendar). + field defaults, default calendar, reminders toggle) and small state + (last-used calendar). - **`ui/`** — one package per screen, each with Screen + ViewModel + UiState. Shared pieces in `ui/common/` (recurrence humanizer, FAB column, drawer, transitions). Selection pickers are full-screen and come from @@ -389,7 +416,113 @@ pre-permission launch); `CalendarVisibilityReconciler` drains it entry by entry, and until it does, the repository and `ReminderNotifier.post` honour it. That gate also covers a snooze re-shown from our own alarm after its calendar was switched off. The drawer's filter sheet (`CalendarPrefs.hiddenCalendarIds`) is a -separate in-app declutter that never touches reminders. +separate in-app declutter that never touches reminders. Narrower still is the per-view hide +(`SettingsPrefs.perCalendarHiddenViews`, #270): each view model asks for its +events through `instancesWithout(range, calendarsHiddenIn(view, …))`, which drops +the calendars hidden in that one view on top of the repository's filters; reminders, search and widgets read +the repository and never see it. The drawer's "Hide in “” view" entry (#517, #143) edits the same +set for the view on show, and the drawer's per-row "Hidden in “” view" notes read it. + +**A channel per calendar (#145).** `ReminderChannels` keeps one notification +channel per calendar, grouped by account (one that syncs no events only gets +its channel once something posts on it), so a calendar can be +muted or given its own sound in the system settings before it ever fires. Every +scan with reminders on syncs them (skipped when nothing changed): missing +channels are created, renamed ones updated, and channels of deleted calendars +removed — but never on an empty snapshot, which is a provider hiccup more often +than every calendar gone. Switched-off calendars keep theirs, so toggling one +never cancels a showing reminder or loses its settings. `post` creates a missing +channel itself, so a reminder never waits on a sync. A new channel copies the sound, vibration and +importance of the pre-#145 single `reminders` channel, which is deleted once +nothing showing still sits on it. Settings → Notifications deep-links into the +system's channel screens for everything but the sound (#340). A sound picked in +the app (#518) can't be set on an existing channel, so +`ReminderChannels.setSound` recreates it under a new version +(`reminders.calendar..v`), copying everything else from the old one. The +current version is simply the highest channel that exists, so the new one only +takes over once written; `SettingsPrefs.reminderChannelVersions` is just a +high-water mark that keeps ids from being reused (a re-used id would bring back +the deleted channel's settings). `setSound` leaves the old version to the sync, +which treats older versions as stale and keeps one while a notification still +shows on it; `ReminderNotifier.post` resolves and posts under the channel lock +(`withChannel`), so a pick never moves a channel mid-post. +Separate from the channels, `SettingsPrefs.mutedReminderCalendarIds` is the in-app per-calendar +off switch (#272): the scan plans nothing for those calendars (so they arm no +wake-ups; toggling it re-scans), and `ReminderNotifier.post` checks it again +for snoozes. The settings screen re-reads `ReminderChannels.status` on every +resume and marks a calendar "Blocked in system settings" when the app, its +channel or its account group is switched off there. + +**Full-screen alerts (#171).** Settings → Notifications gives each calendar an +alert style (`SettingsPrefs.reminderAlertStyles`): a plain notification, a +full-screen alert that sounds once, or one that rings until handled. Only +`ReminderNotifier.post` reads it, and `ReminderChannels.channelFor(id, style)` +picks the channel. "Sound once" stays on the calendar's own channel, so its +sound is still the one chosen in system settings, and adds a full-screen intent +to `ReminderAlertActivity`. "Ring" starts `ReminderRingService`, which goes +foreground on the shared silent `reminders_ring` channel and loops the alarm +sound with vibration through floret-kit's `ring` module — the same player +Clockula's alarms use. One reminder rings at a time; a newer one takes over and +hands the older back to the shade quietly, as does a ring left unanswered for +ten minutes, and switching the calendar away from ringing. Dismiss and Snooze, +from the screen, the notification or a swipe, all go through +`ReminderActionReceiver`, so the ring stops and the screen closes +(`FullScreenAlerts`) however the reminder was handled. Starts and stops reach +the service as commands, so a dismiss sent while a newer ring is on its way +applies in order rather than killing it, and the service re-reads the settings +once a ring arrives, so a style change or mute that raced a scan still wins. A +blocked calendar, account group or ring channel never rings (Settings flags a +blocked ring channel next to each ringing calendar, beside #145's blocked status), the tone pauses +for a phone call, and a ring restarted after a process death only rings out +what was left of its ten minutes. When Android 14+ +withholds `USE_FULL_SCREEN_INTENT`, the intent is left off and the alert is a +heads-up; Settings shows a row leading to the system switch. When Android +refuses the ring service, the reminder falls back to sounding once. + +**Reminders at a set time (#459).** "1 day before at 20:00" on a timed event +is an ordinary `Reminders` row whose offset is the distance from that wall-clock +moment (device zone) to the start, so it syncs and fires everywhere — the scan +plans it like any lead time. Only the editor knows it as a pattern +(`EventForm.fixedReminders`), and it re-derives the offset from the start it +saves with, so moving the event, in the form or by drag, keeps the wall clock. +Reading a row back is a guess, made in one place (`classifyTimedReminder`): an +offset is fixed-time only when it lands on a known pattern — a current or +replaced default, or one saved by hand on this device +(`recentFixedTimeReminders`, capped). Guessing from the offset's shape alone +would turn ordinary leads ("12 hours before") into fixed ones. Limits: where a +lead and a known pattern coincide ("1 day before" on an event at the default's +own time) the pattern wins, and a pattern that falls out of the recents reads as +a lead again — either way the alarm fires at the same moment until the start's +time of day changes. A recurring series stores one offset for all occurrences, +so it counts clock minutes rather than real ones (`wallClock`); the occurrence +whose lead spans a DST change then fires an hour off, as in every other app +reading that row. On another device or app the row is simply a lead time. +New timed events get the default (`SettingsKeys.defaultFixedTimeReminder`, with +a per-calendar inherit/off/value override) like the lead-time defaults. + +**The daily summary (#459)** rides the same scan and watermark: its moment is +due when it falls in `(lastScan, now]` (`scheduleDigest`), only the latest one +counts after a long gap, and it is dropped once the day it lists has passed. +It is independent of the event-reminder switch, posts on its own channel +(`DailyDigestNotifier`), lists switched-on calendars minus its own exclusions, +and replaces the previous summary — or withdraws it when the day is empty. +Each day is listed once: the day is recorded as soon as it is posted +(`ReminderStatePrefs.lastDigestDay`), so neither a pass failing later nor a later +time picked the same evening lists it twice, and changing the switch, time or +day stamps `dailyDigestArmedAt`, so a moment that passed before the change is +not owed by it. A failing summary is logged and skipped; it never costs the +event reminders of the same pass, and a failing reminder pass still arms a retry +and the summary's next moment. Switching between "today's" and "tomorrow's" +events clears the day last listed, so the first summary of the new mode comes. +The notification names its date and times out when that day ends. +Its channel's blocked state is read separately (`DailyDigestNotifier.isChannelOff`, +with the app-wide block from `ReminderChannels.status`); while it is off the +scan neither posts nor records the day, so allowing it brings the summary back. +The channel is created when the summary is switched on, so a phone that starts +new categories off shows it blocked in settings before the first summary. +The per-calendar reminder mute does not apply: a calendar too noisy to ping per +event can still belong in the overview, and the summary has its own +per-calendar switch next to it. Deliberately absent: a fallback to the provider's `EVENT_REMINDER` broadcast. Keeping both would double-post wherever the provider works, and Etar's way out — @@ -462,15 +595,122 @@ after the event — so `toIcsEvent` decodes it back through `fromProviderAllDayMinutes` first, and the importing device re-encodes it against its own setting. -**A backup carries the series' deleted occurrences.** `EXDATE` lives on the -master row, so the export query's `ORIGINAL_ID IS NULL` filter — which does drop -`RECURRENCE-ID` overrides — never hid it; it simply wasn't read. It is now part -of `EventExportProjection`, and `IcsWriter` marks an all-day series' exclusions -`VALUE=DATE`, because RFC 5545 ties `EXDATE`'s value type to `DTSTART`'s and a -bare day code without it reads as a malformed DATE-TIME. Sync adapters disagree -on whether an all-day exclusion is `yyyyMMdd` or a padded midnight stamp, so -`exportExDates` drops the time part on the way out. Without this, an in-app -backup→restore resurrected every occurrence the user had deleted. +**Backups read any calendar; restores still write only into targets.** +`CalendarDataSource.calendarEvents` reads the events of whatever calendar ids it +is given — local, synced or read-only — and leaves the choice to its callers: +export and the automatic backup offer every calendar but the managed mirrors +(#147), defaulting to the writable local ones (`domain/backup/BackupPlan.kt`). A +restore runs through the normal import, whose targets stay `isEventTarget`. The +automatic backup writes one `__