Compare commits

..
Author SHA1 Message Date
makiolaj 2b350e69d5 Release v2.25.0-beta.1
Beta — Codeberg pre-release / detect (push) Successful in 4s
Beta — Codeberg pre-release / beta (push) Successful in 13m19s
2026-11-18 17:44:39 +01:00
makiolaj 71c3a73abf fix(#481): carry the per-calendar settings from #147, #171, #270, #272, #459 and classify the new keys 2026-11-18 17:43:28 +01:00
makiolaj 43e5e67752 Merge feat/481-settings-backup into release/2.25.0
# Conflicts:
#	app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/CalendarPrefs.kt
#	app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/ReminderStatePrefs.kt
#	app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt
#	floret-kit
2026-11-18 16:22:23 +01:00
makiolaj ab88112915 Merge feat/464-notification-map into release/2.25.0
# Conflicts:
#	app/src/main/AndroidManifest.xml
#	app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt
#	floret-kit
2026-11-18 16:21:23 +01:00
makiolaj dae934d136 Merge feat/365-reminder-presets into release/2.25.0 2026-11-18 16:21:03 +01:00
makiolaj 71764ef0b8 Merge feat/429-default-calendar into release/2.25.0
# Conflicts:
#	app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefs.kt
#	app/src/main/java/de/jeanlucmakiola/calendula/domain/EventForm.kt
#	app/src/main/java/de/jeanlucmakiola/calendula/ui/common/EventActionsViewModel.kt
#	app/src/main/java/de/jeanlucmakiola/calendula/ui/detail/EventDetailViewModel.kt
#	app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt
#	app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt
#	app/src/test/java/de/jeanlucmakiola/calendula/ui/edit/EventEditViewModelTest.kt
2026-11-18 16:19:23 +01:00
makiolaj c9ee36cec5 Merge feat/143-group-toggle into release/2.25.0
# Conflicts:
#	app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/CalendarFilterList.kt
#	app/src/main/java/de/jeanlucmakiola/calendula/ui/filter/FilterViewModel.kt
2026-11-18 16:18:21 +01:00
makiolaj 23adec2122 Merge feat/270-per-view-hide into release/2.25.0
# Conflicts:
#	app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefs.kt
#	app/src/main/java/de/jeanlucmakiola/calendula/ui/CalendarHost.kt
#	app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsScreen.kt
#	floret-kit
2026-11-18 16:17:35 +01:00
makiolaj e22befd4c2 Merge feat/240-manual-sync into release/2.25.0
# Conflicts:
#	app/src/main/AndroidManifest.xml
#	app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt
#	docs/PRIVACY.md
2026-11-18 16:17:04 +01:00
makiolaj 55dfb08aa3 Merge feat/516-backup-on-change into release/2.25.0
# Conflicts:
#	app/src/main/java/de/jeanlucmakiola/calendula/data/backup/AutoBackup.kt
2026-11-18 16:16:18 +01:00
makiolaj 3bc2240407 Merge feat/325-copy-events into release/2.25.0
# Conflicts:
#	floret-kit
2026-11-18 16:15:43 +01:00
makiolaj e46891ae87 Merge feat/147-backup-caldav-per-calendar into release/2.25.0
# Conflicts:
#	app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt
#	floret-kit
2026-11-18 16:15:43 +01:00
makiolaj a110e84119 Merge feat/518-ringtone-picker into release/2.25.0
# Conflicts:
#	app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt
#	app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt
#	app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/CalendarReminderSettings.kt
#	app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt
#	app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt
#	app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt
#	app/src/main/res/values/strings.xml
#	app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt
#	app/src/test/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlanTest.kt
#	floret-kit
2026-11-18 16:15:28 +01:00
makiolaj c2a667725b Merge feat/459-fixed-time-reminders into release/2.25.0
# Conflicts:
#	app/src/main/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefs.kt
#	app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/CalendarReminderSettings.kt
#	app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt
#	app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt
#	app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt
#	docs/ARCHITECTURE.md
2026-11-18 16:11:26 +01:00
makiolaj d46d795741 Merge feat/171-fullscreen-alerts into release/2.25.0
# Conflicts:
#	floret-kit
2026-11-18 16:11:01 +01:00
makiolaj 981a966b82 Merge feat/145-per-calendar-notifications into release/2.25.0 2026-11-18 16:11:01 +01:00
makiolaj ce31e506f8 Merge feat/145-per-calendar-notifications into feat/518-ringtone-picker 2026-11-16 21:39:21 +01:00
makiolaj 74549b2ec0 fix(#518): retire the old channel versions right after a sound pick 2026-11-16 21:05:39 +01:00
makiolaj e5a5c10dea fix(#464): an Open link button for reminders whose location is a web link 2026-11-16 20:43:43 +01:00
makiolaj e8d651fe96 fix(#143): the group header itself toggles, without a checkbox of its own 2026-11-16 20:32:26 +01:00
makiolaj 524c4cbb90 fix(#240): a failed read of the sync targets is retried instead of hiding Sync now 2026-11-16 20:24:30 +01:00
makiolaj 1bd055a0b7 fix(#240): Sync now shows the real sync state in the drawer, chip only when closed 2026-11-16 20:20:30 +01:00
makiolaj 2c3e909515 fix(#325): end-of-flow buttons as the app's primary + text button pair 2026-11-16 20:13:15 +01:00
makiolaj 5e03916d12 fix(#240): keep the drawer open after Sync now 2026-11-16 20:03:33 +01:00
makiolaj ec060056dd fix(#325): copy events as a full-screen two-step flow with a route card 2026-11-16 20:01:01 +01:00
makiolaj e23a87c672 Merge feat/145-per-calendar-notifications into feat/459-fixed-time-reminders 2026-11-16 19:52:31 +01:00
makiolaj ed72920da1 fix(#171): stack the alert's large buttons so their labels fit 2026-11-16 19:31:48 +01:00
makiolaj 84acc33bd6 Merge feat/145-per-calendar-notifications into feat/171-fullscreen-alerts 2026-11-16 19:21:54 +01:00
makiolaj efe454f200 fix(#145): an expanded calendar's options round off with a gap below 2026-11-16 19:18:47 +01:00
makiolaj 0884288d8f fix(#147, #411): stable copy owner wins a shared name, suffixed series keep their suffix 2026-11-16 19:17:11 +01:00
makiolaj b1ff5912fc fix(#147, #411): the calendar already owning a name keeps it when another one shares it 2026-11-16 19:10:05 +01:00
makiolaj 10e18ef888 fix(#145): an expanded calendar closes off its own rounded run 2026-11-16 19:09:00 +01:00
makiolaj 14f2dfe158 fix(#145): per-calendar reminders on their own grouped subpage 2026-11-16 18:52:19 +01:00
makiolaj 00a8040efe fix(#516): review round 12 - a watch that fails early is retried 2026-11-14 13:17:13 +01:00
makiolaj 07a2bb632f fix(#516): review round 11 - watch re-armed even when queueing fails or the job is stopped, reconcile off the main thread 2026-11-14 13:05:20 +01:00
makiolaj 281d511402 fix(#516): WorkManager's JobScheduler ids kept below the change watch's 2026-11-14 12:55:49 +01:00
makiolaj ad5f0f4662 fix(#516): review round 10 - the change watch is one JobScheduler job that re-arms itself, startup reconcile can't crash the app 2026-11-14 12:53:58 +01:00
makiolaj a902f5f862 fix(#516): review round 9 - one rule keeps exactly one watch waiting, retired copies lose their hash 2026-11-14 12:42:26 +01:00
makiolaj 783916e3a7 fix(#516): review round 8 - one watch stays armed after runs fire together, notification decided under the lock, lists sorted before ordering 2026-11-14 12:31:41 +01:00
makiolaj 09c20ee90f fix(#516): review round 7 - re-arm queues behind a running slot, hashes only while the option is on, one series in memory at a time 2026-11-14 12:19:24 +01:00
makiolaj fb178a779e fix(#516): review round 6 - early exit holds for blocked and renamed copies, only changed texts kept, run time taken under the lock 2026-11-14 12:11:19 +01:00
makiolaj 95c40c9d88 fix(#517): review round 2 - back off failed pref reads, one derivation for the drawer's hidden-in-view set 2026-11-14 12:09:19 +01:00
makiolaj 34cd75e9a3 fix(#516): review round 5 - hash bound to the copy's name, folder untouched when nothing moved, re-arm under the reconcile lock 2026-11-14 12:03:23 +01:00
makiolaj 8df21b965a fix(#517): review round 1 - keep reading after a failed pref read, drawer count and notes agree, entry row not 'selected' 2026-11-14 12:00:29 +01:00
makiolaj 6758b7fada feat(#516): change runs report on the status line, failure notified once per streak 2026-11-14 11:53:08 +01:00
makiolaj 1aa66ffc99 feat(#517): move the per-view hide entry from the top bar into the drawer 2026-11-14 11:52:48 +01:00
makiolaj d39ceb9ee0 fix(#518): review round 4 — silent channels read as silent, honest pick results, clearer failures 2026-11-14 04:21:27 +01:00
makiolaj 70f72d03db fix(#516): review round 4 - hash dropped before a stable copy is rewritten, overrides stay first in the backup order 2026-11-14 04:17:57 +01:00
makiolaj 081675906b fix(#518): review round 3 — post under the channel lock, refuse unreadable sounds, audible importance 2026-11-14 04:13:36 +01:00
makiolaj dca98bbb2d fix(#516): review round 3 - change runs stay off the status, unlisted copies don't retire the old layout, stable export order for the hash 2026-11-14 04:09:05 +01:00
makiolaj 661300728a fix(#518): review round 2 — late channel resolve, failure feedback, no sound flash, safer picks 2026-11-14 04:06:32 +01:00
makiolaj 93b795ed72 fix(#516): review round 2 - serialised reconcile, change runs skip copies a loading listing hides, failed copies lose their hash, change-run failures reported 2026-11-14 04:01:14 +01:00
makiolaj 18b9f19a61 fix(#518): review round 1 — current version from existing channels, batched picks, silent vs unset 2026-11-14 03:57:51 +01:00
makiolaj 6b108fb585 feat(#518): pick the reminder sound in the app via versioned channels 2026-11-14 03:48:53 +01:00
makiolaj f18ae694a7 fix(#516): review round 1 - two watch slots so changes during a run count, change runs stay off the status line, one serialisation per series 2026-11-14 03:47:47 +01:00
makiolaj d5b51f2c01 fix(#517): review round 3 - close picker in each request handler, keep hidden set alive across page swaps 2026-11-14 03:41:14 +01:00
makiolaj b2498d362b feat(#516): back up after changes, refreshing the stable copies 2026-11-14 03:39:16 +01:00
makiolaj 8e99c46f3e fix(#515, #325): review round 4 - declined rows dropped by row, not by UID 2026-11-14 03:31:47 +01:00
makiolaj dda0164c9f fix(#517): review round 2 - close picker for every external request, clearer title, provider write first 2026-11-14 03:31:43 +01:00
makiolaj 1e83000696 fix(#515, #325): review round 3 - bare-day EXDATE/RDATE on timed series resolved when read, unaccepted occurrences of declined series not copied 2026-11-14 03:22:45 +01:00
makiolaj bbcb8e00ed fix(#517): review round 1 - close picker on external navigation, proper load/failure states, wait for stored hidden views 2026-11-14 03:22:35 +01:00
makiolaj d943937b3a feat(#517): quick per-view calendar toggle in the top bar 2026-11-14 03:14:47 +01:00
makiolaj 05887d2ed0 fix(#515, #325): review round 2 - multi-line and unreadable EXDATE handled, imports all or nothing per event, running copy survives list failures 2026-11-14 03:12:43 +01:00
makiolaj f181ae7ac9 fix(#171): merge review - ring channel up front, held-back status in the calendar header, silenced calendars stop a live ring 2026-11-14 03:10:20 +01:00
makiolaj 04f3b7ec8f Merge feat/145-per-calendar-notifications into feat/171-fullscreen-alerts 2026-11-14 03:04:24 +01:00
makiolaj 028d8d0e1e fix(#515, #325): review round 1 - multi-line RDATE, accepted occurrences of declined series copied, partial copies say so 2026-11-14 03:01:37 +01:00
makiolaj d1880d04b2 fix(#459): post-merge review — summary channel under #145's blocked status, deep-link and Samsung hint 2026-11-14 03:00:14 +01:00
makiolaj 05ac15f63c Merge feat/145-per-calendar-notifications into feat/459-fixed-time-reminders 2026-11-14 02:54:28 +01:00
makiolaj 30af150197 feat(#515): write RDATE into .ics backups and read it back 2026-11-14 02:51:25 +01:00
makiolaj 31ba82a295 fix(#145): review round C — no replay on unmute, fallback channel on write failure, hide pending-off calendars 2026-11-14 02:50:36 +01:00
makiolaj 0345b6a713 fix(#514): import prompt offers the default for the current all-day state 2026-11-14 02:45:12 +01:00
makiolaj 99a584a82d fix(#145): review round B — fresh status for the sound deep-link, one tested status function, no hint flash 2026-11-14 02:42:22 +01:00
makiolaj f1554fbcf3 fix(#514): re-encode reminders when an existing event switches all-day 2026-11-14 02:39:26 +01:00
makiolaj 2e71e4dc5f fix(#145): review round A — group-blocked deep-link, status refresh race, hint dismiss on open 2026-11-14 02:34:07 +01:00
makiolaj 6a384b03e9 refactor(#514): one firing-reminders view for the editor and the import prompt 2026-11-14 02:33:38 +01:00
makiolaj 738a28fc0a fix(#514): show all-day reminders as the day they fire on 2026-11-14 02:26:39 +01:00
makiolaj 955dccff2b feat(#145): show calendars blocked in system settings, one-time Samsung category hint 2026-11-14 02:25:34 +01:00
makiolaj 041f8ec2f7 fix(#147, #325): review round 4 - standalone occurrences imported first in any file order, copy sheet independent of the list state 2026-11-14 01:50:22 +01:00
makiolaj 10208a332e fix(#147, #325): review round 3 - a failed moved occurrence stays at its old time, declined occurrences not copied, unlinked rows kept 2026-11-14 01:41:31 +01:00
makiolaj 0a36a6d287 fix(#147, #325): review round 2 - empty sync-id masters kept, series held when its occurrence fails, declined invites not copied 2026-11-14 01:32:21 +01:00
makiolaj d5079f0618 fix(#147, #325): review round 1 - overrides per calendar, RDATE-only series in files, chosen colours kept, copy row stays while running 2026-11-14 01:23:45 +01:00
makiolaj 3ed56b8596 fix(#147, #325): backups keep moved and deleted occurrences of synced series 2026-11-14 01:15:46 +01:00
makiolaj 1e2ed15e82 refactor(#365): drop picker-side day rounding, placeholder follows the selected unit 2026-11-14 01:13:15 +01:00
makiolaj 145ef6c6bf refactor(#240): one access refresh in the repository, loading state in the access sheet 2026-11-14 01:09:00 +01:00
makiolaj 08d2452c51 fix(#365): keep the default-reminder sentinel out of day rounding 2026-11-14 01:08:22 +01:00
makiolaj 126f1d51ef fix(#365): no duplicate day reminders on all-day events, one placeholder rule 2026-11-14 01:06:06 +01:00
makiolaj 6161efab40 fix(#240): access sheet waits for the first read, manager re-reads access, shared account row 2026-11-14 01:02:58 +01:00
makiolaj 9ed6bbbe8e fix(#365): day-sized custom placeholder in all-day default pickers 2026-11-14 01:01:07 +01:00
makiolaj a6ff2c06ef Revert "fix(#365): round reminders to whole days when an event turns all-day"
This reverts commit b1e03db27c.
2026-11-14 00:58:17 +01:00
makiolaj 34e8e8571c fix(#240): list only dismissals that still apply, keep the access sheet across recreation 2026-11-14 00:56:47 +01:00
makiolaj b1e03db27c fix(#365): round reminders to whole days when an event turns all-day 2026-11-14 00:55:16 +01:00
makiolaj a026f24bed feat(#240): per-account Don't ask for sync access, undone from the calendar manager 2026-11-14 00:51:00 +01:00
makiolaj 2c71b7da4a fix(#365): day-sized custom placeholder on all-day events 2026-11-14 00:49:48 +01:00
makiolaj 2dbc4c49b7 fix(#365): all-day custom reminders offer only days and weeks 2026-11-14 00:49:32 +01:00
makiolaj 3f4bf65b1a fix(#325): review round 3 - sheet failure state, unlinkable exceptions treated as the backup does, one-row colour lookup 2026-11-13 22:28:12 +01:00
makiolaj 026970501e fix(#325): review round 2 - cancelled and orphaned rows left out, re-runs add no duplicate overrides, stopped copies say so 2026-11-13 22:28:12 +01:00
makiolaj 46882d154e fix(#325): review round 1 - visibility and RDATE copied, cancel only stops a copy, sources need a target 2026-11-13 22:28:12 +01:00
makiolaj e5d9b4965b feat(#325): copy events from one calendar into another 2026-11-13 22:28:12 +01:00
makiolaj c6901c9c63 fix(#147, #411): review round 8 - hand-offs end once claimed, back up only after a real settings change 2026-11-13 22:27:10 +01:00
makiolaj 8754f046f2 fix(#147, #411): review round 7 - stable copy ownership on provider renames and hand-offs, ledger writes tied to their folder, back up after settings change 2026-11-13 22:20:58 +01:00
makiolaj 14a0725b21 refactor(#240): grant-flow state in its own helper, clearer receipt when accounts need access 2026-11-13 22:18:09 +01:00
makiolaj bb075d052e fix(#147, #411): review round 6 - ledger reset per folder, atomic ledger updates, stable copies replaced only once the new one landed 2026-11-13 22:14:34 +01:00
makiolaj e88ad7f533 fix(#240): guard double picker launch, flag skipped accounts in the receipt, translatable grant summary 2026-11-13 22:10:04 +01:00
makiolaj 5c05563785 fix(#147, #411): review round 5 - stable copy ownership per series, best-effort writes, layout-switch cleanup 2026-11-13 22:06:46 +01:00
makiolaj 67052352ac fix(#240): access re-read on resume, needs-access receipt, drawer stays open for the next grant 2026-11-13 22:04:44 +01:00
makiolaj 88de8f42b0 feat(#240, #303): grant account access for sync requests instead of an account-less fallback 2026-11-13 21:57:55 +01:00
makiolaj 88c64d5786 feat(#147, #411): stable undated latest copy per backup series 2026-11-13 21:56:54 +01:00
makiolaj 328c874670 fix(#464): keep the detail screen's maps fallback, only skip http(s) link locations 2026-11-13 21:44:50 +01:00
makiolaj 50e1c4e25e fix(#464): skip meeting-link locations, share the maps resolve with the detail screen 2026-11-13 21:39:54 +01:00
makiolaj c03dba9f90 refactor(#464): maps intents in floret-kit, skip link-only locations 2026-11-13 21:35:59 +01:00
makiolaj 5394898af7 feat(#464): open in maps action on reminder notifications 2026-11-13 21:31:35 +01:00
makiolaj d05af5d765 refactor(#365): one rule for reminder grouping and preset choice 2026-11-13 21:26:18 +01:00
makiolaj 739c5f2a50 fix(#481): mirror reminder rewrite against what events carry, duplicate identities, clean reminder lists 2026-11-13 21:25:52 +01:00
makiolaj 2269c2648b fix(#365): stable reminder grouping, keyed rows, shared preset choice 2026-11-13 21:21:17 +01:00
makiolaj fe7a4b4719 fix(#481): rewrite changed mirror reminders, no empty keys, require settings section 2026-11-13 21:17:59 +01:00
makiolaj 5e7918f105 refactor(#365): share grouped lead-time rows, keep all-day list in one group 2026-11-13 21:16:40 +01:00
makiolaj 2a452125eb feat(#365): more day and week reminder presets 2026-11-13 21:11:19 +01:00
makiolaj 47f3844d75 fix(#481): snackbar feedback, uncancellable import, mirror per-type matching, progress 2026-11-13 21:09:06 +01:00
makiolaj f2b27bf6ac fix(#429): keep a requested colour while calendars load, tidy settings state 2026-11-13 21:07:05 +01:00
Jean-Luc Makiola 44ccc15341 Run the Play job on trixie for fastlane's Ruby requirement (#512)
Beta — Codeberg pre-release / detect (push) Successful in 5s
Beta — Codeberg pre-release / beta (push) Skipped
2026-11-13 21:01:54 +01:00
makiolaj 6e1bbf8ec4 fix(#429): drop a requested calendar's colour in one place, pin the shown calendar on colour picks 2026-11-13 19:47:29 +01:00
makiolaj 5ee25c2115 fix(#481): keep per-calendar settings when calendars can't be read, re-apply mirror reminders 2026-11-13 19:46:32 +01:00
makiolaj 38e7910d3c fix(#429): duplicates keep only target calendars, re-picking the shown calendar is no change 2026-11-13 19:41:11 +01:00
makiolaj 90b640054a feat(#481): export and import settings in Backup & restore 2026-11-13 19:39:47 +01:00
makiolaj aa1ce0405a fix(#429): keep the default across renames and restores, drop a duplicate's colour off its calendar 2026-11-13 19:34:27 +01:00
makiolaj 6a9274402a fix(#429): only preselect target calendars, key the default by account and name 2026-11-13 19:26:47 +01:00
makiolaj 9511444c6b fix(#143): review round 3 — rows toggle against the stored set too 2026-11-13 19:20:45 +01:00
makiolaj 9577e6c0c8 feat(#429): default calendar for new events 2026-11-13 19:20:07 +01:00
makiolaj 4186640a63 fix(#143): review round 2 — decide group toggle from the stored set 2026-11-13 19:16:54 +01:00
makiolaj 22173be22e fix(#143): review round 1 — empty group state, inset header ripple, prefs test 2026-11-13 19:12:52 +01:00
makiolaj dad1f2cd9c fix(#270): review round 3 - one write per editor save, best-effort pref tidy-up 2026-11-13 19:11:33 +01:00
makiolaj 60166b349d feat(#143): toggle a whole calendar group from its drawer header 2026-11-13 19:07:41 +01:00
makiolaj db8d649467 fix(#270): review round 2 - safe pref reads, diff-only editor saves, optimistic picker 2026-11-13 19:04:25 +01:00
makiolaj 8c31e0f6ee fix(#303): nudge after failed writes again, per-type account visibility 2026-11-13 19:04:07 +01:00
makiolaj 1688b206a5 fix(#303, #240): one account-less request when any account is hidden, nudge only after a successful write 2026-11-13 18:58:19 +01:00
makiolaj 91fdaba6a2 fix(#270): review round 1 - atomic toggles, no stale editor write, shared per-view filter 2026-11-13 18:54:10 +01:00
makiolaj 55934664e2 fix(#303, #240): fall back to an account-less request for accounts the app can't see 2026-11-13 18:52:42 +01:00
makiolaj e3e9865d3f feat(#270): hide calendars in chosen views 2026-11-13 18:45:17 +01:00
makiolaj d1c601a6e2 fix(#303, #240): see sync adapters behind package visibility, review fixes 2026-11-13 18:44:49 +01:00
makiolaj 13e4908c1e fix(#459): review round 4 — dated summary that times out, mode switch lists afresh, cancel after the scan, no lead doubling a set-time reminder 2026-11-13 18:37:22 +01:00
makiolaj 1dcbffd6f2 fix(#303, #240): only ask accounts with a calendar sync adapter, review fixes 2026-11-13 18:35:03 +01:00
makiolaj c353ac8072 fix(#459): review round 3 — two-week cap, one-off offsets for single occurrences, one summary per listed day, commit from the picker's actions 2026-11-13 18:27:52 +01:00
makiolaj fb5cb226ee feat(#303, #240): nudge sync adapters after writes, add Sync now to the drawer 2026-11-13 18:27:51 +01:00
makiolaj 7361e8d98e fix(#171): review round 6 - mark the redeliverable start done on takeover 2026-11-13 18:18:04 +01:00
makiolaj 741e1e9a65 fix(#459): review round 2 — clock-minute offsets for series, keep replaced defaults known, record summaries by moment 2026-11-13 18:14:44 +01:00
makiolaj 9178828b41 fix(#171): review round 5 - hand back on a hidden ring, counted pending starts, keep the first start's redelivery 2026-11-13 18:13:27 +01:00
makiolaj 0b6cdf992e fix(#171): review round 4 - targeted ring stops, verdict before any sound, stop when the ring notification is hidden, no re-ring of a handed-back reminder 2026-11-13 18:06:17 +01:00
makiolaj 589f2c3862 fix(#459): review round 1 — known patterns only, one summary per day, keep set-time reminders through all-day and copies 2026-11-13 18:02:03 +01:00
makiolaj 014d31f9b9 fix(#171): review round 3 - re-check settings in the ring, follow calls, anchored timeout, close the screen on every stop 2026-11-13 17:56:11 +01:00
makiolaj c28582ae6f feat(#459): reminders at a set time and a daily summary notification 2026-11-13 17:50:21 +01:00
makiolaj 4287862f47 chore(#171): floret-kit ring fixes 2026-11-13 17:45:25 +01:00
makiolaj 6cf6a6fdbf fix(#171): review round 2 - ordered ring commands, hand-back that outlives the service, in-call and blocked-group checks, scrolling alert screen 2026-11-13 17:33:26 +01:00
makiolaj d2b6637f72 chore(#171): floret-kit ring review fixes 2026-11-13 17:20:13 +01:00
makiolaj 0b223f53fc fix(#171): review round 1 - ring ids, hand-back off the main thread, blocked channels, closing the alert screen 2026-11-13 17:12:03 +01:00
makiolaj c52c6c54cc feat(#171): full-screen reminder alerts per calendar 2026-11-13 17:00:46 +01:00
makiolaj d86a09b744 fix(#147, #411): review round 4 - settings read under the run lock, ledger saved before pruning, SAF helpers moved to floret-kit 2026-11-13 16:54:48 +01:00
makiolaj f314761e45 fix(#147, #411): review round 3 - serialised runs, per-series ledger saves, folder change resets ledger 2026-11-13 16:46:38 +01:00
makiolaj 46818cd0ae fix(#147, #411): review round 2 - prune from a ledger of written files, one read per run 2026-11-13 16:38:06 +01:00
makiolaj fa999f8cf0 fix(#145): review round 3 — rescan on mute, serialise channel writes, never drop a reminder for its channel 2026-11-13 16:37:11 +01:00
makiolaj 515c7c3d26 fix(#145): review round 2 — guard empty snapshots and the post path, skip muted calendars in the scan 2026-11-13 16:29:34 +01:00
makiolaj 240ed5237a fix(#147, #411): review round 1 - unique series names, rename-aware pruning, one folder listing, batched reminders 2026-11-13 16:28:42 +01:00
makiolaj 9b5880b719 fix(#145): review round 1 — vibration carry-over, cheaper channel sync, shared account grouping 2026-11-13 16:23:08 +01:00
makiolaj deb2fd4482 feat(#147, #411): automatic backup of chosen calendars, one dated file each 2026-11-13 16:18:53 +01:00
makiolaj 994fc1026f feat(#145, #272, #340): per-calendar reminder channels, in-app mute and sound deep-links 2026-11-13 16:14:54 +01:00
makiolaj e9cf7d66ba Release v2.24.2
Beta — Codeberg pre-release / detect (push) Successful in 4s
Beta — Codeberg pre-release / beta (push) Skipped
2026-11-13 15:51:08 +01:00
Jean-Luc Makiola e01d6efb84 Merge pull request 'chore(deps): update ghcr.io/renovatebot/renovate docker tag to v44' (#510) from deps/renovate-44 into release/2.24.2 2026-11-13 15:43:14 +01:00
Jean-Luc Makiola b7c801c8db Merge pull request 'chore(deps): update dependency fastlane to v2.241.1' (#509) from deps/fastlane into release/2.24.2 2026-11-13 15:42:26 +01:00
Jean-Luc Makiola b15e90cc64 Merge pull request 'fix(deps): update appcompat to v1.8.0' (#508) from deps/appcompat into release/2.24.2 2026-11-13 15:17:14 +01:00
Jean-Luc Makiola 8d3be6aba3 Merge pull request 'fix(deps): update kotlinxdatetime to v0.8.0-0.6.x-compat' (#507) from deps/kotlinxdatetime into release/2.24.2 2026-11-13 15:14:40 +01:00
renovate-bot 464ae8952e chore(deps): update ghcr.io/renovatebot/renovate docker tag to v44 2026-11-13 14:13:53 +01:00
renovate-bot 2007541adf chore(deps): update dependency fastlane to v2.241.1 2026-11-13 14:13:53 +01:00
renovate-bot d6167617a9 fix(deps): update appcompat to v1.8.0 2026-11-13 14:13:53 +01:00
renovate-bot 38d7c1494d fix(deps): update kotlinxdatetime to v0.8.0-0.6.x-compat 2026-11-13 14:13:53 +01:00
Jean-Luc Makiola c0c0d56e86 Merge pull request 'Queue drops instead of silently dropping them (#494)' (#506) from fix/494-queued-drop into release/2.24.2 2026-11-13 14:09:14 +01:00
Jean-Luc Makiolaandmakiolaj 745301d14b Day view: title names the month (#501) (#505)
Beta — Codeberg pre-release / detect (push) Successful in 6s
Beta — Codeberg pre-release / beta (push) Skipped
The day view's top bar now shows the month name (e.g. "November", abbreviated when space is short, with the year outside the current year), the same as the week and 3-day views. Weekday and date already sit in the column header right below, so the old title repeated them.

Closes #501

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/505
2026-11-13 13:37:38 +01:00
makiolaj 8d640b595e Third review round: undo by drop, queued chip messages, recent-write stale check, held strip and seat (#494) 2026-11-13 13:30:49 +01:00
makiolaj 1925e1c2f4 Hold every dropped copy until its own write lands, cancel drops behind a dialog, keep the first Undo (#494) 2026-11-13 13:18:11 +01:00
makiolaj 0595124ecd Drops follow their event if it moved, failures stay on the chip (#494) 2026-11-13 12:45:48 +01:00
makiolaj 8e3202d1ad Give every drop its own token and queue drops in order (#494) 2026-11-13 12:00:37 +01:00
makiolaj 5f8eb39206 Queue a drop made while another move is still saving (#494) 2026-11-13 11:27:46 +01:00
makiolaj e7bf700f36 Release v2.24.1
Beta — Codeberg pre-release / detect (push) Successful in 6s
Beta — Codeberg pre-release / beta (push) Skipped
2026-11-12 15:57:47 +01:00
makiolaj c10342818a Merge Weblate translations (#434) 2026-11-12 15:56:26 +01:00
Weblate 0f29dc4db6 Update translation files
Updated by "Remove blank strings" add-on in Weblate.

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/
2026-11-12 14:52:53 +00:00
Anonymous 80fae240da Translated using Weblate (Chinese (Traditional Han script))
Currently translated at 3.9% (27 of 678 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/zh_Hant/
2026-11-12 14:52:48 +00:00
Anonymous ab2e11a2e4 Translated using Weblate (Dutch)
Currently translated at 100.0% (678 of 678 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/nl/
2026-11-12 14:52:38 +00:00
Anonymous fb4fd17603 Translated using Weblate (Hungarian)
Currently translated at 9.2% (63 of 678 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/hu/
2026-11-12 14:52:28 +00:00
Anonymous 86f7637213 Translated using Weblate (Slovak)
Currently translated at 36.8% (250 of 678 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/sk/
2026-11-12 14:52:17 +00:00
Anonymous c5084b86af Translated using Weblate (Belarusian)
Currently translated at 93.2% (632 of 678 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/be/
2026-11-12 14:52:11 +00:00
Dmitri Gabinski 919b95c378 Translated using Weblate (Belarusian)
Currently translated at 93.2% (632 of 678 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/be/
2026-11-12 14:52:10 +00:00
Anonymous ec7db10601 Translated using Weblate (Czech)
Currently translated at 100.0% (678 of 678 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/cs/
2026-11-12 14:52:01 +00:00
Anonymous 73403ee799 Translated using Weblate (Japanese)
Currently translated at 17.1% (116 of 678 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/ja/
2026-11-12 14:51:50 +00:00
Anonymous a294542eda Translated using Weblate (Portuguese (Brazil))
Currently translated at 84.0% (570 of 678 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/pt_BR/
2026-11-12 14:51:35 +00:00
Anonymous 786bde2965 Translated using Weblate (Arabic)
Currently translated at 100.0% (678 of 678 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/ar/
2026-11-12 14:51:33 +00:00
Sup99999 e2ac8bbdc7 Translated using Weblate (Arabic)
Currently translated at 100.0% (678 of 678 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/ar/
2026-11-12 14:51:33 +00:00
Anonymous 673cfc2f99 Translated using Weblate (Chinese (Simplified Han script))
Currently translated at 83.6% (567 of 678 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/zh_Hans/
2026-11-12 14:51:23 +00:00
Anonymous c533cc0439 Translated using Weblate (Russian)
Currently translated at 37.7% (256 of 678 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/ru/
2026-11-12 14:51:12 +00:00
Anonymous 7a49dffe0d Translated using Weblate (Portuguese)
Currently translated at 67.1% (455 of 678 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/pt/
2026-11-12 14:51:05 +00:00
Anonymous e6ab85d382 Translated using Weblate (Polish)
Currently translated at 83.6% (567 of 678 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/pl/
2026-11-12 14:50:55 +00:00
Anonymous 011356e103 Translated using Weblate (Italian)
Currently translated at 100.0% (678 of 678 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/it/
2026-11-12 14:50:45 +00:00
Anonymous c8595ccedd Translated using Weblate (French)
Currently translated at 87.0% (590 of 678 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/fr/
2026-11-12 14:50:33 +00:00
Louis Leblanc 9e1fd2956d Translated using Weblate (French)
Currently translated at 87.0% (590 of 678 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/fr/
2026-11-12 14:50:32 +00:00
Anonymous 6a1697dc5a Translated using Weblate (Spanish)
Currently translated at 61.5% (417 of 678 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/es/
2026-11-12 14:50:20 +00:00
Anonymous 2641145b60 Translated using Weblate (German)
Currently translated at 100.0% (678 of 678 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/de/
2026-11-12 14:50:15 +00:00
Sup99999 70a7bf1033 Translated using Weblate (Arabic)
Beta — Codeberg pre-release / detect (push) Successful in 5s
Beta — Codeberg pre-release / beta (push) Skipped
Currently translated at 100.0% (678 of 678 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/ar/
2026-11-12 15:47:40 +01:00
Jean-Luc Makiola a92dd013bc Merge pull request 'Widgets: readable dimmed events, pinned theme matches system (#475)' (#500) from fix/475-widget-feedback into release/2.24.1
Beta — Codeberg pre-release / detect (push) Successful in 5s
Beta — Codeberg pre-release / beta (push) Skipped
2026-11-09 21:06:55 +01:00
makiolaj 6d6baf3f35 Merge remote-tracking branch 'origin/release/2.24.1' into fix/475-widget-feedback
# Conflicts:
#	app/src/main/java/de/jeanlucmakiola/calendula/widget/agenda/AgendaWidget.kt
#	floret-kit
2026-11-09 21:05:08 +01:00
Jean-Luc Makiola 72f2b33754 Merge pull request 'Classic agenda widget style and widget opacity (#489)' (#499) from feat/489-classic-agenda into release/2.24.1
Beta — Codeberg pre-release / detect (push) Successful in 5s
Beta — Codeberg pre-release / beta (push) Skipped
2026-11-09 21:03:28 +01:00
makiolaj 89a456f88c Merge remote-tracking branch 'origin/release/2.24.1' into feat/489-classic-agenda
# Conflicts:
#	floret-kit
2026-11-09 21:00:56 +01:00
Jean-Luc Makiola d98d995326 Merge pull request 'Month widget fits events into short weeks (#491)' (#498) from fix/491-month-widget-lanes into release/2.24.1
Beta — Codeberg pre-release / detect (push) Successful in 5s
Beta — Codeberg pre-release / beta (push) Skipped
2026-11-09 20:59:40 +01:00
makiolaj 20a76f1921 Merge remote-tracking branch 'origin/release/2.24.1' into fix/491-month-widget-lanes 2026-11-09 20:57:47 +01:00
Jean-Luc Makiola 0c4a7992a7 Merge pull request 'Week numbers follow the locale and the row's first day (#493)' (#497) from fix/493-week-number into release/2.24.1
Beta — Codeberg pre-release / detect (push) Successful in 5s
Beta — Codeberg pre-release / beta (push) Skipped
2026-11-09 20:57:05 +01:00
makiolaj 5e6b88fa31 Bump floret-kit to main (#493) 2026-11-09 20:55:04 +01:00
makiolaj d8735cc738 Merge remote-tracking branch 'origin/release/2.24.1' into fix/493-week-number 2026-11-09 20:54:51 +01:00
Jean-Luc Makiola 185671adb5 Merge pull request 'Drop unused WorkManager permissions (#448)' (#496) from fix/448-library-permissions into release/2.24.1
Beta — Codeberg pre-release / detect (push) Successful in 5s
Beta — Codeberg pre-release / beta (push) Skipped
2026-11-09 20:54:14 +01:00
makiolaj ee268444b7 Widgets: readable dimmed events, pinned theme matches system (#475) 2026-11-09 20:41:20 +01:00
makiolaj 9387bdc1ee Drop unused WorkManager permissions (#448) 2026-11-09 20:32:00 +01:00
makiolaj 7cfdb43f37 Widget config: readability info as a popover beside Opacity (#489) 2026-11-09 20:18:14 +01:00
makiolaj 06f658917f Classic agenda: invert text colour instead of backings at low opacity (#489) 2026-11-09 20:07:18 +01:00
makiolaj 88d5614158 Bump floret-kit: inset opacity slider row (#489) 2026-11-09 19:58:15 +01:00
makiolaj f896153fb7 Classic agenda: readable dimming on any fill, year on far dates (#489) 2026-11-09 19:27:27 +01:00
makiolaj 1004356e75 Month widget: day totals from countByDay, test split bars (#491) 2026-11-09 19:24:57 +01:00
makiolaj 77b0c6db09 Week numbers follow the device region, shared helper (#493) 2026-11-09 19:22:55 +01:00
makiolaj dec2d1cb05 Month widget: one lane shows bars and per-day counts (#491) 2026-11-09 19:17:57 +01:00
makiolaj 76314aebbd Number weeks by the locale's rules (#493) 2026-11-09 19:15:00 +01:00
makiolaj 7d149d2ab1 Classic agenda: back rows when the fill is see-through (#489) 2026-11-09 19:11:54 +01:00
makiolaj ff4082d5df Classic agenda: line day labels up with the card rows (#489) 2026-11-09 19:02:48 +01:00
makiolaj 51f58e76b2 Classic agenda: seamless day cards, aligned placeholder, shared day action (#489) 2026-11-09 18:59:02 +01:00
makiolaj 347ce74808 Classic agenda: single cap, card inset, shared dim rule (#489) 2026-11-09 18:52:00 +01:00
makiolaj 726dbbbaf3 Month widget: require font scale for lane fitting (#491) 2026-11-09 18:51:00 +01:00
makiolaj fb434f3f15 Month widget: compact-only bar fallback, no compact lane above default font scale (#491) 2026-11-09 18:48:14 +01:00
makiolaj aacd86cebe Classic agenda: cap with labels, visible dimming, solid day cards (#489) 2026-11-09 18:43:56 +01:00
makiolaj bd3b4605cb Fix week number gutter KDoc (#493) 2026-11-09 18:41:40 +01:00
makiolaj f267744c1c Month widget: keep the single lane's bars, compact lane only at normal font scale (#491) 2026-11-09 18:40:30 +01:00
makiolaj fffb033e39 Agenda widget: classic style and background opacity (#489) 2026-11-09 18:31:12 +01:00
makiolaj f574f039f5 Month widget: keep a lane in short week rows (#491) 2026-11-09 18:24:44 +01:00
makiolaj 506ebdb092 Number week rows by their Thursday (#493) 2026-11-09 18:21:56 +01:00
+3 9ccc303a2a Release v2.24.0 (#487)
Release — F-Droid repo + Gitea/Codeberg release + Play / detect (push) Successful in 8s
Renovate / renovate (push) Successful in 2m19s
Release — F-Droid repo + Gitea/Codeberg release + Play / release (push) Successful in 20m28s
Release — F-Droid repo + Gitea/Codeberg release + Play / play (push) Successful in 1m34s
Beta — Codeberg pre-release / detect (push) Successful in 6s
Beta — Codeberg pre-release / beta (push) Skipped
2.24.0: the widget redesign and the fixes collected on release/2.24.0. Full list in CHANGELOG.md under 2.24.0.

- Seven new widgets (quick add, date, week strip, upcoming, today, countdown, month with day), each with its own settings; new look for the agenda and month widgets.
- Drag all-day events between days or into the grid; cancelled and tentative events are marked; month view setting to hide start times.
- Fixes: short events late at night, one notification per event, weekend missing from the week strip widget, split month view animations and back gesture.
- Weblate translations from #434, including the new Traditional Chinese (zh-TW), with its store listing and What's New.

Merges main's v2.23.1 in. #427 is moved out of the milestone until it can be reproduced.

Closes #434

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Co-authored-by: Sup99999 <alelmnour1o234@proton.me>
Co-authored-by: Weblate <noreply-mt-weblate@weblate.org>
Co-authored-by: Benutzer <gabrielegobboch@protonmail.ch>
Co-authored-by: N Donkersloot <n@donkerslootjes.nl>
Co-authored-by: VinCap <vcapaldo@ik.me>
Co-authored-by: AventineC <AventineC@outlook.com>
Co-authored-by: Weblate <noreply@weblate.org>
Co-authored-by: NattyNarwhal <fr.schuessele@gmx.de>
Co-authored-by: James Trivette <trivette@atlas.cz>
Co-authored-by: Dmitri Gabinski <dkgabi@gmail.com>
Co-authored-by: Tritra002 <tritratrulala002@outlook.com>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/487
2026-11-06 17:49:13 +01:00
Jean-Luc Makiolaandmakiolaj a5c4a73de1 Release v2.23.1 (#453)
Release — F-Droid repo + Gitea/Codeberg release + Play / detect (push) Successful in 8s
Renovate / renovate (push) Successful in 2m2s
Release — F-Droid repo + Gitea/Codeberg release + Play / release (push) Successful in 17m11s
Release — F-Droid repo + Gitea/Codeberg release + Play / play (push) Successful in 1m37s
Follow-up to the #142 feedback in the split month view:

- With a day selected, the filter chip now stands in for the day's header, so the date isn't shown twice. Tapping the chip opens the Day view; its ✕ clears the filter.
- The day headers in the agenda pane below the grid use less vertical space.
- Event dots no longer drop on days that show a "+N".

Closes #142

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/453
2026-10-28 20:11:10 +01:00
dbd5ce6700 Release v2.23.0 (#433)
Release — F-Droid repo + Gitea/Codeberg release + Play / detect (push) Successful in 9s
Renovate / renovate (push) Successful in 1m28s
Release — F-Droid repo + Gitea/Codeberg release + Play / release (push) Successful in 18m17s
Release — F-Droid repo + Gitea/Codeberg release + Play / play (push) Successful in 1m31s
Beta — Codeberg pre-release / detect (push) Successful in 5s
Beta — Codeberg pre-release / beta (push) Skipped
Stable 2.23.0 after four betas. It adds long-press select, move, resize and drafting in the timeline, tap-to-call phone numbers, formatted HTML descriptions, scrolling back in the agenda, events from shared text, the option to open the editor on tap, the black theme, Liberapay and more haptics. It also fixes the daylight saving and recurring-move bugs. CHANGELOG.md has the full list, and every store locale has its own What's New.

I merged main into the release branch to pick up Liberapay (#430) and Weblate #421. The Czech and Japanese string conflicts were lines added at the end of each file on both sides, so I kept main's.

Closes #116, closes #141, closes #153, closes #178, closes #181, closes #271, closes #306, closes #339, closes #367, closes #387, closes #413

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Co-authored-by: Tritra002 <tritratrulala002@outlook.com>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/433
2026-10-21 14:10:22 +02:00
Jean-Luc Makiola 068a96b228 Translations update from Weblate (#421)
Release — F-Droid repo + Gitea/Codeberg release + Play / detect (push) Successful in 8s
Release — F-Droid repo + Gitea/Codeberg release + Play / release (push) Skipped
Release — F-Droid repo + Gitea/Codeberg release + Play / play (push) Skipped
Renovate / renovate (push) Successful in 1m56s
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/421
2026-10-21 13:46:56 +02:00
James Trivette 7c522c5903 Translated using Weblate (Czech)
Currently translated at 100.0% (656 of 656 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/cs/
2026-10-21 08:16:14 +00:00
Sup99999 6ef516fe4d Translated using Weblate (Arabic)
Currently translated at 100.0% (651 of 651 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/ar/
2026-10-21 02:38:13 +00:00
mirai yamada 9a7d65be6b Translated using Weblate (Japanese)
Currently translated at 17.6% (115 of 651 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/ja/
2026-10-21 02:38:13 +00:00
mirai yamada c2aae1629f Translated using Weblate (Japanese)
Currently translated at 17.3% (113 of 651 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/ja/
2026-10-21 02:38:13 +00:00
Weblate a697803e29 Translated using Weblate (Japanese)
Currently translated at 17.3% (113 of 651 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/ja/
2026-10-21 02:38:13 +00:00
Weblate f4b6cb3acb Translated using Weblate (Japanese)
Currently translated at 16.4% (107 of 651 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/ja/
2026-10-21 02:38:13 +00:00
mirai yamada c3f3eb83f2 Translated using Weblate (Japanese)
Currently translated at 16.4% (107 of 651 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/ja/
2026-10-21 02:38:13 +00:00
Jean-Luc Makiolaandmakiolaj 5d10f773ca Add Liberapay alongside Ko-fi for donations (#430)
Release — F-Droid repo + Gitea/Codeberg release + Play / detect (push) Successful in 10s
Release — F-Droid repo + Gitea/Codeberg release + Play / release (push) Skipped
Release — F-Droid repo + Gitea/Codeberg release + Play / play (push) Skipped
Renovate / renovate (push) Successful in 2m1s
Adds Liberapay as a second donation option next to Ko-fi.

- Settings: "Support development" now opens a full-screen picker with Ko-fi (one-off tips) and Liberapay (recurring donations) instead of linking straight to Ko-fi.
- README: Liberapay badge next to the Ko-fi badge, plus a short Support section.

No issue for this one.

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/430
2026-10-20 11:09:52 +02:00
Jean-Luc Makiola b2fcc55018 Translations update from Weblate (#391)
Release — F-Droid repo + Gitea/Codeberg release + Play / detect (push) Successful in 8s
Release — F-Droid repo + Gitea/Codeberg release + Play / release (push) Skipped
Release — F-Droid repo + Gitea/Codeberg release + Play / play (push) Skipped
Renovate / renovate (push) Successful in 1m33s
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/391
2026-10-15 16:22:27 +02:00
mirai yamada 10414fcf05 Translated using Weblate (Japanese)
Currently translated at 13.2% (86 of 651 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/ja/
2026-10-15 12:55:25 +00:00
Dmitri Gabinski 49f604bdc2 Translated using Weblate (Belarusian)
Currently translated at 92.6% (603 of 651 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/be/
2026-10-13 12:41:03 +00:00
Dmitri Gabinski 56763f58da Translated using Weblate (Russian)
Currently translated at 39.1% (255 of 651 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/ru/
2026-10-13 12:41:02 +00:00
Dmitri Gabinski af34f014a7 Translated using Weblate (Belarusian)
Currently translated at 90.6% (590 of 651 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/be/
2026-10-13 10:01:47 +00:00
Dmitri Gabinski 3280191309 Translated using Weblate (Belarusian)
Currently translated at 90.3% (588 of 651 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/be/
2026-10-13 09:50:18 +00:00
Jean-Luc Makiola 76cdc1c535 Translations update from Weblate (#356)
Release — F-Droid repo + Gitea/Codeberg release + Play / detect (push) Successful in 36s
Release — F-Droid repo + Gitea/Codeberg release + Play / release (push) Skipped
Release — F-Droid repo + Gitea/Codeberg release + Play / play (push) Skipped
Renovate / renovate (push) Successful in 2m5s
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/356
2026-10-12 21:51:27 +02:00
Sup99999 68c0a262fa Translated using Weblate (Arabic)
Currently translated at 100.0% (651 of 651 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/ar/
2026-10-10 21:10:40 +00:00
makiolaj 39e13e86d2 Translated using Weblate (French)
Currently translated at 90.4% (589 of 651 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/fr/
2026-10-10 21:10:40 +00:00
James Trivette 1cc7f40f7e Translated using Weblate (Czech)
Currently translated at 98.7% (643 of 651 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/cs/
2026-10-10 21:10:40 +00:00
Dmitri Gabinski 8a15325fdc Translated using Weblate (Belarusian)
Currently translated at 87.0% (567 of 651 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/be/
2026-10-10 21:10:40 +00:00
MaxrregMustermann 7f977971ed Translated using Weblate (German)
Currently translated at 98.0% (638 of 651 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/de/
2026-10-10 21:10:40 +00:00
N Donkersloot 632155c016 Translated using Weblate (Dutch)
Currently translated at 100.0% (651 of 651 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/nl/
2026-10-10 21:10:40 +00:00
N Donkersloot 8834884d4e Translated using Weblate (Dutch)
Currently translated at 97.0% (632 of 651 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/nl/
2026-10-10 21:10:40 +00:00
VinCap 236372d740 Translated using Weblate (Italian)
Currently translated at 99.5% (648 of 651 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/it/
2026-10-10 21:10:40 +00:00
Sup99999 678a526cb9 Translated using Weblate (Arabic)
Currently translated at 100.0% (651 of 651 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/ar/
2026-10-10 21:10:40 +00:00
Weblate 84fd51baf6 Translated using Weblate (Arabic)
Currently translated at 100.0% (649 of 649 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/ar/
2026-10-10 21:10:40 +00:00
Sup99999 450b8b0107 Translated using Weblate (Arabic)
Currently translated at 100.0% (649 of 649 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/ar/
2026-10-10 21:10:40 +00:00
Weblate 8078fb4f10 Translated using Weblate (Czech)
Currently translated at 100.0% (633 of 633 strings)

Translation: Calendula/Strings
Translate-URL: https://weblate.dev.jeanlucmakiola.de/projects/calendula/strings/cs/
2026-10-10 21:10:40 +00:00
Jean-Luc Makiolaandmakiolaj 46b88cc03e ci: route jobs to the gradle and light runners (#385)
Release — F-Droid repo + Gitea/Codeberg release + Play / detect (push) Successful in 8s
Release — F-Droid repo + Gitea/Codeberg release + Play / release (push) Skipped
Release — F-Droid repo + Gitea/Codeberg release + Play / play (push) Skipped
Renovate / renovate (push) Successful in 1m34s
Moves Gradle jobs to the dedicated `gradle` runner (capacity 1, 8g per job) and the cheap gate/lint jobs to `light`. Two runners used to share the `docker` label, so two Gradle builds could run at once and the VPS ran out of memory. Only `runs-on` lines change.

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/385
2026-10-10 12:02:34 +02:00
Jean-Luc Makiolaandmakiolaj 6afcfd49f1 Release v2.22.5 (#381)
Renovate / renovate (push) Successful in 1m13s
Release — F-Droid repo + Gitea/Codeberg release + Play / detect (push) Successful in 6s
Beta — Codeberg pre-release / detect (push) Successful in 5s
Beta — Codeberg pre-release / beta (push) Skipped
Release — F-Droid repo + Gitea/Codeberg release + Play / release (push) Successful in 19m27s
Release — F-Droid repo + Gitea/Codeberg release + Play / play (push) Successful in 1m2s
When you reopened the app the next morning, the month view still marked yesterday as today and still had the day you picked the evening before selected.

- New `TodaySource` gives the current date. It rechecks once a minute while a calendar is visible, and also reacts to the system's date, time and time-zone broadcasts. Month, Week/Day/3-day, Agenda and the shared date that every view opens on all use it.
- On a day change, a view still showing the old today moves to the new one, and Split clears the previous day's selection. A view you navigated elsewhere stays where it is.
- Month and Week take today from the live value instead of their cached page data.
- The issue only mentions the month view. The same stale today also affected Week, Day, Agenda and switching between views, so all of them are fixed.
- versionName 2.22.5 / versionCode 2220599, CHANGELOG, What's New in all 17 locales.

Closes #373

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/381
2026-10-07 20:22:50 +02:00
Jean-Luc Makiolaandmakiolaj 5f77cac7ea Move to floret-kit 0.7.0 (#375)
Release — F-Droid repo + Gitea/Codeberg release + Play / detect (push) Successful in 8s
Release — F-Droid repo + Gitea/Codeberg release + Play / release (push) Skipped
Release — F-Droid repo + Gitea/Codeberg release + Play / play (push) Skipped
Renovate / renovate (push) Successful in 1m11s
Repoints the floret-kit submodule at the convergence merge (jlmakiola/floret-kit#11), which folds the clockula/vouch/glance branches back into floret-kit main so all four apps share one line again.

floret-kit's dependency bump requires Gradle >= 9.6 in the consuming build, so this also bumps Gradle 9.5.1 → 9.8.0, AGP 9.2.1 → 9.4.1 and Kotlin 2.3.21 → 2.4.20. No source changes were needed.

**Merge jlmakiola/floret-kit#11 first** so the pinned commit is on floret-kit main.

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/375
2026-10-07 09:56:00 +02:00
Jean-Luc Makiolaandmakiolaj 20a6548ac8 Release v2.22.4 (#374)
Release — F-Droid repo + Gitea/Codeberg release + Play / detect (push) Successful in 9s
Renovate / renovate (push) Successful in 1m57s
Release — F-Droid repo + Gitea/Codeberg release + Play / release (push) Successful in 18m48s
Release — F-Droid repo + Gitea/Codeberg release + Play / play (push) Successful in 1m19s
Promotes 2.22.4-beta.1 to stable. The app code is the same as the beta.

- versionName 2.22.4, versionCode 2220499 (new scheme)
- CHANGELOG.md: the Unreleased entries move under [2.22.4]
- What's New `changelogs/2220499.txt` in all 17 store locales

Includes #370 (re-query after own writes and on return to foreground) and #371 (widgets load only what they show).

Closes #363
Closes #364

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/374
2026-10-07 09:05:32 +02:00
547 changed files with 38994 additions and 10135 deletions

No files matched your search

+2 -2
View File
@@ -15,7 +15,7 @@ jobs:
detect:
# Gitea only; see the same guard in release.yaml.
if: github.repository_owner == 'makiolaj'
runs-on: docker
runs-on: light
outputs:
is_beta: ${{ steps.v.outputs.is_beta }}
version: ${{ steps.v.outputs.version }}
@@ -41,7 +41,7 @@ jobs:
beta:
needs: detect
if: needs.detect.outputs.is_beta == 'true'
runs-on: docker
runs-on: gradle
env:
ANDROID_HOME: /opt/android-sdk
ANDROID_SDK_ROOT: /opt/android-sdk
+6 -3
View File
@@ -43,7 +43,7 @@ jobs:
# secrets. repository_owner differs between the two forges regardless of
# URL, proxy or instance rename, so this closes it permanently.
if: github.repository_owner == 'makiolaj'
runs-on: docker
runs-on: light
outputs:
is_release: ${{ steps.v.outputs.is_release }}
version: ${{ steps.v.outputs.version }}
@@ -85,7 +85,7 @@ jobs:
release:
needs: detect
if: needs.detect.outputs.is_release == 'true' || github.event_name == 'workflow_dispatch'
runs-on: docker
runs-on: gradle
env:
ANDROID_HOME: /opt/android-sdk
ANDROID_SDK_ROOT: /opt/android-sdk
@@ -318,13 +318,16 @@ jobs:
# not provide node inside custom job containers, so JavaScript actions
# (checkout, download-artifact) can't run there. The Renovate job gets away
# with a container because its only step is a shell command. Ruby is installed
# the same way sshpass, jq and fdroidserver are in the job above.
# the same way sshpass, jq and fdroidserver are in the job above, from trixie:
# fastlane >= 2.241 needs Ruby 3.2+, and bookworm's apt only has 3.1.
play:
needs: [detect, release]
# workflow_dispatch is the F-Droid re-sign recovery path — it must never
# touch Play, so gate on a real release only.
if: needs.detect.outputs.is_release == 'true'
runs-on: docker
container:
image: node:22-trixie
env:
VERSION: ${{ needs.detect.outputs.version }}
VERSION_CODE: ${{ needs.detect.outputs.version_code }}
+1 -1
View File
@@ -33,7 +33,7 @@ jobs:
# directly drops the docker-in-docker requirement entirely.
# Full tag pinned; Renovate's github-actions manager keeps it bumped.
container:
image: ghcr.io/renovatebot/renovate:43.232.0
image: ghcr.io/renovatebot/renovate:44.237.3
steps:
- name: Run Renovate
run: renovate
+187
View File
@@ -7,6 +7,130 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
- **Notifications per calendar.** Settings → Notifications → Calendars lists every calendar with its own switch, sound and system channel, grouped by account. Turn one calendar's reminders off without hiding it, give it its own sound, or see that the system blocks it ([#145], [#272], [#340]).
- **Pick the reminder sound in the app.** Choose a sound for all calendars or for one, including Silent, without going through the system settings ([#518]).
- **Full-screen reminders.** A calendar can show its reminders full screen, even on the lock screen, either sounding once or ringing like an alarm until you dismiss or snooze them ([#171]).
- **Reminders at a set time.** Add a reminder like "1 day before at 20:00" to timed events, with a default for new events and per calendar ([#459]).
- **A daily summary.** One notification a day lists today's or tomorrow's events, at a time you choose, with calendars you can leave out ([#459]).
- **More reminder presets.** 2, 3, 4 and 5 days and 2 and 3 weeks before are one tap away, in the editor and the default pickers ([#365]).
- **Open link or map from a reminder.** A reminder whose location holds a meeting link gets an Open link button, one with a place gets Open in maps ([#464]).
- **Hide calendars in chosen views.** A calendar can stay in the agenda but leave the month view, for example. Set it under Settings → Calendars, or from the drawer for the view you're in ([#270], [#517]).
- **Show or hide a whole account at once** by tapping its header in the drawer ([#143]).
- **A default calendar for new events,** under Settings → Event form; Automatic keeps the one you last used ([#429]).
- **Sync now.** The drawer can ask your sync apps to sync, and shows when they are done. Calendula also nudges them after you change an event in a synced calendar, so edits reach the server sooner ([#240], [#303]).
- **Copy events between calendars,** for example from a synced calendar into a local or DAVx5 one, with exceptions of repeating events, progress and Cancel ([#325]).
- **Back up synced calendars too,** each into its own file. The automatic backup keeps one up-to-date copy per calendar next to the dated ones, lets you choose how many dated files to keep, and can run right after a change instead of only on its schedule ([#147], [#411], [#516]).
- **Back up and restore your settings.** Backup & restore → Settings saves Calendula's settings to a file and reads one back, also on another phone; per-calendar settings find their calendar by account and name ([#481]).
### Changed
- **All-day reminders show the day they fire on.** A reminder kept from a timed event no longer reads "30 minutes before" on an all-day event ([#514]).
### Fixed
- **Repeating events with extra dates survive a backup.** `.ics` backups now write and read back RDATE ([#515]).
## [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]).
### 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).
## [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]).
### 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]).
### 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/).
## [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.
### 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]).
### 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]).
## [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]).
### 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]).
## [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]).
### 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]).
### 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.
## [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]).
## [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]).
@@ -1803,6 +1927,7 @@ automatically, with zero telemetry and no internet permission.
[#146]: https://codeberg.org/jlmakiola/calendula/issues/146
[#267]: https://codeberg.org/jlmakiola/calendula/issues/267
[#239]: https://codeberg.org/jlmakiola/calendula/issues/239
[#296]: https://codeberg.org/jlmakiola/calendula/issues/296
[#297]: https://codeberg.org/jlmakiola/calendula/issues/297
[#298]: https://codeberg.org/jlmakiola/calendula/issues/298
[#309]: https://codeberg.org/jlmakiola/calendula/issues/309
@@ -1841,3 +1966,65 @@ automatically, with zero telemetry and no internet permission.
[#361]: https://codeberg.org/jlmakiola/calendula/issues/361
[#363]: https://codeberg.org/jlmakiola/calendula/issues/363
[#364]: https://codeberg.org/jlmakiola/calendula/issues/364
[#367]: https://codeberg.org/jlmakiola/calendula/issues/367
[#373]: https://codeberg.org/jlmakiola/calendula/issues/373
[#141]: https://codeberg.org/jlmakiola/calendula/issues/141
[#153]: https://codeberg.org/jlmakiola/calendula/issues/153
[#339]: https://codeberg.org/jlmakiola/calendula/issues/339
[#387]: https://codeberg.org/jlmakiola/calendula/issues/387
[#271]: https://codeberg.org/jlmakiola/calendula/issues/271
[#181]: https://codeberg.org/jlmakiola/calendula/issues/181
[#306]: https://codeberg.org/jlmakiola/calendula/issues/306
[#178]: https://codeberg.org/jlmakiola/calendula/issues/178
[#116]: https://codeberg.org/jlmakiola/calendula/issues/116
[#388]: https://codeberg.org/jlmakiola/calendula/issues/388
[#413]: https://codeberg.org/jlmakiola/calendula/issues/413
[#71]: https://codeberg.org/jlmakiola/calendula/issues/71
[#90]: https://codeberg.org/jlmakiola/calendula/issues/90
[#229]: https://codeberg.org/jlmakiola/calendula/issues/229
[#292]: https://codeberg.org/jlmakiola/calendula/issues/292
[#372]: https://codeberg.org/jlmakiola/calendula/issues/372
[#376]: https://codeberg.org/jlmakiola/calendula/issues/376
[#386]: https://codeberg.org/jlmakiola/calendula/issues/386
[#420]: https://codeberg.org/jlmakiola/calendula/issues/420
[#435]: https://codeberg.org/jlmakiola/calendula/issues/435
[#436]: https://codeberg.org/jlmakiola/calendula/issues/436
[#437]: https://codeberg.org/jlmakiola/calendula/issues/437
[#438]: https://codeberg.org/jlmakiola/calendula/issues/438
[#439]: https://codeberg.org/jlmakiola/calendula/issues/439
[#440]: https://codeberg.org/jlmakiola/calendula/issues/440
[#441]: https://codeberg.org/jlmakiola/calendula/issues/441
[#454]: https://codeberg.org/jlmakiola/calendula/issues/454
[#457]: https://codeberg.org/jlmakiola/calendula/issues/457
[#463]: https://codeberg.org/jlmakiola/calendula/issues/463
[#473]: https://codeberg.org/jlmakiola/calendula/issues/473
[#476]: https://codeberg.org/jlmakiola/calendula/issues/476
[#483]: https://codeberg.org/jlmakiola/calendula/issues/483
[#448]: https://codeberg.org/jlmakiola/calendula/issues/448
[#475]: https://codeberg.org/jlmakiola/calendula/issues/475
[#489]: https://codeberg.org/jlmakiola/calendula/issues/489
[#491]: https://codeberg.org/jlmakiola/calendula/issues/491
[#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
[#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
+1 -1
View File
@@ -7,4 +7,4 @@ source "https://rubygems.org"
# Pinned exactly; Renovate's bundler manager keeps it bumped. No Gemfile.lock is
# committed on purpose: this resolves an uploader's transitive deps, not the
# app's, and none of it affects the reproducible release build.
gem "fastlane", "2.237.0"
gem "fastlane", "2.241.1"
+9
View File
@@ -23,6 +23,8 @@ It works on top of the system calendar and has no network access.</p>
<a href="https://apps.obtainium.imranr.dev/redirect?r=obtainium://add/https://codeberg.org/jlmakiola/calendula"><img src="https://github.com/ImranR98/Obtainium/blob/main/assets/graphics/badge_obtainium.png?raw=true" alt="Get it on Obtainium" height="56"></a>
&nbsp;
<a href="https://ko-fi.com/jeanlucmakiola"><img src="https://storage.ko-fi.com/cdn/brandasset/v2/support_me_on_kofi_badge_beige.png" alt="Support me on Ko-fi" height="56"></a>
&nbsp;
<a href="https://liberapay.com/Jean-Luc_Makiola/donate"><img src="https://liberapay.com/assets/widgets/donate.svg" alt="Donate using Liberapay" height="56"></a>
</p>
<p>
@@ -203,6 +205,13 @@ anywhere. Your events stay in Android's own calendar store.
[Privacy policy](https://jeanlucmakiola.de/calendula/privacy), written in
[`docs/PRIVACY.md`](docs/PRIVACY.md), which is what that page renders.
## Support
Calendula is free and has no ads. If you'd like to support its development,
you can tip once on [Ko-fi](https://ko-fi.com/jeanlucmakiola) or donate
regularly on [Liberapay](https://liberapay.com/Jean-Luc_Makiola/donate). Both
are linked in the app under *Settings → Support development*.
## License
[MIT](LICENSE), Jean-Luc Makiola, 2026
+8 -2
View File
@@ -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 = 2220401
versionName = "2.22.4-beta.1"
versionCode = 2250001
versionName = "2.25.0-beta.1"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
@@ -175,9 +175,15 @@ dependencies {
implementation("de.jeanlucmakiola.floret:core-time")
implementation("de.jeanlucmakiola.floret:core-locale")
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)
@@ -37,6 +37,7 @@ class CalendarRepositorySmokeTest {
CalendarPrefs(store),
SettingsPrefs(store),
Dispatchers.IO,
AndroidSyncRequester(context),
)
}
@@ -0,0 +1,91 @@
package de.jeanlucmakiola.calendula.data.calendar
import android.Manifest
import android.content.ContentUris
import android.content.ContentValues
import android.provider.CalendarContract
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.rule.GrantPermissionRule
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.domain.toEditForm
import kotlinx.datetime.TimeZone
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/**
* Moving a synced series keeps its deleted and edited occurrences, although the
* moved row has no `_sync_id` for exception rows to attach to.
*/
@RunWith(AndroidJUnit4::class)
class MoveEventExceptionsTest {
@get:Rule
val permissionRule: GrantPermissionRule = GrantPermissionRule.grant(
Manifest.permission.READ_CALENDAR,
Manifest.permission.WRITE_CALENDAR,
)
private val context = InstrumentationRegistry.getInstrumentation().targetContext
private val resolver = context.contentResolver
private val ds = AndroidCalendarDataSource(context)
private val zone = TimeZone.currentSystemDefault()
private val day = 86_400_000L
private val start = 1_893_492_000_000L // 2030-01-01T10:00Z
private val hour = 3_600_000L
/** "day offset:title" of every instance on [calendarId]. */
private fun occurrences(calendarId: Long): List<String> =
ds.instances(start - day, start + 10 * day)
.filter { it.calendarId == calendarId }
.map { "${(it.start.toEpochMilliseconds() - start) / day}:${it.title}" }
.sorted()
@Test
fun movedSeriesKeepsCancelledAndModifiedOccurrences() {
val a = ds.createLocalCalendar("move-test-a", 0xFF336699.toInt(), null)
val b = ds.createLocalCalendar("move-test-b", 0xFF993366.toInt(), null)
try {
val src = insertSyncedSeries(a)
ds.deleteOccurrence(src, start + 2 * day)
val occurrence = ds.eventDetail(src, 540)!!.toEditForm(start + 3 * day, start + 3 * day + hour, zone)
ds.updateOccurrence(src, start + 3 * day, occurrence, occurrence.copy(title = "edited"), 540)
val expected = listOf("0:series", "1:series", "3:edited", "4:series")
assertThat(occurrences(a)).isEqualTo(expected)
val form = ds.eventDetail(src, 540)!!.toEditForm(start, start + hour, zone)
ds.moveEvent(src, b, form, form, 540)
assertThat(occurrences(a)).isEmpty()
assertThat(occurrences(b)).isEqualTo(expected)
} finally {
ds.deleteCalendar(a)
ds.deleteCalendar(b)
}
}
/** A daily series carrying a `_sync_id`, so its exceptions are real exception rows. */
private fun insertSyncedSeries(calendarId: Long): Long {
val accountName = resolver.query(
ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI, calendarId),
arrayOf(CalendarContract.Calendars.ACCOUNT_NAME), null, null, null,
)!!.use { it.moveToFirst(); it.getString(0) }
val uri = CalendarContract.Events.CONTENT_URI.buildUpon()
.appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, accountName)
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, CalendarContract.ACCOUNT_TYPE_LOCAL)
.build()
val values = ContentValues().apply {
put(CalendarContract.Events.CALENDAR_ID, calendarId)
put(CalendarContract.Events.TITLE, "series")
put(CalendarContract.Events.DTSTART, start)
put(CalendarContract.Events.DURATION, "P3600S")
put(CalendarContract.Events.RRULE, "FREQ=DAILY;COUNT=5")
put(CalendarContract.Events.EVENT_TIMEZONE, "UTC")
put(CalendarContract.Events._SYNC_ID, "move-test-series")
}
return ContentUris.parseId(resolver.insert(uri, values)!!)
}
}
@@ -0,0 +1,101 @@
package de.jeanlucmakiola.calendula.ui.detail
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
/**
* The platform phone matcher on real text. It reads the region off the SIM,
* so these stick to international numbers and to text that must never match
* anywhere — domestic formats depend on the device they run on.
*/
@RunWith(AndroidJUnit4::class)
class PhoneLinksPlatformTest {
private fun numbers(text: String) = findPhoneLinks(text).map { it.number }
@Test
fun internationalNumbers_areFound() {
assertThat(numbers("Call +49 30 1234567 or +1 646-558-8656"))
.containsExactly("+49301234567", "+16465588656")
.inOrder()
}
@Test
fun trunkZero_isDroppedWithOrWithoutSpace() {
assertThat(numbers("+49 (0)151 2345678")).containsExactly("+491512345678")
assertThat(numbers("+49 (0) 151 2345678")).containsExactly("+491512345678")
}
@Test
fun neighbouringNumbers_doNotJoinTheNumber() {
assertThat(numbers("Start 10:00 +49 151 2345678")).containsExactly("+491512345678")
assertThat(numbers("Call +49 151 2345678 2 times")).containsExactly("+491512345678")
}
@Test
fun conferenceDialIn_keepsMeetingId() {
assertThat(numbers("One tap mobile: +16465588656,,85012345678# US"))
.containsExactly("+16465588656,,85012345678#")
}
@Test
fun meetingIds_areNotNumbers() {
assertThat(numbers("Meeting ID: 850 1234 5678")).isEmpty()
assertThat(numbers("Conference ID: 123 456 789#")).isEmpty()
}
@Test
fun datesAndTimes_areNotNumbers() {
assertThat(numbers("2026-10-14 10:00")).isEmpty()
assertThat(numbers("Am 14.10.2026 10:00 Uhr")).isEmpty()
assertThat(numbers("14.10.26 - 16.10.26")).isEmpty()
assertThat(numbers("10:00 - 11:30")).isEmpty()
assertThat(numbers("Schuljahr 2025/2026, Season 2025-2026")).isEmpty()
assertThat(numbers("1.10.2026 - 3.10.2026")).isEmpty()
}
@Test
fun amounts_areNotNumbers() {
assertThat(numbers("Budget 1.250.000 EUR, 1 250 000 EUR")).isEmpty()
}
@Test
fun isbn_isNotANumber() {
assertThat(numbers("ISBN 978-3-16-148410-0")).isEmpty()
}
@Test
fun extension_becomesAPause() {
assertThat(numbers("+1 212 555 1234 ext. 567")).containsExactly("+12125551234,567")
}
@Test
fun webexAccessCode_isNotANumber() {
assertThat(numbers("Meeting number (access code): 2732 123 4567")).isEmpty()
}
@Test
fun commaSeparatedNumbers_stayApart() {
assertThat(numbers("+49 30 1234567,+49 151 2345678"))
.containsExactly("+49301234567", "+491512345678")
.inOrder()
}
@Test
fun dottedTimes_areNotNumbers() {
assertThat(numbers("Beginn 9.30 – 12.00 Uhr")).isEmpty()
assertThat(numbers("10.00-11.30")).isEmpty()
}
@Test
fun schemelessUrlDigits_areNotNumbers() {
assertThat(numbers("zoom.us/j/85012345678")).isEmpty()
}
@Test
fun webLinkDigits_areNotNumbers() {
assertThat(numbers("https://zoom.us/j/85012345678?pwd=1")).isEmpty()
}
}
@@ -0,0 +1,140 @@
package de.jeanlucmakiola.calendula.widget.month
import android.Manifest
import android.content.ContentUris
import android.content.ContentValues
import android.net.Uri
import android.os.Parcel
import android.provider.CalendarContract
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.glance.ExperimentalGlanceApi
import androidx.glance.appwidget.compose
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.rule.GrantPermissionRule
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import de.jeanlucmakiola.calendula.R
import java.time.LocalDate
import java.time.ZoneId
/**
* Renders the month widget for a packed month through Glance's own translator
* (#372) and checks what one size costs on the wire: the host's binder buffer is
* 1 MB for every widget update at once, and Exact sends one copy per size (#214).
*/
@OptIn(ExperimentalGlanceApi::class)
@RunWith(AndroidJUnit4::class)
class MonthWidgetPayloadTest {
@get:Rule
val permissionRule: GrantPermissionRule =
GrantPermissionRule.grant(Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR)
private val instrumentation = InstrumentationRegistry.getInstrumentation()
private val context = instrumentation.targetContext
private var calendarId = -1L
private fun Uri.asSyncAdapter(): Uri = buildUpon()
.appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, ACCOUNT)
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, CalendarContract.ACCOUNT_TYPE_LOCAL)
.build()
@Before
fun packTheMonth() {
val calendar = ContentValues().apply {
put(CalendarContract.Calendars.ACCOUNT_NAME, ACCOUNT)
put(CalendarContract.Calendars.ACCOUNT_TYPE, CalendarContract.ACCOUNT_TYPE_LOCAL)
put(CalendarContract.Calendars.NAME, ACCOUNT)
put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, ACCOUNT)
put(CalendarContract.Calendars.CALENDAR_COLOR, 0xFF3F51B5.toInt())
put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_OWNER)
put(CalendarContract.Calendars.OWNER_ACCOUNT, ACCOUNT)
put(CalendarContract.Calendars.VISIBLE, 1)
put(CalendarContract.Calendars.SYNC_EVENTS, 1)
}
val uri = context.contentResolver.insert(CalendarContract.Calendars.CONTENT_URI.asSyncAdapter(), calendar)
calendarId = ContentUris.parseId(requireNotNull(uri))
val zone = ZoneId.systemDefault()
val first = LocalDate.now(zone).withDayOfMonth(1).minusDays(7)
val events = (0 until 49).flatMap { offset ->
val day = first.plusDays(offset.toLong())
(0 until EVENTS_PER_DAY).map { i ->
val start = day.atTime(8 + i, 0).atZone(zone).toInstant().toEpochMilli()
ContentValues().apply {
put(CalendarContract.Events.CALENDAR_ID, calendarId)
put(CalendarContract.Events.TITLE, "Busy $i")
put(CalendarContract.Events.DTSTART, start)
put(CalendarContract.Events.DTEND, start + 30 * 60_000L)
put(CalendarContract.Events.EVENT_TIMEZONE, zone.id)
}
}
}
context.contentResolver.bulkInsert(CalendarContract.Events.CONTENT_URI.asSyncAdapter(), events.toTypedArray())
}
@After
fun removeCalendar() {
if (calendarId < 0) return
context.contentResolver.delete(
ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI, calendarId).asSyncAdapter(),
null,
null,
)
}
@Test
fun aPackedMonthRendersWithinItsPayload() = runBlocking {
for (size in listOf(DpSize(250.dp, 250.dp), DpSize(320.dp, 360.dp), DpSize(420.dp, 520.dp), DpSize(600.dp, 1000.dp))) {
val views = MonthWidget().compose(context, size = size)
val bytes = Parcel.obtain().let { parcel ->
try {
views.writeToParcel(parcel, 0)
parcel.dataSize()
} finally {
parcel.recycle()
}
}
var dayNumbers = 0
var bars = 0
instrumentation.runOnMainSync {
val root = views.apply(context, FrameLayout(context))
fun walk(view: View) {
if (view.id in DAY_IDS && view is TextView && view.text.isNotEmpty()) dayNumbers += 1
if (view.id == R.id.bar_title) bars += 1
if (view is ViewGroup) for (i in 0 until view.childCount) walk(view.getChildAt(i))
}
walk(root)
}
Log.i(TAG, "size=$size bytes=$bytes days=$dayNumbers bars=$bars")
// The grid itself rendered, not Glance's error layout: a number in every day of every week.
assertThat(dayNumbers % 7).isEqualTo(0)
assertThat(dayNumbers).isAtLeast(28)
assertThat(bytes).isAtMost(MAX_BYTES_PER_SIZE)
}
}
private companion object {
const val TAG = "MonthWidgetPayload"
const val ACCOUNT = "calendula-widget-payload-test"
const val EVENTS_PER_DAY = 6
val DAY_IDS = setOf(R.id.day_0, R.id.day_1, R.id.day_2, R.id.day_3, R.id.day_4, R.id.day_5, R.id.day_6)
/** A quarter of the host's buffer, leaving room for a second size and every other widget. */
const val MAX_BYTES_PER_SIZE = 256 * 1024
}
}
+186 -6
View File
@@ -41,6 +41,19 @@
-->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<!-- Lets "Sync now" (#240) follow the sync it asked for: read-only sync state, install-time. -->
<uses-permission android:name="android.permission.READ_SYNC_STATS" />
<!-- WorkManager declares this for network constraints, which the app doesn't use (#448). -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" tools:node="remove" />
<!-- Full-screen reminder alerts and their ring (#171), opt-in per calendar. -->
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SYSTEM_EXEMPTED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<!-- Package visibility (Android 11+): without this, getLaunchIntentForPackage
returns null and the calendar manager's per-account "manage" button can't
open the source sync app (DAVx5, ICSx5, Google Calendar, …). The LAUNCHER
@@ -51,6 +64,21 @@
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent>
<!-- Sync adapters to ask for a calendar sync (#240, #303). -->
<intent>
<action android:name="android.content.SyncAdapter" />
</intent>
<!-- A reminder's "Open link" button only shows when something can open the link (#464). -->
<intent>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="https" />
</intent>
<intent>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="http" />
</intent>
</queries>
<application
@@ -151,6 +179,19 @@
<data android:mimeType="application/ics" />
</intent-filter>
<!-- Text shared or selected in another app opens a prefilled new
event (MainActivity.sharedTextRequestOrNull, issue #306). -->
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<intent-filter android:label="@string/process_text_create_event">
<action android:name="android.intent.action.PROCESS_TEXT" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<!-- Let another app or widget (e.g. the Todo Agenda widget) launch us
to create a new event, the way the AOSP calendar accepts it:
ACTION_INSERT on the events *dir* mime type, carrying the new
@@ -278,6 +319,12 @@
</intent-filter>
</service>
<!-- The change watch behind "Also back up after changes" (#516). -->
<service
android:name=".data.backup.BackupChangeJob"
android:exported="false"
android:permission="android.permission.BIND_JOB_SERVICE" />
<!-- Reminder delivery is the app's own (#75): it plans the alarms from
Instances + Reminders instead of waiting for the provider's
EVENT_REMINDER broadcast, which OEM-modified providers demonstrably
@@ -304,7 +351,31 @@
android:name=".data.reminders.ReminderActionReceiver"
android:exported="false" />
<!-- The full-screen reminder alert (#171), in a task of its own. -->
<activity
android:name=".ui.reminders.ReminderAlertActivity"
android:exported="false"
android:excludeFromRecents="true"
android:launchMode="singleTask"
android:taskAffinity="" />
<!-- Rings a "Ring until dismissed" reminder (#171). -->
<service
android:name=".data.reminders.ReminderRingService"
android:exported="false"
android:foregroundServiceType="systemExempted" />
<!-- Home-screen widgets (Glance). Exported: the launcher/host binds them. -->
<activity
android:name=".widget.config.WidgetConfigActivity"
android:exported="true"
android:excludeFromRecents="true"
android:taskAffinity=""
android:theme="@style/Theme.Calendula.WidgetConfig">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
</intent-filter>
</activity>
<receiver
android:name=".widget.agenda.AgendaWidgetReceiver"
android:label="@string/widget_agenda_label"
@@ -329,14 +400,110 @@
android:resource="@xml/appwidget_info_month" />
</receiver>
<receiver
android:name=".widget.quickadd.QuickAddWidgetReceiver"
android:label="@string/widget_quick_add_label"
android:exported="true">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/appwidget_info_quick_add" />
</receiver>
<receiver
android:name=".widget.date.DateWidgetReceiver"
android:label="@string/widget_date_label"
android:exported="true">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/appwidget_info_date" />
</receiver>
<receiver
android:name=".widget.week.WeekStripWidgetReceiver"
android:label="@string/widget_week_strip_label"
android:exported="true">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/appwidget_info_week_strip" />
</receiver>
<receiver
android:name=".widget.upcoming.UpcomingWidgetReceiver"
android:label="@string/widget_upcoming_label"
android:exported="true">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/appwidget_info_upcoming" />
</receiver>
<receiver
android:name=".widget.today.TodayWidgetReceiver"
android:label="@string/widget_today_label"
android:exported="true">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/appwidget_info_today" />
</receiver>
<receiver
android:name=".widget.countdown.CountdownWidgetReceiver"
android:label="@string/widget_countdown_label"
android:exported="true">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/appwidget_info_countdown" />
</receiver>
<!-- A countdown widget's redraw for when its label changes (#439). -->
<receiver
android:name=".widget.WidgetTickReceiver"
android:exported="false" />
<receiver
android:name=".widget.split.MonthDayWidgetReceiver"
android:label="@string/widget_month_day_label"
android:exported="true">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/appwidget_info_month_day" />
</receiver>
<!-- Keeps both widgets fresh: the calendar provider broadcasts
PROVIDER_CHANGED on any data change (our writes and external sync).
The day boundary arrives as the app's own ROLLOVER alarm (#228), by
explicit PendingIntent, so it needs no filter here; DATE_CHANGED is
a free extra only, since Android 8+ withholds it from manifest
receivers. The four below re-arm that alarm: TIME_SET /
TIMEZONE_CHANGED move the boundary, boot / package-replace wipe it.
PROVIDER_CHANGED on any data change (external sync; the app's own
writes redraw directly). The day boundary arrives as the app's own
ROLLOVER alarm (#228), by explicit PendingIntent, so it needs no
filter here; DATE_CHANGED is a free extra only, since Android 8+
withholds it from manifest receivers. TIME_SET / TIMEZONE_CHANGED
move the boundary, boot / package-replace wipe the alarm, and
LOCALE_CHANGED redraws the labels in the new language.
Exported: the system broadcasts arrive from outside the app. -->
<!-- The app's own redraw request (language change); not exported so
other apps can't trigger it. -->
<receiver
android:name=".widget.WidgetRedrawReceiver"
android:exported="false" />
<receiver
android:name=".widget.WidgetUpdateReceiver"
android:exported="true">
@@ -352,9 +519,22 @@
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
<action android:name="android.intent.action.LOCALE_CHANGED" />
</intent-filter>
</receiver>
<!-- WorkManager initialises on demand from CalendulaApp's configuration. -->
<provider
android:name="androidx.startup.InitializationProvider"
android:authorities="${applicationId}.androidx-startup"
android:exported="false"
tools:node="merge">
<meta-data
android:name="androidx.work.WorkManagerInitializer"
android:value="androidx.startup"
tools:node="remove" />
</provider>
<!-- Hands .ics files we stage in the cache to other apps via a content
Uri (single-event share). Authority tracks applicationId so the
debug suffix doesn't break getUriForFile. -->
@@ -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
@@ -10,9 +12,12 @@ import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesScheduler
import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesSyncWorker
import de.jeanlucmakiola.calendula.data.reminders.ReminderMaintenanceScheduler
import de.jeanlucmakiola.calendula.data.reminders.ReminderMaintenanceWorker
import de.jeanlucmakiola.calendula.widget.WidgetRolloverScheduler
import de.jeanlucmakiola.calendula.widget.publishCalendulaWidgetPreviews
import de.jeanlucmakiola.calendula.widget.syncWidgetRollover
import de.jeanlucmakiola.calendula.widget.widgetEntryPoint
import de.jeanlucmakiola.floret.crash.CrashConfig
import de.jeanlucmakiola.floret.crash.CrashReporter
import de.jeanlucmakiola.floret.locale.AppLanguage
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
@@ -24,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()
@@ -43,6 +52,11 @@ class CalendulaApp : Application() {
chooseIssueUrl = getString(R.string.report_issue_choose_url),
),
)
// Below API 33 only AppCompat activities get the app language; a process
// woken for a widget formats in it too (#90).
AppLanguage.applyDefault(this)
// Before anything that writes, so the widgets see every change (#420).
widgetEntryPoint().widgetRefreshCoordinator().start()
reconcileAutoBackup()
reconcileSpecialDates()
reconcileCalendarVisibility()
@@ -55,10 +69,12 @@ class CalendulaApp : Application() {
* (#228). Idempotent, and it covers what no broadcast reaches — an alarm
* dropped by a force-stop is armed again the next time the app is opened.
* Off the main thread: a handful of binder calls on every process start.
* The picker previews are republished here too, once per update.
*/
private fun reconcileWidgetRollover() {
CoroutineScope(SupervisorJob() + Dispatchers.Default).launch {
WidgetRolloverScheduler.sync(this@CalendulaApp)
syncWidgetRollover(this@CalendulaApp)
publishCalendulaWidgetPreviews(this@CalendulaApp)
}
}
@@ -100,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)
}
}
@@ -6,6 +6,7 @@ import android.content.res.Configuration
import android.net.Uri
import android.os.Bundle
import android.provider.CalendarContract
import android.provider.OpenableColumns
import androidx.activity.SystemBarStyle
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
@@ -25,12 +26,20 @@ import androidx.core.content.IntentCompat
import androidx.core.net.toUri
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.lifecycleScope
import dagger.hilt.android.AndroidEntryPoint
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
import de.jeanlucmakiola.calendula.data.prefs.ThemeMode
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.floret.locale.AppLanguage
import de.jeanlucmakiola.floret.prefs.ThemeMode
import de.jeanlucmakiola.floret.prefs.isDark
import de.jeanlucmakiola.floret.prefs.isPureBlack
import de.jeanlucmakiola.calendula.data.prefs.is24Hour
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.InsertRequest
import de.jeanlucmakiola.calendula.ui.RootScreen
import de.jeanlucmakiola.calendula.ui.common.LocalShowHourGrid
import de.jeanlucmakiola.calendula.ui.common.LocalMultiDayCount
@@ -50,50 +59,48 @@ import de.jeanlucmakiola.floret.crash.CrashReportDialog
import de.jeanlucmakiola.floret.crash.CrashReporter
import de.jeanlucmakiola.floret.crash.submitCrashReport
import de.jeanlucmakiola.calendula.ui.theme.CalendulaTheme
import de.jeanlucmakiola.calendula.ui.theme.WindowThemeCache
import de.jeanlucmakiola.calendula.ui.theme.windowBackgroundRes
import de.jeanlucmakiola.calendula.ui.theme.calendulaTypography
import de.jeanlucmakiola.calendula.ui.theme.resolveFontFamily
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
import javax.inject.Inject
/** A prefilled create form from an external launch, with the source it came from. */
private data class InsertRequest(val form: EventForm, val source: ImportSource)
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
@Inject lateinit var calendarRepository: CalendarRepository
@Inject lateinit var settingsPrefs: SettingsPrefs
// Which of light/dark the system bars are drawn for. The styles installed
// in onCreate read this field live, so androidx's config-change replay
// picks up the in-app override instead of the night resource qualifier.
private var systemBarsDark = false
// The occurrence a reminder notification was tapped for (eventId, begin,
// end — the detail screen's key shape). singleTop + onNewIntent route a
// tap into the running activity; CalendarHost consumes and clears it.
private var requestedDetailKey by mutableStateOf<LongArray?>(null)
private val requests = ExternalRequests(
onExternalFormClosed = {
insertFormOpen = false
if (launchedForInsert) finish()
},
)
// A navigation a home-screen widget asked for (open a date / start a
// create). Consumed once by CalendarHost, same pattern as the detail key.
private var requestedNav by mutableStateOf<WidgetNavRequest?>(null)
// Whether such a form is still open. Only then does a recreation re-read the
// intent to bring it back; a saved or dismissed one stays closed.
private var insertFormOpen = false
// An .ics file opened/shared into the app (ACTION_VIEW/SEND). Consumed once
// by CalendarHost's import flow.
private var requestedImportUri by mutableStateOf<Uri?>(null)
// A prefilled new-event form from an external ACTION_INSERT launch (another
// app/widget asking us to create an event, issue #30). Consumed once by
// CalendarHost, which opens it in the create form for review.
private var requestedInsert by mutableStateOf<InsertRequest?>(null)
// An external "edit this event" (ACTION_EDIT on content://.../events/<id>):
// opens the occurrence in the edit form. Same occurrence-key shape as the
// detail channel; consumed once by CalendarHost.
private var requestedEditKey by mutableStateOf<LongArray?>(null)
// Started just for an external create, so closing its form returns to the
// app that asked instead of leaving the calendar on top of it.
private var launchedForInsert = 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
@@ -115,9 +122,28 @@ class MainActivity : AppCompatActivity() {
return
}
systemBarsDark = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK ==
val systemDark = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK ==
Configuration.UI_MODE_NIGHT_YES
// The stored theme only arrives after the first frame, so a Light, Dark
// or Black override starts from its last mirrored copy: the matching
// backdrop and bar icons instead of the night qualifier's (#181).
val cachedTheme = WindowThemeCache.read(this)
cachedTheme?.windowBackgroundRes()?.let { window.setBackgroundDrawableResource(it) }
systemBarsDark = (cachedTheme ?: ThemeMode.SYSTEM).isDark(systemDark)
applyEdgeToEdge()
val appearance = MutableStateFlow(
Appearance(
themeMode = cachedTheme ?: ThemeMode.SYSTEM,
dynamicColor = WindowThemeCache.readDynamicColor(this),
),
)
lifecycleScope.launch {
combine(settingsPrefs.themeMode, settingsPrefs.dynamicColor, ::Appearance).collect { stored ->
WindowThemeCache.write(this@MainActivity, stored.themeMode, stored.dynamicColor ?: true)
window.setBackgroundDrawableResource(stored.themeMode.windowBackgroundRes() ?: R.color.window_background)
appearance.value = stored
}
}
// Android hands the intent that started the task back to onCreate every
// time the activity is recreated — on a rotation, or on a restart after
// the system reclaimed the process. Re-running a launch that opens one
@@ -128,27 +154,33 @@ class MainActivity : AppCompatActivity() {
//
// 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
// is what carries one through a recreation.
// is what carries one through a recreation — the create form only while
// it's still open.
val replaying = savedInstanceState != null || intent.isRelaunch()
requests.replayed = savedInstanceState != null
if (!replaying) {
requestedDetailKey = intent.detailKeyOrNull() ?: intent.viewEventKeyOrNull()
requestedEditKey = intent.editEventKeyOrNull()
requests.detailKey = intent.detailKeyOrNull() ?: intent.viewEventKeyOrNull()
requests.editKey = intent.editEventKeyOrNull()
}
requestedNav = intent.navRequestOrNull()
requests.nav = intent.navRequestOrNull()
?.takeUnless { replaying && it is WidgetNavRequest.OpenEvent }
requestedImportUri = intent.importUriOrNull()
requestedInsert = intent.insertRequestOrNull()
requests.importUri = intent.importUriOrNull()
val insertOpenBefore = savedInstanceState?.getBoolean(KEY_INSERT_FORM_OPEN) == true
requests.insert = intent.createRequestOrNull()?.takeIf { !replaying || insertOpenBefore }
insertFormOpen = requests.insert != null
launchedForInsert = savedInstanceState?.getBoolean(KEY_LAUNCHED_FOR_INSERT)
?: (requests.insert != null)
if (CrashReporter.shouldPrompt(this)) pendingCrashReport = CrashReporter.pendingReport(this)
setContent {
// One activity-scoped SettingsViewModel drives both the theme here
// and the Settings screen, so a theme change applies app-wide at once.
val settingsViewModel: SettingsViewModel = hiltViewModel()
val settings by settingsViewModel.state.collectAsStateWithLifecycle()
val darkTheme = when (settings.themeMode) {
ThemeMode.SYSTEM -> isSystemInDarkTheme()
ThemeMode.LIGHT -> false
ThemeMode.DARK -> true
}
// Seeded from the cache, so the first frame doesn't draw the default
// theme and palette before the stored choices arrive.
val shownAppearance by appearance.collectAsStateWithLifecycle()
val themeMode = shownAppearance.themeMode
val darkTheme = themeMode.isDark(isSystemInDarkTheme())
// onCreate can only see the night resource qualifier, not the in-app
// override — re-apply from the resolved theme so the bar icons follow
// the app's light/dark choice.
@@ -186,7 +218,8 @@ class MainActivity : AppCompatActivity() {
}
CalendulaTheme(
darkTheme = darkTheme,
dynamicColor = settings.dynamicColor,
dynamicColor = shownAppearance.dynamicColor ?: settings.dynamicColor,
pureBlack = themeMode.isPureBlack,
typography = typography,
) {
Box(modifier = Modifier.fillMaxSize()) {
@@ -199,17 +232,7 @@ class MainActivity : AppCompatActivity() {
) {
RootScreen(
modifier = Modifier.fillMaxSize(),
requestedDetailKey = requestedDetailKey,
onDetailKeyConsumed = { requestedDetailKey = null },
widgetNavRequest = requestedNav,
onWidgetNavConsumed = { requestedNav = null },
requestedImportUri = requestedImportUri,
onImportConsumed = { requestedImportUri = null },
requestedInsertForm = requestedInsert?.form,
requestedInsertSource = requestedInsert?.source ?: ImportSource.Insert,
onInsertConsumed = { requestedInsert = null },
requestedEditKey = requestedEditKey,
onEditKeyConsumed = { requestedEditKey = null },
requests = requests,
)
}
// A persistent corner marker so a debug build is never
@@ -259,15 +282,33 @@ class MainActivity : AppCompatActivity() {
super.onResume()
// Reaching a running UI means startup succeeded; reset the loop trail.
CrashReporter.markHealthy(this)
AppLanguage.syncMirror(this)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean(KEY_INSERT_FORM_OPEN, insertFormOpen)
outState.putBoolean(KEY_LAUNCHED_FOR_INSERT, launchedForInsert)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
(intent.detailKeyOrNull() ?: intent.viewEventKeyOrNull())?.let { requestedDetailKey = it }
intent.navRequestOrNull()?.let { requestedNav = it }
intent.importUriOrNull()?.let { requestedImportUri = it }
intent.insertRequestOrNull()?.let { requestedInsert = it }
intent.editEventKeyOrNull()?.let { requestedEditKey = it }
requests.replayed = false
(intent.detailKeyOrNull() ?: intent.viewEventKeyOrNull())?.let { requests.detailKey = it }
intent.navRequestOrNull()?.let { requests.nav = it }
intent.importUriOrNull()?.let { requests.importUri = it }
intent.createRequestOrNull()?.let {
requests.insert = it
insertFormOpen = true
}
intent.editEventKeyOrNull()?.let { requests.editKey = it }
// The user moved on into the app, so closing the create form no longer
// hands control back to the app that started it.
if (requests.detailKey != null || requests.nav != null || requests.importUri != null ||
requests.editKey != null
) {
launchedForInsert = false
}
}
/**
@@ -288,7 +329,10 @@ class MainActivity : AppCompatActivity() {
private fun Intent.importUriOrNull(): Uri? {
val uri = when (action) {
Intent.ACTION_VIEW -> data
Intent.ACTION_SEND -> IntentCompat.getParcelableExtra(this, Intent.EXTRA_STREAM, Uri::class.java)
// Shared text is a create (#306); a text/plain file is imported only
// when it is calendar data, e.g. an .ics attachment labelled text/plain.
Intent.ACTION_SEND -> sharedStreamOrNull()
?.takeUnless { type == SHARED_TEXT_TYPE && !it.isCalendarFile() }
else -> null
} ?: return null
// The calendar "view time" Uri (a date tap) is also ACTION_VIEW/content;
@@ -324,6 +368,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(),
)
@@ -333,10 +378,66 @@ class MainActivity : AppCompatActivity() {
return InsertRequest(form, if (namesEnd) ImportSource.Insert else ImportSource.InsertOpenEnded)
}
/** Any external request to create an event: shared text or an insert intent. */
private fun Intent.createRequestOrNull(): InsertRequest? = sharedTextRequestOrNull() ?: insertRequestOrNull()
/**
* Plain text shared into us (`ACTION_SEND`) or picked from a text-selection
* menu (`ACTION_PROCESS_TEXT`), as a new event at the default time (#306).
*/
private fun Intent.sharedTextRequestOrNull(): InsertRequest? {
val shared = when (action) {
Intent.ACTION_SEND -> if (type == SHARED_TEXT_TYPE && sharedStreamOrNull()?.isCalendarFile() != true) {
sharedTextOrNull(
subject = getCharSequenceExtra(Intent.EXTRA_SUBJECT)?.toString(),
text = getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString(),
)
} else {
null
}
Intent.ACTION_PROCESS_TEXT ->
sharedTextOrNull(subject = null, text = getCharSequenceExtra(Intent.EXTRA_PROCESS_TEXT)?.toString())
else -> null
} ?: return null
val form = buildInsertEventForm(
title = shared.title,
description = shared.description,
zone = TimeZone.currentSystemDefault(),
now = Clock.System.now(),
)
return InsertRequest(form, ImportSource.InsertOpenEnded)
}
private fun Intent.sharedStreamOrNull(): Uri? =
IntentCompat.getParcelableExtra(this, Intent.EXTRA_STREAM, Uri::class.java)
/** Whether a shared file is iCalendar/vCalendar data, by its resolved type or its name. */
private fun Uri.isCalendarFile(): Boolean {
val resolvedType = runCatching { contentResolver.getType(this) }.getOrNull()
if (resolvedType in CALENDAR_TYPES) return true
val name = when (scheme) {
"content" -> runCatching {
contentResolver.query(this, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)
?.use { c -> if (c.moveToFirst()) c.getString(0) else null }
}.getOrNull()
else -> lastPathSegment
} ?: return false
return CALENDAR_EXTENSIONS.any { name.endsWith(it, ignoreCase = true) }
}
/** A Long extra's value, or null when the extra is absent. */
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/
@@ -458,6 +559,11 @@ class MainActivity : AppCompatActivity() {
// The calendar provider's authority/host. A date tap arrives as
// ACTION_VIEW on content://com.android.calendar/time/<epochMillis>.
private const val CALENDAR_PROVIDER_HOST = "com.android.calendar"
private const val SHARED_TEXT_TYPE = "text/plain"
private val CALENDAR_TYPES = setOf("text/calendar", "text/x-vcalendar", "application/ics")
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 EXTRA_EVENT_ID = "de.jeanlucmakiola.calendula.extra.EVENT_ID"
private const val EXTRA_BEGIN_MILLIS = "de.jeanlucmakiola.calendula.extra.BEGIN"
@@ -502,7 +608,9 @@ class MainActivity : AppCompatActivity() {
*/
fun openDateIntent(context: Context, date: LocalDate, source: CalendarView): Intent =
Intent(context, MainActivity::class.java).apply {
data = "calendula://date/$date".toUri()
// 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()
putExtra(EXTRA_DATE_ISO, date.toString())
putExtra(EXTRA_SOURCE_VIEW, source.name)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
@@ -521,9 +629,24 @@ class MainActivity : AppCompatActivity() {
endMillis: Long,
source: CalendarView,
): Intent = eventDetailIntent(context, eventId, beginMillis, endMillis).apply {
data = "calendula://event/$eventId/$beginMillis/${source.name}".toUri()
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 {
@@ -548,3 +671,6 @@ class MainActivity : AppCompatActivity() {
}
}
}
/** The theme choices the window needs before the settings screen's state loads. */
private data class Appearance(val themeMode: ThemeMode, val dynamicColor: Boolean?)
@@ -5,20 +5,23 @@ import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.pm.PackageManager
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.content.ContextCompat
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
@@ -27,41 +30,87 @@ 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.backupFingerprint
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
* Reconcile the scheduled work with the saved 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.
*
* 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 interval = prefs.autoBackupIntervalMinutes.first().coerceAtLeast(15L)
val request = PeriodicWorkRequestBuilder<BackupWorker>(interval, TimeUnit.MINUTES)
.setInitialDelay(interval, TimeUnit.MINUTES)
.build()
@@ -70,6 +119,44 @@ object BackupScheduler {
ExistingPeriodicWorkPolicy.UPDATE,
request,
)
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<BackupWorker>()
.setConstraints(Constraints.Builder().setRequiresBatteryNotLow(true).build())
.setInputData(workDataOf(KEY_CHANGE_RUN to true))
.build()
workManager.enqueueUniqueWork(WORK_NAME_CHANGE, policy, run).await()
}
/**
@@ -84,11 +171,25 @@ object BackupScheduler {
OneTimeWorkRequestBuilder<BackupWorker>().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<WorkInfo.State>): 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.
@@ -108,33 +209,237 @@ 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(), latestOnly = changeRun)
} 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()
}
private enum class RunOutcome { Written, PartlyFailed, Failed, 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
* [latestOnly] run (#516) leaves the dated files and their retention to the
* schedule and rewrites only the stable copies whose calendars changed.
*/
private suspend fun runBackup(deps: Deps, prefs: SettingsPrefs, folder: Uri, latestOnly: Boolean): RunOutcome {
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<String, String?> = if (latestOnly) {
targets.associate { target -> target.key to export(target)?.let { fingerprintOf(target, it) } }
} else {
emptyMap()
}
if (latestOnly && targets.all { preHashes[it.key].let { hash -> hash != null && hash == fingerprints[it.key] } }) {
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<String>) =
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<String>, 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
val landedLatest = mutableSetOf<String>()
for (plan in plans) {
val target = plan.target
if (latestOnly) {
val hash = preHashes[target.key] ?: run {
failed++
continue
}
rememberBlocked(plan, hash)
if (!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 (!latestOnly) 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 -> RunOutcome.NothingToDo
failed == 0 -> RunOutcome.Written
written == 0 -> RunOutcome.Failed
else -> RunOutcome.PartlyFailed
}
}
private fun clearFailureNotification(context: Context) {
NotificationManagerCompat.from(context).cancel(NOTIFICATION_ID)
}
private fun notifyFailure(context: Context) {
val canPost = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) ==
PackageManager.PERMISSION_GRANTED
context.hasPermission(Manifest.permission.POST_NOTIFICATIONS)
if (!canPost) return
val manager = NotificationManagerCompat.from(context)
manager.createNotificationChannel(
@@ -167,10 +472,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()
}
}
@@ -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)
}
}
@@ -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<Int>? = null,
val allDayReminders: List<Int>? = null,
/** The views it is hidden in only (#270). */
val hiddenInViews: Set<CalendarView> = 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<Pref<*>, Any>,
val calendars: List<CalendarSettings>,
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<CalendarSource>,
managed: List<ManagedCalendarRow>,
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<SettingsBackup> {
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<Int>.cleanReminders(): List<Int> = 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"
@@ -0,0 +1,233 @@
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.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<Preferences>,
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<SettingsImportSummary> = 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<SkippedSetting>)
/**
* 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<String>,
existingMirrors: Set<Long>,
): 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) }
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<Long>,
synced: Boolean,
): LateMatches {
val managed = calendars.findManagedCalendars()
val skipped = mutableListOf<SkippedSetting>()
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<String>,
): 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<String> = 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"
}
}
@@ -0,0 +1,134 @@
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<Pref<*>> = 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.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<Pref<*>> = 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<Pref<*>> = (
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()
}
@@ -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<CalendarSource>?,
val managed: List<ManagedCalendarRow>,
val contactsPermission: Boolean,
val customFonts: Set<FontRole>,
val hasBackupFolder: Boolean,
val supportedLanguages: List<String>,
)
/** 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<SkippedSetting>,
)
/**
* 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<Pref<*>, Any?>,
val calendars: Map<Long, CalendarSettings>?,
val pendingSpecialDates: List<CalendarSettings>,
val language: LanguageChoice?,
val launcherName: LauncherName?,
val skipped: List<SkippedSetting>,
)
/** 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<SkippedSetting>()
val prefs = backup.prefs.toMutableMap<Pref<*>, 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<Long, CalendarSettings>()
val pending = mutableListOf<CalendarSettings>()
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<Long, CalendarSettings>) {
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<SkippedSetting> = 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<String> = when (this) {
FontRole.BRAND -> SettingsKeys.brandFont
FontRole.PLAIN -> SettingsKeys.plainFont
}
@@ -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<Int>): List<Int> =
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
File diff suppressed because it is too large. Load diff
@@ -10,14 +10,23 @@ import de.jeanlucmakiola.calendula.domain.ics.IcsEvent
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 {
fun calendars(): Flow<List<CalendarSource>>
fun instances(range: ClosedRange<Instant>): Flow<List<EventInstance>>
/** One read of event [eventId]'s occurrences overlapping [range], soonest first, whatever calendar it is in. */
suspend fun eventOccurrences(eventId: Long, range: ClosedRange<Instant>): List<EventInstance>
/** Re-query every open [calendars] / [instances] flow. */
fun refresh()
/** Emits on the app's own writes and visibility changes; not on provider notifications or [refresh]. */
val localChanges: Flow<Unit>
suspend fun eventDetail(eventId: Long): EventDetail
/**
@@ -29,7 +38,7 @@ interface CalendarRepository {
/**
* The event-colour palette a calendar's account publishes; empty when it
* exposes none (see [CalendarDataSource.eventColorPalette]).
* exposes none (see [CalendarDataSource.publishedEventColors]).
*/
suspend fun eventColorPalette(calendarId: Long): List<EventColorOption>
@@ -53,18 +62,41 @@ interface CalendarRepository {
suspend fun setCalendarsVisible(ids: Collection<Long>, 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<Long>? = null): List<IcsEvent>
suspend fun exportEvents(calendarIds: Set<Long>): List<IcsEvent>
/**
* 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<ParsedIcsEvent>): IcsImportSummary
suspend fun importEvents(
targetCalendarId: Long,
events: List<ParsedIcsEvent>,
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
@@ -101,6 +133,12 @@ interface CalendarRepository {
form: EventForm,
): Long
/**
* Every series split the app makes ([updateEventFromOccurrence]), so what
* follows a series by id can move on to the part that continues it.
*/
val seriesSplits: Flow<SeriesSplit> get() = emptyFlow()
/**
* Change a recurring event from [beginMillis] onwards (series split);
* returns the new event's `Events._ID`.
@@ -120,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<SyncAccount>): 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<SyncTargets> 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<Unit> get() = emptyFlow()
}
class NoSuchEventException(eventId: Long) :
@@ -128,3 +191,6 @@ class NoSuchEventException(eventId: Long) :
/** A ContentResolver write affected no rows or returned no URI. */
class WriteFailedException(operation: String) :
RuntimeException("Calendar write failed: $operation")
/** A "this and following" edit: [oldEventId] now ends where [newEventId] picks up. */
data class SeriesSplit(val oldEventId: Long, val newEventId: Long)
@@ -1,10 +1,11 @@
package de.jeanlucmakiola.calendula.data.calendar
import android.util.Log
import de.jeanlucmakiola.floret.di.IoDispatcher
import de.jeanlucmakiola.floret.time.toEpochMillis
import de.jeanlucmakiola.calendula.data.di.IoDispatcher
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.domain.curatedForPicker
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.EventColorOption
import de.jeanlucmakiola.calendula.domain.EventDetail
@@ -13,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
@@ -29,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
@@ -46,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. */
@@ -77,15 +85,184 @@ class CalendarRepositoryImpl @Inject constructor(
ticks.tryEmit(Unit)
}
/** Run a provider write on [io], then re-query whether or not it threw. */
private suspend fun <T> write(block: suspend () -> T): T = withContext(io) {
private val writes = MutableSharedFlow<Unit>(
replay = 0,
extraBufferCapacity = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST,
)
override val providerChanges: Flow<Unit> 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 <T> write(
syncCalendars: suspend () -> Collection<Long?>,
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<Long?> = { emptyList() }
private suspend fun syncAccountsOf(calendarIds: suspend () -> Collection<Long?>): Set<SyncAccount> =
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<SyncAccount>.withAdapter(): Set<SyncAccount> {
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<SyncAccount>): 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<SyncAccount>, 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<Long?> =
{ listOf(original?.calendarId ?: dataSource.eventCalendarId(eventId), *others) }
private fun targetsOf(calendars: List<CalendarSource>, dismissed: Set<SyncAccount>): 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<SyncTargets>
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<SyncAccount>): SyncWait =
withContext(io) { syncRequester.awaitSyncs(accounts) }
override val localChanges: Flow<Unit> = merge(
writes,
prefs.pendingDisabledCalendarIds.distinctUntilChanged().drop(1).map {},
prefs.hiddenCalendarIds.distinctUntilChanged().drop(1).map {},
)
/**
* Re-query signal for everything filtered by visibility: the provider's own
* notifications, plus every change to the pending switch-off set.
@@ -125,8 +302,7 @@ class CalendarRepositoryImpl @Inject constructor(
beginMillis = range.start.toEpochMillis(),
endMillis = range.endInclusive.toEpochMillis(),
),
switchedOffCalendarIds = invisibleCalendarIds() +
prefs.pendingDisabledCalendarIds.first(),
switchedOffCalendarIds = switchedOffCalendarIds(),
)
},
prefs.hiddenCalendarIds,
@@ -151,6 +327,10 @@ class CalendarRepositoryImpl @Inject constructor(
.filterNot { it.isVisibleInSystem }
.mapTo(mutableSetOf()) { it.id }
/** [invisibleCalendarIds] plus the switch-offs still waiting to be written. */
private suspend fun switchedOffCalendarIds(): Set<Long> =
invisibleCalendarIds() + prefs.pendingDisabledCalendarIds.first()
private val calendarsLock = Mutex()
private var cachedGeneration = -1L
private var cachedPending: Set<Long>? = null
@@ -177,6 +357,11 @@ class CalendarRepositoryImpl @Inject constructor(
cachedCalendars
}
override suspend fun eventOccurrences(eventId: Long, range: ClosedRange<Instant>): List<EventInstance> =
withContext(io) {
dataSource.eventInstances(eventId, range.start.toEpochMillis(), range.endInclusive.toEpochMillis())
}
override suspend fun eventDetail(eventId: Long): EventDetail = withContext(io) {
dataSource.eventDetail(eventId, allDayReminderTimeMinutes())
?: throw NoSuchEventException(eventId)
@@ -184,21 +369,19 @@ class CalendarRepositoryImpl @Inject constructor(
override suspend fun searchEvents(query: String): List<SearchCandidate> = withContext(io) {
if (query.isBlank()) return@withContext emptyList()
val excluded = prefs.hiddenCalendarIds.first() +
prefs.pendingDisabledCalendarIds.first() +
invisibleCalendarIds()
val excluded = prefs.hiddenCalendarIds.first() + switchedOffCalendarIds()
dataSource.searchEvents(query)
.let { if (excluded.isEmpty()) it else it.filterNot { c -> c.event.calendarId in excluded } }
}
override suspend fun eventColorPalette(calendarId: Long): List<EventColorOption> =
withContext(io) { dataSource.eventColorPalette(calendarId) }
withContext(io) { dataSource.publishedEventColors(calendarId).curatedForPicker() }
override suspend fun createLocalCalendar(
displayName: String,
color: Int,
description: String?,
): Long = write {
): Long = write(noSync) {
dataSource.createLocalCalendar(displayName, color, description)
}
@@ -207,34 +390,55 @@ 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<Long>, visible: Boolean) =
write {
if (dataSource.canWriteCalendars()) {
ids.forEach { dataSource.setCalendarVisible(it, visible) }
// Nothing of ours is left waiting for the provider once the
// write lands (and switching one back on retires its entry).
prefs.removePendingDisabledCalendarIds(ids)
} else if (visible) {
// 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
// lands, and switching one back on retires its entry. With read-only
// permission a switch-off still works, app-side, and the reconciler
// flushes it if WRITE_CALENDAR ever arrives.
if (canWrite || visible) {
prefs.removePendingDisabledCalendarIds(ids)
} else {
// Read-only permission: the switch still works, app-side, and
// the reconciler flushes it if WRITE_CALENDAR ever arrives.
prefs.addPendingDisabledCalendarIds(ids)
}
}
override suspend fun exportEvents(calendarIds: Set<Long>?) =
withContext(io) { dataSource.exportableEvents(calendarIds, allDayReminderTimeMinutes()) }
override suspend fun exportEvents(calendarIds: Set<Long>) = 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<ParsedIcsEvent>,
): 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
@@ -246,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<String, MutableList<Instant>>()
// 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
@@ -264,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
@@ -274,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,
@@ -285,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())
}
@@ -293,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)
}
@@ -306,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(),
)
@@ -317,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(),
)
@@ -328,20 +542,24 @@ class CalendarRepositoryImpl @Inject constructor(
beginMillis: Long,
original: EventForm,
updated: EventForm,
): Long = write {
): Long = write(eventCalendar(eventId, original)) {
dataSource.updateEventFromOccurrence(
eventId, beginMillis, original, updated, allDayReminderTimeMinutes(),
)
}
}.also { newId -> if (newId != eventId) splits.tryEmit(SeriesSplit(eventId, newId)) }
override suspend fun deleteOccurrence(eventId: Long, beginMillis: Long) = write {
private val splits = MutableSharedFlow<SeriesSplit>(extraBufferCapacity = 8)
override val seriesSplits: Flow<SeriesSplit> = splits
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)
}
@@ -353,3 +571,18 @@ class CalendarRepositoryImpl @Inject constructor(
private fun <T> Flow<Unit>.reQuery(block: suspend () -> T): Flow<T> = 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<String>): 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<String, List<Instant>>): 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 })
}
@@ -4,15 +4,15 @@ import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.util.Log
import androidx.core.content.ContextCompat
import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import de.jeanlucmakiola.calendula.data.di.IoDispatcher
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
import de.jeanlucmakiola.calendula.domain.calendarVisibilityPlan
import de.jeanlucmakiola.calendula.domain.hasSystemHiddenCalendars
import de.jeanlucmakiola.floret.android.hasPermission
import de.jeanlucmakiola.floret.di.IoDispatcher
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext
@@ -47,7 +47,7 @@ class CalendarVisibilityReconciler @Inject constructor(
// Settled ahead of the permission gate, so an update installed
// before the first grant can't later look like an upgrade.
if (!isUpgradeInstall()) settleNoticeOnce(pending = false)
if (!hasPermission(Manifest.permission.READ_CALENDAR)) return@withContext
if (!context.hasPermission(Manifest.permission.READ_CALENDAR)) return@withContext
val pending = prefs.pendingDisabledCalendarIds.first()
val noticeSettled = prefs.visibilityNoticePending.first() != null
if (pending.isEmpty() && noticeSettled) return@withContext
@@ -56,7 +56,7 @@ class CalendarVisibilityReconciler @Inject constructor(
// Both decisions below are one-way, so leave them to the next run.
if (calendars.isEmpty()) return@withContext
settleNoticeOnce(hasSystemHiddenCalendars(calendars, pending))
if (pending.isEmpty() || !hasPermission(Manifest.permission.WRITE_CALENDAR)) {
if (pending.isEmpty() || !context.hasPermission(Manifest.permission.WRITE_CALENDAR)) {
return@withContext
}
val plan = calendarVisibilityPlan(calendars, pending)
@@ -97,9 +97,6 @@ class CalendarVisibilityReconciler @Inject constructor(
false
}
private fun hasPermission(permission: String): Boolean =
ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
/** Lets non-injectable entry points (the Application) reach the reconciler. */
@EntryPoint
@InstallIn(SingletonComponent::class)
@@ -1,6 +1,11 @@
package de.jeanlucmakiola.calendula.data.calendar
import android.database.Cursor
import de.jeanlucmakiola.calendula.domain.EventStatus
import de.jeanlucmakiola.calendula.domain.ics.parseRfc2445DurationMillis
import java.time.Instant
import java.time.LocalDate
import java.time.ZoneOffset
/**
* Read-only view over a single row's columns by index. Lets the mappers work
@@ -20,3 +25,33 @@ internal class CursorColumnReader(private val cursor: Cursor) : ColumnReader {
override fun getInt(index: Int): Int = cursor.getInt(index)
override fun isNull(index: Int): Boolean = cursor.isNull(index)
}
internal fun ColumnReader.getIntOrNull(index: Int): Int? = if (isNull(index)) null else getInt(index)
internal fun ColumnReader.getLongOrNull(index: Int): Long? = if (isNull(index)) null else getLong(index)
/**
* The row's end: DTEND, or DTSTART + DURATION for a recurring row, which stores
* no DTEND. Unclamped; a missing/blank both means a zero-length event.
*/
internal fun ColumnReader.endMillis(dtStartMillis: Long, dtEndIndex: Int, durationIndex: Int): Long =
getLongOrNull(dtEndIndex) ?: (dtStartMillis + parseRfc2445DurationMillis(getString(durationIndex)))
/** STATUS shares value 0 with TENTATIVE, so an absent column must read as Confirmed. */
internal fun ColumnReader.eventStatus(index: Int): EventStatus =
getIntOrNull(index)?.let(::mapEventStatus) ?: EventStatus.Confirmed
/** Map every row, reading each through one [CursorColumnReader]. */
internal inline fun <T> Cursor.mapRows(map: ColumnReader.() -> T): List<T> {
val reader = CursorColumnReader(this)
return buildList { while (moveToNext()) add(reader.map()) }
}
/** [mapRows], dropping the rows [map] returns null for. */
internal inline fun <T : Any> Cursor.mapRowsNotNull(map: ColumnReader.() -> T?): List<T> {
val reader = CursorColumnReader(this)
return buildList { while (moveToNext()) reader.map()?.let(::add) }
}
/** The UTC calendar day of [millis] — an all-day row's date, since it sits at UTC midnight. */
internal fun utcDate(millis: Long): LocalDate = Instant.ofEpochMilli(millis).atZone(ZoneOffset.UTC).toLocalDate()
@@ -15,9 +15,7 @@ import de.jeanlucmakiola.calendula.domain.EventStatus
import de.jeanlucmakiola.calendula.domain.Reminder
import de.jeanlucmakiola.calendula.domain.ReminderMethod
import de.jeanlucmakiola.calendula.domain.ics.parseRfc2445DurationMillis
import java.time.Instant
import java.time.ZoneId
import java.time.ZoneOffset
private const val TAG = "EventDetailMapper"
@@ -48,11 +46,8 @@ internal fun ColumnReader.toEventDetailCore(
// — the same trap as the pre-1970 DTSTART bug above (issue #34): it would
// surface as the generic error screen with no way to open the event and fix
// it. Clamp to a zero-length event instead (matching SearchMapper).
val end = if (isNull(EventDetailProjection.IDX_DTEND)) {
begin + parseRfc2445DurationMillis(getString(EventDetailProjection.IDX_DURATION))
} else {
getLong(EventDetailProjection.IDX_DTEND).coerceAtLeast(begin)
}
val end = getLongOrNull(EventDetailProjection.IDX_DTEND)?.coerceAtLeast(begin)
?: (begin + parseRfc2445DurationMillis(getString(EventDetailProjection.IDX_DURATION)))
// Kept raw (no untitled fallback): the detail screen substitutes its own
// localized placeholder, and the edit form must prefill the true value.
@@ -61,11 +56,7 @@ internal fun ColumnReader.toEventDetailCore(
// The event's own colour (null = inherits the calendar's) is kept apart
// from the resolved display colour: the edit form needs to tell the two
// cases apart, while the instance carries the calendar fallback for display.
val eventColor = if (isNull(EventDetailProjection.IDX_EVENT_COLOR)) {
null
} else {
getInt(EventDetailProjection.IDX_EVENT_COLOR)
}
val eventColor = getIntOrNull(EventDetailProjection.IDX_EVENT_COLOR)
val eventColorKey = getString(EventDetailProjection.IDX_EVENT_COLOR_KEY)
val color = eventColor ?: getInt(EventDetailProjection.IDX_CALENDAR_COLOR)
@@ -88,7 +79,7 @@ internal fun ColumnReader.toEventDetailCore(
// and detail screen speak. DTSTART is UTC midnight for all-day events, so the
// event's date is its UTC date.
val displayReminders = if (isAllDay) {
val startDate = Instant.ofEpochMilli(begin).atZone(ZoneOffset.UTC).toLocalDate()
val startDate = utcDate(begin)
val zone = ZoneId.systemDefault()
reminders.map {
it.copy(
@@ -101,14 +92,6 @@ internal fun ColumnReader.toEventDetailCore(
reminders
}
// STATUS shares its 0 value with STATUS_TENTATIVE, so a missing column must
// be distinguished from a present 0 — an absent status means "just confirmed".
val status = if (isNull(EventDetailProjection.IDX_STATUS)) {
EventStatus.Confirmed
} else {
mapEventStatus(getInt(EventDetailProjection.IDX_STATUS))
}
return EventDetail(
instance = instance,
description = getString(EventDetailProjection.IDX_DESCRIPTION),
@@ -116,7 +99,7 @@ internal fun ColumnReader.toEventDetailCore(
attendees = attendees,
rrule = getString(EventDetailProjection.IDX_RRULE),
reminders = displayReminders,
status = status,
status = eventStatus(EventDetailProjection.IDX_STATUS),
// BUSY and DEFAULT are both 0, so a null column folds into the same
// default these mappers already return — no isNull guard needed.
availability = mapAvailability(getInt(EventDetailProjection.IDX_AVAILABILITY)),
@@ -1,15 +1,20 @@
package de.jeanlucmakiola.calendula.data.calendar
import de.jeanlucmakiola.calendula.domain.instantIn
import kotlinx.datetime.toKotlinTimeZone
import android.provider.CalendarContract
import de.jeanlucmakiola.calendula.domain.AccessLevel
import de.jeanlucmakiola.calendula.domain.Availability
import de.jeanlucmakiola.calendula.domain.EventColorOption
import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.FormTime
import de.jeanlucmakiola.calendula.domain.EventStatus
import de.jeanlucmakiola.calendula.domain.forNewEvent
import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent
import de.jeanlucmakiola.calendula.domain.nearestTo
import kotlinx.datetime.toJavaLocalDate
import kotlinx.datetime.toJavaLocalDateTime
import kotlinx.datetime.toJavaZoneOffset
import java.time.Duration
import java.time.Instant
import java.time.ZoneId
@@ -48,8 +53,8 @@ internal fun EventForm.toWriteTimes(zone: ZoneId): EventWriteTimes = if (isAllDa
} else {
val writeZone = writeZone(zone)
EventWriteTimes(
dtStartMillis = start.toJavaLocalDateTime().atZone(writeZone).toInstant().toEpochMilli(),
dtEndMillis = end.toJavaLocalDateTime().atZone(writeZone).toInstant().toEpochMilli(),
dtStartMillis = start.instantIn(writeZone.toKotlinTimeZone()).toEpochMilliseconds(),
dtEndMillis = end.instantIn(writeZone.toKotlinTimeZone()).toEpochMilliseconds(),
timezone = writeZone.id,
)
}
@@ -75,7 +80,7 @@ private fun EventForm.writeZone(deviceZone: ZoneId): ZoneId = if (isAllDay) {
private fun EventForm.anchorLocal(): JavaLocalDateTime = if (isAllDay) {
start.date.toJavaLocalDate().atStartOfDay()
} else {
start.toJavaLocalDateTime()
start.dateTime.toJavaLocalDateTime()
}
/**
@@ -128,6 +133,8 @@ internal fun buildEventInsertValues(
put(CalendarContract.Events.EVENT_TIMEZONE, times.timezone)
put(CalendarContract.Events.AVAILABILITY, form.availability.toProviderValue())
put(CalendarContract.Events.ACCESS_LEVEL, form.accessLevel.toProviderValue())
form.status.forNewEvent().takeIf { it != EventStatus.Confirmed }
?.let { put(CalendarContract.Events.STATUS, it.toProviderStatus()) }
form.location.trim().takeIf { it.isNotEmpty() }
?.let { put(CalendarContract.Events.EVENT_LOCATION, it) }
form.description.trim().takeIf { it.isNotEmpty() }
@@ -175,13 +182,17 @@ internal fun buildEventUpdateValues(
if (updated.accessLevel != original.accessLevel) {
put(CalendarContract.Events.ACCESS_LEVEL, updated.accessLevel.toProviderValue())
}
if (updated.status != original.status) {
put(CalendarContract.Events.STATUS, updated.status.toProviderStatus())
}
if (updated.colorKey != original.colorKey || updated.color != original.color) {
putAll(eventColorColumns(updated.colorKey, updated.color))
}
// A zone change counts as a time change even when the wall-clock is
// untouched: the same 09:00 in another zone is a different instant, so
// DTSTART has to move with it.
// DTSTART has to move with it. So does a switch between the two passes of
// the fall-back hour, which each [FormTime] carries (#387).
val timesChanged = updated.start != original.start ||
updated.end != original.end ||
updated.isAllDay != original.isAllDay ||
@@ -209,15 +220,23 @@ internal fun buildEventUpdateValues(
// is a different offset from the series anchor's whenever a DST boundary
// sits between them, or whenever the zone itself changed. Working in wall
// clock keeps "09:00" meaning 09:00 at both ends.
val seriesLocal = Instant.ofEpochMilli(seriesDtStartMillis)
.atZone(original.writeZone(zone)).toLocalDateTime()
val seriesZoned = Instant.ofEpochMilli(seriesDtStartMillis).atZone(original.writeZone(zone))
val seriesLocal = seriesZoned.toLocalDateTime()
val wallClockShift = Duration.between(original.anchorLocal(), updated.anchorLocal())
val shifted = seriesLocal.plus(wallClockShift)
// An all-day series anchor must sit on a UTC midnight. A pure day move
// already lands there (both ends are midnights), but *switching* a
// recurring event to all-day shifts by a time-of-day too, so snap.
val newSeriesLocal = if (updated.isAllDay) shifted.toLocalDate().atStartOfDay() else shifted
val newSeriesStart = newSeriesLocal.atZone(updated.writeZone(zone))
// A wall clock the fall-back hour repeats keeps the anchor's own pass, or,
// when the anchor is the edited occurrence itself, the pass the form now
// holds: a bare wall clock would always take the earlier one (#387).
val pass = if (seriesLocal == original.anchorLocal()) {
updated.start.offset?.toJavaZoneOffset()
} else {
seriesZoned.offset
}
val newSeriesStart = ZonedDateTime.ofLocal(newSeriesLocal, updated.writeZone(zone), pass)
put(CalendarContract.Events.DTSTART, newSeriesStart.toInstant().toEpochMilli())
put(CalendarContract.Events.DTEND, null)
put(CalendarContract.Events.RRULE, updated.rrule)
@@ -266,6 +285,7 @@ internal fun buildOccurrenceExceptionValues(
put(CalendarContract.Events.EVENT_TIMEZONE, times.timezone)
put(CalendarContract.Events.AVAILABILITY, form.availability.toProviderValue())
put(CalendarContract.Events.ACCESS_LEVEL, form.accessLevel.toProviderValue())
put(CalendarContract.Events.STATUS, form.status.forNewEvent().toProviderStatus())
put(CalendarContract.Events.EVENT_LOCATION, form.location.trim().ifEmpty { null })
put(CalendarContract.Events.DESCRIPTION, form.description.trim().ifEmpty { null })
if (form.colorKey == null) putAll(eventColorColumns(null, form.color))
@@ -341,7 +361,8 @@ internal fun buildMovedMasterValues(
}
put(CalendarContract.Events.AVAILABILITY, snapshot.availability)
put(CalendarContract.Events.ACCESS_LEVEL, snapshot.accessLevel)
snapshot.status?.let { put(CalendarContract.Events.STATUS, it) }
snapshot.status?.takeIf { it != CalendarContract.Events.STATUS_CANCELED }
?.let { put(CalendarContract.Events.STATUS, it) }
put(CalendarContract.Events.EVENT_LOCATION, snapshot.location?.ifEmpty { null })
put(CalendarContract.Events.DESCRIPTION, snapshot.description?.ifEmpty { null })
}
@@ -359,48 +380,11 @@ internal data class ExceptionRowSnapshot(
val exceptionEventId: Long,
val originalInstanceMillis: Long,
val isCancelled: Boolean,
val status: Int?,
val title: String,
val isAllDay: Boolean,
val dtStartMillis: Long,
val dtEndMillis: Long?,
val duration: String?,
val timezone: String?,
val availability: Int,
val accessLevel: Int,
val location: String?,
val description: String?,
)
/**
* Column values replaying a *modified* occurrence [snapshot] against the moved
* series via `CONTENT_EXCEPTION_URI`. Like [buildOccurrenceExceptionValues] the
* length travels as DURATION (the provider rejects DTEND on an exception). A
* cancelled occurrence is written separately (ORIGINAL_INSTANCE_TIME +
* STATUS_CANCELED) — this builder is only for the modified case.
*/
internal fun buildCopiedExceptionValues(snapshot: ExceptionRowSnapshot): Map<String, Any?> =
buildMap {
put(CalendarContract.Events.ORIGINAL_INSTANCE_TIME, snapshot.originalInstanceMillis)
put(CalendarContract.Events.TITLE, snapshot.title)
put(CalendarContract.Events.ALL_DAY, if (snapshot.isAllDay) 1 else 0)
put(CalendarContract.Events.DTSTART, snapshot.dtStartMillis)
put(
CalendarContract.Events.DURATION,
snapshot.duration?.takeIf { it.isNotBlank() }
?: rfc2445Duration(
(snapshot.dtEndMillis ?: snapshot.dtStartMillis) - snapshot.dtStartMillis,
snapshot.isAllDay,
),
)
put(CalendarContract.Events.EVENT_TIMEZONE, snapshot.timezone ?: "UTC")
put(CalendarContract.Events.AVAILABILITY, snapshot.availability)
put(CalendarContract.Events.ACCESS_LEVEL, snapshot.accessLevel)
put(CalendarContract.Events.EVENT_LOCATION, snapshot.location?.ifEmpty { null })
put(CalendarContract.Events.DESCRIPTION, snapshot.description?.ifEmpty { null })
snapshot.status?.let { put(CalendarContract.Events.STATUS, it) }
}
/**
* Column values for a *cancelled*-occurrence exception row ("delete only this
* event"): inserting them at `Events.CONTENT_EXCEPTION_URI/<id>` makes the
@@ -466,9 +450,24 @@ internal fun buildOccurrenceExdateValues(
duration: String?,
timezone: String?,
allDay: Int,
): Map<String, Any?> = buildOccurrencesExdateValues(
existingExdate, listOf(occurrenceMillis), dtStartMillis, rrule, rdate, duration, timezone, allDay,
)
/** [buildOccurrenceExdateValues] excluding every one of [occurrences] in one write. */
internal fun buildOccurrencesExdateValues(
existingExdate: String?,
occurrences: List<Long>,
dtStartMillis: Long,
rrule: String?,
rdate: String?,
duration: String?,
timezone: String?,
allDay: Int,
): Map<String, Any?> = mapOf(
CalendarContract.Events.EXDATE to
mergedExdate(existingExdate, occurrenceMillis, allDay != 0, timezone),
CalendarContract.Events.EXDATE to occurrences.fold(existingExdate) { exdate, millis ->
mergedExdate(exdate, millis, allDay != 0, timezone)
},
CalendarContract.Events.DTSTART to dtStartMillis,
CalendarContract.Events.RRULE to rrule,
CalendarContract.Events.RDATE to rdate,
@@ -618,7 +617,7 @@ internal fun exdateAfter(
* optionally behind the parameter prefix AOSP's `RecurrenceSet` puts in front of
* a zoned one ([exdateListZone] reads that half).
*/
private fun exdateStamps(exdate: String?): List<String> = exdate
internal fun exdateStamps(exdate: String?): List<String> = exdate
?.withoutExdateParameters()
?.split(',')
?.map { it.trim() }
@@ -685,7 +684,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,
@@ -852,10 +851,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),
@@ -867,7 +868,10 @@ 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())
put(CalendarContract.Events.STATUS, event.status.toProviderStatus())
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) }
event.description?.trim()?.takeIf { it.isNotEmpty() }
@@ -888,7 +892,7 @@ internal fun buildImportedEventValues(
*/
private fun importDuration(startMillis: Long, endMillis: Long, isAllDay: Boolean): String {
val span = (endMillis - startMillis).coerceAtLeast(0)
return if (isAllDay) "P${(span / 86_400_000L).coerceAtLeast(1)}D" else "P${span / 1_000L}S"
return rfc2445Duration(if (isAllDay) span.coerceAtLeast(MILLIS_PER_DAY) else span, isAllDay)
}
private fun EventStatus.toProviderStatus(): Int = when (this) {
@@ -1,13 +1,13 @@
package de.jeanlucmakiola.calendula.data.calendar
import de.jeanlucmakiola.floret.time.toKotlinInstantFromEpochMillis
import de.jeanlucmakiola.calendula.domain.EventStatus
import de.jeanlucmakiola.calendula.domain.AccessLevel
import de.jeanlucmakiola.calendula.domain.ics.IcsEvent
import de.jeanlucmakiola.calendula.domain.ics.deriveIcsUid
import de.jeanlucmakiola.calendula.domain.ics.parseRfc2445DurationMillis
import java.time.Instant
import java.time.LocalDate
import java.time.ZoneId
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
/**
* Map one Events row (read through [EventExportProjection]) into an [IcsEvent]
@@ -32,20 +32,11 @@ 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)
// Recurring rows store DURATION instead of DTEND; reconstruct the end from it
// so the writer can render DTEND. A missing/blank both means a zero-length event.
val end = when {
!isNull(EventExportProjection.IDX_DTEND) -> getLong(EventExportProjection.IDX_DTEND)
else -> dtStart + parseRfc2445DurationMillis(getString(EventExportProjection.IDX_DURATION))
}
// STATUS shares value 0 with TENTATIVE, so an absent column must read as Confirmed.
val status = if (isNull(EventExportProjection.IDX_STATUS)) {
EventStatus.Confirmed
} else {
mapEventStatus(getInt(EventExportProjection.IDX_STATUS))
}
// Unclamped: the writer renders DTEND as stored.
val end = endMillis(dtStart, EventExportProjection.IDX_DTEND, EventExportProjection.IDX_DURATION)
return IcsEvent(
uid = deriveIcsUid(getString(EventExportProjection.IDX_UID), eventId, dtStart),
@@ -53,31 +44,28 @@ 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),
reminderMinutes = if (isAllDay) {
val startDate = Instant.ofEpochMilli(dtStart).atZone(ZoneOffset.UTC).toLocalDate()
val startDate = utcDate(dtStart)
reminderMinutes.map {
fromProviderAllDayMinutes(it, startDate, zone, allDayReminderTimeMinutes)
}
} else {
reminderMinutes
},
status = status,
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,
)
}
@@ -109,20 +97,53 @@ internal fun exportExDates(
exdate: String?,
isAllDay: Boolean,
eventTimezone: String? = null,
seriesStartMillis: Long? = null,
): List<String> {
if (exdate.isNullOrBlank()) return emptyList()
val zone = exdateListZone(exdate, eventTimezone)
return exdate
.withoutExdateParameters()
.split(',')
.map { it.trim() }
.filter { it.isNotEmpty() }
.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 `<zone>;<stamps>` 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<String> {
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""")
@@ -25,11 +25,7 @@ internal fun ColumnReader.toEventInstance(): EventInstance? {
// string, so it belongs to the UI layer where it can be localised (#321).
val title = getString(InstanceProjection.IDX_TITLE).orEmpty()
val color = if (isNull(InstanceProjection.IDX_EVENT_COLOR)) {
getInt(InstanceProjection.IDX_CALENDAR_COLOR)
} else {
getInt(InstanceProjection.IDX_EVENT_COLOR)
}
val color = getIntOrNull(InstanceProjection.IDX_EVENT_COLOR) ?: getInt(InstanceProjection.IDX_CALENDAR_COLOR)
return EventInstance(
instanceId = getLong(InstanceProjection.IDX_INSTANCE_ID),
@@ -42,9 +38,17 @@ internal fun ColumnReader.toEventInstance(): EventInstance? {
color = color,
location = getString(InstanceProjection.IDX_LOCATION),
response = mapEventResponse(getInt(InstanceProjection.IDX_SELF_ATTENDEE_STATUS)),
status = eventStatus(InstanceProjection.IDX_STATUS),
)
}
/**
* A [CancelledEventProjection] row as an instance. Its id is the negated event
* id, so it can't collide with a provider instance id.
*/
internal fun ColumnReader.toCancelledOneOff(): EventInstance? =
toEventInstance()?.let { it.copy(instanceId = -it.eventId) }
/**
* `SELF_ATTENDEE_STATUS` as the calendar surfaces read it: a tentative "maybe"
* counts as going, and everything that is not an open or refused invitation —
@@ -1,7 +1,16 @@
package de.jeanlucmakiola.calendula.data.calendar
import android.content.ContentUris
import android.net.Uri
import android.provider.CalendarContract
/** The `Instances` table over the window [beginMillis]..[endMillis]. */
internal fun instancesUri(beginMillis: Long, endMillis: Long): Uri =
CalendarContract.Instances.CONTENT_URI.buildUpon().apply {
ContentUris.appendId(this, beginMillis)
ContentUris.appendId(this, endMillis)
}.build()
internal object CalendarProjection {
val COLUMNS: Array<String> = arrayOf(
CalendarContract.Calendars._ID,
@@ -53,6 +62,7 @@ internal object InstanceProjection {
CalendarContract.Instances.CALENDAR_COLOR,
CalendarContract.Instances.EVENT_LOCATION,
CalendarContract.Instances.SELF_ATTENDEE_STATUS,
CalendarContract.Instances.STATUS,
)
const val IDX_INSTANCE_ID = 0
@@ -66,6 +76,29 @@ internal object InstanceProjection {
const val IDX_CALENDAR_COLOR = 8
const val IDX_LOCATION = 9
const val IDX_SELF_ATTENDEE_STATUS = 10
const val IDX_STATUS = 11
}
/**
* A cancelled one-off straight from the Events table, laid out on
* [InstanceProjection]'s indices so [toCancelledOneOff] reuses its mapper. AOSP
* writes no Instances rows for a cancelled event (#388).
*/
internal object CancelledEventProjection {
val COLUMNS: Array<String> = arrayOf(
CalendarContract.Events._ID,
CalendarContract.Events._ID,
CalendarContract.Events.CALENDAR_ID,
CalendarContract.Events.TITLE,
CalendarContract.Events.DTSTART,
CalendarContract.Events.DTEND,
CalendarContract.Events.ALL_DAY,
CalendarContract.Events.EVENT_COLOR,
CalendarContract.Events.CALENDAR_COLOR,
CalendarContract.Events.EVENT_LOCATION,
CalendarContract.Events.SELF_ATTENDEE_STATUS,
CalendarContract.Events.STATUS,
)
}
internal object EventDetailProjection {
@@ -119,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<String> = arrayOf(
@@ -145,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
@@ -162,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
}
/**
@@ -189,6 +239,7 @@ internal object SearchProjection {
// Excerpted, not just filtered on: a hit has to show what it matched.
CalendarContract.Events.DESCRIPTION,
CalendarContract.Events.SELF_ATTENDEE_STATUS,
CalendarContract.Events.STATUS,
)
const val IDX_ID = 0
@@ -205,6 +256,7 @@ internal object SearchProjection {
const val IDX_RDATE = 11
const val IDX_DESCRIPTION = 12
const val IDX_SELF_ATTENDEE_STATUS = 13
const val IDX_STATUS = 14
}
/**
@@ -251,40 +303,26 @@ internal object MoveMasterProjection {
/**
* The exception rows of a recurring series (`ORIGINAL_ID` = the series), read to
* replay them against a moved copy (see [ExceptionRowSnapshot]). Both modified
* carry them over to a moved copy (see [ExceptionRowSnapshot]). Both modified
* occurrences and cancellations (`STATUS_CANCELED`) are read; the query filters
* `DELETED = 0` so provider tombstones aren't replayed.
* `DELETED = 0` so provider tombstones aren't carried over.
*/
internal object ExceptionProjection {
val COLUMNS: Array<String> = arrayOf(
CalendarContract.Events._ID,
CalendarContract.Events.ORIGINAL_INSTANCE_TIME,
CalendarContract.Events.STATUS,
CalendarContract.Events.TITLE,
CalendarContract.Events.ALL_DAY,
CalendarContract.Events.DTSTART,
CalendarContract.Events.DTEND,
CalendarContract.Events.DURATION,
CalendarContract.Events.EVENT_TIMEZONE,
CalendarContract.Events.AVAILABILITY,
CalendarContract.Events.ACCESS_LEVEL,
CalendarContract.Events.EVENT_LOCATION,
CalendarContract.Events.DESCRIPTION,
)
const val IDX_ID = 0
const val IDX_ORIGINAL_INSTANCE_TIME = 1
const val IDX_STATUS = 2
const val IDX_TITLE = 3
const val IDX_ALL_DAY = 4
const val IDX_DTSTART = 5
const val IDX_DTEND = 6
const val IDX_DURATION = 7
const val IDX_EVENT_TIMEZONE = 8
const val IDX_AVAILABILITY = 9
const val IDX_ACCESS_LEVEL = 10
const val IDX_LOCATION = 11
const val IDX_DESCRIPTION = 12
const val IDX_DTSTART = 3
const val IDX_DTEND = 4
const val IDX_DURATION = 5
}
internal object AttendeeProjection {
@@ -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<Long>,
alertsOnly: Boolean,
): Map<Long, List<Int>> {
if (eventIds.isEmpty()) return emptyMap()
val out = mutableMapOf<Long, MutableList<Int>>()
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
}
@@ -2,7 +2,6 @@ package de.jeanlucmakiola.calendula.data.calendar
import de.jeanlucmakiola.floret.time.toKotlinInstantFromEpochMillis
import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.domain.ics.parseRfc2445DurationMillis
/**
* Map an Events-table row (a search hit) to an [EventInstance]. Unlike the
@@ -16,17 +15,11 @@ internal fun ColumnReader.toSearchResult(): EventInstance? {
// long-running birthdays/anniversaries still surface in search.
if (isNull(SearchProjection.IDX_DTSTART)) return null
val dtStart = getLong(SearchProjection.IDX_DTSTART)
val end = when {
!isNull(SearchProjection.IDX_DTEND) -> getLong(SearchProjection.IDX_DTEND)
else -> dtStart + parseRfc2445DurationMillis(getString(SearchProjection.IDX_DURATION))
}.coerceAtLeast(dtStart)
val end = endMillis(dtStart, SearchProjection.IDX_DTEND, SearchProjection.IDX_DURATION)
.coerceAtLeast(dtStart)
val title = getString(SearchProjection.IDX_TITLE).orEmpty()
val color = if (isNull(SearchProjection.IDX_EVENT_COLOR)) {
getInt(SearchProjection.IDX_CALENDAR_COLOR)
} else {
getInt(SearchProjection.IDX_EVENT_COLOR)
}
val color = getIntOrNull(SearchProjection.IDX_EVENT_COLOR) ?: getInt(SearchProjection.IDX_CALENDAR_COLOR)
val eventId = getLong(SearchProjection.IDX_ID)
return EventInstance(
@@ -42,5 +35,6 @@ internal fun ColumnReader.toSearchResult(): EventInstance? {
isRecurring = !getString(SearchProjection.IDX_RRULE).isNullOrEmpty() ||
!getString(SearchProjection.IDX_RDATE).isNullOrEmpty(),
response = mapEventResponse(getInt(SearchProjection.IDX_SELF_ATTENDEE_STATUS)),
status = eventStatus(SearchProjection.IDX_STATUS),
)
}
@@ -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<String>
/**
* 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<String>): Set<SyncAccount>?
/**
* 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<Unit>
}
/** 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<SyncAccount>,
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<SyncAccount>()
// One already running when asked is someone else's sync: it only counts once idle again.
var priorRuns: MutableSet<SyncAccount>? = 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 <queries> entry.
override fun adapterAccountTypes(): Set<String> =
ContentResolver.getSyncAdapterTypes()
.filter { it.authority == CalendarContract.AUTHORITY }
.mapTo(mutableSetOf()) { it.accountType }
override fun addressableAccounts(types: Set<String>): Set<SyncAccount>? {
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<Unit> = 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<CalendarSource>.syncAccounts(): Set<SyncAccount> =
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<SyncAccount>,
val needsAccess: Set<SyncAccount>,
val dismissed: Set<SyncAccount> = 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<SyncAccount> = emptySet())
@@ -2,16 +2,15 @@ package de.jeanlucmakiola.calendula.data.contacts
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.provider.ContactsContract
import android.provider.ContactsContract.CommonDataKinds.Event
import android.util.Log
import androidx.core.content.ContextCompat
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.calendula.domain.contacts.ContactSpecialDate
import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
import de.jeanlucmakiola.calendula.domain.contacts.managedUid
import de.jeanlucmakiola.calendula.domain.contacts.parseContactEventDate
import de.jeanlucmakiola.floret.android.hasPermission
import javax.inject.Inject
import javax.inject.Singleton
@@ -31,8 +30,7 @@ interface ContactSpecialDatesDataSource {
/** Whether `READ_CONTACTS` is granted — the gate for every contacts read. */
fun Context.hasContactsPermission(): Boolean =
ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) ==
PackageManager.PERMISSION_GRANTED
hasPermission(Manifest.permission.READ_CONTACTS)
/** Map a `ContactsContract` event `TYPE` to our calendar bucket. */
internal fun specialDateTypeForRawEventType(type: Int): SpecialDateType = when (type) {
@@ -8,6 +8,7 @@ import de.jeanlucmakiola.floret.reminders.ReminderOverride
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.domain.Availability
import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.FormTime
import de.jeanlucmakiola.calendula.domain.RecurrenceFreq
import de.jeanlucmakiola.calendula.domain.SimpleRecurrence
import de.jeanlucmakiola.calendula.domain.contacts.ContactSpecialDate
@@ -212,8 +213,8 @@ class SpecialDatesSyncEngine @Inject constructor(
calendarId = calendarId,
title = title,
isAllDay = true,
start = start,
end = start,
start = FormTime(start),
end = FormTime(start),
reminders = reminderCtx.resolveAllDay(calendarId),
availability = Availability.Free,
rrule = YEARLY_RRULE,
@@ -2,6 +2,7 @@ package de.jeanlucmakiola.calendula.data.di
import javax.inject.Qualifier
/** The process-wide `CoroutineScope` that app-lifetime singletons share their flows in. */
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class IoDispatcher
annotation class ApplicationScope
@@ -11,17 +11,24 @@ 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
import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesCalendarSpec
import de.jeanlucmakiola.calendula.data.reminders.ProviderReminderInstanceSource
import de.jeanlucmakiola.calendula.data.reminders.ReminderInstanceSource
import kotlinx.coroutines.CoroutineDispatcher
import de.jeanlucmakiola.calendula.data.time.AndroidTodaySource
import de.jeanlucmakiola.calendula.data.time.AndroidZoneSource
import de.jeanlucmakiola.calendula.data.time.TodaySource
import de.jeanlucmakiola.calendula.data.time.ZoneSource
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import javax.inject.Singleton
private val Context.calendulaDataStore: DataStore<Preferences> by preferencesDataStore(
@@ -44,6 +51,12 @@ abstract class DataBindModule {
impl: CalendarRepositoryImpl,
): CalendarRepository
@Binds
@Singleton
abstract fun bindSyncRequester(
impl: AndroidSyncRequester,
): SyncRequester
@Binds
@Singleton
abstract fun bindReminderInstanceSource(
@@ -61,6 +74,18 @@ abstract class DataBindModule {
abstract fun bindSpecialDatesCalendarSpec(
impl: AndroidSpecialDatesCalendarSpec,
): SpecialDatesCalendarSpec
@Binds
@Singleton
abstract fun bindTodaySource(
impl: AndroidTodaySource,
): TodaySource
@Binds
@Singleton
abstract fun bindZoneSource(
impl: AndroidZoneSource,
): ZoneSource
}
@Module
@@ -73,6 +98,7 @@ object DataProvideModule {
context.calendulaDataStore
@Provides
@IoDispatcher
fun provideIoDispatcher(): CoroutineDispatcher = Dispatchers.IO
@Singleton
@ApplicationScope
fun provideApplicationScope(): CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
}
@@ -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<String>): Set<String> =
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
}
/**
@@ -1,15 +1,15 @@
package de.jeanlucmakiola.calendula.data.prefs
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.MutablePreferences
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import de.jeanlucmakiola.floret.prefs.Pref
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 kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton
@@ -26,17 +26,17 @@ import javax.inject.Singleton
*/
@Singleton
class CalendarPrefs @Inject constructor(
private val store: DataStore<Preferences>,
store: DataStore<Preferences>,
) {
private val prefs = PrefStore(store)
// Both id sets are deduped: the store is shared with SettingsPrefs, so any
// unrelated write would otherwise re-emit an identical set.
val hiddenCalendarIds: Flow<Set<Long>> = store.data
.map { prefs -> prefs[HIDDEN_IDS_KEY].parseIds() }
.distinctUntilChanged()
val hiddenCalendarIds: Flow<Set<Long>> = prefs.flow(CalendarPrefKeys.hiddenCalendarIds)
suspend fun setHiddenCalendarIds(ids: Set<Long>) {
store.edit { prefs -> prefs.writeIds(HIDDEN_IDS_KEY, ids) }
suspend fun setHiddenCalendarIds(ids: Set<Long>) = prefs.set(CalendarPrefKeys.hiddenCalendarIds, ids)
/** Rewrite the drawer's hidden set atomically from its current value. */
suspend fun updateHiddenCalendarIds(transform: (Set<Long>) -> Set<Long>) {
prefs.update(CalendarPrefKeys.hiddenCalendarIds, transform)
}
/**
@@ -48,24 +48,18 @@ 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<Set<Long>> = store.data
.map { prefs -> prefs[DISABLED_IDS_KEY].parseIds() }
.distinctUntilChanged()
val pendingDisabledCalendarIds: Flow<Set<Long>> = prefs.flow(CalendarPrefKeys.pendingDisabledCalendarIds)
suspend fun addPendingDisabledCalendarIds(ids: Collection<Long>) =
editPendingDisabled { it + ids }
suspend fun addPendingDisabledCalendarIds(ids: Collection<Long>) {
prefs.update(CalendarPrefKeys.pendingDisabledCalendarIds) { it + ids }
}
/**
* Drop [ids] from the pending set, one at a time as the reconciler flushes
* them, so a run that fails part-way never re-applies what already landed.
*/
suspend fun removePendingDisabledCalendarIds(ids: Collection<Long>) =
editPendingDisabled { it - ids.toSet() }
private suspend fun editPendingDisabled(transform: (Set<Long>) -> Set<Long>) {
store.edit { prefs ->
prefs.writeIds(DISABLED_IDS_KEY, transform(prefs[DISABLED_IDS_KEY].parseIds()))
}
suspend fun removePendingDisabledCalendarIds(ids: Collection<Long>) {
prefs.update(CalendarPrefKeys.pendingDisabledCalendarIds) { it - ids.toSet() }
}
/**
@@ -73,39 +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<Boolean?> = store.data.map { prefs ->
prefs[VISIBILITY_NOTICE_KEY]
}
val visibilityNoticePending: Flow<Boolean?> = prefs.flow(CalendarPrefKeys.visibilityNoticePending)
suspend fun setVisibilityNoticePending(pending: Boolean) {
store.edit { prefs -> prefs[VISIBILITY_NOTICE_KEY] = 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<Long?> = store.data.map { prefs ->
prefs[LAST_USED_CALENDAR_KEY]
}
val lastUsedCalendarId: Flow<Long?> = prefs.flow(CalendarPrefKeys.lastUsedCalendarId)
suspend fun setLastUsedCalendarId(id: Long) {
store.edit { prefs -> prefs[LAST_USED_CALENDAR_KEY] = id }
}
suspend fun setLastUsedCalendarId(id: Long) = prefs.set(CalendarPrefKeys.lastUsedCalendarId, id)
companion object {
internal val HIDDEN_IDS_KEY = stringPreferencesKey("hidden_calendar_ids")
internal val DISABLED_IDS_KEY = stringPreferencesKey("disabled_calendar_ids")
internal val VISIBILITY_NOTICE_KEY = booleanPreferencesKey("visibility_notice_pending")
internal val LAST_USED_CALENDAR_KEY = longPreferencesKey("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<Set<SyncAccount>> = prefs.flow(CalendarPrefKeys.syncAccessDismissed)
suspend fun setSyncAccessDismissed(account: SyncAccount, dismissed: Boolean) {
prefs.update(CalendarPrefKeys.syncAccessDismissed) { if (dismissed) it + account else it - account }
}
}
private fun String?.parseIds(): Set<Long> = orEmpty()
.split(',')
.mapNotNull { it.trim().toLongOrNull() }
.toSet()
/** Every key [CalendarPrefs] stores; the names are on-disk data. */
internal object CalendarPrefKeys {
val hiddenCalendarIds: Pref<Set<Long>> = idSetPref("hidden_calendar_ids")
val pendingDisabledCalendarIds: Pref<Set<Long>> = idSetPref("disabled_calendar_ids")
val visibilityNoticePending: Pref<Boolean?> = nullableBooleanPref("visibility_notice_pending")
val lastUsedCalendarId: Pref<Long?> = nullableLongPref("last_used_calendar_id")
val syncAccessDismissed: Pref<Set<SyncAccount>> = stringSetPref("sync_access_dismissed").map(
{ stored -> stored.mapNotNullTo(mutableSetOf()) { it.toSyncAccount() } },
{ accounts -> accounts.mapTo(mutableSetOf()) { "${it.type}$FIELD_SEPARATOR${it.name}" } },
)
private fun MutablePreferences.writeIds(key: Preferences.Key<String>, ids: Set<Long>) {
if (ids.isEmpty()) remove(key) else set(key, ids.sorted().joinToString(","))
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. */
internal fun idSetPref(name: String): Pref<Set<Long>> = nullableStringPref(name).map(
{ stored -> stored.orEmpty().split(',').mapNotNull { it.trim().toLongOrNull() }.toSet() },
{ ids -> if (ids.isEmpty()) null else ids.sorted().joinToString(",") },
)
@@ -2,10 +2,11 @@ package de.jeanlucmakiola.calendula.data.prefs
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.longPreferencesKey
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
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
@@ -20,17 +21,30 @@ import javax.inject.Singleton
*/
@Singleton
class ReminderStatePrefs @Inject constructor(
private val store: DataStore<Preferences>,
store: DataStore<Preferences>,
) {
private val prefs = PrefStore(store)
/** The watermark, or `null` before the first scan has ever run. */
suspend fun lastScanMillis(): Long? = store.data.map { it[LAST_SCAN_KEY] }.first()
suspend fun lastScanMillis(): Long? = prefs.get(ReminderStateKeys.lastScanMillis)
suspend fun setLastScanMillis(millis: Long) {
store.edit { prefs -> prefs[LAST_SCAN_KEY] = millis }
}
suspend fun setLastScanMillis(millis: Long) = prefs.set(ReminderStateKeys.lastScanMillis, millis)
private companion object {
val LAST_SCAN_KEY = longPreferencesKey("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<Long?> = nullableLongPref("reminder_last_scan_millis")
val lastDigestDay: Pref<String?> = nullableStringPref("reminder_last_digest_day")
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,157 @@
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 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.time.format.DateTimeFormatter
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<ReminderEventInstance>) {
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 = DateTimeFormatter.ofPattern(
android.text.format.DateFormat.getBestDateTimePattern(locale, "EEEdMMM"),
locale,
).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
}
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
}
}
@@ -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<Long, Pair<ReminderAlert, Int>>()
/** 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<Long>(
extraBufferCapacity = 8,
onBufferOverflow = BufferOverflow.DROP_OLDEST,
)
/** The [ReminderAlert.key]s of reminders as they are dismissed, snoozed or handed back. */
val handled: SharedFlow<Long> = 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
}
}
@@ -6,18 +6,15 @@ import android.content.Intent
import androidx.core.net.toUri
import dagger.hilt.android.AndroidEntryPoint
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import de.jeanlucmakiola.floret.android.goAsync
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
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.
@@ -41,30 +38,24 @@ class ReminderActionReceiver : BroadcastReceiver() {
ACTION_DISMISS -> notifier.cancel(alert)
ACTION_SNOOZE -> {
// Tapped on a stale view: the reminder that replaced it stays put.
if (notifier.isSuperseded(alert)) return
// Cancel now so the notification doesn't linger until the alarm;
// the snooze delay read is the only async work.
notifier.cancel(alert)
val pendingResult = goAsync()
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
try {
val minutes = settingsPrefs.snoozeMinutes.first()
val triggerAt = System.currentTimeMillis() + minutes * 60_000L
scheduler.schedule(alert, triggerAt)
} finally {
pendingResult.finish()
}
goAsync {
val minutes = settingsPrefs.snoozeMinutes.first()
val triggerAt = System.currentTimeMillis() + minutes * 60_000L
scheduler.schedule(alert, triggerAt)
}
}
ACTION_SHOW -> {
val pendingResult = goAsync()
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
try {
if (settingsPrefs.remindersEnabled.first() && notifier.canPost()) {
notifier.post(alert)
}
} finally {
pendingResult.finish()
goAsync {
// A later reminder posted while this one was snoozed has taken its place.
if (notifier.isSuperseded(alert)) return@goAsync
if (settingsPrefs.remindersEnabled.first() && notifier.canPost()) {
notifier.post(alert)
}
}
}
@@ -83,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"
@@ -95,26 +89,33 @@ class ReminderActionReceiver : BroadcastReceiver() {
/**
* An explicit intent to this receiver carrying [alert] as extras. The
* data URI duplicates no information but is what keeps two reminders'
* `PendingIntent`s apart — `filterEquals` never compares extras.
* `PendingIntent`s apart — `filterEquals` never compares extras. The
* snooze alarm is the exception: one per occurrence, so a later snooze
* replaces an earlier one and a newer reminder can cancel it.
*/
fun intent(context: Context, action: String, alert: ReminderAlert): Intent =
Intent(context, ReminderActionReceiver::class.java).apply {
this.action = action
data = "calendula://reminder/${alert.key}".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)
data = "calendula://reminder/${identity(alert, action)}".toUri()
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;
* the top bits it drops are separated by [intent]'s per-reminder URI.
* the top bits it drops are separated by [intent]'s URI.
*/
fun requestCode(alert: ReminderAlert, action: String): Int {
val actionOffset = when (action) {
@@ -122,12 +123,16 @@ class ReminderActionReceiver : BroadcastReceiver() {
ACTION_DISMISS -> 2
ACTION_SHOW -> 3
ACTION_OPEN -> 4
ACTION_ALERT_SCREEN -> 5
else -> 0
}
return (alert.key.toInt() shl 3) + actionOffset
return (identity(alert, action).toInt() shl 3) + actionOffset
}
private fun alertFrom(intent: Intent): ReminderAlert? {
private fun identity(alert: ReminderAlert, action: String): Long =
if (action == ACTION_SHOW) alert.occurrenceKey else alert.key
fun alertFrom(intent: Intent): ReminderAlert? {
if (!intent.hasExtra(EXTRA_ALERT_KEY)) return null
return ReminderAlert(
key = intent.getLongExtra(EXTRA_ALERT_KEY, 0L),
@@ -4,20 +4,12 @@ import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.content.getSystemService
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.floret.android.setWakeup
import javax.inject.Inject
import javax.inject.Singleton
/**
* True on API < 31 (no restriction), and on 31+ when the exact-alarm capability
* is held — auto-granted via `USE_EXACT_ALARM` on API 33+ (Calendula is a
* calendar app), user-revocable on 31–32.
*/
internal fun AlarmManager.canScheduleExactCompat(): Boolean =
Build.VERSION.SDK_INT < Build.VERSION_CODES.S || canScheduleExactAlarms()
/**
* Holds the app's own wake-up for the next reminder (#75). Exactly one alarm
* exists at a time, for the earliest reminder ahead; every firing re-scans and
@@ -31,16 +23,7 @@ class ReminderAlarmScheduler @Inject constructor(
fun scheduleScan(triggerAtMillis: Long) {
val alarmManager = context.getSystemService<AlarmManager>() ?: return
val pendingIntent = scanPendingIntent(PendingIntent.FLAG_UPDATE_CURRENT)
if (alarmManager.canScheduleExactCompat()) {
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent,
)
} else {
alarmManager.setAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent,
)
}
alarmManager.setWakeup(triggerAtMillis, scanPendingIntent(PendingIntent.FLAG_UPDATE_CURRENT))
}
/** Drop the pending wake-up — reminders are off, or there is nothing to wait for. */
@@ -1,6 +1,7 @@
package de.jeanlucmakiola.calendula.data.reminders
import de.jeanlucmakiola.calendula.domain.reminders.PlannedReminder
import de.jeanlucmakiola.calendula.domain.reminders.occurrenceKey
/**
* One reminder as the notification layer needs it: what to show, and the stable
@@ -20,6 +21,13 @@ data class ReminderAlert(
val isAllDay: Boolean,
)
/**
* The occurrence [ReminderAlert] belongs to. Keys the notification and the
* snooze alarm, so a later reminder for the same occurrence replaces the earlier
* one instead of stacking beside it (#463).
*/
val ReminderAlert.occurrenceKey: Long get() = occurrenceKey(eventId, beginMillis)
fun PlannedReminder.toAlert(): ReminderAlert = ReminderAlert(
key = key,
eventId = instance.eventId,
@@ -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<Long, Int>? {
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<String>, highWater: Map<Long, Int>): Map<Long, Int> {
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<ReminderChannelGroupSpec>,
val channels: List<ReminderChannelSpec>,
/**
* 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<ReminderChannelSpec>,
/** The [groups] holding a channel that exists or is about to be written. */
val groupsInUse: List<ReminderChannelGroupSpec>,
val staleChannelIds: List<String>,
val staleGroupIds: List<String>,
/** Stale channels kept for now, because a notification on them is still showing. */
val keptChannelIds: List<String> = 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<CalendarSource>,
existing: Collection<ExistingReminderChannel>,
existingGroupIds: Collection<String>,
unnamed: String,
description: String,
versions: Map<Long, Int> = emptyMap(),
showingChannelIds: Set<String> = 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<Long> = emptySet(),
/** The blocked ones whose whole account group is off, which only the app's own screen can undo. */
val groupBlockedCalendarIds: Set<Long> = 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<Long>,
appEnabled: Boolean,
channels: Map<String, ReminderChannelState>,
blockedGroupIds: Set<String>,
versions: Map<Long, Int> = 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,
)
}
@@ -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<CalendarSource>, channelIds: Set<String>, versions: Map<Long, Int>): 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<Long, Int> = emptyMap()
private fun currentVersions(existingChannelIds: Collection<String>): Map<Long, Int> =
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<String>): Set<String> = 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 <T> 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<Long>): 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<Long>): Map<Long, Uri?> {
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<Long>, 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<Long, Int>, 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<CalendarSource>,
existing: List<NotificationChannel>,
existingGroupIds: List<String>,
versions: Map<Long, Int>,
showingChannelIds: Set<String> = 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<ReminderChannelGroupSpec>,
channels: List<ReminderChannelSpec>,
existing: List<NotificationChannel>,
) {
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
}
}
@@ -1,9 +1,10 @@
package de.jeanlucmakiola.calendula.data.reminders
import android.content.Context
import android.content.ContentUris
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
@@ -37,10 +38,7 @@ class ProviderReminderInstanceSource @Inject constructor(
) : ReminderInstanceSource {
override fun occurrences(fromMillis: Long, toMillis: Long): List<ReminderEventInstance> {
val uri = CalendarContract.Instances.CONTENT_URI.buildUpon().apply {
ContentUris.appendId(this, fromMillis)
ContentUris.appendId(this, toMillis)
}.build()
val uri = instancesUri(fromMillis, toMillis)
// `visible` is the flag the app's one visibility model writes (#75).
// The status clause mirrors CalendarDataSource.instances: NULL means
// "normal", so a bare `!= CANCELED` would drop every ordinary event.
@@ -75,28 +73,8 @@ class ProviderReminderInstanceSource @Inject constructor(
} ?: emptyList()
}
override fun reminderMinutes(eventIds: Collection<Long>): Map<Long, List<Int>> {
if (eventIds.isEmpty()) return emptyMap()
val out = mutableMapOf<Long, MutableList<Int>>()
// 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<Long>): Map<Long, List<Int>> =
context.contentResolver.reminderMinutesByEvent(eventIds, alertsOnly = true)
override fun longestReminderMinutes(): Int = context.contentResolver.query(
CalendarContract.Reminders.CONTENT_URI,
@@ -108,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,
@@ -119,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,
)
}
}
@@ -1,16 +1,16 @@
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.pm.PackageManager
import android.content.Intent
import androidx.core.net.toUri
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.calendula.MainActivity
import de.jeanlucmakiola.calendula.R
@@ -19,6 +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,13 +37,14 @@ import javax.inject.Inject
import javax.inject.Singleton
/**
* Posts one notification per due reminder 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 reminder's stable key, so a scan that posts the same reminder
* again — a catch-up pass overlapping the alarm that already fired — replaces
* its notification silently ([NotificationCompat.Builder.setOnlyAlertOnce])
* instead of stacking a second one.
* 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
* same one posted again — a catch-up pass overlapping the alarm that already
* fired — replaces its notification silently.
*/
@Singleton
class ReminderNotifier @Inject constructor(
@@ -43,35 +52,108 @@ 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. */
fun canPost(): Boolean {
val granted = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) ==
PackageManager.PERMISSION_GRANTED
context.hasPermission(Manifest.permission.POST_NOTIFICATIONS)
return granted && NotificationManagerCompat.from(context).areNotificationsEnabled()
}
/**
* 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. Returns whether the
* notification was put up, which the snooze re-show path uses to tell a
* silenced reminder from a delivered one.
* 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): Boolean {
if (isSilenced(alert.calendarId)) return false
ensureChannel()
val title = alert.title.ifBlank { context.getString(R.string.event_untitled) }
suspend fun post(alert: ReminderAlert, quiet: Boolean = false, ring: Boolean = true) {
if (isSilenced(alert.calendarId)) return
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()
@@ -79,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,
@@ -92,18 +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(true)
.setContentIntent(detailIntent(alert))
.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(if (ringing) alertScreenIntent(alert) else detailIntent(alert))
.addAction(
R.drawable.ic_notification_snooze,
context.getString(R.string.reminder_action_snooze),
@@ -114,23 +213,94 @@ 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 {
NotificationManagerCompat.from(context)
.notify(alert.key.toString(), NOTIFICATION_ID, notification)
manager.notify(alert.occurrenceKey.toString(), NOTIFICATION_ID, notification)
} catch (e: SecurityException) {
// POST_NOTIFICATIONS was revoked between canPost() and here.
Log.w(TAG, "Could not post reminder for event ${alert.eventId}", e)
}
// Handled either way — a retry hits the same revoked permission.
return true
}
/** Remove a posted reminder (snooze re-shows it later; dismiss is final). */
/**
* Remove [alert]'s notification (snooze re-shows it later; dismiss is final),
* unless a later reminder has replaced it — an action tapped on a stale view
* mustn't take the newer one with it.
*/
fun cancel(alert: ReminderAlert) {
NotificationManagerCompat.from(context).cancel(alert.key.toString(), NOTIFICATION_ID)
val manager = NotificationManagerCompat.from(context)
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 {
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? {
val tag = alert.occurrenceKey.toString()
return NotificationManagerCompat.from(context).activeNotifications
.firstOrNull { it.tag == tag && it.id == NOTIFICATION_ID }
?.notification?.extras
?.takeIf { it.containsKey(EXTRA_REMINDER_KEY) }
?.getLong(EXTRA_REMINDER_KEY)
}
/**
* Remove a reminder for the same occurrence posted before reminders shared a
* notification. It carries no reminder key; its time and title identify it.
*/
private fun cancelLegacy(alert: ReminderAlert) {
val manager = NotificationManagerCompat.from(context)
manager.activeNotifications
.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) }
.forEach { manager.cancel(it.tag, it.id) }
}
private fun displayTitle(alert: ReminderAlert): String =
alert.title.ifBlank { context.getString(R.string.event_untitled) }
private fun actionIntent(alert: ReminderAlert, action: String): PendingIntent =
PendingIntent.getBroadcast(
context,
@@ -139,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.
@@ -149,24 +326,49 @@ 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 (alert id) already keys the
// One id, distinct tags: the tag (occurrence) already keys the
// notification, so a fixed id keeps cancellation/replacement simple.
const val NOTIFICATION_ID = 1
const val EXTRA_REMINDER_KEY = "de.jeanlucmakiola.calendula.reminder_key"
}
}
@@ -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
}
}
}
}
@@ -2,19 +2,22 @@ package de.jeanlucmakiola.calendula.data.reminders
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.util.Log
import androidx.core.content.ContextCompat
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.di.IoDispatcher
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
import de.jeanlucmakiola.floret.android.hasPermission
import de.jeanlucmakiola.floret.di.IoDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.SupervisorJob
@@ -44,8 +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,23 +125,76 @@ 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()) {
schedule.due.forEach { notifier.post(it.toAlert()) }
schedule.due.forEach {
val alert = it.toAlert()
snoozes.cancel(alert)
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
}
private fun hasReadCalendar(): Boolean = ContextCompat.checkSelfPermission(
context, Manifest.permission.READ_CALENDAR,
) == PackageManager.PERMISSION_GRANTED
/**
* 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)
/**
* Re-scan when the provider changes, so a saved or deleted event re-arms the
@@ -156,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
}
}
@@ -4,10 +4,7 @@ import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import de.jeanlucmakiola.floret.android.goAsync
import javax.inject.Inject
/**
@@ -29,14 +26,7 @@ class ReminderScheduleReceiver : BroadcastReceiver() {
// exported and the broadcasts it takes are protected, so any other
// action did not come from where it claims to.
if (intent.action !in HANDLED_ACTIONS) return
val pendingResult = goAsync()
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
try {
scanner.scan()
} finally {
pendingResult.finish()
}
}
goAsync { scanner.scan() }
}
companion object {
@@ -3,9 +3,9 @@ package de.jeanlucmakiola.calendula.data.reminders
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.os.Build
import androidx.core.content.getSystemService
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.floret.android.setWakeup
import javax.inject.Inject
import javax.inject.Singleton
@@ -31,24 +31,18 @@ class ReminderSnoozeScheduler @Inject constructor(
ReminderActionReceiver.intent(context, ReminderActionReceiver.ACTION_SHOW, alert),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
if (canScheduleExact(alarmManager)) {
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent,
)
} else {
// Exact alarms revoked (API 31–32); an inexact wake is the best
// available without nagging for SCHEDULE_EXACT_ALARM.
alarmManager.setAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent,
)
}
alarmManager.setWakeup(triggerAtMillis, pendingIntent)
}
/**
* True on API < 31 (no restriction), and on 31+ when the exact-alarm
* capability is held — auto-granted via `USE_EXACT_ALARM` on API 33+
* (Calendula is a calendar app), user-revocable on 31–32.
*/
private fun canScheduleExact(alarmManager: AlarmManager): Boolean =
Build.VERSION.SDK_INT < Build.VERSION_CODES.S || alarmManager.canScheduleExactAlarms()
/** Drop a snooze still pending for [alert]'s occurrence, so it can't re-show over a newer reminder. */
fun cancel(alert: ReminderAlert) {
val pendingIntent = PendingIntent.getBroadcast(
context,
ReminderActionReceiver.requestCode(alert, ReminderActionReceiver.ACTION_SHOW),
ReminderActionReceiver.intent(context, ReminderActionReceiver.ACTION_SHOW, alert),
PendingIntent.FLAG_NO_CREATE or PendingIntent.FLAG_IMMUTABLE,
) ?: return
context.getSystemService<AlarmManager>()?.cancel(pendingIntent)
pendingIntent.cancel()
}
}
@@ -1,5 +1,6 @@
package de.jeanlucmakiola.calendula.data.reminders
import de.jeanlucmakiola.calendula.domain.runsMidnightToMidnight
import de.jeanlucmakiola.calendula.ui.common.timeOfDayFormatter
import java.time.DayOfWeek
import java.time.Instant
@@ -11,6 +12,8 @@ import java.time.format.FormatStyle
import java.time.format.TextStyle
import java.time.temporal.ChronoUnit
import java.util.Locale
import kotlinx.datetime.toKotlinTimeZone
import kotlin.time.Instant as KInstant
/**
* The one line of time context in a reminder notification. Pure so it can be
@@ -32,7 +35,8 @@ import java.util.Locale
* - all-day, multi-day: "Tomorrow – 12 Jun 2026" (relative start, explicit end)
*
* All-day instances store UTC midnights with an exclusive end, so they are read
* in UTC and the end day is the last *covered* day (issue #308).
* in UTC and the end day is the last *covered* day (issue #308). A timed event
* from local midnight to local midnight reads like one too, in [zone] (#296).
*/
fun reminderTimeText(
beginMillis: Long,
@@ -47,11 +51,17 @@ fun reminderTimeText(
tomorrowLabel: String,
yesterdayLabel: String,
): String {
if (isAllDay) {
val wholeDays = !isAllDay && runsMidnightToMidnight(
KInstant.fromEpochMilliseconds(beginMillis),
KInstant.fromEpochMilliseconds(endMillis),
zone.toKotlinTimeZone(),
)
if (isAllDay || wholeDays) {
val dayZone = if (isAllDay) ZoneOffset.UTC else zone
val dateFormat = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(locale)
// (atZone().toLocalDate() instead of LocalDate.ofInstant — API 34+)
val firstDay = Instant.ofEpochMilli(beginMillis).atZone(ZoneOffset.UTC).toLocalDate()
val lastDay = Instant.ofEpochMilli(endMillis).atZone(ZoneOffset.UTC).toLocalDate()
val firstDay = Instant.ofEpochMilli(beginMillis).atZone(dayZone).toLocalDate()
val lastDay = Instant.ofEpochMilli(endMillis).atZone(dayZone).toLocalDate()
.minusDays(1)
.coerceAtLeast(firstDay)
val start = relativeDayPrefix(
@@ -0,0 +1,73 @@
package de.jeanlucmakiola.calendula.data.time
import android.content.Context
import android.content.Intent
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.calendula.data.di.ApplicationScope
import de.jeanlucmakiola.floret.android.broadcastTicks
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.transformLatest
import kotlinx.datetime.LocalDate
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime
import javax.inject.Inject
import kotlin.time.Clock
/** The current local date, re-emitted whenever it changes (#373). */
interface TodaySource {
val today: Flow<LocalDate>
}
/**
* Re-reads the date on every minute boundary while collected, and at once on the
* system's date, time and zone broadcasts, which can arrive late or not at all.
* One receiver and tick loop is shared by every collector.
*/
@OptIn(ExperimentalCoroutinesApi::class)
class AndroidTodaySource @Inject constructor(
@ApplicationContext private val context: Context,
@ApplicationScope scope: CoroutineScope,
) : TodaySource {
override val today: Flow<LocalDate> = context
.broadcastTicks(Intent.ACTION_DATE_CHANGED, Intent.ACTION_TIME_CHANGED, Intent.ACTION_TIMEZONE_CHANGED)
.transformLatest {
while (true) {
emit(currentDate())
delay(MINUTE_MILLIS - Clock.System.now().toEpochMilliseconds() % MINUTE_MILLIS)
}
}
.distinctUntilChanged()
.shareIn(scope, SharingStarted.WhileSubscribed(replayExpirationMillis = 0), replay = 1)
}
private const val MINUTE_MILLIS = 60_000L
fun currentDate(): LocalDate = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).date
/**
* Today as a hot flow seeded with [initial]. [onRollover] runs with the previous
* and the new date each time the day changes while collected, so a screen left
* open over midnight can move off yesterday (#373).
*/
fun Flow<LocalDate>.stateFollowingDays(
scope: CoroutineScope,
initial: LocalDate,
onRollover: (old: LocalDate, new: LocalDate) -> Unit,
): StateFlow<LocalDate> {
var last = initial
return onEach { date ->
val old = last
last = date
if (old != date) onRollover(old, date)
}.stateWhileSubscribed(scope, initial)
}
@@ -0,0 +1,42 @@
package de.jeanlucmakiola.calendula.data.time
import android.content.Context
import android.content.Intent
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.calendula.data.di.ApplicationScope
import de.jeanlucmakiola.floret.android.broadcastTicks
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.shareIn
import kotlinx.datetime.TimeZone
import javax.inject.Inject
/**
* The zone the device is in. Every screen that turns wall clock into instants
* reads it from here, so the timeline, the event form and a saved move use the
* same zone (#387).
*/
interface ZoneSource {
/** The device's zone, re-emitted whenever it changes. */
val zone: Flow<TimeZone>
/** The device's zone right now. */
fun current(): TimeZone
}
/** Follows the system's zone broadcast, one receiver shared by every collector. */
class AndroidZoneSource @Inject constructor(
@ApplicationContext private val context: Context,
@ApplicationScope scope: CoroutineScope,
) : ZoneSource {
override val zone: Flow<TimeZone> = context.broadcastTicks(Intent.ACTION_TIMEZONE_CHANGED)
.map { current() }
.distinctUntilChanged()
.shareIn(scope, SharingStarted.WhileSubscribed(replayExpirationMillis = 0), replay = 1)
override fun current(): TimeZone = TimeZone.currentSystemDefault()
}
@@ -1,18 +1,35 @@
package de.jeanlucmakiola.calendula.domain
import kotlinx.datetime.TimeZone
import kotlinx.datetime.atStartOfDayIn
import kotlin.time.Instant
/** Lower values appear first in lists and get the upper visible lanes in grids. */
fun EventInstance.displayPriority(zone: TimeZone): Int = when {
isDeclined -> 3
isCrossedOut -> 3
spansMultipleDays(zone) -> 0
isAllDay -> 1
coversWholeDays(zone) -> 1
else -> 2
}
/** Shared order for agenda and split day lists. Grid bars add their lane geometry. */
fun eventDisplayComparator(zone: TimeZone): Comparator<EventInstance> =
compareBy<EventInstance> { it.displayPriority(zone) }
.thenBy { it.start }
.thenBy { it.title }
.thenBy { it.instanceId }
/**
* Shared order for agenda and split day lists. Grid bars add their lane geometry.
* Each event's priority is worked out once, not on every comparison.
*/
fun List<EventInstance>.sortedForDisplay(zone: TimeZone): List<EventInstance> =
map { Triple(it, it.displayPriority(zone), it.displayStart(zone)) }
.sortedWith(
compareBy<Triple<EventInstance, Int, Instant>> { it.second }
.thenBy { it.third }
.thenBy { it.first.title }
.thenBy { it.first.instanceId },
)
.map { it.first }
/**
* Where an event starts for ordering: a whole-day event at local midnight of its
* first day, since an all-day one is stored at UTC midnight and would otherwise
* sort around timed events by the device's offset (#296).
*/
internal fun EventInstance.displayStart(zone: TimeZone): Instant =
if (coversWholeDays(zone)) spanFirstDay(zone).atStartOfDayIn(zone) else start
@@ -1,10 +1,12 @@
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
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toInstant
import kotlinx.datetime.UtcOffset
import kotlinx.datetime.toLocalDateTime
import kotlin.time.Instant
@@ -17,8 +19,8 @@ data class EventForm(
val calendarId: Long?,
val title: String = "",
val isAllDay: Boolean = false,
val start: LocalDateTime,
val end: LocalDateTime,
val start: FormTime,
val end: FormTime,
/**
* The zone [start]/[end] are wall-clock values in, or null to follow the
* device — null is not "no zone", it is "whichever zone the device is in
@@ -40,8 +42,16 @@ data class EventForm(
val description: String = "",
/** Reminder lead times in minutes before the start, deduplicated. */
val reminders: List<Int> = 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<FixedTimeReminder> = emptyList(),
val availability: Availability = Availability.Busy,
val accessLevel: AccessLevel = AccessLevel.Default,
/** Confirmed / Tentative / Cancelled (#388). */
val status: EventStatus = EventStatus.Confirmed,
/**
* Bare RRULE value (`Events.RRULE` convention, no "RRULE:" prefix); null
* means a one-off event. May hold rules the simple picker can't express —
@@ -70,6 +80,19 @@ data class EventForm(
val attendees: List<EventAttendee> = emptyList(),
)
/**
* One end of a form's span: a wall-clock [dateTime] in the form's zone, and the
* [offset] it was read at when the fall-back hour repeats that wall clock — both
* of the hour's instants share one [LocalDateTime] (#387). Null everywhere else,
* so a time changed and changed back compares equal again. A time picked by hand
* gets its pass from [repicked]; one without an offset reads as the earlier
* pass. One value, so a time never changes without its pass. See [toFormTime].
*/
data class FormTime(val dateTime: LocalDateTime, val offset: UtcOffset? = null) {
val date: LocalDate get() = dateTime.date
val time: LocalTime get() = dateTime.time
}
/**
* One editable guest: the user controls the [email] (the identity we dedup and
* write on), an optional display [name], and whether they're [optional] rather
@@ -100,6 +123,7 @@ enum class EventFormField {
Reminders,
Recurrence,
Availability,
Status,
Visibility,
Color,
Attendees,
@@ -135,26 +159,23 @@ enum class EventFormProblem {
fun EventDetail.toEditForm(beginMillis: Long, endMillis: Long, zone: TimeZone): EventForm {
// All-day events are date-anchored and carry a nominal "UTC" that is an
// anchor, not a location, so they never pin a zone.
val pinnedZone = if (instance.isAllDay) {
val pinned = if (instance.isAllDay) {
null
} else {
eventTimezone
?.takeIf { it != zone.id }
// An unparseable id (a malformed sync row) can't be honoured or
// shown; fall back to the device zone rather than failing the open.
?.takeIf { runCatching { TimeZone.of(it) }.isSuccess }
?.let { id -> zoneOrNull(id)?.let { id to it } }
}
val formZone = pinnedZone?.let { TimeZone.of(it) } ?: zone
val pinnedZone = pinned?.first
val formZone = pinned?.second ?: zone
val begin = Instant.fromEpochMilliseconds(beginMillis)
val finish = Instant.fromEpochMilliseconds(endMillis)
val (start, end) = if (instance.isAllDay) {
val startDate = Instant.fromEpochMilliseconds(beginMillis)
.toLocalDateTime(TimeZone.UTC).date
val endExclusive = Instant.fromEpochMilliseconds(endMillis)
.toLocalDateTime(TimeZone.UTC).date
val endDate = maxOf(startDate, LocalDate.fromEpochDays(endExclusive.toEpochDays() - 1))
LocalDateTime(startDate, LocalTime(9, 0)) to LocalDateTime(endDate, LocalTime(10, 0))
allDayFormTimes(begin.toLocalDateTime(TimeZone.UTC).date, finish.toLocalDateTime(TimeZone.UTC).date)
} else {
Instant.fromEpochMilliseconds(beginMillis).toLocalDateTime(formZone) to
Instant.fromEpochMilliseconds(endMillis).toLocalDateTime(formZone)
begin.toFormTime(formZone) to finish.toFormTime(formZone)
}
return EventForm(
calendarId = instance.calendarId,
@@ -168,7 +189,8 @@ fun EventDetail.toEditForm(beginMillis: Long, endMillis: Long, zone: TimeZone):
reminders = reminders.map { it.minutes }.distinct().sorted(),
availability = availability,
accessLevel = accessLevel,
rrule = rrule?.removePrefix("RRULE:")?.takeIf { it.isNotBlank() },
status = status,
rrule = rrule.normalizedRrule(),
// The provider fills EVENT_COLOR from the key, so [color] is the
// swatch either way; a null colour means the event inherits its
// calendar's colour.
@@ -203,7 +225,7 @@ fun EventDetail.toEditForm(beginMillis: Long, endMillis: Long, zone: TimeZone):
* re-deriving with the same occurrence would mask an externally moved
* event. Guests are covered (the form writes editable attendees), so an
* external attendee change now also trips the conflict check. Still not
* covered: status, the user's own response, reminder methods, the
* covered: the user's own response, reminder methods, the
* organizer/resource rows, and a recurring event's duration.
*/
data class EditSnapshot(
@@ -221,20 +243,46 @@ fun EventDetail.toEditSnapshot(beginMillis: Long, endMillis: Long, zone: TimeZon
)
/**
* The form's times as they land in [target] — what a pinned event's wall-clock
* actually means where the user is standing. Null when there's nothing to
* disambiguate: an unpinned event (already in [target]), one pinned to [target]
* itself, an all-day event (no zone), or an unparseable pinned zone.
*
* The form edits a pinned event in its own zone, so this is what lets the UI
* show the other side of the pair rather than making the user do the arithmetic.
* Form times for an all-day span stored as UTC midnights with an exclusive
* end: the last covered day (never before [start]), with placeholder
* wall-clock times kept in case the user switches the event to timed.
*/
fun EventForm.timesIn(target: TimeZone): Pair<LocalDateTime, LocalDateTime>? {
if (isAllDay) return null
val pinned = timezone?.let { runCatching { TimeZone.of(it) }.getOrNull() } ?: return null
if (pinned.id == target.id) return null
return start.toInstant(pinned).toLocalDateTime(target) to
end.toInstant(pinned).toLocalDateTime(target)
internal fun allDayFormTimes(start: LocalDate, endExclusive: LocalDate?): Pair<FormTime, FormTime> {
val end = endExclusive?.let { maxOf(start, LocalDate.fromEpochDays(it.toEpochDays() - 1)) } ?: start
return FormTime(LocalDateTime(start, LocalTime(9, 0))) to FormTime(LocalDateTime(end, LocalTime(10, 0)))
}
/** The bare RRULE value the form edits; blank means none. */
internal fun String?.normalizedRrule(): String? = this?.removePrefix("RRULE:")?.takeIf { it.isNotBlank() }
/**
* Whether this form may be saved apart from its series, as one modified
* occurrence or as a split-off "this & following" tail. A cancelled exception
* row is how Android records a deleted occurrence, and Google reads an inserted
* cancelled event as deleted, so either would vanish rather than show struck
* through (#388).
*/
fun EventForm.canSaveApartFromSeries(): Boolean = status != EventStatus.Cancelled
/**
* The status a newly inserted row may carry. Google reads an inserted cancelled
* event as deleted, so every new row (a copy, an import, a calendar move or an
* exception) starts confirmed instead (#388).
*/
fun EventStatus.forNewEvent(): EventStatus = if (this == EventStatus.Cancelled) EventStatus.Confirmed else this
/**
* Whether this form's times mean something else in [target] — a timed event
* pinned to another zone. False when there's nothing to disambiguate: an
* unpinned event (already in [target]), one pinned to [target] itself, an
* all-day event (no zone), or an unparseable pinned zone.
*
* The form edits a pinned event in its own zone, so this is what tells the UI
* to show the other side of the pair rather than making the user do the arithmetic.
*/
fun EventForm.isPinnedAwayFrom(target: TimeZone): Boolean {
if (isAllDay) return false
return resolvedZone(target).id != target.id
}
/**
@@ -246,17 +294,28 @@ fun EventForm.populatedFields(): Set<EventFormField> = 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)
if (accessLevel != AccessLevel.Default) add(EventFormField.Visibility)
if (colorKey != null || color != null) add(EventFormField.Color)
if (attendees.isNotEmpty()) add(EventFormField.Attendees)
}
fun EventForm.problems(): Set<EventFormProblem> = buildSet {
/**
* What stops this form from saving. A timed span is checked as instants in the
* form's zone (else [deviceZone]): one ending in the fall-back hour's repeat can
* end on an earlier wall clock than it starts (#387).
*/
fun EventForm.problems(deviceZone: TimeZone): Set<EventFormProblem> = buildSet {
if (calendarId == null) add(EventFormProblem.NoCalendar)
val endsTooEarly = if (isAllDay) end.date < start.date else end < start
val endsTooEarly = if (isAllDay) {
end.date < start.date
} else {
val zone = resolvedZone(deviceZone)
endInstant(zone) < startInstant(zone)
}
if (endsTooEarly) add(EventFormProblem.EndBeforeStart)
// An UNTIL before the first day would make the provider generate zero
// occurrences — the event would silently vanish from every view.
@@ -265,3 +324,44 @@ fun EventForm.problems(): Set<EventFormProblem> = buildSet {
add(EventFormProblem.RecurrenceEndsBeforeStart)
}
}
/**
* 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 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(
zone: TimeZone,
knownFixed: Set<FixedTimeReminder> = emptySet(),
): EventForm =
toEditForm(
beginMillis = instance.start.toEpochMilliseconds(),
endMillis = instance.end.toEpochMilliseconds(),
zone = zone,
).withFixedTimeRemindersRead(knownFixed, zone).copy(
rrule = null,
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<FixedTimeReminder>, 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<Int> {
if (isAllDay || fixedReminders.isEmpty()) return emptyList()
val start = startInstant(resolvedZone(deviceZone))
return fixedReminders.map { it.offsetMinutes(start, deviceZone, wallClock = rrule != null) }
}
@@ -1,8 +1,8 @@
package de.jeanlucmakiola.calendula.domain
import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.LocalDate
import kotlinx.datetime.TimeZone
import kotlinx.datetime.YearMonth
import kotlinx.datetime.atStartOfDayIn
import kotlinx.datetime.number
import kotlinx.datetime.plus
@@ -101,19 +101,13 @@ object EventSearch {
val today = todayStart.toLocalDateTime(zone).date
val matched = candidates.mapNotNull { candidate -> match(candidate, tokens, now, zone) }
val upcoming = { m: Matched -> m.event.spanLastDay(zone) >= today }
val order = compareBy<Matched> { if (upcoming(it)) 0 else 1 }
.thenComparator { a, b ->
// What is left reads forwards; what is behind us reads backwards
// from today, nearest first.
if (upcoming(a)) {
a.event.dayStart(zone).compareTo(b.event.dayStart(zone))
} else {
b.event.dayStart(zone).compareTo(a.event.dayStart(zone))
}
}
val (upcoming, past) = matched.partition { it.event.spanLastDay(zone) >= today }
// What is left reads forwards; what is behind us reads backwards from
// today, nearest first.
val ordered = upcoming.sortedBy { it.event.dayStart(zone) } +
past.sortedByDescending { it.event.dayStart(zone) }
val (inDescriptions, dated) = matched.sortedWith(order).partition { it.descriptionOnly }
val (inDescriptions, dated) = ordered.partition { it.descriptionOnly }
return SearchResults(
months = groupByMonth(dated, zone, todayStart),
inDescriptions = inDescriptions.map { it.hit },
@@ -126,33 +120,18 @@ object EventSearch {
zone: TimeZone,
todayStart: Instant,
): List<SearchMonth> {
val currentKey = monthKey(todayStart.toLocalDateTime(zone).date)
return dated
.groupBy { monthKey(it.event.spanFirstDay(zone)) }
.entries
.sortedWith(
compareBy<Map.Entry<Int, List<Matched>>> {
when {
it.key == currentKey -> 0
it.key > currentKey -> 1
else -> 2
}
}.thenComparator { a, b ->
if (a.key > currentKey) a.key.compareTo(b.key) else b.key.compareTo(a.key)
},
val current = todayStart.toLocalDateTime(zone).date.let { YearMonth(it.year, it.month) }
val groups = dated.groupBy { m -> m.event.spanFirstDay(zone).let { YearMonth(it.year, it.month) } }
val (behind, ahead) = groups.keys.partition { it < current }
return (ahead.sorted() + behind.sortedDescending()).map { month ->
SearchMonth(
year = month.year,
monthNumber = month.month.number,
hits = groups.getValue(month).map { it.hit },
)
.map { (key, entries) ->
SearchMonth(
year = key / 12,
monthNumber = key % 12 + 1,
hits = entries.map { it.hit },
)
}
}
}
/** Year and month as one comparable number. */
private fun monthKey(date: LocalDate): Int = date.year * 12 + (date.month.number - 1)
private fun match(
candidate: SearchCandidate,
tokens: List<String>,
@@ -162,16 +141,20 @@ object EventSearch {
val title = candidate.title?.takeIf { it.isNotBlank() }
val location = candidate.event.location?.takeIf { it.isNotBlank() }
// Collapsed so a multi-line description matches the way it is drawn.
val description = candidate.description
val rich = candidate.description?.let(::descriptionRichText)
val description = rich?.text
?.replace(WHITESPACE, " ")
?.trim()
?.takeIf { it.isNotEmpty() }
// A link's address isn't in the drawn text, but "zoom.us" should still find the invite.
val linkUrls = rich?.links.orEmpty().map { it.url }
// Mid-word counts: "termin" has to keep finding "Zahnarzttermin".
val present = { token: String ->
title?.contains(token, ignoreCase = true) == true ||
location?.contains(token, ignoreCase = true) == true ||
description?.contains(token, ignoreCase = true) == true
description?.contains(token, ignoreCase = true) == true ||
linkUrls.any { it.contains(token, ignoreCase = true) }
}
if (!tokens.all(present)) return null
@@ -3,17 +3,137 @@ package de.jeanlucmakiola.calendula.domain
import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.TimeZone
import kotlinx.datetime.UtcOffset
import kotlinx.datetime.offsetAt
import kotlinx.datetime.plus
import kotlinx.datetime.toInstant
import kotlinx.datetime.toJavaLocalDateTime
import kotlinx.datetime.toJavaZoneId
import kotlinx.datetime.toJavaZoneOffset
import kotlinx.datetime.toKotlinUtcOffset
import kotlinx.datetime.toLocalDateTime
import java.time.ZonedDateTime
import kotlin.time.Instant
import kotlin.time.toJavaInstant
import kotlin.time.toKotlinInstant
/** [id] as a zone, or null when the tz database doesn't know it. */
internal fun zoneOrNull(id: String): TimeZone? = runCatching { TimeZone.of(id) }.getOrNull()
/**
* The zone this form's wall-clock times mean, matching what the data layer
* resolves them in at write time: the form's own pinned zone, else [deviceZone].
*/
fun EventForm.resolvedZone(deviceZone: TimeZone): TimeZone =
timezone?.let { runCatching { TimeZone.of(it) }.getOrNull() } ?: deviceZone
timezone?.let(::zoneOrNull) ?: deviceZone
/**
* This wall-clock time in [zone], at [preferred] when the fall-back hour repeats
* it and that is one of its two offsets — otherwise the earlier one (#387).
*/
fun LocalDateTime.resolveIn(zone: TimeZone, preferred: UtcOffset?): Instant =
ZonedDateTime.ofLocal(toJavaLocalDateTime(), zone.toJavaZoneId(), preferred?.toJavaZoneOffset())
.toInstant().toKotlinInstant()
/** Whether this instant's wall clock in [zone] is one the fall-back hour repeats. */
fun Instant.inRepeatedHour(zone: TimeZone): Boolean {
val zid = zone.toJavaZoneId()
return zid.rules.getTransition(java.time.LocalDateTime.ofInstant(toJavaInstant(), zid))?.isOverlap == true
}
/**
* [at]'s offset in this zone when its wall clock is one the fall-back hour
* repeats, else null: elsewhere the wall clock alone already names the instant.
* What a [FormTime.offset] holds (#387).
*/
fun TimeZone.repeatedHourOffsetAt(at: Instant): UtcOffset? = if (at.inRepeatedHour(this)) offsetAt(at) else null
/** This instant as a [FormTime] in [zone], keeping its pass of a repeated hour. */
fun Instant.toFormTime(zone: TimeZone): FormTime = FormTime(toLocalDateTime(zone), zone.repeatedHourOffsetAt(this))
/** This time as an instant in [zone], on its kept pass of a repeated hour. */
fun FormTime.instantIn(zone: TimeZone): Instant = dateTime.resolveIn(zone, offset)
/**
* This edge of an event moved to [picked] by hand — a picker or a resize handle —
* as a [FormTime] in [zone]. A time in the spring-forward gap moves on to the
* real one, as the provider would read it. A wall clock the fall-back hour
* repeats has two instants; which one it means (#387):
* - [original]'s, when [picked] is the wall clock the event was opened with, so
* a time changed and changed back is the time it was;
* - else the one that moves the edge in the direction the user moved it:
* earlier than this edge's instant when [picked] is before [shownAt] (where
* the edge was on screen), later when after;
* - kept within [notBefore]..[notAfter] (the other edge), and to the ones
* [drawable] accepts — where the screen can show it — when any fit.
*/
fun FormTime.repicked(
picked: LocalDateTime,
zone: TimeZone,
shownAt: LocalDateTime = dateTime,
original: FormTime? = null,
notBefore: Instant? = null,
notAfter: Instant? = null,
drawable: (Instant) -> Boolean = { true },
): FormTime {
if (picked == dateTime && picked == shownAt) return this
val offsets = zone.toJavaZoneId().rules.getValidOffsets(picked.toJavaLocalDateTime())
if (offsets.isEmpty()) return FormTime(picked).instantIn(zone).toFormTime(zone)
if (offsets.size == 1) return FormTime(picked)
val passes = offsets.map { picked.toInstant(it.toKotlinUtcOffset()) }.sorted()
val bounded = passes.filter { (notBefore == null || it >= notBefore) && (notAfter == null || it <= notAfter) }
.ifEmpty { passes }
val fitting = bounded.filter(drawable).ifEmpty { bounded }
if (original?.dateTime == picked && original.offset != null && original.instantIn(zone) in fitting) return original
val from = instantIn(zone)
val chosen = when {
picked < shownAt -> fitting.lastOrNull { it < from }
picked > shownAt -> fitting.firstOrNull { it > from }
else -> null
} ?: fitting.minBy { (it - from).absoluteValue }
return chosen.toFormTime(zone)
}
/** The form's start as an instant in [zone]. */
fun EventForm.startInstant(zone: TimeZone): Instant = start.instantIn(zone)
/** The form's end as an instant in [zone]. */
fun EventForm.endInstant(zone: TimeZone): Instant = end.instantIn(zone)
/** The form's timed span set to these instants, read in [zone]. */
fun EventForm.withTimes(start: Instant, end: Instant, zone: TimeZone): EventForm =
copy(start = start.toFormTime(zone), end = end.toFormTime(zone))
/**
* The form pinned to [zoneId] (null: the device). A kept pass of a repeated hour
* was one of the old zone's, so it goes when the zone the times mean changes.
*/
fun EventForm.withTimezone(zoneId: String?, deviceZone: TimeZone): EventForm {
val pinned = copy(timezone = zoneId)
if (pinned.resolvedZone(deviceZone) == resolvedZone(deviceZone)) return pinned
return pinned.withoutKeptPasses()
}
/**
* The form with its start picked by hand, keeping its length. A repeated hour's
* pass is [repicked]: [original] is the start the event was opened with.
*/
fun EventForm.withStart(start: LocalDateTime, zone: TimeZone, original: FormTime? = null): EventForm {
val span = endInstant(zone) - startInstant(zone)
val startAt = this.start.repicked(start, zone, original = original).instantIn(zone)
return withTimes(startAt, startAt + span, zone)
}
/**
* The form with its end picked by hand. A repeated hour's pass is [repicked],
* kept after the start where it can be: [original] is the end the event was
* opened with.
*/
fun EventForm.withEnd(end: LocalDateTime, zone: TimeZone, original: FormTime? = null): EventForm =
copy(end = this.end.repicked(end, zone, original = original, notBefore = startInstant(zone)))
/** The form with no kept passes: its times as the wall clock alone says them. */
fun EventForm.withoutKeptPasses(): EventForm = copy(start = FormTime(start.dateTime), end = FormTime(end.dateTime))
/**
* The form moved so it starts at [newStart], keeping its **instant** duration —
@@ -26,11 +146,8 @@ fun EventForm.resolvedZone(deviceZone: TimeZone): TimeZone =
fun EventForm.shiftedTo(newStart: Instant, deviceZone: TimeZone): EventForm {
if (isAllDay) return this
val zone = resolvedZone(deviceZone)
val span = end.toInstant(zone) - start.toInstant(zone)
return copy(
start = newStart.toLocalDateTime(zone),
end = (newStart + span).toLocalDateTime(zone),
)
val span = endInstant(zone) - startInstant(zone)
return withTimes(newStart, newStart + span, zone)
}
/**
@@ -43,11 +160,24 @@ fun EventForm.shiftedByDays(days: Int, deviceZone: TimeZone): EventForm {
val newStart = LocalDateTime(start.date.plus(days, DateTimeUnit.DAY), start.time)
if (isAllDay) {
return copy(
start = newStart,
end = LocalDateTime(end.date.plus(days, DateTimeUnit.DAY), end.time),
start = FormTime(newStart),
end = FormTime(LocalDateTime(end.date.plus(days, DateTimeUnit.DAY), end.time)),
)
}
val zone = resolvedZone(deviceZone)
val span = end.toInstant(zone) - start.toInstant(zone)
return copy(start = newStart, end = (newStart.toInstant(zone) + span).toLocalDateTime(zone))
val span = endInstant(zone) - startInstant(zone)
val startAt = FormTime(newStart, start.offset).instantIn(zone)
// The start keeps the wall clock it was moved to, even one the spring-forward
// gap skips, so a recurring series still sees a whole-day move.
val movedStart = startAt.toFormTime(zone).takeIf { it.dateTime == newStart } ?: FormTime(newStart)
return copy(start = movedStart, end = (startAt + span).toFormTime(zone))
}
/**
* The form with new start and end, each in the form's own zone — a resize. An
* all-day event becomes timed: one dragged out of the all-day strip.
*/
fun EventForm.resizedTo(newStart: Instant, newEnd: Instant, deviceZone: TimeZone): EventForm {
val timed = copy(isAllDay = false)
return timed.withTimes(newStart, newEnd, timed.resolvedZone(deviceZone))
}
@@ -0,0 +1,396 @@
package de.jeanlucmakiola.calendula.domain
/** Inline formatting an HTML description keeps; fonts, sizes and colours are dropped. */
enum class InlineStyle { Bold, Italic, Underline, Strikethrough, Superscript, Subscript, Monospace }
data class StyleRange(val start: Int, val end: Int, val style: InlineStyle)
/** A link from an `<a href>`, spanning [start] until [end] (exclusive). */
data class LinkRange(val start: Int, val end: Int, val url: String)
/** Text as drawn, with the formatting and links that sit on it. Plain text has neither. */
data class RichText(
val text: String,
val styles: List<StyleRange> = emptyList(),
val links: List<LinkRange> = emptyList(),
) {
/**
* [text] with each link's address after it, where the text doesn't already
* show it, so a copied "Join the meeting" still carries its URL.
*/
fun copyText(): String {
if (links.isEmpty()) return text
val out = StringBuilder(text)
for (link in links.sortedByDescending { it.end }) {
val address = link.url.removePrefix("mailto:").removePrefix("tel:")
if (address !in text.substring(link.start, link.end)) out.insert(link.end, " ($address)")
}
return out.toString()
}
}
fun looksLikeHtml(text: String): Boolean = htmlTagRegex.containsMatchIn(text)
/** [description] as it reads: HTML rendered down to [RichText], plain text as it is. */
fun descriptionRichText(description: String): RichText =
if (looksLikeHtml(description)) parseHtml(description) else RichText(description)
private val BLOCK_TAGS = setOf(
"p", "div", "ul", "ol", "li", "table", "tr", "blockquote", "pre", "hr", "section", "article",
"header", "footer", "dl", "dt", "dd", "address", "center", "h1", "h2", "h3", "h4", "h5", "h6",
)
// Their content is never text to show.
private val SKIPPED_TAGS = setOf("head", "style", "script", "title", "xml", "template")
private val STYLE_TAGS = mapOf(
"b" to InlineStyle.Bold, "strong" to InlineStyle.Bold, "th" to InlineStyle.Bold,
"h1" to InlineStyle.Bold, "h2" to InlineStyle.Bold, "h3" to InlineStyle.Bold,
"h4" to InlineStyle.Bold, "h5" to InlineStyle.Bold, "h6" to InlineStyle.Bold,
"i" to InlineStyle.Italic, "em" to InlineStyle.Italic, "cite" to InlineStyle.Italic,
"u" to InlineStyle.Underline, "ins" to InlineStyle.Underline,
"s" to InlineStyle.Strikethrough, "strike" to InlineStyle.Strikethrough, "del" to InlineStyle.Strikethrough,
"sup" to InlineStyle.Superscript, "sub" to InlineStyle.Subscript,
"code" to InlineStyle.Monospace, "tt" to InlineStyle.Monospace, "pre" to InlineStyle.Monospace,
)
// A real tag the renderer knows, not prose like "<3" or "a < b". Google
// Calendar and Exchange both store their descriptions as HTML.
private val htmlTagRegex = Regex(
(BLOCK_TAGS + SKIPPED_TAGS + STYLE_TAGS.keys + setOf("html", "body", "br", "span", "a", "font", "img", "meta", "td"))
.joinToString("|", prefix = """</?(?:""", postfix = """)(?:\s[^<>]*)?/?>"""),
RegexOption.IGNORE_CASE,
)
private val LINK_SCHEMES = listOf("http://", "https://", "mailto:", "tel:")
private const val NBSP = '\u00A0'
private const val CELL_SEPARATOR = " · "
/**
* Render [html] down to text with its inline formatting and links. Blocks and
* `<br>` become line breaks, list items get a bullet or number, table rows a
* line each with their cells side by side. Lenient about broken markup:
* whatever doesn't parse as a tag stays text.
*/
fun parseHtml(html: String): RichText = HtmlRenderer(html).render()
// Markup that sets its own lines. Without any, the text's newlines are the
// lines: "Agenda:\n1. Intro" with one <a href> in it stays on two lines.
private val lineTagRegex = Regex("""<(?:br|p|div|li|tr|h[1-6]|pre|blockquote|table)\b""", RegexOption.IGNORE_CASE)
private class HtmlRenderer(private val html: String) {
private val out = StringBuilder()
private val styles = mutableListOf<StyleRange>()
private val links = mutableListOf<LinkRange>()
private val openStyles = mutableListOf<Pair<String, Int>>()
private var openLink: Pair<String, Int>? = null
private val lists = mutableListOf<ListState>()
private val keepNewlines = !lineTagRegex.containsMatchIn(html)
private var preDepth = 0
private var rowStart = 0
private var cellNeedsSeparator = false
// Where the current list item's bullet ends, so a <p> inside the item
// doesn't push its text off the bullet's line.
private var markerEnd = -1
private class ListState(val ordered: Boolean, var count: Int = 0)
fun render(): RichText {
var i = 0
while (i < html.length) {
val lt = html.indexOf('<', i)
if (lt < 0) {
text(html.substring(i))
break
}
if (lt > i) text(html.substring(i, lt))
i = tag(lt)
}
return normalize()
}
/** Handle the markup at [lt]; returns where reading continues. */
private fun tag(lt: Int): Int {
if (html.startsWith("<!--", lt)) {
val end = html.indexOf("-->", lt + 4)
return if (end < 0) html.length else end + 3
}
if (html.startsWith("<!", lt) || html.startsWith("<?", lt)) {
val end = html.indexOf('>', lt)
return if (end < 0) html.length else end + 1
}
val closing = html.getOrNull(lt + 1) == '/'
val nameStart = if (closing) lt + 2 else lt + 1
if (html.getOrNull(nameStart)?.isLetter() != true) {
text("<")
return lt + 1
}
val end = tagEnd(lt)
if (end < 0) {
text("<")
return lt + 1
}
if (!closing && isAutolink(html.substring(nameStart, end))) {
text(html.substring(lt, end + 1))
return end + 1
}
var nameEnd = nameStart
while (nameEnd < end && (html[nameEnd].isLetterOrDigit() || html[nameEnd] == ':')) nameEnd++
val name = html.substring(nameStart, nameEnd).lowercase()
val attrs = html.substring(nameEnd, end)
if (closing) {
close(name)
} else if (name in SKIPPED_TAGS && !attrs.trimEnd().endsWith("/")) {
// Never closed (an omitted </head> is valid): just ignore the tag.
val closeAt = html.indexOf("</$name", end, ignoreCase = true)
if (closeAt < 0) return end + 1
val closeEnd = html.indexOf('>', closeAt)
return if (closeEnd < 0) html.length else closeEnd + 1
} else {
open(name, attrs)
}
return end + 1
}
/** An angle-bracketed URL or address (`<https://…>`, `<a@b.c>`), kept as text. */
private fun isAutolink(inner: String): Boolean =
LINK_SCHEMES.any { inner.startsWith(it, ignoreCase = true) } ||
('@' in inner && inner.none { it.isWhitespace() || it == '=' })
/** The `>` closing the tag at [lt], skipping any inside quoted attributes. */
private fun tagEnd(lt: Int): Int {
var quote: Char? = null
for (j in lt + 1 until html.length) {
val c = html[j]
when {
quote != null -> if (c == quote) quote = null
c == '"' || c == '\'' -> quote = c
c == '>' -> return j
c == '<' -> return -1
}
}
return -1
}
private fun open(name: String, attrs: String) {
when (name) {
"br" -> newline()
"li" -> {
markerEnd = -1
cellNeedsSeparator = false
lineBreak()
val list = lists.lastOrNull()
out.append("$NBSP$NBSP".repeat((lists.size - 1).coerceAtLeast(0)))
if (list?.ordered == true) {
list.count++
out.append("${list.count}. ")
} else {
out.append("• ")
}
markerEnd = out.length
}
"ul", "ol" -> {
cellNeedsSeparator = false
lineBreak()
val start = startRegex.find(attrs)?.groupValues?.get(1)?.toIntOrNull() ?: 1
lists += ListState(ordered = name == "ol", count = start - 1)
}
"tr" -> {
lineBreak()
rowStart = out.length
cellNeedsSeparator = false
}
"td", "th" -> {
// An empty spacer cell leaves nothing behind, not even its &nbsp;.
if (rowStart <= out.length && (rowStart until out.length).none { out[it].isContent() }) {
cut(rowStart)
} else {
cellNeedsSeparator = true
}
}
"a" -> {
closeLink()
hrefRegex.find(attrs)
?.groupValues?.drop(1)?.firstOrNull { it.isNotEmpty() }
?.let(::decodeEntities)
?.trim()
?.let { href ->
val scheme = LINK_SCHEMES.firstOrNull { href.startsWith(it, ignoreCase = true) }
?: return@let
// Intent filters match the scheme case-sensitively.
openLink = scheme + href.substring(scheme.length) to out.length
}
}
else -> if (name in BLOCK_TAGS) lineBreak()
}
if (name == "pre") preDepth++
STYLE_TAGS[name]?.let { openStyles += name to out.length }
}
private fun close(name: String) {
// A row's last cell, if empty, leaves a separator pending; it ends with the row.
if (name == "tr" || name == "table") cellNeedsSeparator = false
val index = openStyles.indexOfLast { it.first == name }
if (index >= 0) {
val (_, start) = openStyles.removeAt(index)
if (out.length > start) styles += StyleRange(start, out.length, STYLE_TAGS.getValue(name))
}
if (name == "pre") preDepth = (preDepth - 1).coerceAtLeast(0)
if (name == "li" || name == "ul" || name == "ol") {
if (out.length == markerEnd) cut(out.lastIndexOf("\n") + 1)
markerEnd = -1
}
when (name) {
"ul", "ol" -> {
lists.removeLastOrNull()
lineBreak()
}
"a" -> closeLink()
else -> if (name in BLOCK_TAGS) lineBreak()
}
}
private fun closeLink() {
val (url, start) = openLink ?: return
if (out.length > start) links += LinkRange(start, out.length, url)
openLink = null
}
private fun text(raw: String) {
val decoded = decodeEntities(raw)
if (preDepth > 0) {
out.append(decoded.replace("\r\n", "\n"))
return
}
for (c in decoded) {
if (c == '\n' && keepNewlines) {
newline()
} else if (c == ' ' || c == '\n' || c == '\t' || c == '\r' || c == '\u000C') {
if (out.isNotEmpty() && out.last() != ' ' && out.last() != '\n') out.append(' ')
} else {
if (cellNeedsSeparator && c.isContent()) separateCell()
out.append(c)
}
}
}
/** Put this cell's text beside the row's last, even after a block in that cell ended its line. */
private fun separateCell() {
cellNeedsSeparator = false
var end = out.length
while (end > rowStart && !out[end - 1].isContent()) end--
cut(end)
out.append(CELL_SEPARATOR)
openStyles.replaceAll { (name, start) -> name to if (start >= end) out.length else start }
openLink = openLink?.let { (url, start) -> url to if (start >= end) out.length else start }
}
private fun Char.isContent() = !isWhitespace() && this != NBSP
private fun newline() {
trimTrailingSpaces()
out.append('\n')
}
/** End the current line, unless it's already ended or holds just a bullet. */
private fun lineBreak() {
if (out.length == markerEnd) return
trimTrailingSpaces()
if (out.isNotEmpty() && out.last() != '\n') out.append('\n')
}
private fun trimTrailingSpaces() {
while (out.isNotEmpty() && out.last() == ' ') out.setLength(out.length - 1)
}
/** Drop the output from [length] on, with whatever formatting lay only there. */
private fun cut(length: Int) {
if (length >= out.length) return
out.setLength(length)
styles.replaceAll { it.copy(end = minOf(it.end, length)) }
styles.removeAll { it.end <= it.start }
links.replaceAll { it.copy(end = minOf(it.end, length)) }
links.removeAll { it.end <= it.start }
openStyles.replaceAll { (name, start) -> name to minOf(start, length) }
openLink = openLink?.let { (url, start) -> url to minOf(start, length) }
}
/**
* Tidy the rendered text: no-break spaces become plain, lines lose trailing
* blanks, runs of empty lines shrink to one and the ends are trimmed. Spans
* move with the text they cover.
*/
private fun normalize(): RichText {
closeLink()
for ((name, start) in openStyles) {
if (out.length > start) styles += StyleRange(start, out.length, STYLE_TAGS.getValue(name))
}
val src = out.toString().replace(NBSP, ' ')
val map = IntArray(src.length + 1)
val result = StringBuilder()
var i = 0
while (i < src.length) {
var lineEnd = src.indexOf('\n', i)
if (lineEnd < 0) lineEnd = src.length
var contentEnd = lineEnd
while (contentEnd > i && src[contentEnd - 1].isWhitespace()) contentEnd--
for (j in i until lineEnd) {
map[j] = result.length
if (j < contentEnd) result.append(src[j])
}
if (lineEnd < src.length) {
map[lineEnd] = result.length
if (!result.endsWith("\n\n")) result.append('\n')
}
i = lineEnd + 1
}
map[src.length] = result.length
val leading = result.length - result.trimStart().length
val text = result.trim().toString()
fun at(index: Int) = (map[index] - leading).coerceIn(0, text.length)
return RichText(
text = text,
styles = styles.mapNotNull { r -> StyleRange(at(r.start), at(r.end), r.style).takeIf { it.end > it.start } },
links = links.mapNotNull { r -> LinkRange(at(r.start), at(r.end), r.url).takeIf { it.end > it.start } },
)
}
}
private val startRegex = Regex("""(?:^|\s)start\s*=\s*["']?(-?\d{1,6})""", RegexOption.IGNORE_CASE)
private val hrefRegex = Regex("""(?:^|\s)href\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))""", RegexOption.IGNORE_CASE)
// Latin-1 (&nbsp; … &yuml;) in code point order, then the common extras.
private val LATIN1_ENTITIES = ("nbsp iexcl cent pound curren yen brvbar sect uml copy ordf laquo not shy reg macr " +
"deg plusmn sup2 sup3 acute micro para middot cedil sup1 ordm raquo frac14 frac12 frac34 iquest " +
"Agrave Aacute Acirc Atilde Auml Aring AElig Ccedil Egrave Eacute Ecirc Euml Igrave Iacute Icirc Iuml " +
"ETH Ntilde Ograve Oacute Ocirc Otilde Ouml times Oslash Ugrave Uacute Ucirc Uuml Yacute THORN szlig " +
"agrave aacute acirc atilde auml aring aelig ccedil egrave eacute ecirc euml igrave iacute icirc iuml " +
"eth ntilde ograve oacute ocirc otilde ouml divide oslash ugrave uacute ucirc uuml yacute thorn yuml").split(' ')
private val ENTITIES: Map<String, String> = LATIN1_ENTITIES.withIndex()
.associate { (i, name) -> name to (0xA0 + i).toChar().toString() } + mapOf(
"amp" to "&", "lt" to "<", "gt" to ">", "quot" to "\"", "apos" to "'",
"ndash" to "–", "mdash" to "—", "hellip" to "…", "bull" to "•",
"lsquo" to "‘", "rsquo" to "’", "ldquo" to "“", "rdquo" to "”", "sbquo" to "‚", "bdquo" to "„",
"euro" to "€", "trade" to "™", "OElig" to "Œ", "oelig" to "œ", "Scaron" to "Š", "scaron" to "š",
"zwnj" to "\u200C", "zwj" to "\u200D", "ensp" to "\u2002", "emsp" to "\u2003", "thinsp" to "\u2009",
)
// A named reference needs its ";": "?id=5&reg=eu" in a link is a query, not "®".
private val entityRegex = Regex("""&(?:(#[0-9]{1,7}|#[xX][0-9a-fA-F]{1,6});?|([a-zA-Z][a-zA-Z0-9]{1,31});)""")
/** Decode character references; an unknown name is left as written. */
internal fun decodeEntities(text: String): String {
if ('&' !in text) return text
return entityRegex.replace(text) { match ->
val name = match.groupValues[2]
if (name.isNotEmpty()) return@replace ENTITIES[name] ?: match.value
val body = match.groupValues[1]
val code = when {
body.startsWith("#x", ignoreCase = true) -> body.substring(2).toIntOrNull(16)
else -> body.substring(1).toIntOrNull()
}
if (code == null || code == 0 || !Character.isValidCodePoint(code)) "�" else String(Character.toChars(code))
}
}
@@ -1,10 +1,6 @@
package de.jeanlucmakiola.calendula.domain
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.Duration.Companion.hours
import kotlin.time.Instant
@@ -17,48 +13,39 @@ 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`.
*/
fun buildInsertEventForm(
beginMillis: Long?,
endMillis: Long?,
isAllDay: Boolean,
beginMillis: Long? = null,
endMillis: Long? = null,
isAllDay: Boolean = false,
title: String?,
description: String?,
location: String?,
rrule: String?,
location: String? = null,
rrule: String? = null,
calendarId: Long? = null,
zone: TimeZone,
now: Instant,
): EventForm {
val (start, end) = if (isAllDay) {
// All-day provider times are UTC midnights with an exclusive end; show
// the last covered day and keep placeholder wall-clock times in case the
// user switches the event to timed (mirrors EventDetail.toEditForm).
val startDate = beginMillis
?.let { Instant.fromEpochMilliseconds(it).toLocalDateTime(TimeZone.UTC).date }
?: now.toLocalDateTime(zone).date
val endDate = endMillis
?.let { Instant.fromEpochMilliseconds(it).toLocalDateTime(TimeZone.UTC).date }
?.let { exclusive -> maxOf(startDate, LocalDate.fromEpochDays(exclusive.toEpochDays() - 1)) }
?: startDate
LocalDateTime(startDate, LocalTime(9, 0)) to LocalDateTime(endDate, LocalTime(10, 0))
val endExclusive = endMillis?.let { Instant.fromEpochMilliseconds(it).toLocalDateTime(TimeZone.UTC).date }
allDayFormTimes(startDate, endExclusive)
} else {
val startTime = beginMillis
?.let { Instant.fromEpochMilliseconds(it).toLocalDateTime(zone) }
?: nextFullHour(now, zone)
val endTime = endMillis
?.let { Instant.fromEpochMilliseconds(it).toLocalDateTime(zone) }
?.takeIf { it >= startTime }
?: (startTime.toInstant(zone) + 1.hours).toLocalDateTime(zone)
startTime to endTime
val startAt = beginMillis?.let(Instant::fromEpochMilliseconds) ?: nextFullHour(now)
val endAt = endMillis?.let(Instant::fromEpochMilliseconds)?.takeIf { it >= startAt }
?: (startAt + 1.hours)
startAt.toFormTime(zone) to endAt.toFormTime(zone)
}
return EventForm(
calendarId = null,
calendarId = calendarId,
title = title.orEmpty(),
isAllDay = isAllDay,
start = start,
@@ -67,12 +54,38 @@ fun buildInsertEventForm(
description = description.orEmpty(),
// Bare RRULE value (Events.RRULE convention); tolerate a leading "RRULE:"
// some callers include.
rrule = rrule?.removePrefix("RRULE:")?.takeIf { it.isNotBlank() },
rrule = rrule.normalizedRrule(),
)
}
private fun nextFullHour(now: Instant, zone: TimeZone): LocalDateTime {
/** The first full hour after [now]: may roll into the next day before midnight. */
internal fun nextFullHour(now: Instant): Instant {
val hourMillis = 3_600_000L
val rounded = (now.toEpochMilliseconds() / hourMillis + 1) * hourMillis
return Instant.fromEpochMilliseconds(rounded).toLocalDateTime(zone)
return Instant.fromEpochMilliseconds((now.toEpochMilliseconds() / hourMillis + 1) * hourMillis)
}
/** Title and description for text shared or selected into the app (#306). */
data class SharedText(val title: String, val description: String)
/**
* Split shared text into an event title and description: the share's subject
* becomes the title and the text the description. Without a subject the text's
* first non-blank line is the title and the rest the description. A title longer
* than [maxTitle] is cut, and the full text then stays in the description.
* Null when there is nothing to use.
*/
fun sharedTextOrNull(subject: String?, text: String?, maxTitle: Int = 255): SharedText? {
val body = text?.trim().orEmpty()
val given = subject?.trim()?.takeIf { it.isNotEmpty() }
val (title, rest) = if (given != null) {
given to body
} else {
val lines = body.lines()
val first = lines.firstOrNull()?.trim()?.takeIf { it.isNotEmpty() } ?: return null
first to lines.drop(1).joinToString("\n").trim()
}
if (title.length <= maxTitle) return SharedText(title, rest)
val cut = title.take(maxTitle).let { if (it.last().isHighSurrogate()) it.dropLast(1) else it }
val full = if (given != null) listOf(given, body).filter { it.isNotEmpty() }.joinToString("\n\n") else body
return SharedText(cut.trimEnd(), full)
}
@@ -2,6 +2,7 @@ package de.jeanlucmakiola.calendula.domain
import kotlinx.datetime.LocalDate
import kotlinx.datetime.TimeZone
import kotlinx.datetime.atStartOfDayIn
import kotlinx.datetime.toLocalDateTime
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Instant
@@ -72,6 +73,8 @@ data class EventInstance(
* (#180, #230).
*/
val response: EventResponse = EventResponse.Going,
/** The event's own Confirmed / Tentative / Cancelled (`Events.STATUS`, #388). */
val status: EventStatus = EventStatus.Confirmed,
)
/**
@@ -94,16 +97,33 @@ enum class EventResponse {
Declined,
}
/** Shorthand for the declined case, which most surfaces test on its own (#180). */
val EventInstance.isDeclined: Boolean get() = response == EventResponse.Declined
/**
* Struck through on every surface and sorted last: an invitation you declined
* (#180), or an event its organizer cancelled (#388). Neither plans reminders.
*/
val EventInstance.isCrossedOut: Boolean
get() = response == EventResponse.Declined || status == EventStatus.Cancelled
/**
* Drawn as an outline, still undecided: an invitation you have not answered
* (#230), or a tentative event (#388).
*/
val EventInstance.isOutlined: Boolean
get() = !isCrossedOut && (response == EventResponse.Invited || status == EventStatus.Tentative)
/**
* Whether this event has finished relative to [now] — its end is at or before
* the current instant. An in-progress event (already started but not yet ended)
* is *not* considered ended. All-day events end at the exclusive next-midnight,
* so they only count as ended once their day is fully over.
* is *not* considered ended. All-day events end at the exclusive next-midnight
* in [zone] rather than the UTC midnight they are stored on, so they only count
* as ended once their local day is fully over.
*/
fun EventInstance.hasEnded(now: Instant): Boolean = end <= now
fun EventInstance.hasEnded(now: Instant, zone: TimeZone = TimeZone.currentSystemDefault()): Boolean =
localEnd(zone) <= now
/** [EventInstance.end], with an all-day event's UTC midnight moved to local midnight in [zone]. */
fun EventInstance.localEnd(zone: TimeZone): Instant =
if (isAllDay) end.toLocalDateTime(TimeZone.UTC).date.atStartOfDayIn(zone) else end
/**
* The zone this event's calendar dates live in: the device [zone] for timed
@@ -130,6 +150,20 @@ fun EventInstance.spanLastDay(zone: TimeZone): LocalDate {
fun EventInstance.spansMultipleDays(zone: TimeZone): Boolean =
spanFirstDay(zone) != spanLastDay(zone)
/**
* Whether this event fills whole days in [zone], so the grids and lists lay it
* out with the all-day events: an all-day event, or a timed one running from
* local midnight to local midnight (#296). The event itself stays timed.
*/
fun EventInstance.coversWholeDays(zone: TimeZone): Boolean = isAllDay || runsMidnightToMidnight(start, end, zone)
/** Whether a timed span from [start] to [end] runs from local midnight to local midnight in [zone] (#296). */
fun runsMidnightToMidnight(start: Instant, end: Instant, zone: TimeZone): Boolean =
end > start && start.isStartOfDay(zone) && end.isStartOfDay(zone)
private fun Instant.isStartOfDay(zone: TimeZone): Boolean =
this == toLocalDateTime(zone).date.atStartOfDayIn(zone)
data class EventDetail(
val instance: EventInstance,
val description: String?,
@@ -165,6 +199,17 @@ data class EventDetail(
val isException: Boolean = false,
)
/**
* This event on one occurrence's times. The Events row holds the series start,
* so a recurring event needs the tapped occurrence pinned to render and share right.
*/
fun EventDetail.atOccurrence(beginMillis: Long, endMillis: Long): EventDetail = copy(
instance = instance.copy(
start = Instant.fromEpochMilliseconds(beginMillis),
end = Instant.fromEpochMilliseconds(endMillis),
),
)
/**
* One selectable event colour published by a calendar's account
* (`CalendarContract.Colors`, `TYPE_EVENT`): [key] is the account-scoped
@@ -264,3 +309,7 @@ enum class FailureReason {
EventNotFound,
Unknown,
}
/** [this] without the events of [hidden] calendars. */
fun List<EventInstance>.withoutCalendars(hidden: Set<Long>): List<EventInstance> =
if (hidden.isEmpty()) this else filterNot { it.calendarId in hidden }
@@ -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>): 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<CalendarSource>,
): 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>): CalendarSource? =
default?.find(calendars)?.takeIf { it.isEventTarget }
@@ -1,5 +1,8 @@
package de.jeanlucmakiola.calendula.domain
import de.jeanlucmakiola.calendula.domain.ics.parseBasicDate
import de.jeanlucmakiola.calendula.domain.ics.parseBasicDateTime
import de.jeanlucmakiola.calendula.domain.ics.toUtcBasic
import kotlinx.datetime.DayOfWeek
import kotlinx.datetime.LocalDate
import kotlinx.datetime.LocalDateTime
@@ -57,24 +60,13 @@ fun parseSimpleRecurrence(
rrule: String,
zone: TimeZone = TimeZone.currentSystemDefault(),
): SimpleRecurrence? {
val parts = rrule.removePrefix("RRULE:").split(';')
.filter { it.isNotBlank() }
.associate { token ->
val eq = token.indexOf('=')
if (eq <= 0) return null
token.substring(0, eq).uppercase() to token.substring(eq + 1)
}
val parts = rruleParts(rrule).associate { part -> (part.key ?: return null) to part.value }
if (parts.keys.any { it !in setOf("FREQ", "INTERVAL", "UNTIL", "COUNT", "WKST", "BYDAY") }) {
return null
}
val freq = when (parts["FREQ"]?.uppercase()) {
"DAILY" -> RecurrenceFreq.Daily
"WEEKLY" -> RecurrenceFreq.Weekly
"MONTHLY" -> RecurrenceFreq.Monthly
"YEARLY" -> RecurrenceFreq.Yearly
else -> return null
}
val freq = RecurrenceFreq.entries.firstOrNull { it.name.equals(parts["FREQ"], ignoreCase = true) }
?: return null
val interval = parts["INTERVAL"]?.let { it.toIntOrNull()?.takeIf { n -> n >= 1 } ?: return null } ?: 1
// BYDAY is simple only as plain weekday picks on a weekly rule; ordinal
@@ -124,20 +116,27 @@ fun SimpleRecurrence.toRRule(zone: TimeZone = TimeZone.currentSystemDefault()):
when (val e = end) {
RecurrenceEnd.Never -> Unit
is RecurrenceEnd.Until -> {
val utc = LocalDateTime(e.date, LocalTime(23, 59, 59))
.toInstant(zone)
.toLocalDateTime(TimeZone.UTC)
append(
";UNTIL=%04d%02d%02dT%02d%02d%02dZ".format(
utc.year, utc.month.number, utc.day,
utc.hour, utc.minute, utc.second,
),
)
append(";UNTIL=")
append(LocalDateTime(e.date, LocalTime(23, 59, 59)).toInstant(zone).toUtcBasic())
}
is RecurrenceEnd.Count -> append(";COUNT=${e.times}")
}
}
/** One `;`-separated part of an RRULE as written; [key] is null when it has no `KEY=`. */
internal class RrulePart(val raw: String) {
private val eq = raw.indexOf('=')
val key: String? = if (eq > 0) raw.substring(0, eq).uppercase() else null
val value: String = if (eq > 0) raw.substring(eq + 1) else ""
}
/**
* [rule]'s non-blank parts, after an optional leading "RRULE:". What to do
* with a malformed one (reject, repair or skip) is the caller's call.
*/
internal fun rruleParts(rule: String): List<RrulePart> =
rule.removePrefix("RRULE:").split(';').filter { it.isNotBlank() }.map(::RrulePart)
internal val RRULE_DAY_CODES: Map<DayOfWeek, String> = mapOf(
DayOfWeek.MONDAY to "MO",
DayOfWeek.TUESDAY to "TU",
@@ -165,11 +164,7 @@ fun rruleTruncatedAt(rrule: String, untilUtcMillis: Long): String {
val key = part.substringBefore('=').trim().uppercase()
key == "UNTIL" || key == "COUNT"
}
val until = Instant.fromEpochMilliseconds(untilUtcMillis).toLocalDateTime(TimeZone.UTC)
val untilPart = "UNTIL=%04d%02d%02dT%02d%02d%02dZ".format(
until.year, until.month.number, until.day,
until.hour, until.minute, until.second,
)
val untilPart = "UNTIL=" + Instant.fromEpochMilliseconds(untilUtcMillis).toUtcBasic()
return (kept + untilPart).joinToString(";")
}
@@ -178,20 +173,8 @@ fun rruleTruncatedAt(rrule: String, untilUtcMillis: Long): String {
* forms are UTC (RFC 5545); the date is taken after converting into [zone] so
* a [toRRule]-rendered value round-trips to the day the user picked.
*/
private fun parseUntilDate(raw: String, zone: TimeZone): LocalDate? = runCatching {
val date = LocalDate(
raw.substring(0, 4).toInt(),
raw.substring(4, 6).toInt(),
raw.substring(6, 8).toInt(),
)
if (raw.length >= 15 && raw[8] == 'T') {
val time = LocalTime(
raw.substring(9, 11).toInt(),
raw.substring(11, 13).toInt(),
raw.substring(13, 15).toInt(),
)
LocalDateTime(date, time).toInstant(TimeZone.UTC).toLocalDateTime(zone).date
} else {
date
}
}.getOrNull()
private fun parseUntilDate(raw: String, zone: TimeZone): LocalDate? {
val date = parseBasicDate(raw) ?: return null
if (raw.length < 15 || raw[8] != 'T') return date
return parseBasicDateTime(raw)?.toInstant(TimeZone.UTC)?.toLocalDateTime(zone)?.date
}
@@ -19,30 +19,30 @@ import kotlinx.datetime.LocalDate
fun realignRecurrence(rrule: String, oldStart: LocalDate, newStart: LocalDate): String? {
if (oldStart == newStart) return rrule
val prefix = if (rrule.startsWith("RRULE:")) "RRULE:" else ""
val parts = rrule.removePrefix("RRULE:").split(';').filter { it.isNotBlank() }
val parts = rruleParts(rrule)
if (parts.isEmpty()) return null
var freq = false
var weekly = false
var byDay = false
val rebuilt = parts.map { part ->
val eq = part.indexOf('=')
if (eq <= 0) return null
val key = part.substring(0, eq).uppercase()
val value = part.substring(eq + 1).trim()
when (key) {
val value = part.value.trim()
when (part.key) {
"FREQ" -> {
freq = true
weekly = value.equals("WEEKLY", ignoreCase = true)
part
part.raw
}
"BYDAY" -> {
byDay = true
val old = RRULE_DAY_CODES[oldStart.dayOfWeek] ?: return null
if (!value.equals(old, ignoreCase = true)) return null
"BYDAY=${RRULE_DAY_CODES.getValue(newStart.dayOfWeek)}"
}
"INTERVAL", "COUNT", "UNTIL", "WKST" -> part
"INTERVAL", "COUNT", "UNTIL", "WKST" -> part.raw
else -> return null
}
}
// BYDAY is only simple on a weekly rule, matching parseSimpleRecurrence.
if (!weekly && parts.any { it.substringBefore('=').trim().uppercase() == "BYDAY" }) return null
if (parts.none { it.substringBefore('=').trim().uppercase() == "FREQ" }) return null
if (!freq || (byDay && !weekly)) return null
return prefix + rebuilt.joinToString(";")
}
@@ -157,14 +157,36 @@ fun timeZoneOptionOf(
* the offset isn't stated twice in ICU's spelling and ours.
*/
fun zoneDescriptor(option: TimeZoneOption): String {
val abbrev = option.shortName
return when {
abbrev == "UTC" -> "UTC"
abbrev.startsWith("GMT") -> formatGmtOffset(option.offsetMinutes)
else -> "$abbrev · ${formatGmtOffset(option.offsetMinutes)}"
}
val name = zoneAbbreviation(option)
val statesOffset = option.shortName == "UTC" || option.shortName.startsWith("GMT")
return if (statesOffset) name else "$name · ${formatGmtOffset(option.offsetMinutes)}"
}
/**
* [option]'s short name on its own — "CEST", "UTC" — with an offset-shaped one
* normalised to our GMT form, as [zoneDescriptor] spells it.
*/
fun zoneAbbreviation(option: TimeZoneOption): String = abbreviation(option.shortName, option.offsetMinutes)
/**
* Zone [id]'s abbreviation [at] an instant, as [zoneAbbreviation] spells it,
* without the localized long name a whole [TimeZoneOption] would look up. Null
* for an id the tz database can't parse.
*/
fun zoneAbbreviationAt(
id: String,
locale: Locale,
at: Instant,
regionOf: (String) -> String? = { null },
): String? {
val zone = runCatching { ZoneId.of(id) }.getOrNull() ?: return null
val shortName = resolveAbbreviation(zone.id, zone.rules.isDaylightSavings(at), locale, regionOf)
return abbreviation(shortName, zone.rules.getOffset(at).totalSeconds / 60)
}
private fun abbreviation(shortName: String, offsetMinutes: Int): String =
if (shortName.startsWith("GMT")) formatGmtOffset(offsetMinutes) else shortName
/**
* [options] matching [query], best matches first; a blank query returns the list
* unchanged. Matching is accent- and case-insensitive and treats underscores as
@@ -0,0 +1,402 @@
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<Long> = emptySet(),
val excluded: Set<Long> = 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<Long>,
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<String>,
/** Earlier files of this series beyond the retention count, oldest first. */
val prune: List<String>,
/**
* The stable, undated copy overwritten every run (`<base>.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<String> = 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<String> = 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<String, List<String>>
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<Int> = 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; 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. 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<CalendarSource>,
combined: Boolean,
ledger: BackupLedger = emptyMap(),
existing: Set<String>? = null,
): List<BackupTarget> {
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()) {
it.id to safeFileName(it.displayName, MAX_BASE_BYTES, fallback = "calendar")
}
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.isEmpty()) break
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" }
}
}
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<Long>, bases: Map<Long, String>): 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<BackupTarget>,
ledger: BackupLedger,
existing: Set<String>,
at: LocalDateTime,
keep: Int,
): List<BackupFilePlan> {
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<BackupTarget>,
ledger: BackupLedger,
existing: Set<String>,
): Map<String, List<String>> {
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<String>,
liveKeys: Set<String>,
): 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<String> =
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()
/** 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<String, String>
/**
* 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<String>,
): 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 scheduled run.
*/
fun BackupFilePlan.needsRefresh(
fingerprint: String,
stored: BackupFingerprints,
listed: Set<String>,
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<IcsEvent>.inBackupOrder(): List<IcsEvent> =
map {
it.copy(
reminderMinutes = it.reminderMinutes.sorted(),
exDates = it.exDates.sorted(),
recurrenceDates = it.recurrenceDates.sorted(),
)
}.sortedWith(
compareBy<IcsEvent>(
{ it.overrideOf == null }, { it.start }, { it.uid }, { it.overrideAt }, { it.calendarName },
{ it.toString() },
),
)
@@ -0,0 +1,47 @@
package de.jeanlucmakiola.calendula.domain.ics
import kotlinx.datetime.LocalDate
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.LocalTime
import kotlinx.datetime.TimeZone
import kotlinx.datetime.format
import kotlinx.datetime.format.char
import kotlinx.datetime.toLocalDateTime
import kotlin.time.Instant
/** RFC 5545 basic format, `yyyyMMddTHHmmss`. */
private val BASIC_DATE_TIME = LocalDateTime.Format {
date(LocalDate.Formats.ISO_BASIC)
char('T')
hour()
minute()
second()
}
/** `yyyyMMdd`. */
internal fun LocalDate.toBasic(): String = format(LocalDate.Formats.ISO_BASIC)
/** `yyyyMMddTHHmmss`, floating. */
internal fun LocalDateTime.toBasic(): String = format(BASIC_DATE_TIME)
/** `yyyyMMddTHHmmssZ`, the instant in UTC. */
internal fun Instant.toUtcBasic(): String = toLocalDateTime(TimeZone.UTC).toBasic() + "Z"
/**
* The date in the first eight characters of a basic-format value; whatever
* follows (a time, a `Z`) is ignored. Null when those aren't a valid date.
*/
internal fun parseBasicDate(s: String): LocalDate? = runCatching {
LocalDate(s.substring(0, 4).toInt(), s.substring(4, 6).toInt(), s.substring(6, 8).toInt())
}.getOrNull()
/** `yyyyMMddTHHmm[ss]`; the separator isn't checked and missing seconds read as zero. */
internal fun parseBasicDateTime(s: String): LocalDateTime? = runCatching {
val date = parseBasicDate(s) ?: return null
val time = LocalTime(
s.substring(9, 11).toInt(),
s.substring(11, 13).toInt(),
if (s.length >= 15) s.substring(13, 15).toInt() else 0,
)
LocalDateTime(date, time)
}.getOrNull()
@@ -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<ParsedIcsEvent> {
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(),
)
@@ -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<MasterRow>,
val overrides: List<OverrideRow>,
)
/**
* [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<IcsEvent> {
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<Long, MutableList<String>>()
val detached = mutableListOf<Pair<Long, IcsEvent>>()
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())
}
}
@@ -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<String> = 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
@@ -1,20 +1,19 @@
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 kotlinx.datetime.LocalDate
import de.jeanlucmakiola.calendula.domain.zoneOrNull
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.LocalTime
import kotlinx.datetime.TimeZone
import kotlinx.datetime.atStartOfDayIn
import kotlinx.datetime.number
import kotlinx.datetime.toInstant
import kotlinx.datetime.toLocalDateTime
import kotlin.math.ceil
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Instant
/** Milliseconds in a calendar day; all-day times are UTC midnights, so this is exact. */
private const val DAY_MILLIS = 86_400_000L
private const val MINUTES_PER_DAY = 1_440
/**
@@ -47,6 +46,17 @@ data class ParsedIcsEvent(
val exDates: List<String> = 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<String> = emptyList(),
val accessLevel: AccessLevel = AccessLevel.Default,
)
/**
@@ -214,7 +224,10 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault
var calendarColor: Int? = null
val reminders = mutableListOf<Int>()
val exDateLines = mutableListOf<IcsContentLine>()
val rDateLines = mutableListOf<IcsContentLine>()
var skipAsOverride = false
var overrideOf: String? = null
var overrideAt: Instant? = null
var i = 0
while (i < body.size) {
@@ -235,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)
@@ -243,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
@@ -281,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,
@@ -296,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,
)
}
@@ -318,13 +338,9 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault
dtEnd: IcsDateTime?,
duration: String?,
): Instant {
val explicit = dtEnd?.instant ?: duration?.let {
Instant.fromEpochMilliseconds(
start.instant.toEpochMilliseconds() + parseRfc2445DurationMillis(it),
)
}
val explicit = dtEnd?.instant ?: duration?.let { start.instant + parseRfc2445DurationMillis(it).milliseconds }
if (!start.isAllDay) return explicit ?: start.instant
return explicit?.takeIf { it > start.instant } ?: start.instant.plusDays(1)
return explicit?.takeIf { it > start.instant } ?: (start.instant + 1.days)
}
/**
@@ -340,20 +356,23 @@ 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<IcsContentLine>, start: IcsDateTime): List<String> {
if (lines.isEmpty()) return emptyList()
val startZone = runCatching { TimeZone.of(start.zoneId) }.getOrNull() ?: deviceZone
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
start.isAllDay -> parseBasicDate(token.substringBefore('T'))?.let(::dayCode)
token.contains('T') -> parseExDateTime(token, line, startZone)?.let(::utcStamp)
start.isAllDay -> parseBasicDate(token.substringBefore('T'))?.toBasic()
token.contains('T') -> parseExDateTime(token, line, startZone)?.toUtcBasic()
else -> parseBasicDate(token)
?.let { utcStamp(LocalDateTime(it, startTime).toInstant(startZone)) }
?.let { LocalDateTime(it, startTime).toInstant(startZone).toUtcBasic() }
}
}
.distinct()
@@ -373,7 +392,7 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault
val ldt = parseBasicDateTime(token.removeSuffix("Z")) ?: return null
val zone = when {
token.endsWith("Z") -> TimeZone.UTC
else -> line.params["TZID"]?.let { runCatching { TimeZone.of(it) }.getOrNull() }
else -> line.params["TZID"]?.let(::zoneOrNull)
?: startZone
}
return ldt.toInstant(zone)
@@ -409,7 +428,7 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault
if (isUtc) return IcsDateTime(ldt.toInstant(TimeZone.UTC), isAllDay = false, zoneId = "UTC")
val tzid = line.params["TZID"]
val resolved = tzid?.let { id -> runCatching { TimeZone.of(id) }.getOrNull()?.let { id to it } }
val resolved = tzid?.let { id -> zoneOrNull(id)?.let { id to it } }
if (tzid != null && resolved == null) warnings.add(IcsParseWarning.UnknownTimezone)
val (zoneId, zone) = resolved ?: (deviceZone.id to deviceZone)
return IcsDateTime(ldt.toInstant(zone), isAllDay = false, zoneId = zoneId)
@@ -421,16 +440,6 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault
fun IcsContentLine.isBegin(component: String) =
name == "BEGIN" && value.trim().equals(component, true)
fun Instant.plusDays(days: Int): Instant =
Instant.fromEpochMilliseconds(toEpochMilliseconds() + days * DAY_MILLIS)
fun dayCode(date: LocalDate): String =
"%04d%02d%02d".format(date.year, date.month.number, date.day)
fun utcStamp(instant: Instant): String = with(instant.toLocalDateTime(TimeZone.UTC)) {
"%04d%02d%02dT%02d%02d%02dZ".format(year, month.number, day, hour, minute, second)
}
/**
* A single-valued `CATEGORIES`, which is what the Fossify family writes
* for the source calendar's name. A multi-item list is a tag list and
@@ -449,59 +458,26 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault
.takeIf { it.isNotEmpty() && !it.equals("null", true) }
}
/** Index of the matching `END:<component>` at/after [from], or list end. */
/**
* Where an unterminated component's body has to stop: the next top-level
* `VEVENT` / `VTODO` in `[from, end)`, or [end] when there is none. A
* nested `VALARM` is part of the body and is not a boundary.
*/
fun indexOfNextComponent(lines: List<String>, from: Int, end: Int): Int {
var i = from
while (i < end) {
fun indexOfNextComponent(lines: List<String>, from: Int, end: Int): Int =
(from until end).firstOrNull { i ->
val line = parseContentLine(lines[i])
if (line != null && (line.isBegin("VEVENT") || line.isBegin("VTODO"))) {
return i
}
i++
}
return end
}
line != null && (line.isBegin("VEVENT") || line.isBegin("VTODO"))
} ?: end
fun indexOfEnd(lines: List<String>, from: Int, component: String): Int {
var i = from
while (i < lines.size) {
/** Index of the matching `END:<component>` at/after [from], or list end. */
fun indexOfEnd(lines: List<String>, from: Int, component: String): Int =
(from until lines.size).firstOrNull { i ->
val line = parseContentLine(lines[i])
if (line != null && line.name == "END" &&
line.value.trim().equals(component, true)
) {
return i
}
i++
}
return lines.size
}
line != null && line.name == "END" && line.value.trim().equals(component, true)
} ?: lines.size
fun mapIcsStatus(value: String): EventStatus = when (value.trim().uppercase()) {
"TENTATIVE" -> EventStatus.Tentative
"CANCELLED" -> EventStatus.Cancelled
else -> EventStatus.Confirmed
}
fun parseBasicDate(s: String): LocalDate? = runCatching {
LocalDate(s.substring(0, 4).toInt(), s.substring(4, 6).toInt(), s.substring(6, 8).toInt())
}.getOrNull()
fun parseBasicDateTime(s: String): LocalDateTime? = runCatching {
val date = LocalDate(
s.substring(0, 4).toInt(), s.substring(4, 6).toInt(), s.substring(6, 8).toInt(),
)
// Format is YYYYMMDD 'T' HHMMSS; seconds optional.
val time = LocalTime(
s.substring(9, 11).toInt(),
s.substring(11, 13).toInt(),
if (s.length >= 15) s.substring(13, 15).toInt() else 0,
)
LocalDateTime(date, time)
}.getOrNull()
fun mapIcsStatus(value: String): EventStatus =
EventStatus.entries.firstOrNull { it.name.equals(value.trim(), ignoreCase = true) }
?: EventStatus.Confirmed
}
}
@@ -1,5 +1,7 @@
package de.jeanlucmakiola.calendula.domain.ics
import de.jeanlucmakiola.calendula.domain.rruleParts
private val VALID_FREQ = setOf(
"SECONDLY", "MINUTELY", "HOURLY", "DAILY", "WEEKLY", "MONTHLY", "YEARLY",
)
@@ -64,7 +66,9 @@ data class SanitizedRrule(val rule: String?, val repaired: Boolean)
* rule at all — gives up entirely.
*/
fun sanitizeRrule(raw: String?): SanitizedRrule {
val rule = raw?.trim()?.removePrefix("RRULE:")?.trim().orEmpty()
val rule = raw?.trim()
?.let { if (it.startsWith("RRULE:", ignoreCase = true)) it.drop("RRULE:".length) else it }
?.trim().orEmpty()
if (rule.isEmpty()) return SanitizedRrule(rule = null, repaired = false)
var freqSeen = false
@@ -79,13 +83,12 @@ fun sanitizeRrule(raw: String?): SanitizedRrule {
return kept.takeIf { it.isNotEmpty() }?.joinToString(",")
}
for (part in rule.split(';')) {
// A stray separator ("FREQ=DAILY;") normalises away; nothing was lost.
// A part that carries text but no '=' ("FREQ=WEEKLY;BYDAY") is a part
// being dropped, so it falls through and marks the rule repaired.
if (part.isBlank()) continue
val key = part.substringBefore('=', "").trim().uppercase()
val value = if ('=' in part) part.substringAfter('=').trim() else ""
// A stray separator ("FREQ=DAILY;") normalises away; nothing was lost.
// A part that carries text but no '=' ("FREQ=WEEKLY;BYDAY") is a part
// being dropped, so it falls through and marks the rule repaired.
for (part in rruleParts(rule)) {
val key = part.key?.trim()?.uppercase().orEmpty()
val value = part.value.trim()
val kept = when {
key.isEmpty() || value.isEmpty() -> null
key == "FREQ" ->
@@ -2,9 +2,8 @@ package de.jeanlucmakiola.calendula.domain.ics
import de.jeanlucmakiola.calendula.domain.Availability
import de.jeanlucmakiola.calendula.domain.EventStatus
import kotlinx.datetime.LocalDateTime
import de.jeanlucmakiola.calendula.domain.zoneOrNull
import kotlinx.datetime.TimeZone
import kotlinx.datetime.number
import kotlinx.datetime.toLocalDateTime
import kotlin.time.Instant
@@ -26,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<IcsEvent>, dtStamp: Instant): String {
/** [calendarName], when given, names the whole file (`X-WR-CALNAME`), as a one-calendar backup does. */
fun writeCalendar(events: List<IcsEvent>, 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")
}
@@ -41,11 +42,12 @@ class IcsWriter(private val prodId: String = ICS_PROD_ID) {
private fun MutableList<String>.appendEvent(event: IcsEvent, dtStamp: Instant) {
add("BEGIN:VEVENT")
add("UID:${event.uid}")
add("DTSTAMP:${utcStamp(dtStamp)}")
add("DTSTAMP:${dtStamp.toUtcBasic()}")
add("SUMMARY:${escapeText(event.summary)}")
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)}") }
@@ -55,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)
}
@@ -63,27 +68,35 @@ class IcsWriter(private val prodId: String = ICS_PROD_ID) {
private fun MutableList<String>.appendTimes(event: IcsEvent) = when {
event.isAllDay -> {
add("DTSTART;VALUE=DATE:${utcDate(event.start)}")
add("DTEND;VALUE=DATE:${utcDate(event.end)}")
add("DTSTART;VALUE=DATE:${event.start.toLocalDateTime(TimeZone.UTC).date.toBasic()}")
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 -> {
val zone = runCatching { TimeZone.of(event.zoneId) }.getOrNull()
event.recurs -> {
val zone = zoneOrNull(event.zoneId)
if (zone != null) {
add("DTSTART;TZID=${event.zoneId}:${localStamp(event.start, zone)}")
add("DTEND;TZID=${event.zoneId}:${localStamp(event.end, zone)}")
add("DTSTART;TZID=${event.zoneId}:${event.start.toLocalDateTime(zone).toBasic()}")
add("DTEND;TZID=${event.zoneId}:${event.end.toLocalDateTime(zone).toBasic()}")
} else {
// Unknown zone id → fall back to plain UTC instants.
add("DTSTART:${utcStamp(event.start)}")
add("DTEND:${utcStamp(event.end)}")
add("DTSTART:${event.start.toUtcBasic()}")
add("DTEND:${event.end.toUtcBasic()}")
}
}
else -> {
add("DTSTART:${utcStamp(event.start)}")
add("DTEND:${utcStamp(event.end)}")
add("DTSTART:${event.start.toUtcBasic()}")
add("DTEND:${event.end.toUtcBasic()}")
}
}
/** Extra occurrences: the same UTC stamps / `VALUE=DATE` days as [appendExDates]. */
private fun MutableList<String>.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
@@ -91,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<String>.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:"
@@ -120,20 +133,5 @@ class IcsWriter(private val prodId: String = ICS_PROD_ID) {
// A lead time of 0 fires at start (PT0M); anything positive is "before".
fun triggerValue(minutes: Int): String =
if (minutes <= 0) "PT0M" else "-PT${minutes}M"
fun utcStamp(instant: Instant): String =
basic(instant.toLocalDateTime(TimeZone.UTC)) + "Z"
fun localStamp(instant: Instant, zone: TimeZone): String =
basic(instant.toLocalDateTime(zone))
fun utcDate(instant: Instant): String {
val dt = instant.toLocalDateTime(TimeZone.UTC)
return "%04d%02d%02d".format(dt.year, dt.month.number, dt.day)
}
fun basic(dt: LocalDateTime): String = "%04d%02d%02dT%02d%02d%02d".format(
dt.year, dt.month.number, dt.day, dt.hour, dt.minute, dt.second,
)
}
}
@@ -1,15 +1,16 @@
package de.jeanlucmakiola.calendula.domain.ics
import de.jeanlucmakiola.calendula.domain.EventForm
import kotlinx.datetime.LocalDate
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.LocalTime
import de.jeanlucmakiola.calendula.domain.allDayFormTimes
import de.jeanlucmakiola.calendula.domain.forNewEvent
import de.jeanlucmakiola.calendula.domain.normalizedRrule
import de.jeanlucmakiola.calendula.domain.toFormTime
import kotlinx.datetime.TimeZone
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).
@@ -21,12 +22,9 @@ import kotlinx.datetime.toLocalDateTime
*/
fun ParsedIcsEvent.toEventForm(zone: TimeZone): EventForm {
val (start, end) = if (isAllDay) {
val startDate = this.start.toLocalDateTime(TimeZone.UTC).date
val endExclusive = this.end.toLocalDateTime(TimeZone.UTC).date
val endDate = maxOf(startDate, LocalDate.fromEpochDays(endExclusive.toEpochDays() - 1))
LocalDateTime(startDate, LocalTime(9, 0)) to LocalDateTime(endDate, LocalTime(10, 0))
allDayFormTimes(this.start.toLocalDateTime(TimeZone.UTC).date, this.end.toLocalDateTime(TimeZone.UTC).date)
} else {
this.start.toLocalDateTime(zone) to this.end.toLocalDateTime(zone)
this.start.toFormTime(zone) to this.end.toFormTime(zone)
}
return EventForm(
calendarId = null,
@@ -38,6 +36,7 @@ fun ParsedIcsEvent.toEventForm(zone: TimeZone): EventForm {
description = description.orEmpty(),
reminders = semanticReminderMinutes(),
availability = availability,
rrule = recurrenceRule?.removePrefix("RRULE:")?.takeIf { it.isNotBlank() },
status = status.forNewEvent(),
rrule = recurrenceRule.normalizedRrule(),
)
}
@@ -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<Long> = 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<ReminderEventInstance>,
day: LocalDate,
zone: ZoneId,
excludedCalendarIds: Set<Long>,
): List<ReminderEventInstance> {
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()
}
@@ -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<Int>,
val fixed: List<FixedTimeReminder>,
)
/**
* 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<FixedTimeReminder>,
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<Int>,
start: Instant,
zone: TimeZone,
known: Set<FixedTimeReminder>,
wallClock: Boolean = false,
): TimedReminders {
val leads = mutableListOf<Int>()
val fixed = mutableListOf<FixedTimeReminder>()
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<FixedTimeReminder> =
compareByDescending<FixedTimeReminder> { it.daysBefore }.thenBy { it.minuteOfDay }
private const val MINUTES_PER_DAY = 1_440
@@ -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<Long, ReminderAlertStyle>.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<Long, ReminderAlertStyle> =
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<Long, ReminderAlertStyle>.toStoredAlertStyles(): String =
entries.filter { it.value != ReminderAlertStyle.Notification }
.sortedBy { it.key }
.joinToString(";") { (id, style) -> "$id=${style.storageValue}" }
@@ -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('.', ',', ';', ')', '>') }
@@ -32,19 +32,26 @@ data class PlannedReminder(
val minutes: Int,
val alarmMillis: Long,
) {
/** The occurrence this reminder belongs to; it shares one notification with its siblings (#463). */
val occurrenceKey: Long = occurrenceKey(instance.eventId, instance.beginMillis)
/**
* Stable identity, keying the notification tag and the snooze/dismiss
* Stable identity of this one reminder, keying the snooze/dismiss
* `PendingIntent`s. Survives reboot, re-scan and reinstall.
*/
val key: Long = key(instance.eventId, instance.beginMillis, minutes)
val key: Long = mix64(occurrenceKey + minutes)
}
private companion object {
fun key(eventId: Long, beginMillis: Long, minutes: Int): Long {
var h = eventId * 1_000_003L
h = (h xor beginMillis) * 31L
return h + minutes
}
}
/** Stable identity of one occurrence, shared by every reminder on it. */
fun occurrenceKey(eventId: Long, beginMillis: Long): Long =
mix64(mix64(eventId) + beginMillis)
/** SplitMix64's finaliser: spreads close inputs across all 64 bits. */
private fun mix64(value: Long): Long {
var z = value + -0x61c8864680b583ebL
z = (z xor (z ushr 30)) * -0x40a7b892e31b1a47L
z = (z xor (z ushr 27)) * -0x6b2fb644ecceee15L
return z xor (z ushr 31)
}
/** What one scan concluded: post these now, and wake up again at [nextAlarmMillis]. */
@@ -146,7 +153,8 @@ private fun allDayAlarmMillis(
*
* Due means the fire instant falls in `(lastFiredMillis, nowMillis]`, so a scan
* running twice cannot post twice while a late one still catches up. Reminders
* whose event has ended are dropped ([isStillRelevant]). [nextAlarmMillis] is
* whose event has ended are dropped ([isStillRelevant]), and of several due on
* one occurrence only the latest is kept — they'd replace each other anyway (#463). [nextAlarmMillis] is
* capped at [horizonMillis] so the lookahead window keeps rolling forward.
*/
fun scheduleReminders(
@@ -158,7 +166,8 @@ fun scheduleReminders(
val due = planned
.filter { it.alarmMillis in (lastFiredMillis + 1)..nowMillis }
.filter { it.instance.isStillRelevant(nowMillis) }
.distinctBy { it.key }
.groupBy { it.occurrenceKey }
.values.map { siblings -> siblings.maxBy { it.alarmMillis } }
.sortedWith(compareBy({ it.instance.beginMillis }, { it.key }))
val nextPending = planned
.filter { it.alarmMillis > nowMillis }
@@ -4,8 +4,10 @@ import androidx.activity.compose.BackHandler
import androidx.activity.compose.PredictiveBackHandler
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.AnimatedVisibilityScope
import androidx.compose.animation.ExperimentalSharedTransitionApi
import androidx.compose.animation.SharedTransitionLayout
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.animation.core.SeekableTransitionState
import androidx.compose.animation.core.rememberTransition
import androidx.compose.animation.fadeIn
@@ -19,6 +21,7 @@ import androidx.compose.material3.Scaffold
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.setValue
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
@@ -27,9 +30,13 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.Saver
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
import androidx.compose.ui.layout.onGloballyPositioned
@@ -37,6 +44,7 @@ import androidx.compose.ui.layout.positionInWindow
import androidx.compose.ui.platform.LocalDensity
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import de.jeanlucmakiola.calendula.data.time.currentDate
import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.ui.agenda.AgendaScreen
@@ -45,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
@@ -55,7 +71,13 @@ import de.jeanlucmakiola.floret.identity.fadeThrough
import de.jeanlucmakiola.floret.identity.predictiveBackExit
import de.jeanlucmakiola.floret.identity.rememberReduceMotion
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.common.EventActionsViewModel
import de.jeanlucmakiola.calendula.ui.common.EventMoveHost
import de.jeanlucmakiola.calendula.ui.common.EventSelectionHost
import de.jeanlucmakiola.calendula.ui.common.eventActionFailureMessage
import de.jeanlucmakiola.calendula.ui.common.rememberFabSelection
import de.jeanlucmakiola.calendula.ui.common.canWriteCalendar
import de.jeanlucmakiola.calendula.ui.common.rememberWriteAction
import de.jeanlucmakiola.calendula.ui.common.EventMoveScope
import de.jeanlucmakiola.calendula.ui.common.LocalEventMove
import de.jeanlucmakiola.calendula.ui.common.LocalManageCalendars
@@ -76,6 +98,7 @@ import de.jeanlucmakiola.calendula.ui.common.rememberCalendarSlideSpec
import de.jeanlucmakiola.calendula.ui.common.selectView
import de.jeanlucmakiola.calendula.ui.common.viewBaseStack
import de.jeanlucmakiola.calendula.ui.detail.EventDetailScreen
import de.jeanlucmakiola.calendula.ui.edit.EventEditViewModel
import de.jeanlucmakiola.calendula.ui.edit.EventEditScreen
import de.jeanlucmakiola.calendula.ui.edit.ImportSource
import de.jeanlucmakiola.calendula.ui.imports.ImportScreen
@@ -83,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
@@ -90,7 +115,7 @@ import kotlinx.datetime.LocalDate
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime
import kotlin.coroutines.cancellation.CancellationException
import kotlin.time.Clock
import kotlin.time.Instant
/**
* Holds the top-level view back stack (spec M1) and swaps between the calendar
@@ -106,28 +131,18 @@ import kotlin.time.Clock
* 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.
*
* [requestedDetailKey] is an externally requested occurrence (a tapped
* reminder notification routed through MainActivity): it opens the detail
* overlay exactly like an event tap and is cleared via [onDetailKeyConsumed]
* so a later recomposition can't re-open it. (A widget event tap instead arrives
* as [WidgetNavRequest.OpenEvent], which also roots the back stack in the
* widget's view.)
* [requests] carries what notifications, widgets and other apps asked to
* open. A tapped reminder's occurrence opens the detail overlay exactly like an
* event tap; each request is cleared once acted on so a later recomposition
* can't re-open it. (A widget event tap instead arrives as
* [WidgetNavRequest.OpenEvent], which also roots the back stack in the widget's
* view.)
*/
@OptIn(ExperimentalSharedTransitionApi::class)
@Composable
fun CalendarHost(
requests: ExternalRequests,
modifier: Modifier = Modifier,
requestedDetailKey: LongArray? = null,
onDetailKeyConsumed: () -> Unit = {},
widgetNavRequest: WidgetNavRequest? = null,
onWidgetNavConsumed: () -> Unit = {},
requestedImportUri: android.net.Uri? = null,
onImportConsumed: () -> Unit = {},
requestedInsertForm: EventForm? = null,
requestedInsertSource: ImportSource = ImportSource.Insert,
onInsertConsumed: () -> Unit = {},
requestedEditKey: LongArray? = null,
onEditKeyConsumed: () -> Unit = {},
viewModel: CalendarHostViewModel = hiltViewModel(),
) {
// Wait for the persisted default view before seeding the stack, so the app
@@ -146,14 +161,27 @@ fun CalendarHost(
mutableStateOf(listOf(defaultView))
}
var navigationVersion by remember { mutableIntStateOf(0) }
// True after backing out of a day opened from the view now shown, so the
// agenda returns to where it was instead of today (#367).
var returnedFromDay by remember { mutableStateOf(false) }
val view = viewStack.last()
// The date every view opens on and carries along (#184); tapping a day
// anywhere focuses it and opens the day view there.
val focus = rememberSaveable(saver = ViewFocusSaver) { ViewFocus(localToday()) }
val focus = rememberSaveable(saver = ViewFocusSaver) { ViewFocus(currentDate()) }
// A focus still on yesterday follows the date over, so the next view opened
// doesn't land on the old day (#373); one moved elsewhere stays put.
val today = viewModel.today.collectAsStateWithLifecycle().value
var focusToday by rememberSaveable { mutableStateOf(today.toString()) }
LaunchedEffect(today) {
val old = LocalDate.parse(focusToday)
if (old != today && focus.date == old) focus.date = today
focusToday = today.toString()
}
val switchScope = rememberCoroutineScope()
val switchTo: ((List<CalendarView>) -> List<CalendarView>) -> Unit = { move ->
navigationVersion++
returnedFromDay = false
viewStack = move(viewStack)
}
val onSelectView: (CalendarView) -> Unit = { target -> switchTo { it.selectView(target) } }
@@ -170,27 +198,22 @@ fun CalendarHost(
// it overlays whichever calendar view is active. We forward the tapped
// occurrence's own times (eventId + begin + end, packed as a saveable
// long[]) so recurring events show the correct date, not the series start.
// [heldKey] keeps the last shown key alive through the slide-out (when
// [detailKey] is cleared); it is set in the tap callback — never a [0,0,0]
// placeholder — so the destination never loads a bogus id=0 on first frame.
// Like every overlay below, it draws its last key through the slide-out
// ([rememberHeld]) rather than a placeholder.
var detailKey by rememberSaveable { mutableStateOf<LongArray?>(null) }
var heldKey by remember { mutableStateOf<LongArray?>(null) }
val onEventClick: (EventInstance) -> Unit = { event ->
val key = longArrayOf(
event.eventId,
event.start.toEpochMilliseconds(),
event.end.toEpochMilliseconds(),
)
heldKey = key
detailKey = key
}
val onOpenDetail: (EventInstance) -> Unit = { event -> detailKey = event.occurrenceKey() }
// The drawer's "Hide in this 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) }
// A tapped reminder notification asks for a specific occurrence.
val requestedDetailKey = requests.detailKey
LaunchedEffect(requestedDetailKey) {
if (requestedDetailKey != null) {
heldKey = requestedDetailKey
showViewCalendars = false
detailKey = requestedDetailKey
onDetailKeyConsumed()
requests.detailKey = null
}
}
@@ -204,6 +227,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
@@ -214,19 +238,17 @@ fun CalendarHost(
// calendar list rather than by preferences. Reached from both.
var showBackup by rememberSaveable { mutableStateOf(false) }
// Event form (v1.2 create) — same held-key pattern as the detail screen:
// [heldCreateIso] keeps the prefill date alive through the slide-out.
// [createStartMinutes] is the tapped slot's start (minutes from midnight)
// when the form is opened from a day/week grid tap; null from the FAB.
var createDateIso by rememberSaveable { mutableStateOf<String?>(null) }
var heldCreateIso by remember { mutableStateOf<String?>(null) }
var createStartMinutes by rememberSaveable { mutableStateOf<Int?>(null) }
var heldCreateMinutes by remember { mutableStateOf<Int?>(null) }
val onCreateEvent: (LocalDate, Int?) -> Unit = { date, startMinutes ->
heldCreateIso = date.toString()
createDateIso = date.toString()
heldCreateMinutes = startMinutes
createStartMinutes = startMinutes
// Event form (v1.2 create), opened on a date, a tapped slot or a drafted block.
var createRequest by rememberSaveable(stateSaver = createRequestSaver) {
mutableStateOf<CreateRequest?>(null)
}
fun openCreate(dateIso: String, startMinutes: Int? = null, draftMillis: LongArray? = null) {
createRequest = CreateRequest(dateIso, startMinutes, draftMillis)
}
val onCreateEvent: (LocalDate, Int?) -> Unit = { date, startMinutes -> openCreate(date.toString(), startMinutes) }
val onCreateDraft: (Instant, Instant) -> Unit = { start, end ->
val date = start.toLocalDateTime(TimeZone.currentSystemDefault()).date
openCreate(date.toString(), draftMillis = longArrayOf(start.toEpochMilliseconds(), end.toEpochMilliseconds()))
}
// Edit form (v1.3) — reuses the detail screen's occurrence key; for
@@ -236,21 +258,57 @@ fun CalendarHost(
// falling back to the auto-refreshing calendar is the only honest
// destination.
var editKey by rememberSaveable { mutableStateOf<LongArray?>(null) }
var heldEditKey by remember { mutableStateOf<LongArray?>(null) }
// An opened/received .ics file. [ImportScreen] parses it and either opens
// the prefilled create form (one event → [importForm]) or its own bulk
// picker (many). A plain conditional overlay (no slide) — it's transient.
var importUri by remember { mutableStateOf<android.net.Uri?>(null) }
var importForm by remember { mutableStateOf<EventForm?>(null) }
var importUri by rememberSaveable { mutableStateOf<android.net.Uri?>(null) }
val importViewModel: EventEditViewModel = hiltViewModel(key = "import")
// Saved as "open"; a recreation takes the form back from the ViewModel, which
// still holds the user's edits.
var importForm by rememberSaveable(
stateSaver = Saver<EventForm?, Boolean>(
save = { it != null },
restore = { open -> if (open) importViewModel.currentForm() else null },
),
) { mutableStateOf<EventForm?>(null) }
// Which channel filled [importForm]: an .ics file (prompt to apply the default
// reminder) or an ACTION_INSERT intent (apply it automatically) — #49.
var importFormSource by remember { mutableStateOf(ImportSource.File) }
var importFormSource by rememberSaveable { mutableStateOf(ImportSource.File) }
// Bumped per open, so even an equal prefill starts a fresh form.
var importFormId by rememberSaveable { mutableIntStateOf(0) }
// Whether [importForm] came from an external create request (#30, #306);
// closing it then hands control back to whoever asked.
var importFromRequest by rememberSaveable { mutableStateOf(false) }
// A second external request that arrived while a prefilled form was open:
// it waits behind that form's unsaved-changes prompt, then opens.
var pendingInsert by remember { mutableStateOf<Pair<EventForm, ImportSource>?>(null) }
val createViewModel: EventEditViewModel = hiltViewModel(key = "create")
val editViewModel: EventEditViewModel = hiltViewModel(key = "edit")
fun openImportForm(form: EventForm, source: ImportSource, fromRequest: Boolean = false) {
importFormSource = source
importForm = form
importFormId++
importFromRequest = fromRequest
}
fun closeImportForm() {
val next = pendingInsert
pendingInsert = null
if (next != null) {
openImportForm(next.first, next.second, fromRequest = true)
} else {
importForm = null
if (importFromRequest) {
importFromRequest = false
requests.onExternalFormClosed()
}
}
}
// A restore (in-app "Restore from .ics" button) always runs the full import
// flow — picker + summary — even for a single-event file, because the intent
// is "restore a backup", not "add this one event". An externally opened .ics
// keeps routing a single event straight into the prefilled create form.
var importForceMany by remember { mutableStateOf(false) }
var importForceMany by rememberSaveable { mutableStateOf(false) }
// Where a restore came from, so closing the import puts it back: the import
// overlays are declared under Backup & restore and the manager, so starting
// one has to close them — without this, finishing a restore drops you on the
@@ -261,81 +319,116 @@ fun CalendarHost(
// what tells it a *re-import of the same file* is new work and not the run
// it already finished; a rotation keeps the number and keeps the result.
var importSession by rememberSaveable { mutableStateOf(0) }
// A recreation re-reads the launch intent; when the import it carries came
// back with the saved state, that replay is the same work, not a new one.
fun isReplayOfRestoredImport(): Boolean {
val replay = requests.replayed && (importUri != null || importForm != null)
requests.replayed = false
return replay
}
val requestedImportUri = requests.importUri
LaunchedEffect(requestedImportUri) {
if (requestedImportUri != null) {
if (isReplayOfRestoredImport()) {
requests.importUri = null
return@LaunchedEffect
}
showViewCalendars = false
importUri = requestedImportUri
importForceMany = false
importSession++
onImportConsumed()
requests.importUri = null
}
}
// An external ACTION_INSERT launch (another app/widget creating an event,
// issue #30) arrives already prefilled — open it in the same create form the
// single-event .ics path uses. [importForm] is the topmost overlay, so it
// reveals on top of whatever was open without extra dismissal.
LaunchedEffect(requestedInsertForm) {
if (requestedInsertForm != null) {
importFormSource = requestedInsertSource
importForm = requestedInsertForm
onInsertConsumed()
val requestedInsert = requests.insert
LaunchedEffect(requestedInsert) {
if (requestedInsert != null) {
if (isReplayOfRestoredImport()) {
requests.insert = null
return@LaunchedEffect
}
showViewCalendars = false
if (importForm == null) {
openImportForm(requestedInsert.form, requestedInsert.source, fromRequest = true)
} else {
pendingInsert = requestedInsert.form to requestedInsert.source
}
requests.insert = null
}
}
// Close every overlay that can sit over the calendar, so an externally
// requested destination (a widget/shortcut/QS-tile launch) is revealed on
// top instead of underneath whatever the user had open.
fun dismissCoveringOverlays() {
// top instead of underneath whatever the user had open. The create form,
// declared under the edit form, can stay for an edit to open over it.
fun dismissCoveringOverlays(keepCreate: Boolean = false) {
showSettings = false
showSearch = false
showViewCalendars = false
showCalendars = false
showBackup = false
detailKey = null
editKey = null
if (!keepCreate) createRequest = null
importUri = null
importForm = null
if (importFromRequest) {
importFromRequest = false
requests.onExternalFormClosed()
}
pendingInsert = null
importViewModel.reset()
}
// An external "edit this event" (ACTION_EDIT, e.g. an assistant/task app or
// widget) opens the occurrence straight in the edit form. Drop any covering
// overlay first — the edit overlay sits below Settings/import in the Box, so
// without this it would open hidden underneath them. Same held-key pattern as
// a detail-screen "Edit" tap; a saved edit just returns to the calendar.
// without this it would open hidden underneath them. A saved edit just
// returns to the calendar.
val requestedEditKey = requests.editKey
LaunchedEffect(requestedEditKey) {
if (requestedEditKey != null) {
dismissCoveringOverlays()
heldEditKey = requestedEditKey
// An open edit form stays on screen, so it starts over here rather
// than once it has slid away.
if (editKey != null) editViewModel.reset()
dismissCoveringOverlays(keepCreate = true)
editKey = requestedEditKey
onEditKeyConsumed()
requests.editKey = null
}
}
// 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
// [requestedDetailKey]. Date/event opens root the stack in the widget's own
// 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.
val widgetNavRequest = requests.nav
LaunchedEffect(widgetNavRequest) {
if (widgetNavRequest != null) navigationVersion++
if (widgetNavRequest != null) {
navigationVersion++
returnedFromDay = false
}
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.
dismissCoveringOverlays()
createDateIso = null
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()
onWidgetNavConsumed()
requests.nav = null
}
is WidgetNavRequest.OpenEvent -> {
// Root the stack in the widget's view, then open the occurrence
// detail over it (same key shape as a tapped event / reminder).
dismissCoveringOverlays()
createDateIso = null
viewStack = viewBaseStack(defaultView, req.source)
val key = longArrayOf(req.eventId, req.beginMillis, req.endMillis)
heldKey = key
detailKey = key
onWidgetNavConsumed()
detailKey = longArrayOf(req.eventId, req.beginMillis, req.endMillis)
requests.nav = null
}
is WidgetNavRequest.OpenView -> {
// A widget header tap: land on a top-level view with no date
@@ -343,24 +436,19 @@ fun CalendarHost(
// the stack on the target (null → the default home) over the
// default home — so backing out returns to the default, then exits.
dismissCoveringOverlays()
createDateIso = null
focus.navigateTo(localToday())
focus.navigateTo(currentDate())
viewStack = viewBaseStack(defaultView, req.view ?: defaultView)
onWidgetNavConsumed()
requests.nav = null
}
is WidgetNavRequest.Create -> {
// External "new event" entries (QS tile / launcher shortcut /
// widget) must land on top of whatever is open — the form overlay
// sits below Settings/calendars in the Box, so without this it
// would open hidden underneath them.
if (createRequest != null) createViewModel.reset()
dismissCoveringOverlays()
val iso = req.dateIso ?: Clock.System.now()
.toLocalDateTime(TimeZone.currentSystemDefault()).date.toString()
heldCreateIso = iso
createDateIso = iso
heldCreateMinutes = null
createStartMinutes = null
onWidgetNavConsumed()
openCreate(req.dateIso ?: currentDate().toString())
requests.nav = null
}
null -> {}
}
@@ -370,14 +458,55 @@ fun CalendarHost(
// survives view switches; the calendar surfaces read it out of LocalEventMove.
val reschedule: RescheduleViewModel = hiltViewModel()
val movableCalendarIds by reschedule.movableCalendarIds.collectAsStateWithLifecycle()
val onEditEvent: (EventInstance) -> Unit = { event ->
val key = longArrayOf(
event.eventId,
event.start.toEpochMilliseconds(),
event.end.toEpochMilliseconds(),
)
heldEditKey = key
editKey = key
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
// tap time, so a tap before they've loaded still routes right.
val tapScope = rememberCoroutineScope()
val tapContext = LocalContext.current
// A refused write upgrade is asked once; later taps just open the details.
var tapWriteRefused by rememberSaveable { mutableStateOf(false) }
// The tap waiting on the WRITE_CALENDAR prompt, saved so a rotation keeps it.
var tapAwaitingWrite by rememberSaveable { mutableStateOf<LongArray?>(null) }
val editAwaitingTap = rememberWriteAction(
onDenied = {
tapAwaitingWrite?.let { key ->
tapWriteRefused = true
detailKey = key
}
tapAwaitingWrite = null
},
) {
tapAwaitingWrite?.let { editKey = it }
tapAwaitingWrite = null
}
val onEventClick: (EventInstance) -> Unit = { event ->
tapScope.launch {
val toEditor = viewModel.tapOpensEditor() && eventActions.canModify(event.calendarId)
when {
!toEditor -> onOpenDetail(event)
tapContext.canWriteCalendar() -> onEditEvent(event)
tapWriteRefused -> onOpenDetail(event)
else -> {
tapAwaitingWrite = event.occurrenceKey()
editAwaitingTap()
}
}
}
}
// Off by preference (#173) switches off the gesture, not the scope: blocks
// register no drag, while the edit form and its TalkBack action stay put.
@@ -387,22 +516,16 @@ fun CalendarHost(
movableCalendarIds = movableCalendarIds,
dragEnabled = dragToReschedule,
move = { reschedule.move(it) },
inFlight = reschedule.inFlight,
drops = reschedule.drops,
undoStarted = reschedule.undoStarted,
abandoned = reschedule.abandoned,
edit = onEditEvent,
)
}
val slideSpec = rememberCalendarSlideSpec()
// Overlays leave from the predictive-back preview (#184): shrinking on from
// where the gesture let go instead of snapping back and sliding off.
val overlayExit = predictiveBackExit()
// Base-level back: pop the view stack while no overlay covers it (each overlay
// owns its own BackHandler and takes precedence). Disabled at the home view,
// so back there falls through to the system and exits the app.
val anyOverlayVisible = showSearch || detailKey != null || createDateIso != null ||
val anyOverlayVisible = showSearch || detailKey != null || createRequest != null ||
editKey != null || showSettings || showCalendars || showBackup ||
importUri != null || importForm != null
// The view switch runs on a seekable transition, so a back gesture can scrub
@@ -415,11 +538,14 @@ fun CalendarHost(
if (reduceMotion) {
BackHandler(enabled = viewBackEnabled) {
navigationVersion++
returnedFromDay = viewStack.last() == CalendarView.Day
viewStack = viewStack.dropLast(1)
}
} else {
PredictiveBackHandler(enabled = viewBackEnabled) { events ->
val previous = viewStack[viewStack.size - 2]
// Set before the seek, which already composes the previous view.
returnedFromDay = viewStack.last() == CalendarView.Day
try {
events.collect { viewTransition.seekTo(it.progress, targetState = previous) }
navigationVersion++
@@ -443,6 +569,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() }
@@ -463,6 +592,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.
@@ -493,6 +631,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() }
},
)
},
) {
@@ -508,7 +661,26 @@ fun CalendarHost(
showTodayButton = todayInToolbar,
)
},
floatingActionButton = { CalendarFab(chromeHost, todayInToolbar) },
floatingActionButton = {
// While an event is selected the FAB is its action bar's toggle (#141).
val fabSelection = rememberFabSelection(
host = chromeHost,
viewModel = eventActions,
onEdit = onEditEvent,
onDuplicate = { form ->
// A fresh event, like a duplicate from the detail screen (#52).
openImportForm(form, ImportSource.Insert)
},
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)
},
) { innerPadding ->
SharedTransitionLayout(
Modifier
@@ -539,6 +711,7 @@ fun CalendarHost(
onOpenDay = onOpenDay,
onEventClick = onEventClick,
onCreateEvent = onCreateEvent,
onCreateDraft = onCreateDraft,
)
ViewScreen.Month -> MonthScreen(
onOpenDay = onOpenDay,
@@ -551,6 +724,7 @@ fun CalendarHost(
onEventClick = onEventClick,
onCreateEvent = onCreateEvent,
quickSwitchViews = quickSwitchViews,
restorePosition = returnedFromDay,
)
}
}
@@ -562,15 +736,30 @@ fun CalendarHost(
// Scope prompt + confirmation/undo snackbar for a dropped event, declared
// right after the calendar views so later overlays cover it.
EventMoveHost(reschedule, modifier = Modifier.fillMaxSize())
EventMoveHost(
reschedule,
modifier = Modifier.fillMaxSize(),
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)
// Search overlay — below detail/edit in the Box so a tapped result's
// detail screen draws on top, and closing it returns to the results.
AnimatedVisibility(
visible = showSearch,
enter = slideInHorizontally(slideSpec) { it } + fadeIn(),
exit = overlayExit,
) {
SlideOverlay(visible = showSearch) {
SearchScreen(
onBack = { showSearch = false },
onEventClick = onEventClick,
@@ -578,29 +767,20 @@ fun CalendarHost(
)
}
// Prefer the live key; fall back to the held one only while sliding out.
val activeKey = detailKey ?: heldKey
AnimatedVisibility(
visible = detailKey != null,
enter = slideInHorizontally(slideSpec) { it } + fadeIn(),
exit = overlayExit,
) {
activeKey?.let { key ->
val shownDetailKey = rememberHeld(detailKey)
SlideOverlay(visible = detailKey != null) {
shownDetailKey?.let { key ->
EventDetailScreen(
eventId = key[0],
beginMillis = key[1],
endMillis = key[2],
onBack = { detailKey = null },
onEdit = {
heldEditKey = key
editKey = key
},
onEdit = { editKey = key },
onDuplicate = { form ->
// Reuse the prefilled-create overlay: a duplicate is a
// fresh event, so it applies the default reminder like an
// in-app new event (#52).
importFormSource = ImportSource.Insert
importForm = form
openImportForm(form, ImportSource.Insert)
detailKey = null
},
visible = detailKey != null,
@@ -609,30 +789,28 @@ fun CalendarHost(
}
// Event form (v1.2) — full-screen destination, slides over the calendar.
AnimatedVisibility(
visible = createDateIso != null,
enter = slideInHorizontally(slideSpec) { it } + fadeIn(),
exit = overlayExit,
) {
(createDateIso ?: heldCreateIso)?.let { iso ->
EventEditScreen(
initialDateIso = iso,
initialStartMinutes = createStartMinutes ?: heldCreateMinutes,
onClose = { createDateIso = null },
onSaved = { createDateIso = null },
onManageCalendars = { showCalendars = true },
visible = createDateIso != null,
)
val shownCreate = rememberHeld(createRequest)
SlideOverlay(visible = createRequest != null, onHidden = createViewModel::reset) {
shownCreate?.let { create ->
key(create) {
EventEditScreen(
initialDateIso = create.dateIso,
initialStartMinutes = create.startMinutes,
initialDraft = create.draftMillis,
onClose = { createRequest = null },
onSaved = { createRequest = null },
onManageCalendars = { showCalendars = true },
visible = createRequest != null,
viewModel = createViewModel,
)
}
}
}
// Edit form (v1.3) — slides over the detail screen.
AnimatedVisibility(
visible = editKey != null,
enter = slideInHorizontally(slideSpec) { it } + fadeIn(),
exit = overlayExit,
) {
(editKey ?: heldEditKey)?.let { key ->
val shownEditKey = rememberHeld(editKey)
SlideOverlay(visible = editKey != null, onHidden = editViewModel::reset) {
shownEditKey?.let { key ->
EventEditScreen(
initialDateIso = null,
editKey = key,
@@ -642,17 +820,23 @@ fun CalendarHost(
detailKey = null
},
onManageCalendars = { showCalendars = true },
onDuplicate = { form ->
openImportForm(form, ImportSource.Insert)
},
// Opened straight from a tap (#178) there's no detail screen
// below to show why, so open it.
onLoadFailed = {
editKey = null
if (detailKey == null) detailKey = key
},
visible = editKey != null,
viewModel = editViewModel,
)
}
}
// Settings (M4) — full-screen destination, slides over the calendar.
AnimatedVisibility(
visible = showSettings,
enter = slideInHorizontally(slideSpec) { it } + fadeIn(),
exit = overlayExit,
) {
SlideOverlay(visible = showSettings) {
SettingsScreen(
onBack = { showSettings = false },
onManageCalendars = { showCalendars = true },
@@ -688,29 +872,29 @@ fun CalendarHost(
importUri = null
calendarsAfterImport = false
backupAfterImport = false
importFormSource = ImportSource.File
importForm = form
openImportForm(form, ImportSource.File)
},
)
}
importForm?.let { form ->
EventEditScreen(
initialDateIso = null,
initialForm = form,
initialFormSource = importFormSource,
onClose = { importForm = null },
onSaved = { importForm = null },
onManageCalendars = { showCalendars = true },
)
key(importFormId) {
EventEditScreen(
initialDateIso = null,
initialForm = form,
initialFormSource = importFormSource,
onClose = ::closeImportForm,
onSaved = ::closeImportForm,
onManageCalendars = { showCalendars = true },
leaveRequested = pendingInsert != null,
onLeaveDeclined = { pendingInsert = null },
viewModel = importViewModel,
)
}
}
// Declared last so it covers every overlay that can open it: Settings,
// both event forms, and the .ics import picker (#76).
AnimatedVisibility(
visible = showCalendars,
enter = slideInHorizontally(slideSpec) { it } + fadeIn(),
exit = overlayExit,
) {
SlideOverlay(visible = showCalendars) {
CalendarsScreen(
onBack = { showCalendars = false },
onOpenBackup = { showBackup = true },
@@ -719,11 +903,7 @@ fun CalendarHost(
}
// Backup & restore — over the manager, since the manager links into it.
AnimatedVisibility(
visible = showBackup,
enter = slideInHorizontally(slideSpec) { it } + fadeIn(),
exit = overlayExit,
) {
SlideOverlay(visible = showBackup) {
// Settings can open this screen without the manager underneath, so
// its failure states' "Manage calendars" way out has to open the
// manager rather than just pop — popping alone lands on Settings
@@ -762,5 +942,48 @@ private val viewStackSaver = listSaver<List<CalendarView>, Int>(
restore = { ordinals -> ordinals.map { CalendarView.entries[it] } },
)
private fun localToday(): LocalDate =
Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).date
/**
* An overlay's slide-in from the end edge, leaving from the predictive-back
* preview (#184): shrinking on from where the gesture let go instead of
* snapping back and sliding off.
*/
@Composable
private fun SlideOverlay(
visible: Boolean,
onHidden: () -> Unit = {},
content: @Composable AnimatedVisibilityScope.() -> Unit,
) {
val state = remember { MutableTransitionState(visible) }
state.targetState = visible
val hidden = state.isIdle && !state.currentState
LaunchedEffect(hidden) {
if (hidden) onHidden()
}
AnimatedVisibility(
visibleState = state,
enter = slideInHorizontally(rememberCalendarSlideSpec()) { it } + fadeIn(),
exit = predictiveBackExit(),
content = content,
)
}
/** The detail and edit overlays' key for one occurrence: eventId, begin, end. */
private fun EventInstance.occurrenceKey(): LongArray =
longArrayOf(eventId, start.toEpochMilliseconds(), end.toEpochMilliseconds())
/**
* A create-form open: its date, plus the tapped slot's start (minutes from
* midnight) from a day/week grid tap, or a drafted block's start and end (#153)
* as epoch millis. Instants rather than minutes into a day, so the form opens at
* the times drawn even across a DST change (#387).
*/
private class CreateRequest(
val dateIso: String,
val startMinutes: Int?,
val draftMillis: LongArray?,
)
private val createRequestSaver = Saver<CreateRequest?, List<Any?>>(
save = { request -> request?.let { listOf(it.dateIso, it.startMinutes, it.draftMillis) } },
restore = { CreateRequest(it[0] as String, it[1] as Int?, it[2] as LongArray?) },
)
@@ -4,12 +4,15 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.data.time.TodaySource
import de.jeanlucmakiola.calendula.data.time.currentDate
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.common.IMPLEMENTED_VIEWS
import kotlinx.coroutines.flow.SharingStarted
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.first
import kotlinx.datetime.LocalDate
import javax.inject.Inject
/**
@@ -21,36 +24,39 @@ import javax.inject.Inject
@HiltViewModel
class CalendarHostViewModel @Inject constructor(
prefs: SettingsPrefs,
todaySource: TodaySource,
) : ViewModel() {
val defaultView: StateFlow<CalendarView?> = prefs.defaultView.stateIn(
/** Today, kept current across midnight so the shared focus can follow it (#373). */
val today: StateFlow<LocalDate> = todaySource.today.stateWhileSubscribed(
scope = viewModelScope,
initialValue = currentDate(),
)
val defaultView: StateFlow<CalendarView?> = prefs.defaultView.stateWhileSubscribed(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = null,
)
/** Views the top-bar quick-switch pill cycles through, in the user's order (#24). */
val quickSwitchViews: StateFlow<List<CalendarView>> = prefs.quickSwitchConfig
.map { it.cycle }
.stateIn(
.stateWhileSubscribed(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = IMPLEMENTED_VIEWS,
)
/** Order of the views in the navigation drawer (#24); every view always shown. */
val drawerViewOrder: StateFlow<List<CalendarView>> = prefs.drawerViewOrder
.stateIn(
.stateWhileSubscribed(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = IMPLEMENTED_VIEWS,
)
/** Whether each view's jump-to-today control lives in the top bar, not the FAB (#60). */
val todayButtonInToolbar: StateFlow<Boolean> = prefs.todayButtonInToolbar
.stateIn(
.stateWhileSubscribed(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = false,
)
@@ -62,9 +68,13 @@ class CalendarHostViewModel @Inject constructor(
* switched off to be rid of.
*/
val dragToReschedule: StateFlow<Boolean> = prefs.dragToReschedule
.stateIn(
.stateWhileSubscribed(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = false,
)
private val tapOpensEditorPref = prefs.tapOpensEditor
/** Whether tapping an event opens the edit form rather than the detail screen (#178). */
suspend fun tapOpensEditor(): Boolean = tapOpensEditorPref.first()
}
@@ -0,0 +1,45 @@
package de.jeanlucmakiola.calendula.ui
import android.net.Uri
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.ui.edit.ImportSource
/**
* What a notification, widget, shortcut or another app asked the running app to
* open. MainActivity fills it from each intent (singleTop + onNewIntent route a
* new one into the running activity); CalendarHost acts on a request and clears
* 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.
*/
@Stable
class ExternalRequests(val onExternalFormClosed: () -> Unit = {}) {
/** A tapped reminder notification's occurrence (eventId, begin, end), for the detail screen. */
var detailKey by mutableStateOf<LongArray?>(null)
/** A home-screen widget, shortcut or tile navigation (open a date, an event, a view, or create). */
var nav by mutableStateOf<WidgetNavRequest?>(null)
/** An .ics file opened or shared into the app (ACTION_VIEW/SEND). */
var importUri by mutableStateOf<Uri?>(null)
/**
* A prefilled new-event form from an external ACTION_INSERT launch (#30) or
* shared text (#306), opened in the create form for review.
*/
var insert by mutableStateOf<InsertRequest?>(null)
/** An external "edit this event" (ACTION_EDIT), in the detail key's shape. */
var editKey by mutableStateOf<LongArray?>(null)
/** Whether these came from re-reading the launch intent on a recreation. */
var replayed = false
}
/** A prefilled create form from an external launch, with the source it came from. */
data class InsertRequest(val form: EventForm, val source: ImportSource)
@@ -1,7 +1,5 @@
package de.jeanlucmakiola.calendula.ui
import android.Manifest
import android.content.pm.PackageManager
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
@@ -20,11 +18,11 @@ import androidx.compose.ui.platform.LocalContext
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.core.content.ContextCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesScheduler
import de.jeanlucmakiola.calendula.data.contacts.hasContactsPermission
import de.jeanlucmakiola.calendula.ui.common.canReadCalendar
import de.jeanlucmakiola.calendula.ui.common.rememberCalendarFadeSpec
import de.jeanlucmakiola.calendula.ui.onboarding.OnboardingStep
import de.jeanlucmakiola.calendula.ui.onboarding.OnboardingSteps
@@ -43,26 +41,12 @@ private sealed interface RootTarget {
@Composable
fun RootScreen(
requests: ExternalRequests,
modifier: Modifier = Modifier,
requestedDetailKey: LongArray? = null,
onDetailKeyConsumed: () -> Unit = {},
widgetNavRequest: WidgetNavRequest? = null,
onWidgetNavConsumed: () -> Unit = {},
requestedImportUri: android.net.Uri? = null,
onImportConsumed: () -> Unit = {},
requestedInsertForm: de.jeanlucmakiola.calendula.domain.EventForm? = null,
requestedInsertSource: de.jeanlucmakiola.calendula.ui.edit.ImportSource =
de.jeanlucmakiola.calendula.ui.edit.ImportSource.Insert,
onInsertConsumed: () -> Unit = {},
requestedEditKey: LongArray? = null,
onEditKeyConsumed: () -> Unit = {},
) {
val context = LocalContext.current
var hasPermission by remember {
mutableStateOf(
ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CALENDAR)
== PackageManager.PERMISSION_GRANTED
)
mutableStateOf(context.canReadCalendar())
}
// A launch scan already covers the app coming up with the permission, so
@@ -73,9 +57,7 @@ fun RootScreen(
DisposableEffect(lifecycle) {
val obs = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME) {
hasPermission = ContextCompat.checkSelfPermission(
context, Manifest.permission.READ_CALENDAR
) == PackageManager.PERMISSION_GRANTED
hasPermission = context.canReadCalendar()
// Refresh the contact special-dates mirror on foreground (the
// worker is debounced and no-ops when the feature is off). Gated
// on the permission so users without the opt-in never enqueue it.
@@ -145,18 +127,8 @@ fun RootScreen(
when (shown) {
RootTarget.Loading -> Unit
RootTarget.App -> CalendarHost(
requests = requests,
modifier = modifier,
requestedDetailKey = requestedDetailKey,
onDetailKeyConsumed = onDetailKeyConsumed,
widgetNavRequest = widgetNavRequest,
onWidgetNavConsumed = onWidgetNavConsumed,
requestedImportUri = requestedImportUri,
onImportConsumed = onImportConsumed,
requestedInsertForm = requestedInsertForm,
requestedInsertSource = requestedInsertSource,
onInsertConsumed = onInsertConsumed,
requestedEditKey = requestedEditKey,
onEditKeyConsumed = onEditKeyConsumed,
)
// Both halves of a transition read their position out of the live
// plan; the one the outgoing step was drawn with is already gone.
@@ -3,8 +3,9 @@ package de.jeanlucmakiola.calendula.ui.agenda
import de.jeanlucmakiola.floret.locale.localizedDateFormatter
import kotlinx.datetime.DayOfWeek
import kotlinx.datetime.LocalDate
import java.time.YearMonth
import java.util.Locale
import kotlinx.datetime.toJavaLocalDate
import kotlinx.datetime.yearMonth
/**
* How far ahead the agenda (screen or widget) shows events, starting at today.
@@ -50,7 +51,7 @@ fun AgendaRange.dayCount(anchor: LocalDate, weekStart: DayOfWeek): Int = when (t
DAYS_PER_WEEK - sinceWeekStart
}
AgendaRange.ThisMonth -> {
val daysInMonth = YearMonth.of(anchor.year, anchor.month.ordinal + 1).lengthOfMonth()
val daysInMonth = anchor.yearMonth.numberOfDays
daysInMonth - anchor.day + 1
}
is AgendaRange.Custom -> days.coerceIn(AgendaRange.MIN_CUSTOM_DAYS, AgendaRange.MAX_CUSTOM_DAYS)
@@ -105,8 +106,8 @@ fun agendaRangeWindowSummary(
locale: Locale,
monthAsSpan: Boolean = false,
): String {
val javaStart = java.time.LocalDate.of(start.year, start.month.ordinal + 1, start.day)
val javaEnd = java.time.LocalDate.of(end.year, end.month.ordinal + 1, end.day)
val javaStart = start.toJavaLocalDate()
val javaEnd = end.toJavaLocalDate()
val dayMonth = localizedDateFormatter(locale, "dMMM")
val dayMonthYear = localizedDateFormatter(locale, "dMMMy")
return when {
@@ -1,8 +1,9 @@
package de.jeanlucmakiola.calendula.ui.agenda
import androidx.annotation.StringRes
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
@@ -10,6 +11,8 @@ 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.lazy.LazyListScope
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Coffee
@@ -29,35 +32,43 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.domain.isDeclined
import de.jeanlucmakiola.calendula.domain.isCrossedOut
import de.jeanlucmakiola.calendula.ui.common.EventDimAlpha
import de.jeanlucmakiola.calendula.ui.common.ViewMorphKey
import de.jeanlucmakiola.calendula.ui.common.declinedTitle
import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors
import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat
import de.jeanlucmakiola.calendula.ui.common.eventAccent
import de.jeanlucmakiola.calendula.ui.common.eventFill
import de.jeanlucmakiola.calendula.ui.common.formatTimeOfDay
import de.jeanlucmakiola.calendula.ui.common.morphEvent
import de.jeanlucmakiola.floret.components.GroupedRow
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.currentLocale
import de.jeanlucmakiola.floret.locale.localizedDateFormatter
import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.LocalDate
import kotlinx.datetime.TimeZone
import kotlinx.datetime.plus
import kotlinx.datetime.toLocalDateTime
import kotlin.time.Instant
import kotlinx.datetime.toJavaLocalDate
import java.util.Locale
// The agenda's row vocabulary, split out of AgendaScreen so the month view's
// split style can list a day with exactly the same visual language instead of
// growing a parallel set of event rows.
/**
* A day's header; tapping it opens the Day view. [compact] trims the padding for
* the month view's split pane, where vertical space is short (#142).
*/
@Composable
internal fun AgendaDayHeader(
date: LocalDate,
today: LocalDate,
onOpenDay: (LocalDate) -> Unit,
compact: Boolean = false,
) {
Surface(
color = MaterialTheme.colorScheme.surface,
@@ -73,7 +84,12 @@ internal fun AgendaDayHeader(
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
modifier = Modifier.padding(start = 28.dp, end = 28.dp, top = 16.dp, bottom = 8.dp),
modifier = Modifier.padding(
start = 28.dp,
end = 28.dp,
top = if (compact) 8.dp else 16.dp,
bottom = if (compact) 4.dp else 8.dp,
),
)
}
}
@@ -127,12 +143,12 @@ internal fun AgendaEventRow(
modifier: Modifier = Modifier,
onClick: () -> Unit,
) {
val dark = isSystemInDarkTheme()
val dark = LocalFloretDarkTheme.current
val soften = LocalSoftenColors.current
val title = event.title.ifBlank { stringResource(R.string.event_untitled) }
GroupedRow(
modifier = if (dimmed) modifier.alpha(EventDimAlpha) else modifier,
title = declinedTitle(title, event.isDeclined),
title = declinedTitle(title, event.isCrossedOut),
summary = AnnotatedString(agendaTimeSummary(event, day, zone)),
position = position,
minHeight = 64.dp,
@@ -177,34 +193,75 @@ internal fun agendaTimeSummary(event: EventInstance, day: LocalDate, zone: TimeZ
AgendaTimeLabel.AllDay -> stringResource(R.string.event_detail_all_day)
is AgendaTimeLabel.Starts -> stringResource(
R.string.agenda_span_starts,
formatTime(label.start, zone, is24Hour, locale),
formatTimeOfDay(label.start, zone, is24Hour, locale),
)
is AgendaTimeLabel.Ends -> stringResource(
R.string.agenda_span_ends,
formatTime(label.end, zone, is24Hour, locale),
formatTimeOfDay(label.end, zone, is24Hour, locale),
)
is AgendaTimeLabel.Range -> "${formatTime(label.start, zone, is24Hour, locale)} – " +
formatTime(label.end, zone, is24Hour, locale)
is AgendaTimeLabel.Range -> "${formatTimeOfDay(label.start, zone, is24Hour, locale)} – " +
formatTimeOfDay(label.end, zone, is24Hour, locale)
}
val location = event.location?.takeIf { it.isNotBlank() }
return if (location != null) "$time · $location" else time
}
private fun formatTime(
instant: Instant,
zone: TimeZone,
is24Hour: Boolean,
locale: Locale,
): String {
val t = instant.toLocalDateTime(zone).time
return formatTimeOfDay(t.hour, t.minute, is24Hour, locale)
}
private fun formatAgendaDate(date: LocalDate): String {
val locale = Locale.getDefault()
val java = java.time.LocalDate.of(date.year, date.month.ordinal + 1, date.day)
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)
}
/**
* The agenda's day-by-day list body: a sticky header per day, its events or a
* placeholder row for an event-less day, then a gap. Shared by the Agenda screen
* and the month view's split pane so both lists read the same.
*/
@OptIn(ExperimentalFoundationApi::class)
internal fun LazyListScope.agendaDays(
days: List<AgendaDay>,
today: LocalDate,
zone: TimeZone,
@StringRes emptyText: Int,
onEmptyClick: (LocalDate) -> Unit,
dimmed: (EventInstance, LocalDate) -> Boolean,
onOpenDay: (LocalDate) -> Unit,
onEventClick: (EventInstance) -> Unit,
compact: Boolean = false,
) {
days.forEach { day ->
stickyHeader(key = "header-${day.date}") {
AgendaDayHeader(date = day.date, today = today, onOpenDay = onOpenDay, compact = compact)
}
if (day.events.isEmpty()) {
item(key = "placeholder-${day.date}") {
AgendaEmptyDayRow(
text = stringResource(emptyText),
onClick = { onEmptyClick(day.date) },
)
}
} else {
itemsIndexed(
items = day.events,
// Scope the key by day: a multi-day event appears under every
// day it spans, so its instanceId alone is not unique across
// the list (LazyColumn requires unique keys).
key = { _, event -> "${day.date}-${event.instanceId}" },
) { index, event ->
AgendaEventRow(
event = event,
day = day.date,
zone = zone,
position = positionOf(index, day.events.size),
dimmed = dimmed(event, day.date),
modifier = animateItemMotion().morphEvent(ViewMorphKey.event(event, day.date)),
onClick = { onEventClick(event) },
)
}
}
item(key = "gap-${day.date}") { Spacer(Modifier.height(if (compact) 4.dp else 8.dp)) }
}
}
@@ -1,19 +1,16 @@
package de.jeanlucmakiola.calendula.ui.agenda
import de.jeanlucmakiola.calendula.ui.common.FabClearance
import de.jeanlucmakiola.calendula.ui.common.PublishChrome
import de.jeanlucmakiola.calendula.ui.common.ScreenActions
import de.jeanlucmakiola.calendula.ui.common.ScreenBody
import de.jeanlucmakiola.calendula.ui.common.ScreenChrome
import de.jeanlucmakiola.calendula.ui.common.LocalViewFocus
import de.jeanlucmakiola.calendula.ui.common.EnterOnFocus
import kotlinx.coroutines.flow.drop
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.runtime.rememberUpdatedState
import de.jeanlucmakiola.calendula.ui.common.ViewMorphKey
import de.jeanlucmakiola.calendula.ui.common.morphEvent
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -27,7 +24,6 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Coffee
@@ -38,7 +34,16 @@ import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableIntState
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
@@ -53,16 +58,14 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay
import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.domain.hasEnded
import de.jeanlucmakiola.calendula.ui.common.isPastOn
import de.jeanlucmakiola.calendula.ui.common.AgendaRangePicker
import de.jeanlucmakiola.calendula.ui.common.AppBarSpacing
import de.jeanlucmakiola.calendula.ui.common.QuickSwitchConfig
import de.jeanlucmakiola.calendula.ui.common.agendaRangeLabel
import de.jeanlucmakiola.floret.identity.animateItemMotion
import de.jeanlucmakiola.calendula.ui.common.CalendarFailure
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.common.IMPLEMENTED_VIEWS
import de.jeanlucmakiola.floret.components.positionOf
import de.jeanlucmakiola.calendula.ui.common.rememberCurrentMinute
import de.jeanlucmakiola.floret.locale.currentLocale
import kotlinx.coroutines.launch
@@ -82,11 +85,23 @@ fun AgendaScreen(
onCreateEvent: (LocalDate, Int?) -> Unit,
quickSwitchViews: List<CalendarView> = IMPLEMENTED_VIEWS,
modifier: Modifier = Modifier,
restorePosition: Boolean = false,
viewModel: AgendaViewModel = hiltViewModel(),
) {
// Opens on the focused date and hands back the day scrolled to the top.
// Opens on today, not on the day another view was on (#367). Backing out of
// a day opened from here, or a recreated screen, returns to the day last at
// the top. The top day still goes back to the shared focus.
val focus = LocalViewFocus.current
EnterOnFocus(viewModel) { if (it != viewModel.anchor.value) viewModel.goToDate(it) }
val opened = rememberSaveable { mutableStateOf(false) }
val restoreTop = remember(viewModel) {
if (restorePosition || opened.value) {
viewModel.lastTopDate
} else {
viewModel.goToToday()
null
}
}
SideEffect { opened.value = true }
val state by viewModel.state.collectAsStateWithLifecycle()
val anchor by viewModel.anchor.collectAsStateWithLifecycle()
val pastDisplay by viewModel.pastEventDisplay.collectAsStateWithLifecycle()
@@ -106,20 +121,19 @@ fun AgendaScreen(
// list scroll, not an anchor change — "today" has to bring the list back to
// the top as well, and stay offered while it is scrolled away (#305).
val listState = rememberLazyListState()
// Past days load above the anchor (#367), so the anchor's row counts as the
// start of the list.
val anchorIndex = remember { mutableIntStateOf(0) }
val scrolledAway by remember {
derivedStateOf {
listState.firstVisibleItemIndex > 0 || listState.firstVisibleItemScrollOffset > 0
listState.firstVisibleItemIndex != anchorIndex.intValue ||
listState.firstVisibleItemScrollOffset > 0
}
}
// A new window is rendered from its first day, so the list belongs at the
// top. Keyed on the anchor the days arrived with, not the one just
// requested: scrolling before the new rows compose leaves the list keyed to
// a row that reappears further down, and it follows it there.
LaunchedEffect(successState?.anchor) { listState.scrollToItem(0) }
val jumpToToday: () -> Unit = {
// Off today, moving the anchor is what resets the list (above); on today
// Off today, moving the anchor is what repositions the list; on today
// the window doesn't change, so the scroll back is the whole action.
if (isOnToday) scope.launch { listState.animateScrollToItem(0) }
if (isOnToday) scope.launch { listState.animateScrollToItem(anchorIndex.intValue) }
viewModel.goToToday()
(state as? AgendaUiState.Success)?.today?.let { focus?.date = it }
}
@@ -188,11 +202,17 @@ fun AgendaScreen(
pastDisplay = pastDisplay,
showToday = showToday,
listState = listState,
anchorIndex = anchorIndex,
initialTopDate = restoreTop,
onLoadEarlier = viewModel::loadEarlier,
onRetry = viewModel::goToToday,
onEventClick = onEventClick,
onOpenDay = onOpenDay,
onTopDay = if (successState?.anchor == anchor) {
{ focus?.date = it }
{
focus?.date = it
viewModel.rememberTopDay(it)
}
} else null,
modifier = Modifier
.weight(1f)
@@ -294,6 +314,9 @@ internal fun AgendaContent(
onOpenDay: (LocalDate) -> Unit,
modifier: Modifier = Modifier,
listState: LazyListState = rememberLazyListState(),
anchorIndex: MutableIntState = remember { mutableIntStateOf(0) },
initialTopDate: LocalDate? = null,
onLoadEarlier: () -> Unit = {},
onTopDay: ((LocalDate) -> Unit)? = null,
) {
when (state) {
@@ -308,28 +331,34 @@ internal fun AgendaContent(
// away (or fade) as they end while the screen stays open.
val filtered = if (pastDisplay == PastEventDisplay.HIDE) {
state.days.mapNotNull { day ->
val remaining = day.events.filterNot { it.hasEnded(now) }
val remaining = day.events.filterNot { it.isPastOn(day.date, now, state.zone) }
if (remaining.isEmpty()) null else day.copy(events = remaining)
}
} else {
state.days
}
// Anchor today with a "nothing left today" placeholder — but only when
// the window actually starts on today; a jumped-to date has no today in
// it, so anchoring there would be misleading (#35).
// the agenda actually opens on today; a jumped-to date has no today
// in it, so anchoring there would be misleading (#35).
val days = anchorTodayIfMissing(
days = filtered,
today = state.today,
enabled = showToday && state.anchor == state.today,
)
if (days.isEmpty()) {
// Past days alone don't count as anything coming up.
if (days.none { it.date >= state.anchor }) {
// Nothing to scroll: drop the position a previous list left, so
// the today FAB doesn't linger over an empty screen.
LaunchedEffect(Unit) { listState.scrollToItem(0) }
SideEffect { anchorIndex.intValue = 0 }
AgendaEmpty(modifier)
} else {
AgendaList(
days = days,
anchor = state.anchor,
anchorIndex = anchorIndex,
initialTopDate = initialTopDate,
onLoadEarlier = onLoadEarlier,
today = state.today,
zone = state.zone,
listState = listState,
@@ -345,10 +374,13 @@ internal fun AgendaContent(
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun AgendaList(
days: List<AgendaDay>,
anchor: LocalDate,
anchorIndex: MutableIntState,
initialTopDate: LocalDate?,
onLoadEarlier: () -> Unit,
today: LocalDate,
zone: TimeZone,
listState: LazyListState,
@@ -359,59 +391,67 @@ private fun AgendaList(
onTopDay: ((LocalDate) -> Unit)?,
modifier: Modifier = Modifier,
) {
val itemDates = agendaItemDates(days)
val anchorRow = itemDates.indexOfFirst { it >= anchor }.coerceAtLeast(0)
SideEffect { anchorIndex.intValue = anchorRow }
// A new anchor opens on its row from the first frame; keyed on the anchor
// the days arrived with, not the one requested. The first run may restore.
val pendingRestore = remember { arrayOf(initialTopDate) }
DisposableEffect(anchor) {
val target = pendingRestore[0]
pendingRestore[0] = null
val index = target?.let { date -> itemDates.indexOfFirst { it >= date } }
?.takeIf { it >= 0 }
?: anchorRow
listState.requestScrollToItem(index)
onDispose {}
}
// Scrolling up near the first loaded day loads earlier days.
val currentLoadEarlier by rememberUpdatedState(onLoadEarlier)
val loadOnScrollUp = remember(listState) {
object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
if (available.y > 0 && listState.firstVisibleItemIndex < LOAD_EARLIER_WITHIN) {
currentLoadEarlier()
}
return Offset.Zero
}
}
}
if (onTopDay != null) {
val itemDates by rememberUpdatedState(agendaItemDates(days))
val currentItemDates by rememberUpdatedState(itemDates)
val currentOnTopDay by rememberUpdatedState(onTopDay)
// The day the list opened on is where the view already is; only a
// scroll moves it on.
LaunchedEffect(listState) {
snapshotFlow { listState.firstVisibleItemIndex }
.drop(1)
.collect { index -> itemDates.getOrNull(index)?.let(currentOnTopDay) }
.collect { index -> currentItemDates.getOrNull(index)?.let(currentOnTopDay) }
}
}
LazyColumn(
modifier = modifier,
modifier = modifier.nestedScroll(loadOnScrollUp),
state = listState,
// Bottom inset clears the FAB stack so the last row stays tappable.
contentPadding = PaddingValues(top = 8.dp, bottom = 96.dp),
contentPadding = PaddingValues(top = 8.dp, bottom = FabClearance),
) {
days.forEach { day ->
stickyHeader(key = "header-${day.date}") {
AgendaDayHeader(date = day.date, today = today, onOpenDay = onOpenDay)
}
if (day.events.isEmpty()) {
// An anchored, event-less today (#35) — "nothing left today".
item(key = "placeholder-${day.date}") {
AgendaEmptyDayRow(
text = stringResource(R.string.agenda_no_more_today),
onClick = { onOpenDay(day.date) },
)
}
} else {
itemsIndexed(
items = day.events,
// Scope the key by day: a multi-day event appears under every
// day it spans, so its instanceId alone is not unique across
// the list (LazyColumn requires unique keys).
key = { _, event -> "${day.date}-${event.instanceId}" },
) { index, event ->
AgendaEventRow(
event = event,
day = day.date,
zone = zone,
position = positionOf(index, day.events.size),
dimmed = dimPast && event.hasEnded(now),
modifier = animateItemMotion().morphEvent(ViewMorphKey.event(event, day.date)),
onClick = { onEventClick(event) },
)
}
}
item(key = "gap-${day.date}") { Spacer(Modifier.height(8.dp)) }
}
agendaDays(
days = days,
today = today,
zone = zone,
// An anchored, event-less today (#35) — "nothing left today".
emptyText = R.string.agenda_no_more_today,
onEmptyClick = onOpenDay,
dimmed = { event, day -> dimPast && event.isPastOn(day, now, zone) },
onOpenDay = onOpenDay,
onEventClick = onEventClick,
)
}
}
/** How close to the first loaded row an upward scroll starts loading earlier days. */
private const val LOAD_EARLIER_WITHIN = 10
/** The day of each item [AgendaList] lays out for [days], in its order. */
internal fun agendaItemDates(days: List<AgendaDay>): List<LocalDate> =
days.flatMap { day ->
@@ -1,7 +1,8 @@
package de.jeanlucmakiola.calendula.ui.agenda
import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.domain.eventDisplayComparator
import de.jeanlucmakiola.calendula.domain.coversWholeDays
import de.jeanlucmakiola.calendula.domain.sortedForDisplay
import de.jeanlucmakiola.calendula.domain.FailureReason
import de.jeanlucmakiola.calendula.domain.spanFirstDay
import de.jeanlucmakiola.calendula.domain.spanLastDay
@@ -18,7 +19,7 @@ import kotlin.time.Instant
* surface only formats the instants into its own locale/24h string.
*/
sealed interface AgendaTimeLabel {
/** An all-day event, or a whole in-between day of a multi-day span. */
/** An event filling whole days (#296), or a whole in-between day of a multi-day span. */
data object AllDay : AgendaTimeLabel
/** The first day of a multi-day timed event: when it begins. */
data class Starts(val start: Instant) : AgendaTimeLabel
@@ -30,7 +31,7 @@ sealed interface AgendaTimeLabel {
/** The [AgendaTimeLabel] for [event] as it appears on [day], resolved in [zone]. */
fun agendaTimeLabel(event: EventInstance, day: LocalDate, zone: TimeZone): AgendaTimeLabel {
if (event.isAllDay) return AgendaTimeLabel.AllDay
if (event.coversWholeDays(zone)) return AgendaTimeLabel.AllDay
val firstDay = event.spanFirstDay(zone)
val lastDay = event.spanLastDay(zone)
return when {
@@ -87,28 +88,27 @@ fun groupAgendaDays(
return byDay.map { (date, dayEvents) ->
AgendaDay(
date = date,
events = dayEvents.sortedWith(eventDisplayComparator(zone)),
events = dayEvents.sortedForDisplay(zone),
)
}
}
/**
* Ensure [today] surfaces as the first agenda day even when it carries no
* (remaining) events, by prepending an empty-event [AgendaDay] the agenda widget
* Ensure [today] surfaces in the agenda even when it carries no (remaining)
* events, by inserting an empty-event [AgendaDay] in date order that the agenda
* renders as a "nothing left today" placeholder. A no-op unless [enabled], and
* when today already has its own day in [days]. Keeps today anchored at the top
* so a glance tells today's events apart from a future day's (issue #35).
* when today already has its own day in [days]. Keeps today anchored so a glance
* tells today's events apart from a future day's (issue #35).
*/
fun anchorTodayIfMissing(
days: List<AgendaDay>,
today: LocalDate,
enabled: Boolean,
): List<AgendaDay> =
if (enabled && days.none { it.date == today }) {
listOf(AgendaDay(today, emptyList())) + days
} else {
days
}
): List<AgendaDay> {
if (!enabled || days.any { it.date == today }) return days
val at = days.indexOfFirst { it.date > today }.let { if (it < 0) days.size else it }
return days.take(at) + AgendaDay(today, emptyList()) + days.drop(at)
}
/**
* State for the Agenda view: a flat, forward-looking list of upcoming events
@@ -118,8 +118,10 @@ sealed interface AgendaUiState {
data object Loading : AgendaUiState
data class Failure(val reason: FailureReason) : AgendaUiState
data class Success(
/** First day of the loaded window (today, or a jumped-to date). */
/** The day the agenda opens on (today, or a jumped-to date). */
val anchor: LocalDate,
/** First loaded day, before [anchor] once past days are loaded (#367). */
val windowStart: LocalDate,
val today: LocalDate,
val days: List<AgendaDay>,
/** The range currently in effect — the saved default or a session override. */
@@ -1,17 +1,25 @@
package de.jeanlucmakiola.calendula.ui.agenda
import de.jeanlucmakiola.calendula.ui.common.dayRange
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.di.IoDispatcher
import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.data.prefs.firstDayOfWeek
import de.jeanlucmakiola.calendula.data.time.TodaySource
import de.jeanlucmakiola.calendula.data.time.currentDate
import de.jeanlucmakiola.calendula.data.time.stateFollowingDays
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
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
@@ -21,17 +29,14 @@ import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.DayOfWeek
import kotlinx.datetime.LocalDate
import kotlinx.datetime.TimeZone
import kotlinx.datetime.atStartOfDayIn
import kotlinx.datetime.atTime
import kotlinx.datetime.minus
import kotlinx.datetime.plus
import kotlinx.datetime.toInstant
import kotlinx.datetime.toLocalDateTime
import kotlin.time.Clock
import kotlin.time.Instant
import javax.inject.Inject
@@ -40,9 +45,12 @@ import javax.inject.Inject
class AgendaViewModel @Inject constructor(
private val repository: CalendarRepository,
settingsPrefs: SettingsPrefs,
todaySource: TodaySource,
@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,
@@ -62,9 +70,8 @@ class AgendaViewModel @Inject constructor(
* the screen combines it with a per-minute "now" to fade or drop past rows.
*/
val pastEventDisplay: StateFlow<PastEventDisplay> = settingsPrefs.pastEventDisplay
.stateIn(
.stateWhileSubscribed(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = PastEventDisplay.SHOW,
)
@@ -75,19 +82,35 @@ class AgendaViewModel @Inject constructor(
* alongside the data state like [pastEventDisplay] rather than re-querying.
*/
val showToday: StateFlow<Boolean> = settingsPrefs.agendaShowToday
.stateIn(
.stateWhileSubscribed(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = true,
)
private val zone = TimeZone.currentSystemDefault()
private val todayDate: LocalDate
get() = Clock.System.now().toLocalDateTime(zone).date
get() = currentDate()
private val _anchor = MutableStateFlow(todayDate)
val anchor: StateFlow<LocalDate> = _anchor
// The anchor and how many days before it are loaded, moved together so a
// jump never queries a window that pairs the new anchor with the old span.
private val _window = MutableStateFlow(AgendaWindow(todayDate, PAST_CHUNK_DAYS))
val anchor: StateFlow<LocalDate> = _window
.map { it.anchor }
.stateIn(viewModelScope, SharingStarted.Eagerly, todayDate)
/** The day last scrolled to the top, so a return to the agenda lands back on it. */
var lastTopDate: LocalDate? = null
private set
/**
* Today, kept current across midnight (#373). An agenda still starting on
* yesterday moves on to the new day; one jumped elsewhere stays put.
*/
private val today: StateFlow<LocalDate> =
todaySource.today.stateFollowingDays(viewModelScope, todayDate) { old, date ->
if (_window.value.anchor == old) _window.value = _window.value.copy(anchor = date)
}
// A transient, in-view override of the saved agenda range. Held in memory
// (not persisted), so it survives view switches and rotation within the
@@ -95,9 +118,17 @@ class AgendaViewModel @Inject constructor(
private val _rangeOverride = MutableStateFlow<AgendaRange?>(null)
val state: StateFlow<AgendaUiState> =
combine(_anchor, agendaSettings, _rangeOverride, weekStart) { anchor, settings, override, weekStart ->
combine(
_window,
agendaSettings,
_rangeOverride,
weekStart,
settingsPrefs.pastEventDisplay,
) { window, settings, override, weekStart, pastDisplay ->
AgendaParams(
anchor = anchor,
anchor = window.anchor,
// Hidden past events leave nothing to scroll back to (#367).
pastDays = if (pastDisplay == PastEventDisplay.HIDE) 0 else window.pastDays,
range = override ?: settings.range,
rangeIsOverride = override != null && override != settings.range,
weekStart = weekStart,
@@ -106,32 +137,52 @@ class AgendaViewModel @Inject constructor(
}
.flatMapLatest { params ->
val window = agendaRange(
params.anchor,
params.range.dayCount(params.anchor, params.weekStart) - 1,
params.windowStart,
params.pastDays + params.range.dayCount(params.anchor, params.weekStart) - 1,
zone,
)
combine(
repository.calendars(),
repository.instances(window),
) { calendars, instances ->
buildState(params, calendars, instances)
repository.instancesWithout(window, hiddenHere),
today,
) { calendars, instances, today ->
buildState(params, calendars, instances, today)
}
}
.catch { emit(AgendaUiState.Failure(FailureReason.ProviderUnavailable)) }
.flowOn(io)
.stateIn(
.stateWhileSubscribed(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = AgendaUiState.Loading,
)
fun goToToday() {
_anchor.value = todayDate
goToDate(todayDate)
}
/** Jump the agenda window to start on a specific date (drawer jump-to-date). */
fun goToDate(date: LocalDate) {
_anchor.value = date
if (_window.value.anchor == date) return
_window.value = AgendaWindow(date, PAST_CHUNK_DAYS)
lastTopDate = null
}
/**
* Extend the window further back (#367), doubling what's loaded (at least
* [PAST_CHUNK_DAYS], at most [MAX_PAST_STEP_DAYS]) so a long scroll back
* re-queries only a few times. Ignored while the previous extension is
* still loading.
*/
fun loadEarlier() {
val loaded = (state.value as? AgendaUiState.Success)?.windowStart ?: return
val window = _window.value
if (loaded != window.start) return
val step = window.pastDays.coerceIn(PAST_CHUNK_DAYS, MAX_PAST_STEP_DAYS)
_window.value = window.copy(pastDays = window.pastDays + step)
}
fun rememberTopDay(date: LocalDate) {
lastTopDate = date
}
/** Temporarily override the agenda range for this session (the bottom-left pill). */
@@ -144,18 +195,26 @@ class AgendaViewModel @Inject constructor(
val showBar: Boolean,
)
private data class AgendaWindow(val anchor: LocalDate, val pastDays: Int) {
val start: LocalDate get() = anchor.minus(pastDays, DateTimeUnit.DAY)
}
private data class AgendaParams(
val anchor: LocalDate,
val pastDays: Int,
val range: AgendaRange,
val rangeIsOverride: Boolean,
val weekStart: DayOfWeek,
val showRangeBar: Boolean,
)
) {
val windowStart: LocalDate get() = anchor.minus(pastDays, DateTimeUnit.DAY)
}
private fun buildState(
params: AgendaParams,
calendars: List<CalendarSource>,
instances: List<EventInstance>,
today: LocalDate,
): AgendaUiState {
calendarListFailure(calendars)?.let { return AgendaUiState.Failure(it) }
val anchor = params.anchor
@@ -163,10 +222,11 @@ class AgendaViewModel @Inject constructor(
params.range.dayCount(anchor, params.weekStart) - 1,
DateTimeUnit.DAY,
)
val days = groupAgendaDays(anchor, rangeEnd, instances, zone)
val days = groupAgendaDays(params.windowStart, rangeEnd, instances, zone)
return AgendaUiState.Success(
anchor = anchor,
today = todayDate,
windowStart = params.windowStart,
today = today,
days = days,
range = params.range,
rangeIsOverride = params.rangeIsOverride,
@@ -177,9 +237,12 @@ class AgendaViewModel @Inject constructor(
}
}
/** How many days each scroll back into the past loads (#367). */
internal const val PAST_CHUNK_DAYS = 30
/** The most one scroll back adds, so an empty past grows the window by years, not exponentially. */
internal const val MAX_PAST_STEP_DAYS = 365
/** Inclusive instant range from the start of [anchor] through [days] days ahead. */
internal fun agendaRange(anchor: LocalDate, days: Int, zone: TimeZone): ClosedRange<Instant> {
val from = anchor.atStartOfDayIn(zone)
val to = anchor.plus(days, DateTimeUnit.DAY).atTime(23, 59, 59).toInstant(zone)
return from..to
}
internal fun agendaRange(anchor: LocalDate, days: Int, zone: TimeZone): ClosedRange<Instant> =
dayRange(anchor, anchor.plus(days, DateTimeUnit.DAY), zone)
@@ -6,8 +6,8 @@ import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.Dp
import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay
import de.jeanlucmakiola.calendula.ui.common.ScaledViewPreview
import de.jeanlucmakiola.calendula.ui.common.sampleAgendaEvents
import de.jeanlucmakiola.floret.components.ScaledViewPreview
import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.LocalDate
import kotlinx.datetime.TimeZone
@@ -51,6 +51,7 @@ private fun sampleAgendaState(today: LocalDate, zone: TimeZone): AgendaUiState.S
val windowEnd = today.plus(PREVIEW_WINDOW_DAYS, DateTimeUnit.DAY)
return AgendaUiState.Success(
anchor = today,
windowStart = today,
today = today,
days = groupAgendaDays(today, windowEnd, sampleAgendaEvents(today, zone), zone),
range = AgendaRange.Custom(PREVIEW_WINDOW_DAYS),
@@ -1,7 +1,6 @@
package de.jeanlucmakiola.calendula.ui.calendars
import android.net.Uri
import android.text.format.DateUtils
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Box
@@ -11,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
@@ -50,7 +50,10 @@ 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
@@ -58,9 +61,13 @@ import de.jeanlucmakiola.floret.components.CollapsingScaffold
import de.jeanlucmakiola.floret.components.DialogAmountField
import de.jeanlucmakiola.floret.components.DialogUnitDropdown
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
// SAF mime filter for the restore picker. Source apps hand `.ics` files out
@@ -72,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.
@@ -84,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<Long?>(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.
@@ -109,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<BackupSelection?>(null) }
var showKeep by rememberSaveable { mutableStateOf(false) }
val backupFailedText = stringResource(R.string.calendars_backup_failed)
LaunchedEffect(backupResult) {
@@ -129,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 ->
@@ -169,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,
@@ -179,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() {
@@ -194,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.
@@ -203,13 +296,19 @@ private fun defaultBackupName(): String = "calendula-backup-${LocalDate.now()}.i
private fun BackupContent(
exportable: List<CalendarSource>,
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
@@ -222,24 +321,26 @@ private fun BackupContent(
val onRestoreClick = if (canImport) onRestore else (manageCalendars ?: onRestore)
if (exportable.isEmpty()) {
SectionHeader(stringResource(R.string.calendars_restore_header))
HintText(restoreSummary)
GroupedSectionHeader(stringResource(R.string.calendars_restore_header))
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
}
HintText(stringResource(R.string.calendars_backup_hint))
GroupedHint(stringResource(R.string.calendars_backup_hint), style = MaterialTheme.typography.bodySmall)
GroupedRow(
title = stringResource(R.string.calendars_backup_action),
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),
@@ -248,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),
@@ -269,22 +372,84 @@ private fun BackupContent(
GroupedRow(
title = stringResource(R.string.calendars_auto_backup_interval),
summary = backupIntervalLabel(autoBackup.intervalMinutes),
position = Position.Bottom,
position = Position.Middle,
onClick = onEditInterval,
)
HintText(backupStatusText(autoBackup.status))
GroupedSwitchRow(
title = stringResource(R.string.calendars_auto_backup_on_change),
summary = stringResource(R.string.calendars_auto_backup_on_change_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 = Position.Middle,
)
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,
)
}
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<CalendarSource>,
onExport: (Uri, Set<Long>?) -> Unit,
onExport: (Uri, Set<Long>) -> Unit,
onDismiss: () -> Unit,
) {
// Deliberately not keyed on [calendars]: that list is observer-driven, so
@@ -295,7 +460,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"),
@@ -309,31 +475,19 @@ private fun ExportCalendarPicker(
FullScreenPicker(
title = stringResource(R.string.calendars_export_title),
onDismiss = onDismiss,
predictiveBack = true,
) {
HintText(stringResource(R.string.calendars_export_hint))
calendars.forEachIndexed { index, calendar ->
val isSelected = calendar.id in selected
GroupedRow(
title = calendar.displayName.ifBlank { stringResource(R.string.calendar_unnamed) },
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
},
)
}
GroupedHint(stringResource(R.string.calendars_export_hint), style = MaterialTheme.typography.bodySmall)
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
@@ -345,6 +499,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<CalendarSource>,
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? {
@@ -376,9 +563,7 @@ private fun backupIntervalLabel(minutes: Long): String {
@Composable
private fun backupStatusText(status: BackupStatus): String {
if (status.lastRun == 0L) return stringResource(R.string.calendars_auto_backup_status_never)
val relative = DateUtils.getRelativeTimeSpanString(
status.lastRun, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS,
).toString()
val relative = relativeTimeAgo(status.lastRun)
return if (status.lastSuccess) {
stringResource(R.string.calendars_auto_backup_status_ok, relative)
} else {
@@ -431,5 +616,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
@@ -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<CalendarSource>,
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<CalendarSource>): 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<CalendarSource>): List<CalendarSource> {
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<CalendarSource>, sourceId: Long?): List<CalendarSource> =
calendars.filter { it.isEventTarget && it.id != sourceId }
@@ -3,37 +3,31 @@ 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
import androidx.compose.foundation.isSystemInDarkTheme
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.fillMaxSize
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.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.icons.automirrored.filled.Notes
import androidx.compose.material.icons.automirrored.filled.OpenInNew
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Backup
import androidx.compose.material.icons.filled.CalendarMonth
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Palette
import androidx.compose.material.icons.filled.PhoneAndroid
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
@@ -41,23 +35,18 @@ import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
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.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
@@ -67,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
@@ -85,6 +75,11 @@ 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
import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors
@@ -94,13 +89,22 @@ import de.jeanlucmakiola.calendula.ui.common.eventInk
import de.jeanlucmakiola.calendula.ui.common.LeadingAvatar
import de.jeanlucmakiola.calendula.ui.common.SourceLogo
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
import de.jeanlucmakiola.floret.identity.expandEnter
import de.jeanlucmakiola.floret.identity.predictiveBack
import de.jeanlucmakiola.floret.components.GroupedListInset
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
@@ -139,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<Long?>(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<Long?>(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,
@@ -154,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
},
@@ -174,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,
@@ -181,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 },
)
}
}
}
}
}
@@ -191,6 +224,7 @@ fun CalendarsScreen(
private fun CalendarsList(
local: List<CalendarSource>,
synced: List<CalendarSource>,
hiddenViews: Map<Long, Set<CalendarView>>,
error: Boolean,
onConsumeError: () -> Unit,
onOpenBackup: () -> Unit,
@@ -198,8 +232,11 @@ private fun CalendarsList(
visible: Boolean,
onAdd: () -> Unit,
onEdit: (CalendarSource) -> Unit,
onEditHiddenViews: (CalendarSource) -> Unit,
onSetVisible: (Long, Boolean) -> Unit,
onSetAccountVisible: (Collection<Long>, Boolean) -> Unit,
syncAccessDismissed: List<SyncAccount>,
onAskSyncAccessAgain: (SyncAccount) -> Unit,
) {
val context = LocalContext.current
val snackbarHostState = remember { SnackbarHostState() }
@@ -224,7 +261,7 @@ private fun CalendarsList(
visible = visible,
) {
// What the per-calendar / per-account switches below actually do.
HintText(stringResource(R.string.calendars_visibility_hint))
GroupedHint(stringResource(R.string.calendars_visibility_hint), style = MaterialTheme.typography.bodySmall)
// Local (device-only) calendars — one collapsible group. The header's
// "+" adds a calendar; the switch enables/disables them all at once;
@@ -245,24 +282,14 @@ private fun CalendarsList(
onToggleAll = { enabled -> onSetAccountVisible(local.map { it.id }, enabled) },
) {
if (local.isEmpty()) {
HintText(stringResource(R.string.calendars_local_empty))
GroupedHint(stringResource(R.string.calendars_local_empty), style = MaterialTheme.typography.bodySmall)
} else {
local.forEachIndexed { index, calendar ->
val disabled = !calendar.isVisibleInSystem
GroupedRow(
title = calendar.displayName.ifBlank { stringResource(R.string.calendar_unnamed) },
summary = calendarRowSummary(calendar),
position = if (index == local.lastIndex) Position.Bottom else Position.Middle,
container = MaterialTheme.colorScheme.surfaceContainerHighest,
dimmed = disabled,
leading = { CalendarColorChip(calendar.color, dimIf(disabled)) },
trailing = {
EnableSwitch(
calendarName = calendar.displayName.ifBlank { stringResource(R.string.calendar_unnamed) },
enabled = !disabled,
onToggle = { enabled -> onSetVisible(calendar.id, enabled) },
)
},
CalendarManagerRow(
calendar = calendar,
hiddenViews = hiddenViews[calendar.id].orEmpty(),
last = index == local.lastIndex,
onSetVisible = onSetVisible,
onClick = { onEdit(calendar) },
)
}
@@ -291,8 +318,8 @@ private fun CalendarsList(
// Synced calendars — read-only, grouped by account. Each account is a
// collapsible group whose header opens the source app (icon) and toggles
// all of its calendars at once (switch).
SectionHeader(stringResource(R.string.calendars_synced_header))
HintText(stringResource(R.string.calendars_synced_hint))
GroupedSectionHeader(stringResource(R.string.calendars_synced_header))
GroupedHint(stringResource(R.string.calendars_synced_hint), style = MaterialTheme.typography.bodySmall)
synced
.groupByAccount()
.forEach { group ->
@@ -333,31 +360,30 @@ private fun CalendarsList(
// bottom, dimmed and switchless.
val ordered = cals.orderedForManager()
ordered.forEachIndexed { index, calendar ->
val disabled = !calendar.isVisibleInSystem || calendar.isNotSynced
GroupedRow(
title = calendar.displayName.ifBlank { stringResource(R.string.calendar_unnamed) },
summary = calendarRowSummary(calendar),
position = if (index == ordered.lastIndex) Position.Bottom else Position.Middle,
container = MaterialTheme.colorScheme.surfaceContainerHighest,
dimmed = disabled,
leading = { CalendarColorChip(calendar.color, dimIf(disabled)) },
trailing = if (calendar.hasVisibilitySwitch) {
{
EnableSwitch(
calendarName = calendar.displayName.ifBlank { stringResource(R.string.calendar_unnamed) },
enabled = calendar.isVisibleInSystem,
onToggle = { enabled ->
onSetVisible(calendar.id, enabled)
},
)
}
} else {
null
},
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) },
)
}
}
}
}
@@ -376,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<CalendarView, Boolean>) -> Unit,
onDelete: () -> Unit,
onClose: () -> Unit,
deleteLocked: Boolean = false,
showHiddenViews: Boolean = false,
initialHiddenViews: Set<CalendarView> = 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(
@@ -440,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 })
@@ -447,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 },
@@ -478,7 +538,7 @@ private fun CalendarNameField(
onNameChange: (String) -> Unit,
onImeAction: () -> Unit,
) {
val dark = isSystemInDarkTheme()
val dark = LocalFloretDarkTheme.current
val soften = LocalSoftenColors.current
GroupedSurface(position = Position.Alone, modifier = Modifier.padding(horizontal = 16.dp)) {
Row(
@@ -522,7 +582,7 @@ private fun CalendarNameField(
*/
@Composable
private fun CalendarColorGrid(selected: Int, onSelect: (Int) -> Unit) {
val dark = isSystemInDarkTheme()
val dark = LocalFloretDarkTheme.current
val soften = LocalSoftenColors.current
GroupedSurface(position = Position.Alone, modifier = Modifier.padding(horizontal = 16.dp)) {
Column(
@@ -673,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<CalendarView>): String? {
val states = calendar.stateLabels().map { label ->
stringResource(
when (label) {
@@ -683,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 }
}
@@ -692,20 +753,86 @@ private fun calendarRowSummary(calendar: CalendarSource): String? {
* `Calendars.VISIBLE`. Unchecked drops the calendar out of every surface and
* stops its reminders. Carries its own content description.
*/
/**
* One calendar in a group: dimmed while switched off or not syncing, with the
* visibility switch only where it can change anything.
*/
@Composable
private fun EnableSwitch(
calendarName: String,
enabled: Boolean,
onToggle: (Boolean) -> Unit,
private fun CalendarManagerRow(
calendar: CalendarSource,
hiddenViews: Set<CalendarView>,
last: Boolean,
onSetVisible: (Long, Boolean) -> Unit,
onClick: (() -> Unit)? = null,
) {
val label = stringResource(R.string.calendars_visibility_a11y, calendarName)
Switch(
checked = enabled,
onCheckedChange = onToggle,
modifier = Modifier.semantics { contentDescription = label },
val disabled = !calendar.isVisibleInSystem || calendar.isNotSynced
GroupedRow(
title = calendar.displayName.orUnnamed(),
summary = calendarRowSummary(calendar, hiddenViews),
position = if (last) Position.Bottom else Position.Middle,
container = MaterialTheme.colorScheme.surfaceContainerHighest,
dimmed = disabled,
leading = { CalendarColorChip(calendar.color, dimIf(disabled)) },
trailing = if (calendar.hasVisibilitySwitch) {
{
CalendarVisibilitySwitch(
calendarName = calendar.displayName.orUnnamed(),
enabled = calendar.isVisibleInSystem,
onToggle = { enabled -> onSetVisible(calendar.id, enabled) },
)
}
} else {
null
},
onClick = onClick,
)
}
/**
* 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<CalendarView>,
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<CalendarView>): 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
@@ -841,33 +968,6 @@ private fun CalendarGroupMenu(
}
@Composable
internal fun SectionHeader(text: String) {
Text(
text = text,
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary,
// The cards' own edge, so header and group share a left margin.
modifier = Modifier.padding(
start = GroupedListInset,
end = GroupedListInset,
top = 16.dp,
bottom = 4.dp,
),
)
}
@Composable
internal fun HintText(text: String) {
Text(
text = text,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = GroupedListInset, vertical = 4.dp),
)
}
/**
* Pick the app to open for managing a synced calendar's account. The account's
* own authenticator package (resolved from [AccountManager], no permission
@@ -3,22 +3,30 @@ 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.di.IoDispatcher
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.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
@@ -26,7 +34,6 @@ import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.coroutines.cancellation.CancellationException
@@ -52,12 +59,28 @@ class CalendarsViewModel @Inject constructor(
repository.calendars()
.catch { emit(emptyList()) }
.flowOn(io)
.stateIn(
.stateWhileSubscribed(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
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<List<SyncAccount>> =
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
@@ -68,25 +91,31 @@ class CalendarsViewModel @Inject constructor(
.map { backupUiState(it) }
.catch { emit(BackupUiState.Failure(FailureReason.ProviderUnavailable)) }
.flowOn(io)
.stateIn(
.stateWhileSubscribed(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = BackupUiState.Loading,
)
/** Automatic-backup settings + last-run status, for the Backup section UI. */
val autoBackup: StateFlow<AutoBackupUiState> = 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.autoBackupOnChange,
) { base, selection, combined, keep, onChange ->
base.copy(selection = selection, combined = combined, keep = keep, onChange = onChange)
}
.flowOn(io)
.stateIn(
.stateWhileSubscribed(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = AutoBackupUiState(),
)
@@ -103,12 +132,24 @@ class CalendarsViewModel @Inject constructor(
if (!enabled) emptySet() else sources.filter { it.isManaged }.map { it.id }.toSet()
}
.flowOn(io)
.stateIn(
.stateWhileSubscribed(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = emptySet(),
)
/** The views each calendar is hidden in (#270); null until first read. */
val hiddenViews: StateFlow<Map<Long, Set<CalendarView>>?> =
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<Boolean> = _error.asStateFlow()
@@ -120,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<Long>? = null) {
fun exportBackup(uri: Uri, calendarIds: Set<Long>) {
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
}
@@ -144,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<CalendarView, Boolean>,
) = 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<CalendarView, Boolean>,
) = 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)
}
}
/**
@@ -209,13 +279,58 @@ class CalendarsViewModel @Inject constructor(
}
}
/** Selection writes since the calendar picker opened; the run after it waits for them. */
private val selectionWrites = mutableListOf<Job>()
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 {
settingsPrefs.setAutoBackupOnChange(enabled)
reschedule()
}
}
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) {
@@ -237,6 +352,10 @@ 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,
)
/** Outcome of a whole-calendar backup, surfaced once to the screen. */
@@ -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>): CalendarSource? {
val held = remember(id) { mutableStateOf<CalendarSource?>(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,
)
}
}
}
}
@@ -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<CopyCalendars> =
repository.calendars()
.map<List<CalendarSource>, CopyCalendars> { CopyCalendars.Ready(it) }
.catch { emit(CopyCalendars.Failure) }
.stateWhileSubscribed(scope = viewModelScope, initialValue = CopyCalendars.Loading)
val selection: StateFlow<CopySelection> = combine(
savedState.getStateFlow<Long?>(KEY_SOURCE, null),
savedState.getStateFlow<Long?>(KEY_TARGET, null),
) { source, target -> CopySelection(source, target) }
.stateIn(viewModelScope, SharingStarted.Eagerly, CopySelection())
private val _run = MutableStateFlow<CopyRunState>(CopyRunState.Idle)
val run: StateFlow<CopyRunState> = _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<CalendarSource>) : 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
}
@@ -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<String?>,
val export: () -> Unit,
val import: () -> Unit,
)
@Composable
fun rememberSettingsBackupActions(viewModel: SettingsBackupViewModel): SettingsBackupActions {
val busy by viewModel.busy.collectAsStateWithLifecycle()
val pendingImport = rememberSaveable { mutableStateOf<String?>(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
}
Loaded 100 of 547 files, more files were not shown because too many files have changed in this diff. Show more