Compare commits

...
33 Commits
Author SHA1 Message Date
Jean-Luc Makiolaandmakiolaj b627ed04b7 Move onto floret's shared rows, onboarding pieces and Android helpers (#410)
Beta — Codeberg pre-release / detect (push) Successful in 6s
Beta — Codeberg pre-release / beta (push) Skipped
Stacked on #409 (its commit shows here until it merges). Bumps floret-kit to 5093e1c (floret main, floret-kit#14) and deletes the local copies of what moved there. Widget code untouched.

- `GroupedRow(checked)` for the check-mark rows; `GroupedSwitchRow` for 16 switch rows; `OptionRows` in the three settings preview pickers; `CustomExpandRow` for the three "Custom" picker rows
- `IconInfoCard` replaces `EditCard` and `DetailCard`; `GroupedHint` replaces `SettingsHint` / `HintText` / `PickerDescription`
- Onboarding steps use `OnboardingScaffold(headline, supporting)` and `OnboardingPrimaryButton`
- `LanguagePickerRow(header, predictiveBack)` replaces the local `LanguageRow`
- `relativeTimeAgo`, `ReminderOverride.minutesOrEmpty()`
- New `core-android` dependency: `goAsync { }` in the reminder receivers, `hasPermission` for all non-widget permission checks, `broadcastTicks` behind TodaySource / ZoneSource, `setWakeup` in the reminder and snooze alarms, `stateWhileSubscribed` for the 39 `WhileSubscribed(5_000)` sites

One visible change: the expand rows in Event form and Notification settings show floret's rotating chevron instead of swapping ExpandLess/ExpandMore.

Kept local on purpose: the Reliable delivery row (no selected highlight today), the Dynamic colour switch (isn't dimmed when unavailable), HiddenCalendarsStep's headline (needs its inset padding) and ViewStep's onboarding block (headlineSmall).

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/410
2026-10-15 23:06:26 +02:00
Jean-Luc Makiolaandmakiolaj d8e3250af9 Share test event builders and repository wiring (#408)
Beta — Codeberg pre-release / detect (push) Successful in 7s
Beta — Codeberg pre-release / beta (push) Skipped
Step 3 of the simplification review. Tests only, no production code changes.

- `TestEvents.kt`: defaulted `testEvent` / `allDayEvent` / `timedEvent` / `testDetail` builders replace the full `EventInstance(...)` / `EventDetail(...)` spellings and the per-file `allDay`/`timed` helpers. Helpers with test-specific titles, colours or zones stay as one-line wrappers, so every built event is unchanged.
- `TestRepositories.kt`: `testDataStore` / `testPrefs` / `testSettings` / `testRepository` plus a JUnit 5 `MainDispatcherExtension` replace the repeated DataStore, repository and setMain/resetMain wiring.

Same 1302 tests before and after; widget tests untouched.

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/408
2026-10-15 16:37:46 +02:00
Jean-Luc Makiolaandmakiolaj 8bd2ac7a9a Remove dead code and unused imports (#407)
Beta — Codeberg pre-release / detect (push) Successful in 51s
Beta — Codeberg pre-release / beta (push) Skipped
First step of the simplification review. No behaviour change.

- Unreachable paged-month path (`MonthContent` / `MonthPager` / `MonthPage`); the month branch is now scrolling vs split
- `ui/day/` and its test, `MonthViewModel.anchorPage`, `PagedTimelineViewModel.goToDate`, `SettingsPrefs.setQuickSwitchConfig`, `TimelineHours.span`
- `PermissionViewModel` / `PermissionUiState`, replaced by a saveable `denied` flag in `PermissionScreen`
- `ReminderNotifier.post` no longer returns a value nobody read
- 38 unused imports outside the widget code

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/407
2026-10-15 16:36:08 +02:00
Jean-Luc Makiolaandmakiolaj c1c529d4bd Keep deleted and edited occurrences when moving a series (#404)
Beta — Codeberg pre-release / detect (push) Successful in 7s
Beta — Codeberg pre-release / beta (push) Skipped
Moving a recurring event to another calendar re-inserted its exception rows under the new event. That event has no `_sync_id` yet, so the rows never attached: deleted occurrences came back, and edited ones showed twice (original plus the edited copy).

The move now does what delete and edit-this-occurrence already do for unsynced series: cancelled occurrences become EXDATE entries on the moved series, edited ones become EXDATE plus a standalone event on the target calendar. The standalone copies are rolled back with the rest if the move fails.

`buildCopiedExceptionValues` is gone with its tests, and `ExceptionRowSnapshot`/`ExceptionProjection` only read the columns still used.

Adds `MoveEventExceptionsTest` (instrumented), which fails on the old code and passes now.

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/404
2026-10-15 16:25:34 +02:00
Jean-Luc Makiolaandmakiolaj aca048e593 Open the until-date picker on today's local date (#405)
Beta — Codeberg pre-release / detect (push) Successful in 10s
Beta — Codeberg pre-release / beta (push) Skipped
The repeat-until picker defaulted to today's UTC date, so near midnight it opened on yesterday or tomorrow depending on the zone. It now uses the device zone's today.

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/405
2026-10-15 16:25:12 +02:00
Jean-Luc Makiolaandmakiolaj 440f85d89f Predictive back for the export calendar picker (#406)
Beta — Codeberg pre-release / detect (push) Successful in 6s
Beta — Codeberg pre-release / beta (push) Skipped
ExportCalendarPicker was the only full-screen picker without `predictiveBack = true`.

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/406
2026-10-15 16:24:55 +02:00
Jean-Luc Makiolaandmakiolaj bf2e59a14e Update the selection bar's times live while moving or resizing (#141) (#403)
Beta — Codeberg pre-release / detect (push) Successful in 9s
Beta — Codeberg pre-release / beta (push) Skipped
Feedback from #141: when resizing with the left hand, the finger covers both the event's own time and the hour-column badge.

While a selected event is moved or resized, the time under its title in the top bar now follows the gesture. It shows what letting go would save, using the same calculation as the drop (real duration for a move, the untouched edge kept for a resize, DST-safe), and stays on the saved times until the event leaves its starting slot. It only recalculates when the snapped slot changes.

Closes #141

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/403
2026-10-15 16:21:25 +02:00
Jean-Luc Makiolaandmakiolaj 19f0dcae5d Say Create instead of Save when the editor makes a new event (#141) (#402)
Beta — Codeberg pre-release / detect (push) Successful in 7s
Beta — Codeberg pre-release / beta (push) Skipped
Feedback from the #141 beta: a duplicate opened the editor with the same title and a plain Save button, so it looked like editing the original.

The editor button now says Create for every new event (new, duplicate, shared text, .ics, long-press draft) and Save only when editing an existing event. The label is taken from how the editor was opened, so it doesn't flip while the form loads.

The other two feedback points (handle shape, start time under the finger) are left as they are, see the comment on #141.

Closes #141

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/402
2026-10-15 14:42:39 +02:00
Jean-Luc Makiolaandmakiolaj c3401ed61c Add haptics to split-pane swipes and event drops (#116) (#401)
Beta — Codeberg pre-release / detect (push) Successful in 6s
Beta — Codeberg pre-release / beta (push) Skipped
- Swiping between days in the split month pane now ticks, like pulling the pane open and closed already did.
- Dropping a moved or resized event gives a confirm buzz. It only fires on a real drop; putting an event back where it was, cancelling, or undoing stays silent.
- Fixes a #141 flicker: after a resize, the block dimmed briefly as the floating copy faded out. It now takes over at full opacity, as a block released in place already did.

Deviation from the issue: the original ask (haptics when swiping the split view up and down) shipped in 2.22.0, so this covers the remaining gaps from the analysis. Month and week paging stays silent on purpose, and settings switches are left for a later floret-kit change.

Closes #116

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/401
2026-10-15 14:22:47 +02:00
makiolaj e880500ed8 Release v2.23.0-beta.4 (#178, #181, #271, #306, #339, #387)
Beta — Codeberg pre-release / detect (push) Successful in 6s
Beta — Codeberg pre-release / beta (push) Skipped
2026-10-14 17:55:05 +02:00
Jean-Luc Makiolaandmakiolaj 0121aa5b1d Keep the edit form's results from landing on the next one (#178) (#397)
Beta — Codeberg pre-release / detect (push) Successful in 7s
Beta — Codeberg pre-release / beta (push) Skipped
Follow-up to #394, from two review passes on the tap-opens-editor change.

- The edit form's view model is reused between opens, so work still running for a closed form could land on the next one. Backing out of a slow load and tapping another event showed the old event, and Save wrote to it. A delete finishing after back closed the next editor. Results from a closed form are now dropped.
- Back is ignored while a save or delete runs. The write can't be called back, so the form waits for the result and then closes or reports the error.
- Unsaved changes are now measured against the form as it opened, defaults included, instead of a flag every setter had to set.
- Taps read the setting and whether the calendar takes writes when they happen, so a tap right after a cold start or a return to the app opens the right screen.
- Without write access, the first tap asks once. A refusal opens the details from then on, until the permission is granted.
- Pinning an event to the tapped occurrence lives in one helper (`EventDetail.atOccurrence`), used by the detail, edit and selection-bar paths.

Closes #178

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/397
2026-10-14 17:49:53 +02:00
Jean-Luc Makiolaandmakiolaj cf3c4e96cd Add a black theme for AMOLED screens (#181) (#399)
Beta — Codeberg pre-release / detect (push) Successful in 7s
Beta — Codeberg pre-release / beta (push) Skipped
Settings → Appearance → Theme gets a fourth option, Black, next to System, Light and Dark. It's the dark theme with pure black backgrounds, and it works with Material You as well as Calendula's own palette.

- The month cells and the hour grid are `surfaceContainer` tiles on a `surface` ground, so making every container black would erase the grid lines. floret-kit's `toPureBlack()` sets the ground to #000 and scales the containers down to about #13, #1A, #25 and #30. The tiles stay a shade above black, and sheets and menus still stand out from the page.
- Black always means dark. It's an option in the theme picker, so it doesn't follow the system's light/dark setting.
- Event colours read `isSystemInDarkTheme()` in 15 places, so an in-app Dark or Black on a phone in light mode got light-theme tints. They now read `LocalFloretDarkTheme`, the theme's own decision. The bug also affected Dark, so the changelog has a Fixed entry for it.
- The window backdrop came from the night resource qualifier, so an in-app theme flashed the system's light or dark background before the first frame. `WindowThemeCache` keeps a SharedPreferences copy of the theme choice, and `onCreate` reads it to set the backdrop and bar icons. The copy is written when the stored setting loads, so the first cold start after updating still shows the old backdrop.
- Widgets keep their current themes. They get their theme work in the next milestone.

Needs jlmakiola/floret-kit#13, which is merged. The submodule is pinned to its merge commit on floret-kit `main` (`b1905da`).

Tested with new unit tests for the transform and for saving and reloading `BLACK`, and by hand on the emulator.

Closes #181

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/399
2026-10-14 17:41:34 +02:00
Jean-Luc Makiola 0dd7e07aa0 Show HTML event descriptions as formatted text (#271) (#398)
Beta — Codeberg pre-release / detect (push) Successful in 6s
Beta — Codeberg pre-release / beta (push) Skipped
Event descriptions from Exchange/Outlook and Google Calendar are often HTML. The detail view now renders them instead of showing the raw markup.

- A new converter in `domain/HtmlText.kt` turns HTML into text plus styles and links. It only kicks in when the description has real tags, so plain text with `<3` or `<https://…>` is left alone.
- Kept: bold, italic, underline, strikethrough, super/subscript, monospace, line breaks, paragraphs, lists (bullets, numbers, `start`, nesting) and `<a href>` links (http(s), mailto, tel). Dropped: fonts, sizes, colours, images, and `<head>`/`<style>`/`<script>`/comments.
- Each table row becomes one line with its cells joined by " · ", and empty spacer cells disappear. There's no real grid yet; one can go on top later if invites need it.
- URL and phone autolinking runs on the rendered text and skips text that's already a link.
- Long-press copy gives the rendered text, with each link's address in brackets after it.
- Search matches the rendered text and link addresses, and snippets show clean text.
- The edit form still shows the raw HTML, as discussed in the issue, so saving never breaks the formatting.

The issue suggested a settings toggle that strips tags. Following the discussion in the comments, this renders HTML automatically instead, with no setting.

Known limit: the SQL pre-filter in search still runs on the raw column. A word that's stored as an entity (`R&amp;D`) or split by tags (`<b>Kick</b>off`) isn't found.

I wrote my own parser instead of using `AnnotatedString.fromHtml`, because that goes through `android.text.Html`, which is stubbed in JVM unit tests, and search lives in the Compose-free domain layer.

Closes #271
2026-10-14 17:30:16 +02:00
Jean-Luc Makiolaandmakiolaj 2b2a31ecda Create an event from shared or selected text (#306) (#396)
Beta — Codeberg pre-release / detect (push) Successful in 6s
Beta — Codeberg pre-release / beta (push) Skipped
Shared text, or text picked with the new "Create event" entry in the selection menu, opens the new-event form prefilled. The share's subject becomes the title, or the first line if there is no subject, and the rest of the text goes into the description. Start and length use the usual defaults (next full hour, default duration). Calendula doesn't try to read a date out of the text.

Differences from the plan in the issue comment:
- The line used as the title is left out of the description, so it doesn't show up twice.
- Titles are capped at 255 characters. If a title gets cut, the full text stays in the description.
- Sharing a plain-text file no longer sends it to the .ics importer.
- A saved or dismissed prefilled form no longer reopens after rotating the phone. This also fixes it for "add to calendar" requests from other apps.
- If a second request comes in while a prefilled form is open, it replaces the form when nothing was changed. Otherwise the save / discard / keep editing prompt comes first.
- If Calendula was started just for the request, closing or saving the form takes you back to the app you came from.

Closes #306

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/396
2026-10-14 15:57:32 +02:00
Jean-Luc Makiolaandmakiolaj 0f75d2638b Show events at their real time on days the clocks change (#387) (#393)
Beta — Codeberg pre-release / detect (push) Successful in 6s
Beta — Codeberg pre-release / beta (push) Skipped
On the day the clocks change, the day, 3-day and week views placed events by the time elapsed since midnight, so every event after the change sat an hour off. A 14:45 event on 25 October showed at 15:45. Blocks are now placed by wall clock.

When the clocks go back, 02:00 to 03:00 happens twice, and a wall-clock time alone can't say which of the two it means. This branch keeps track of it:

- The event form holds each time as a `FormTime`, the wall clock plus its UTC offset when that time is in the repeated hour. Validation and saving read the real instants from it, so a span ending in the repeated hour is valid and switching between the two passes is saved.
- A time picked in the form or dragged with a resize handle goes back to the event's original pass when it's set back to its original time. Otherwise it moves in the direction it was moved, stays after the start, and takes a pass the grid can draw where it was dropped.
- A drop onto a repeated time lands on the first pass, unless the event was already on the second.
- A block that runs into the repeated hour from before it is drawn to 03:00, and its label shows its real end.
- The editor, the event details and the pinned zone's "local time" line add the zone abbreviation (CEST or CET) to a time in the repeated hour.
- A recurring series that starts in the repeated hour keeps its pass when it's edited.

Also in this PR:

- `ZoneSource`, provided through Hilt, gives the timeline, the event form and reschedules the device zone. The timeline lays its pages out again when the zone changes.
- A drafted block (#153) opens the form at its exact start and end.
- A day move onto the spring-forward day keeps its wall-clock start, so moving a weekly series there is still offered for all events.

## Testing

The 1,258 unit tests pass. The instrumented suite has the same two failures as `release/v2.23.0` (`CalendarRepositorySmokeTest` and `PermissionScreenTest`), so nothing new.

I also checked it by hand on an emulator in Europe/Berlin, with the clock moved to each DST day:

- 25 October: the event from the issue (14:45, Europe/Brussels) is drawn at 14:45. A run from 02:10 CEST to 02:20 CET is drawn to 03:00 and labelled with its real end.
- Pulling the end of a 02:30 to 03:30 CET event up to 02:45 saves 02:45 CET, after its start.
- Pulling the end of a 01:00 CEST to 04:00 CET event up to 02:15 saves 02:15 CEST, and the block stays where it was dropped.
- 29 March: a 01:00 to 04:00 run and a 14:00 event both sit at their own times.

Picking times in the form and moving a series in the month view are covered by unit tests only.

Closes #387

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/393
2026-10-14 15:54:14 +02:00
Jean-Luc Makiolaandmakiolaj 9fe1ebb0fb Tap a phone number in an event to call it (#339) (#395)
Beta — Codeberg pre-release / detect (push) Successful in 6s
Beta — Codeberg pre-release / beta (push) Skipped
Phone numbers in an event's title, location and description are now links. Tapping one opens the dialer with the number filled in. Nothing is called until you press call, so the app needs no new permission.

- Android's own matcher finds the numbers (Linkify, backed by libphonenumber and the SIM's region). Its loose setting links too much in event text, so a cleanup step drops meeting IDs and PINs after a label, dates, dotted times like "9.30 – 12.00", amounts, anything under 7 digits and digits inside URLs.
- "+49 (0)151 …" dials without the (0). An extension ("ext. 567") becomes a pause, and a Zoom-style dial-in suffix (",,850…#") is kept.
- Detection runs in the detail ViewModel while the event loads, so the links are there on the first frame and survive rotation.
- Long-pressing a field copies it even when the press lands on a link. Before, the link swallowed the press.
- PhoneLinksTest covers the cleanup on the JVM. PhoneLinksPlatformTest (androidTest) runs the real matcher and passes on an emulator with a US SIM.

Known limit: on a device without a SIM (Wi-Fi tablets, some emulators) Android gives the matcher no region, so only numbers starting with + are linked.

Closes #339

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/395
2026-10-14 15:24:03 +02:00
Jean-Luc Makiolaandmakiolaj 951ad9cd6d Tapping an event can open the edit form (#178) (#394)
Beta — Codeberg pre-release / detect (push) Successful in 6s
Beta — Codeberg pre-release / beta (push) Skipped
New setting under Settings → Views → Events: "Tapping an event opens" Details (default) or Edit form. The long-press toggle moves into the same group.

- Taps in the views and in search open the editor directly for events in writable calendars. Read-only events, reminder notifications and widgets always open the details.
- Installs without write access are asked for it on the tap; refusing opens the details instead.
- The editor gets a back guard: with unsaved changes it asks to save, discard or keep editing; otherwise it closes silently.
- The editor gets Duplicate, Share and Delete in an overflow menu, so skipping the details doesn't lose them.
- If the event can't be loaded, the details screen opens and shows why.
- Each editor overlay (create, edit, duplicate/import) now has its own ViewModel. Duplicating from an edited form previously reused the edit form's state.
- Deletes from the details screen, the editor and the selection bar share one error mapping. Deleting an event that's already gone counts as deleted in the details screen and the editor.

Deviation from the issue: it asked for back to save automatically. Following the discussion in the comments, auto-save isn't in this PR. Back asks only when something actually changed, and Details stays the default.

Closes #178

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/394
2026-10-14 14:33:38 +02:00
makiolaj 6cb2f62627 Release v2.23.0-beta.3 (#153)
Beta — Codeberg pre-release / detect (push) Successful in 5s
Beta — Codeberg pre-release / beta (push) Successful in 36m8s
2026-10-12 22:48:23 +02:00
Jean-Luc Makiolaandmakiolaj 427e87c6e6 Long press an empty slot to draft an event (#153) (#390)
Beta — Codeberg pre-release / detect (push) Successful in 6s
Beta — Codeberg pre-release / beta (push) Skipped
Long press on free time in the day, 3-day and week views drops a block of the default event length there. It can be moved while still held, or dragged and resized with its handles after letting go. The tick opens the new-event form at that span; the ✕, a tap elsewhere or back discards it. The draft is a stand-in event that reuses the #141 selection, drag and resize machinery, so nothing is written until the form saves.

Also smooths the lift handover for all selected blocks: no one-frame dip when letting go, no bounce on the handles or on a block landing after a drop or resize, and the floating copy's time label now matches the block's so the text doesn't shift on pickup.

Deviations from the issue / agreed design:
- An unresized draft opens the form with the length it shows (the global default) rather than the per-calendar default, so the form never opens at a different time than the block on screen.
- A draft dropped on a day off screen snaps back instead of moving there, since nothing would draw it.
- The in-editor timeline picker from the issue isn't included; per the issue comments it isn't needed for now.

Also moves the Gitea release/beta jobs onto the light/gradle runners.

Closes #153

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/390
2026-10-12 22:48:13 +02:00
makiolaj dce83005ea Release v2.23.0-beta.2 (#141)
Beta — Codeberg pre-release / detect (push) Successful in 5s
Beta — Codeberg pre-release / beta (push) Successful in 8m15s
2026-10-09 22:23:14 +02:00
Jean-Luc Makiola 1ac486cc4b Select, move and resize timeline events with a long press (#141) (#384)
Beta — Codeberg pre-release / detect (push) Successful in 12s
Beta — Codeberg pre-release / beta (push) Skipped
2026-10-09 22:23:06 +02:00
makiolaj 549ef1dfbf Release v2.23.0-beta.1 (#367)
Beta — Codeberg pre-release / detect (push) Successful in 5s
Beta — Codeberg pre-release / beta (push) Successful in 9m45s
2026-10-09 10:25:48 +02:00
Jean-Luc Makiolaandmakiolaj 164b5fb25d Scroll back into past days in the agenda (#367) (#382)
Beta — Codeberg pre-release / detect (push) Successful in 4s
Beta — Codeberg pre-release / beta (push) Skipped
The agenda opens on today, and scrolling up loads earlier days 30 at a time. Past days follow the past-events setting: Dim fades them, and with Hide the agenda still starts at today.

The agenda no longer picks up the day the month or day view was on, so "Next 30 days" always counts from today. That fixes the bug from the issue comment. It also means the agenda no longer follows the shared view date from #184 when you switch to it. Backing out of a day opened from the agenda keeps your scroll position.

Not in the issue: multi-day events that are still running now dim on the days already behind you, in the agenda, month, week and day views. Before, they stayed at full strength until the whole event ended. A spanning bar dims once the last day it covers in that row has passed.

The widget is unchanged and still starts at today.

Closes #367

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/382
2026-10-09 10:25:25 +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
Jean-Luc Makiolaandmakiolaj 9c35712573 ci(release): beta releases as Codeberg-only pre-releases (#369)
Release — F-Droid repo + Gitea/Codeberg release + Play / detect (push) Successful in 6s
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 1m30s
Beta — Codeberg pre-release / detect (push) Successful in 5s
Beta — Codeberg pre-release / beta (push) Skipped
### What this changes

Adds beta releases, ported from Agendula (#38 and #40 there). Pushing a `release/*` branch whose `versionName` is `X.Y.Z-beta.N` runs the new `.gitea/workflows/beta.yaml`: unit tests, build + sign with the app key, then a **Codeberg pre-release** (APK + `.sha256`) and a Gitea pre-release (R8 mapping). F-Droid (self-hosted and official) and Play never get a beta; Obtainium only offers it with *Include prereleases* on.

- **New versionCode scheme**, derived in one place by `scripts/version_info.sh`. 2.22.3 is the last legacy version (`X*10000 + Y*100 + Z`); from **2.22.4** on it is `X*1000000 + Y*10000 + Z*100 + N` for a beta (N = 1–98) and `+ 99` for stable, so `2.22.4` → `2220499`, `2.23.0-beta.1` → `2230001`.
- **`scripts/release_gate.sh`** decides in both `detect` jobs whether the version still needs publishing. Tags are read by exact name via `git ls-remote`: Codeberg's `git/refs/tags/<name>` matches by prefix, so a beta tag would otherwise hide its stable release. A beta counts as done only once its Codeberg pre-release carries the APK (a failed publish is redone by the next push) and must be newer than the latest stable.
- **Shared scripts** `publish_codeberg_release.sh`, `publish_gitea_release.sh`, `release_notes.sh`, `write_keystore.sh`, and a local composite action `.gitea/actions/android-env` for the toolchain setup, used by both `release.yaml` and `beta.yaml`. The stable path behaves as before (Codeberg step stays best-effort).
- **Guards:** CI fails a PR whose `versionCode` doesn't match its `versionName`, or that brings a beta into `main`; `release.yaml` refuses a beta as a backstop; betas get no store What's New (`sync_changelog_to_fastlane.sh`, `check_changelog_lengths.sh`).
- **Docs:** versionCode table and "Cutting a beta" in `docs/RELEASING.md`, the Obtainium note in the README, `build.gradle.kts` comment.
- `gradle/gradle-daemon-jvm.properties` now points at JetBrains' own JBR 21.0.11 downloads instead of foojay, which dropped JetBrains 21 from its index (the pinned ids return 400, so a clean runner can't provision the daemon JVM).

### Why

To ship test builds of an upcoming version to opted-in testers before the stable release, without them reaching F-Droid or Play users.

Infra-only, so this targets `main` directly; no version bump. When cutting 2.22.4, its What's New file is `changelogs/2220499.txt`.

### Checklist

- [x] Targeting `main` (infra change, noted above)
- [x] No `values-*/strings.xml` touched
- [x] `CHANGELOG.md` not updated: release infrastructure, not a user-visible change
- [x] No planning or design documents committed

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/369
2026-10-06 18:43:45 +02:00
renovate-bot 4342c6ab6d fix(deps): update composebom to v2026.09.00 (#238)
Release — F-Droid repo + Gitea/Codeberg release + Play / detect (push) Successful in 6s
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 1m6s
This PR contains the following updates:

| Package | Type | Change | Age | [Confidence](https://docs.renovatebot.com/merge-confidence/) |
|---|---|---|---|---|
| [androidx.compose:compose-bom](https://developer.android.com/jetpack) | dependencies | `2026.06.01` → `2026.09.00` | 25 d | ![confidence](https://developer.mend.io/api/mc/badges/confidence/maven/androidx.compose:compose-bom/2026.06.01/2026.09.00?slim=true) |

---

### Configuration

📅 **Schedule**: (UTC)

- Branch creation
  - Between 04:00 AM and 06:59 AM, only on Monday (`* 4-6 * * 1`)
- Automerge
  - At any time (no schedule defined)

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Mend Renovate](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0My4yMzIuMCIsInVwZGF0ZWRJblZlciI6IjQzLjIzMi4wIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6WyJkZXBlbmRlbmNpZXMiXX0=-->

Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/238
2026-10-05 13:40:00 +02:00
renovate-bot 57bad5c74c fix(deps): update material3 (alpha) to v1.5.0-alpha29 (#274)
Release — F-Droid repo + Gitea/Codeberg release + Play / detect (push) Successful in 7s
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) Canceled after 0s
This PR contains the following updates:

| Package | Type | Change | Age | [Confidence](https://docs.renovatebot.com/merge-confidence/) |
|---|---|---|---|---|
| [androidx.compose.material3:material3](https://developer.android.com/jetpack/androidx/releases/compose-material3#1.4.0) ([source](https://cs.android.com/androidx/platform/frameworks/support)) | dependencies | `1.5.0-alpha26` → `1.5.0-alpha29` | 11 d | ![confidence](https://developer.mend.io/api/mc/badges/confidence/maven/androidx.compose.material3:material3/1.5.0-alpha26/1.5.0-alpha29?slim=true) |

---

### Configuration

📅 **Schedule**: (UTC)

- Branch creation
  - Between 04:00 AM and 06:59 AM, only on Monday (`* 4-6 * * 1`)
- Automerge
  - At any time (no schedule defined)

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Mend Renovate](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0My4yMzIuMCIsInVwZGF0ZWRJblZlciI6IjQzLjIzMi4wIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6WyJkZXBlbmRlbmNpZXMiXX0=-->

Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/274
2026-10-05 13:39:41 +02:00
renovate-bot ebf833d0bd fix(deps): update glance to v1.2.0 (#275)
Release — F-Droid repo + Gitea/Codeberg release + Play / detect (push) Successful in 6s
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 1m10s
This PR contains the following updates:

| Package | Type | Change | Age | [Confidence](https://docs.renovatebot.com/merge-confidence/) |
|---|---|---|---|---|
| [androidx.glance:glance-material3](https://developer.android.com/jetpack/androidx/releases/glance#1.2.0) ([source](https://cs.android.com/androidx/platform/frameworks/support)) | dependencies | `1.1.1` → `1.2.0` | 39 d | ![confidence](https://developer.mend.io/api/mc/badges/confidence/maven/androidx.glance:glance-material3/1.1.1/1.2.0?slim=true) |
| [androidx.glance:glance-appwidget](https://developer.android.com/jetpack/androidx/releases/glance#1.2.0) ([source](https://cs.android.com/androidx/platform/frameworks/support)) | dependencies | `1.1.1` → `1.2.0` | 39 d | ![confidence](https://developer.mend.io/api/mc/badges/confidence/maven/androidx.glance:glance-appwidget/1.1.1/1.2.0?slim=true) |

---

### Configuration

📅 **Schedule**: (UTC)

- Branch creation
  - Between 04:00 AM and 06:59 AM, only on Monday (`* 4-6 * * 1`)
- Automerge
  - At any time (no schedule defined)

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about these updates again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Mend Renovate](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0My4yMzIuMCIsInVwZGF0ZWRJblZlciI6IjQzLjIzMi4wIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6WyJkZXBlbmRlbmNpZXMiXX0=-->

Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/275
2026-10-05 13:39:03 +02:00
renovate-bot 2f24a9878c fix(deps): update lifecyclecompose to v2.11.0 (#277)
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 1m5s
This PR contains the following updates:

| Package | Type | Change | Age | [Confidence](https://docs.renovatebot.com/merge-confidence/) |
|---|---|---|---|---|
| [androidx.lifecycle:lifecycle-runtime-compose](https://developer.android.com/jetpack/androidx/releases/lifecycle#2.11.0) ([source](https://cs.android.com/androidx/platform/frameworks/support)) | dependencies | `2.10.0` → `2.11.0` | 109 d | ![confidence](https://developer.mend.io/api/mc/badges/confidence/maven/androidx.lifecycle:lifecycle-runtime-compose/2.10.0/2.11.0?slim=true) |

---

### Configuration

📅 **Schedule**: (UTC)

- Branch creation
  - Between 04:00 AM and 06:59 AM, only on Monday (`* 4-6 * * 1`)
- Automerge
  - At any time (no schedule defined)

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Mend Renovate](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0My4yMzIuMCIsInVwZGF0ZWRJblZlciI6IjQzLjIzMi4wIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6WyJkZXBlbmRlbmNpZXMiXX0=-->

Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/277
2026-10-05 13:37:03 +02:00
Jean-Luc Makiolaandmakiolaj 2313671965 chore(renovate): rebase conflicted PRs on every merge to main (#366)
Release — F-Droid repo + Gitea/Codeberg release + Play / detect (push) Successful in 30s
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 1m29s
Renovate only rebases while it runs, and it ran once a week, so merging one dependency PR left the others conflicted until the next Monday.

- `renovate.yml`: also run on push to `main` (mirror syncs fire push events, like `release.yaml`).
- `renovate.json5`: new PRs only in a Monday window (`* 4-6 * * 1`) around the weekly cron; on-merge runs only rebase conflicted PRs (`rebaseWhen: "conflicted"`).

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/calendula/pulls/366
2026-10-05 13:33:59 +02:00
Jean-Luc Makiola e1b80d9f89 Release v2.22.3 (#362)
Release — F-Droid repo + Gitea/Codeberg release + Play / detect (push) Successful in 8s
Release — F-Droid repo + Gitea/Codeberg release + Play / release (push) Successful in 14m42s
Release — F-Droid repo + Gitea/Codeberg release + Play / play (push) Successful in 1m40s
Patch release for #361. No app changes.

- `title.txt` in every store locale is now "Calendula: Calendar", with "Calendar" taken from the app's own translation of the word (`event_detail_calendar`). Since 2.22.0 the Play listing is pushed from the repo, and the repo title was only "Calendula", which replaced the suffixed name from the Play Console.
- ja has no translation for that string yet, so it uses カレンダー. zh-CN has "Calendula" as its translation of "Calendar" on Weblate, so the title uses 日历 instead. That string should be fixed on Weblate.
- F-Droid reads the same `title.txt`, so the F-Droid listing gets the suffix too.

Plus the release commit: CHANGELOG section, versionName 2.22.3 / versionCode 22203, and the 22203 changelogs for every store locale. Merging this to main triggers the release pipeline.

Closes #361
2026-10-02 22:14:34 +02:00
258 changed files with 8999 additions and 3759 deletions
+16 -1
View File
@@ -37,9 +37,24 @@ jobs:
- name: Reproducible-release invariant - name: Reproducible-release invariant
run: bash scripts/check_reproducible_release.sh run: bash scripts/check_reproducible_release.sh
# versionCode must match versionName (the official F-Droid repo builds the
# tag as committed), and a beta must never reach main.
- name: Committed version is well-formed
env:
BASE: ${{ github.base_ref }}
run: |
set -e
bash scripts/version_info.sh --check
if [ "${BASE#refs/heads/}" = "main" ] && [ "$(bash scripts/version_info.sh channel)" = "beta" ]; then
echo "ERROR: versionName $(bash scripts/version_info.sh version) is a beta." >&2
echo "Set the stable version (and its versionCode) before merging into main." >&2
exit 1
fi
# Play rejects a "What's New" over 500 characters, which would fail the # Play rejects a "What's New" over 500 characters, which would fail the
# upload after the release had already shipped everywhere else. Cheap, so # upload after the release had already shipped everywhere else. Cheap, so
# it runs on every PR rather than only on the release merge. # it runs on every PR rather than only on the release merge. A beta ships
# no What's New, so only the older files are checked for one.
- name: Changelog length invariant - name: Changelog length invariant
run: bash scripts/check_changelog_lengths.sh run: bash scripts/check_changelog_lengths.sh
+57
View File
@@ -0,0 +1,57 @@
name: Android build environment
description: JDK 17, Android SDK + build tools, Gradle cache and jq for the release and beta pipelines.
runs:
using: composite
steps:
- name: Setup Java
uses: actions/setup-java@v4
with:
distribution: 'zulu'
java-version: '17'
- name: Setup Android SDK
uses: android-actions/setup-android@v3
with:
packages: ''
- name: Setup Android SDK cache
uses: actions/cache@v4
with:
path: /opt/android-sdk
key: ${{ runner.os }}-android-sdk-37-36.0.0
- name: Install Android SDK packages
shell: bash
run: |
yes | sdkmanager --licenses >/dev/null || true
sdkmanager \
"platform-tools" \
"platforms;android-37.0" \
"build-tools;36.0.0"
- name: Setup Gradle cache
uses: actions/cache@v4
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties', 'gradle/libs.versions.toml') }}
restore-keys: |
${{ runner.os }}-gradle-
- name: Install jq
shell: bash
run: |
set -e
SUDO=""
if command -v sudo >/dev/null 2>&1; then SUDO="sudo"; fi
if command -v apt-get >/dev/null 2>&1; then
$SUDO apt-get update
$SUDO apt-get install -y jq
elif command -v apk >/dev/null 2>&1; then
$SUDO apk add --no-cache jq
fi
- name: Grant execute permission for gradlew
shell: bash
run: chmod +x ./gradlew
+97
View File
@@ -0,0 +1,97 @@
name: Beta — Codeberg pre-release
# Pushing a release/* branch whose versionName is X.Y.Z-beta.N publishes a
# Codeberg pre-release (APK + SHA-256) and a Gitea pre-release (R8 mapping).
# Betas never reach F-Droid or Play. See docs/RELEASING.md.
on:
push:
branches: ['release/**']
concurrency:
group: beta
cancel-in-progress: false
jobs:
detect:
# Gitea only; see the same guard in release.yaml.
if: github.repository_owner == 'makiolaj'
runs-on: light
outputs:
is_beta: ${{ steps.v.outputs.is_beta }}
version: ${{ steps.v.outputs.version }}
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Resolve version and whether it still needs publishing
id: v
run: |
set -e
INFO=$(bash scripts/version_info.sh)
echo "$INFO"
echo "$INFO" >> "$GITHUB_OUTPUT"
if [ "$(bash scripts/version_info.sh channel)" != beta ]; then
echo "Not a beta — nothing to do."
echo "is_beta=false" >> "$GITHUB_OUTPUT"
exit 0
fi
GATE=$(bash scripts/release_gate.sh)
echo "is_beta=${GATE#cut=}" >> "$GITHUB_OUTPUT"
beta:
needs: detect
if: needs.detect.outputs.is_beta == 'true'
runs-on: gradle
env:
ANDROID_HOME: /opt/android-sdk
ANDROID_SDK_ROOT: /opt/android-sdk
VERSION: ${{ needs.detect.outputs.version }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
submodules: recursive
- name: Android build environment
uses: ./.gitea/actions/android-env
- name: Pin versionCode to versionName
run: bash scripts/version_info.sh --pin
- name: Unit tests
run: ./gradlew testDebugUnitTest
# The real app key, so a beta updates in place to later betas and stable.
- name: Setup Android Keystore
env:
KEYSTORE_BASE64: ${{ secrets.KEYSTORE_BASE64 }}
KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }}
KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
run: bash scripts/write_keystore.sh
- name: Build release APK
run: ./gradlew assembleRelease
- name: Create tag + Gitea pre-release
env:
TOKEN: ${{ secrets.GITHUB_TOKEN }}
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
SHA: ${{ github.sha }}
run: |
set -e
bash scripts/release_notes.sh "$VERSION" > release-notes.md
cat release-notes.md
TAG="v$VERSION" PRERELEASE=true NOTES_FILE=release-notes.md \
MAPPING=app/build/outputs/mapping/release/mapping.txt \
bash scripts/publish_gitea_release.sh
- name: Publish pre-release to Codeberg
env:
TOKEN: ${{ secrets.CODEBERG_RELEASE_TOKEN }}
API: https://codeberg.org/api/v1/repos/jlmakiola/calendula
SHA: ${{ github.sha }}
run: |
set -e
TAG="v$VERSION" PRERELEASE=true NOTES_FILE=release-notes.md \
APK=app/build/outputs/apk/release/app-release.apk \
bash scripts/publish_codeberg_release.sh
+34 -257
View File
@@ -7,7 +7,9 @@ name: Release — F-Droid repo + Gitea/Codeberg release + Play
# that release to Codeberg with the signed APK + a SHA-256 checksum as a # that release to Codeberg with the signed APK + a SHA-256 checksum as a
# direct-download channel — the tag is an output of the pipeline, not its # direct-download channel — the tag is an output of the pipeline, not its
# trigger. Ordinary merges (no version bump) fall through `detect` and do # trigger. Ordinary merges (no version bump) fall through `detect` and do
# nothing. # nothing. Betas (X.Y.Z-beta.N) never come through here: beta.yaml cuts them
# from release/* branches as Codeberg-only pre-releases, and `detect` refuses
# one that reaches main.
# #
# A trailing `play` job then uploads the App Bundle to Google Play. It is last # A trailing `play` job then uploads the App Bundle to Google Play. It is last
# and separate because Play is the only channel that can reject a good build for # and separate because Play is the only channel that can reject a good build for
@@ -41,7 +43,7 @@ jobs:
# secrets. repository_owner differs between the two forges regardless of # secrets. repository_owner differs between the two forges regardless of
# URL, proxy or instance rename, so this closes it permanently. # URL, proxy or instance rename, so this closes it permanently.
if: github.repository_owner == 'makiolaj' if: github.repository_owner == 'makiolaj'
runs-on: docker runs-on: light
outputs: outputs:
is_release: ${{ steps.v.outputs.is_release }} is_release: ${{ steps.v.outputs.is_release }}
version: ${{ steps.v.outputs.version }} version: ${{ steps.v.outputs.version }}
@@ -54,56 +56,28 @@ jobs:
- name: Resolve version and whether it is a new release - name: Resolve version and whether it is a new release
id: v id: v
env:
# Tags are read from Codeberg, which is canonical — deliberately NOT
# from the Gitea API this workflow runs on. The Codeberg -> Gitea sync
# is a push mirror, i.e. `git push --mirror`, which deletes refs the
# source does not have. A tag minted here on Gitea is therefore wiped
# by the next sync (Codeberg does not have it yet) and only reappears
# once the tag push at the end of this workflow propagates back.
# Asking Gitea inside that window would report "no tag" for a release
# that already shipped, and cut it a second time.
# Public repo, so this read needs no token.
TAG_API: https://codeberg.org/api/v1/repos/jlmakiola/calendula
run: | run: |
set -e set -e
VERSION=$(grep -oP 'versionName\s*=\s*"\K[^"]+' app/build.gradle.kts) INFO=$(bash scripts/version_info.sh)
if [ -z "$VERSION" ]; then echo "No versionName in app/build.gradle.kts" >&2; exit 1; fi echo "$INFO"
MAJOR=$(echo "$VERSION" | cut -d. -f1); MINOR=$(echo "$VERSION" | cut -d. -f2); PATCH=$(echo "$VERSION" | cut -d. -f3) echo "$INFO" >> "$GITHUB_OUTPUT"
MAJOR=${MAJOR:-0}; MINOR=${MINOR:-0}; PATCH=${PATCH:-0} VERSION=$(echo "$INFO" | sed -n 's/^version=//p')
VERSION_CODE=$(( MAJOR * 10000 + MINOR * 100 + PATCH )) CHANNEL=$(echo "$INFO" | sed -n 's/^channel=//p')
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
echo "version_code=$VERSION_CODE" >> "$GITHUB_OUTPUT"
echo "Resolved version $VERSION (code $VERSION_CODE)"
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
echo "Manual dispatch — re-sign path, not a release." echo "Manual dispatch — re-sign path, not a release."
echo "is_release=false" >> "$GITHUB_OUTPUT" echo "is_release=false" >> "$GITHUB_OUTPUT"
exit 0 exit 0
fi fi
# A tag for this version already existing means the release shipped on # Backstop for CI's guard: betas ship from release/* via beta.yaml.
# an earlier push; do nothing. Absent => this merge cuts the release. if [ "$CHANNEL" != "stable" ]; then
# echo "versionName $VERSION on main is a beta. Set the stable version before merging to main." >&2
# Anything other than a clean 200/404 is treated as fatal rather than exit 1
# as "no tag". A Codeberg outage or a network blip would otherwise fi
# read as absent and re-cut a release that has already shipped — # Tags are read from Codeberg, the canonical forge: a tag minted here is
# republishing to F-Droid and Play. Failing here is recoverable; a # wiped by the next mirror sync until Codeberg has it. A lookup error is
# duplicate release is not. # fatal, since guessing "no tag" would re-cut a shipped release.
STATUS=$(curl -s -o /dev/null -w '%{http_code}' "$TAG_API/git/refs/tags/v$VERSION" || echo 000) GATE=$(bash scripts/release_gate.sh)
case "$STATUS" in echo "is_release=${GATE#cut=}" >> "$GITHUB_OUTPUT"
200)
echo "Tag v$VERSION already exists on Codeberg — nothing to release."
echo "is_release=false" >> "$GITHUB_OUTPUT"
;;
404)
echo "No tag for v$VERSION on Codeberg yet — cutting the release."
echo "is_release=true" >> "$GITHUB_OUTPUT"
;;
*)
echo "Codeberg tag lookup for v$VERSION returned HTTP $STATUS." >&2
echo "Refusing to guess: treating this as 'no tag' could re-cut a shipped release." >&2
exit 1
;;
esac
# Releases: build + sign + publish, then mint the tag and Gitea release. # Releases: build + sign + publish, then mint the tag and Gitea release.
# Also runs on manual dispatch, where it skips the build and just re-signs and # Also runs on manual dispatch, where it skips the build and just re-signs and
@@ -111,7 +85,7 @@ jobs:
release: release:
needs: detect needs: detect
if: needs.detect.outputs.is_release == 'true' || github.event_name == 'workflow_dispatch' if: needs.detect.outputs.is_release == 'true' || github.event_name == 'workflow_dispatch'
runs-on: docker runs-on: gradle
env: env:
ANDROID_HOME: /opt/android-sdk ANDROID_HOME: /opt/android-sdk
ANDROID_SDK_ROOT: /opt/android-sdk ANDROID_SDK_ROOT: /opt/android-sdk
@@ -124,65 +98,13 @@ jobs:
with: with:
submodules: recursive submodules: recursive
- name: Setup Java - name: Android build environment
uses: actions/setup-java@v4 uses: ./.gitea/actions/android-env
with:
distribution: 'zulu'
java-version: '17'
- name: Setup Android SDK # The committed versionName is the source of truth; pin the derived code.
uses: android-actions/setup-android@v3
with:
packages: ''
- name: Setup Android SDK cache
uses: actions/cache@v4
with:
path: /opt/android-sdk
key: ${{ runner.os }}-android-sdk-37-36.0.0
- name: Install Android SDK packages
run: |
yes | sdkmanager --licenses >/dev/null || true
sdkmanager \
"platform-tools" \
"platforms;android-37.0" \
"build-tools;36.0.0"
- name: Setup Gradle cache
uses: actions/cache@v4
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties', 'gradle/libs.versions.toml') }}
restore-keys: |
${{ runner.os }}-gradle-
- name: Install jq
run: |
set -e
SUDO=""
if command -v sudo >/dev/null 2>&1; then SUDO="sudo"; fi
if command -v apt-get >/dev/null 2>&1; then
$SUDO apt-get update
$SUDO apt-get install -y jq
elif command -v apk >/dev/null 2>&1; then
$SUDO apk add --no-cache jq
fi
- name: Grant execute permission for gradlew
run: chmod +x ./gradlew
# The committed versionName is the source of truth. Pin versionCode to the
# value derived from it so the published APK's code is always
# MAJOR*10000 + MINOR*100 + PATCH even if the committed code was forgotten.
- name: Pin versionCode to versionName - name: Pin versionCode to versionName
if: env.IS_RELEASE == 'true' if: env.IS_RELEASE == 'true'
run: | run: bash scripts/version_info.sh --pin
set -e
sed -i "s/versionCode = .*/versionCode = $VERSION_CODE/" app/build.gradle.kts
grep -E 'versionName|versionCode' app/build.gradle.kts
# Test the exact commit being shipped (only on a real release). # Test the exact commit being shipped (only on a real release).
- name: Unit tests - name: Unit tests
@@ -195,15 +117,7 @@ jobs:
KEYSTORE_BASE64: ${{ secrets.KEYSTORE_BASE64 }} KEYSTORE_BASE64: ${{ secrets.KEYSTORE_BASE64 }}
KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }} KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }}
KEY_ALIAS: ${{ secrets.KEY_ALIAS }} KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
run: | run: bash scripts/write_keystore.sh
mkdir -p app
echo "$KEYSTORE_BASE64" | base64 --decode > app/upload-keystore.jks
cat > key.properties <<EOF
storePassword=$KEY_PASSWORD
keyPassword=$KEY_PASSWORD
keyAlias=$KEY_ALIAS
storeFile=upload-keystore.jks
EOF
- name: Build release APK - name: Build release APK
if: env.IS_RELEASE == 'true' if: env.IS_RELEASE == 'true'
@@ -312,6 +226,7 @@ jobs:
# Creating it with target_commitish makes Gitea create the vX.Y.Z tag at # Creating it with target_commitish makes Gitea create the vX.Y.Z tag at
# this commit, so the tag only ever marks a fully-shipped release (and a # this commit, so the tag only ever marks a fully-shipped release (and a
# failure before here leaves no tag, so re-running the workflow retries). # failure before here leaves no tag, so re-running the workflow retries).
# Also attaches the R8 mapping, best-effort.
- name: Create tag + Gitea release - name: Create tag + Gitea release
if: env.IS_RELEASE == 'true' if: env.IS_RELEASE == 'true'
env: env:
@@ -320,74 +235,10 @@ jobs:
SHA: ${{ github.sha }} SHA: ${{ github.sha }}
run: | run: |
set -e set -e
TAG="v$VERSION" bash scripts/release_notes.sh "$VERSION" > release-notes.md
# Notes = this version's CHANGELOG section. TAG="v$VERSION" PRERELEASE=false NOTES_FILE=release-notes.md \
awk -v ver="$VERSION" ' MAPPING=app/build/outputs/mapping/release/mapping.txt \
$0 ~ "^## \\[" ver "\\]" { flag = 1; next } bash scripts/publish_gitea_release.sh
/^## \[/ { flag = 0 }
flag' CHANGELOG.md > release-notes.md
sed -i -e '/./,$!d' release-notes.md
if [ ! -s release-notes.md ]; then
echo "_No changelog entry for ${VERSION} — see CHANGELOG.md._" > release-notes.md
fi
python3 - "$TAG" "$SHA" <<'PY' > payload.json
import json, sys
print(json.dumps({
"tag_name": sys.argv[1],
"target_commitish": sys.argv[2],
"name": sys.argv[1],
"body": open("release-notes.md").read(),
"draft": False,
"prerelease": False,
}))
PY
# Upsert (re-run safe): PATCH if a release for the tag already exists,
# else POST a new one (which also creates the tag at target_commitish).
curl -s -H "Authorization: token $TOKEN" "$API/releases/tags/$TAG" > existing.json
ID=$(jq -r '.id // empty' existing.json 2>/dev/null || true)
if [ -n "$ID" ]; then
CODE=$(curl -s -o response.json -w '%{http_code}' -X PATCH \
-H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
-d @payload.json "$API/releases/$ID")
OK=200
else
CODE=$(curl -s -o response.json -w '%{http_code}' -X POST \
-H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
-d @payload.json "$API/releases")
OK=201
fi
cat response.json
if [ "$CODE" != "$OK" ]; then
echo "Release upsert failed with HTTP $CODE (expected $OK)" >&2
exit 1
fi
echo "Created/updated release $TAG at $SHA"
# Archive the R8 mapping so user crash stacktraces stay deobfuscatable.
# Attached to the release (it's not an APK, so it fits the no-binaries
# rule). Best-effort: never fail a release over it.
- name: Attach R8 mapping to Gitea release
if: env.IS_RELEASE == 'true'
continue-on-error: true
env:
TOKEN: ${{ secrets.GITHUB_TOKEN }}
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
run: |
set -e
MAP="app/build/outputs/mapping/release/mapping.txt"
if [ ! -f "$MAP" ]; then echo "No mapping.txt (R8 off?) — skipping."; exit 0; fi
TAG="v$VERSION"
ASSET="mapping-${VERSION}.txt.gz"
gzip -c "$MAP" > "/tmp/$ASSET"
ID=$(curl -s -H "Authorization: token $TOKEN" "$API/releases/tags/$TAG" | jq -r '.id // empty')
if [ -z "$ID" ]; then echo "Could not resolve release id — skipping."; exit 0; fi
# Replace any prior asset of the same name (re-run safe).
OLD=$(curl -s -H "Authorization: token $TOKEN" "$API/releases/$ID/assets" \
| jq -r --arg n "$ASSET" '.[] | select(.name==$n) | .id')
[ -n "$OLD" ] && curl -s -X DELETE -H "Authorization: token $TOKEN" "$API/releases/$ID/assets/$OLD" >/dev/null || true
curl -s -X POST -H "Authorization: token $TOKEN" \
-F "attachment=@/tmp/$ASSET" \
"$API/releases/$ID/assets?name=$ASSET" -o /dev/null -w "asset upload HTTP %{http_code}\n"
# Mirror the release to the Codeberg mirror as a direct-download channel # Mirror the release to the Codeberg mirror as a direct-download channel
# for users who don't want F-Droid. Gitea already push-mirrors branches + # for users who don't want F-Droid. Gitea already push-mirrors branches +
@@ -406,84 +257,10 @@ jobs:
SHA: ${{ github.sha }} SHA: ${{ github.sha }}
run: | run: |
set -e set -e
if [ -z "${TOKEN:-}" ]; then [ -s release-notes.md ] || bash scripts/release_notes.sh "$VERSION" > release-notes.md
echo "CODEBERG_RELEASE_TOKEN not set — skipping Codeberg publish." TAG="v$VERSION" PRERELEASE=false NOTES_FILE=release-notes.md \
exit 0 APK=app/build/outputs/apk/release/app-release.apk \
fi bash scripts/publish_codeberg_release.sh
TAG="v$VERSION"
APK="app/build/outputs/apk/release/app-release.apk"
if [ ! -f "$APK" ]; then echo "No release APK found — skipping." >&2; exit 1; fi
ASSET_APK="calendula_v${VERSION}.apk"
ASSET_SUM="${ASSET_APK}.sha256"
cp "$APK" "/tmp/$ASSET_APK"
( cd /tmp && sha256sum "$ASSET_APK" > "$ASSET_SUM" )
# Release notes: reuse the section extracted for the Gitea release,
# fall back to the CHANGELOG entry if that step's file is gone.
if [ ! -s release-notes.md ]; then
awk -v ver="$VERSION" '
$0 ~ "^## \\[" ver "\\]" { flag = 1; next }
/^## \[/ { flag = 0 }
flag' CHANGELOG.md > release-notes.md
sed -i -e '/./,$!d' release-notes.md
fi
[ -s release-notes.md ] || echo "_See CHANGELOG.md for ${VERSION}._" > release-notes.md
# The pipeline creates the tag via the Gitea API, which the push mirror
# (sync_on_commit only fires on real git pushes) doesn't propagate
# promptly — so a release POST that carries a target_commitish can
# outrun the mirror and 500 on a commit/tag Codeberg hasn't received.
# Push the tag straight to Codeberg so it's guaranteed present, then
# attach the release to that existing tag with NO target_commitish
# (which is what triggered the 500).
git tag -f "$TAG" "$SHA"
git push -f "https://jlmakiola:${TOKEN}@codeberg.org/jlmakiola/calendula.git" \
"refs/tags/$TAG"
python3 - "$TAG" <<'PY' > cb-payload.json
import json, sys
print(json.dumps({
"tag_name": sys.argv[1],
"name": sys.argv[1],
"body": open("release-notes.md").read(),
"draft": False,
"prerelease": False,
}))
PY
# Create (or update) the release. Codeberg 500s on a POST/GET against a
# tag it has only just received — the release request outruns the
# indexing of the ref we pushed a moment ago — so a single attempt kept
# failing and skipping the mirror even though the very same call
# succeeds seconds later. Retry with backoff, and PATCH in place if a
# release already exists (re-run safe). A 5xx body still exits curl 0,
# so the loop, not `set -e`, controls the flow.
ID=""
for attempt in 1 2 3 4 5 6; do
EXIST=$(curl -s -H "Authorization: token $TOKEN" "$API/releases/tags/$TAG" | jq -r '.id // empty' 2>/dev/null || true)
if [ -n "$EXIST" ]; then
curl -s -o /dev/null -w "release PATCH HTTP %{http_code}\n" -X PATCH \
-H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
-d @cb-payload.json "$API/releases/$EXIST"
ID="$EXIST"; break
fi
CODE=$(curl -s -o cb-response.json -w "%{http_code}" -X POST \
-H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
-d @cb-payload.json "$API/releases")
echo "release POST attempt $attempt HTTP $CODE"
ID=$(jq -r '.id // empty' cb-response.json 2>/dev/null || true)
[ -n "$ID" ] && break
sleep $((attempt * 10))
done
if [ -z "$ID" ]; then echo "Could not resolve Codeberg release id after retries." >&2; exit 1; fi
# Attach APK + checksum, replacing any prior asset of the same name.
for A in "$ASSET_APK" "$ASSET_SUM"; do
OLD=$(curl -s -H "Authorization: token $TOKEN" "$API/releases/$ID/assets" \
| jq -r --arg n "$A" '.[] | select(.name==$n) | .id')
[ -n "$OLD" ] && curl -s -X DELETE -H "Authorization: token $TOKEN" "$API/releases/$ID/assets/$OLD" >/dev/null || true
curl -s -X POST -H "Authorization: token $TOKEN" \
-F "attachment=@/tmp/$A" \
"$API/releases/$ID/assets?name=$A" -o /dev/null -w "asset $A HTTP %{http_code}\n"
done
echo "Published $TAG to Codeberg."
# Play takes an App Bundle, not the APK, so it is a second artifact from # Play takes an App Bundle, not the APK, so it is a second artifact from
# the same source and the same signing config — not a repackage of the # the same source and the same signing config — not a repackage of the
+11 -2
View File
@@ -1,8 +1,17 @@
name: Renovate name: Renovate
on: on:
# Weekly sweep. Mondays 05:00 UTC — this cron owns the cadence; the repo's # Every merge to main. Mirror syncs from Codeberg fire push events here (the
# renovate.json5 deliberately has no internal schedule (avoids double-gating). # same trigger release.yaml relies on), so a merged Renovate PR is followed
# within minutes by a run that rebases the sibling PRs it just conflicted —
# most bumps touch gradle/libs.versions.toml. Outside renovate.json5's
# `schedule` window such a run only maintains existing branches
# (updateNotScheduled), it never opens new PRs. Renovate's own rebases push
# to renovate/* branches, not main, so this cannot loop.
push:
branches: [main]
# Weekly sweep for new updates. Mondays 05:00 UTC, inside the schedule window
# in renovate.json5 — keep the two in step.
schedule: schedule:
- cron: '0 5 * * 1' - cron: '0 5 * * 1'
# Manual run for an on-demand sweep from the Actions tab. # Manual run for an on-demand sweep from the Actions tab.
+45
View File
@@ -7,6 +7,38 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased] ## [Unreleased]
### 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. 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]).
### 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]).
## [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]).
## [2.22.3] — 2026-10-02
### Fixed
- **The store listing is called "Calendula: Calendar" again,** with "Calendar" in each store language. Since 2.22.0 the Play listing comes from the repository, whose title was only "Calendula". The app is unchanged ([#361]).
## [2.22.2] — 2026-10-02 ## [2.22.2] — 2026-10-02
### Fixed ### Fixed
@@ -1829,3 +1861,16 @@ automatically, with zero telemetry and no internet permission.
[#336]: https://codeberg.org/jlmakiola/calendula/issues/336 [#336]: https://codeberg.org/jlmakiola/calendula/issues/336
[#357]: https://codeberg.org/jlmakiola/calendula/issues/357 [#357]: https://codeberg.org/jlmakiola/calendula/issues/357
[#359]: https://codeberg.org/jlmakiola/calendula/issues/359 [#359]: https://codeberg.org/jlmakiola/calendula/issues/359
[#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
+2 -1
View File
@@ -136,7 +136,8 @@ For automatic updates from Codeberg, use
[add Calendula in one tap](https://apps.obtainium.imranr.dev/redirect?r=obtainium://add/https://codeberg.org/jlmakiola/calendula), [add Calendula in one tap](https://apps.obtainium.imranr.dev/redirect?r=obtainium://add/https://codeberg.org/jlmakiola/calendula),
or add it by hand: *Add App*, paste `https://codeberg.org/jlmakiola/calendula`, or add it by hand: *Add App*, paste `https://codeberg.org/jlmakiola/calendula`,
then *Add*. Obtainium then watches the releases and tells you when a new one then *Add*. Obtainium then watches the releases and tells you when a new one
is out. is out. Betas of upcoming versions are published there too, as pre-releases; to
test them, switch on *Include prereleases* for Calendula in Obtainium.
### Google Play ### Google Play
+10 -4
View File
@@ -26,10 +26,14 @@ android {
// These committed values ARE the source of truth for a release: merging // These committed values ARE the source of truth for a release: merging
// a bumped versionName into main triggers .gitea/workflows/release.yaml, // a bumped versionName into main triggers .gitea/workflows/release.yaml,
// which builds this version and then creates the matching vX.Y.Z tag + // which builds this version and then creates the matching vX.Y.Z tag +
// release itself (versionCode is pinned to MAJOR*10000 + MINOR*100 + // release itself. A versionName of X.Y.Z-beta.N pushed to a release/*
// PATCH from versionName, e.g. 2.7.2 -> 20702). See docs/RELEASING.md. // branch instead cuts a Codeberg-only pre-release (beta.yaml).
versionCode = 22202 // versionCode is derived from versionName by scripts/version_info.sh
versionName = "2.22.2" // (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 = 2230004
versionName = "2.23.0-beta.4"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
} }
@@ -171,7 +175,9 @@ dependencies {
implementation("de.jeanlucmakiola.floret:core-time") implementation("de.jeanlucmakiola.floret:core-time")
implementation("de.jeanlucmakiola.floret:core-locale") implementation("de.jeanlucmakiola.floret:core-locale")
implementation("de.jeanlucmakiola.floret:core-crash") implementation("de.jeanlucmakiola.floret:core-crash")
implementation("de.jeanlucmakiola.floret:core-di")
implementation("de.jeanlucmakiola.floret:core-reminders") implementation("de.jeanlucmakiola.floret:core-reminders")
implementation("de.jeanlucmakiola.floret:core-android")
implementation("de.jeanlucmakiola.floret:identity") implementation("de.jeanlucmakiola.floret:identity")
implementation("de.jeanlucmakiola.floret:components") implementation("de.jeanlucmakiola.floret:components")
implementation(libs.kotlinx.coroutines.core) implementation(libs.kotlinx.coroutines.core)
@@ -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()
}
}
+13
View File
@@ -151,6 +151,19 @@
<data android:mimeType="application/ics" /> <data android:mimeType="application/ics" />
</intent-filter> </intent-filter>
<!-- Text shared or selected in another app opens a prefilled new
event (MainActivity.sharedTextExtrasOrNull, 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 <!-- 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: to create a new event, the way the AOSP calendar accepts it:
ACTION_INSERT on the events *dir* mime type, carrying the new ACTION_INSERT on the events *dir* mime type, carrying the new
@@ -25,11 +25,15 @@ import androidx.core.content.IntentCompat
import androidx.core.net.toUri import androidx.core.net.toUri
import androidx.hilt.navigation.compose.hiltViewModel import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.lifecycleScope
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.data.prefs.ThemeMode import de.jeanlucmakiola.calendula.data.prefs.ThemeMode
import de.jeanlucmakiola.calendula.data.prefs.is24Hour import de.jeanlucmakiola.calendula.data.prefs.is24Hour
import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.buildInsertEventForm import de.jeanlucmakiola.calendula.domain.buildInsertEventForm
import de.jeanlucmakiola.calendula.domain.sharedTextOrNull
import de.jeanlucmakiola.calendula.ui.RootScreen import de.jeanlucmakiola.calendula.ui.RootScreen
import de.jeanlucmakiola.calendula.ui.common.LocalShowHourGrid import de.jeanlucmakiola.calendula.ui.common.LocalShowHourGrid
import de.jeanlucmakiola.calendula.ui.common.LocalMultiDayCount import de.jeanlucmakiola.calendula.ui.common.LocalMultiDayCount
@@ -49,13 +53,17 @@ import de.jeanlucmakiola.floret.crash.CrashReportDialog
import de.jeanlucmakiola.floret.crash.CrashReporter import de.jeanlucmakiola.floret.crash.CrashReporter
import de.jeanlucmakiola.floret.crash.submitCrashReport import de.jeanlucmakiola.floret.crash.submitCrashReport
import de.jeanlucmakiola.calendula.ui.theme.CalendulaTheme 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.calendulaTypography
import de.jeanlucmakiola.calendula.ui.theme.resolveFontFamily import de.jeanlucmakiola.calendula.ui.theme.resolveFontFamily
import kotlinx.coroutines.launch
import kotlinx.datetime.LocalDate import kotlinx.datetime.LocalDate
import kotlinx.datetime.TimeZone import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime import kotlinx.datetime.toLocalDateTime
import kotlin.time.Clock import kotlin.time.Clock
import kotlin.time.Instant import kotlin.time.Instant
import javax.inject.Inject
/** A prefilled create form from an external launch, with the source it came from. */ /** A prefilled create form from an external launch, with the source it came from. */
private data class InsertRequest(val form: EventForm, val source: ImportSource) private data class InsertRequest(val form: EventForm, val source: ImportSource)
@@ -63,6 +71,9 @@ private data class InsertRequest(val form: EventForm, val source: ImportSource)
@AndroidEntryPoint @AndroidEntryPoint
class MainActivity : AppCompatActivity() { 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 // 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 // in onCreate read this field live, so androidx's config-change replay
// picks up the in-app override instead of the night resource qualifier. // picks up the in-app override instead of the night resource qualifier.
@@ -82,10 +93,18 @@ class MainActivity : AppCompatActivity() {
private var requestedImportUri by mutableStateOf<Uri?>(null) private var requestedImportUri by mutableStateOf<Uri?>(null)
// A prefilled new-event form from an external ACTION_INSERT launch (another // 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 // app/widget asking us to create an event, issue #30) or shared text (#306).
// CalendarHost, which opens it in the create form for review. // Consumed once by CalendarHost, which opens it in the create form for review.
private var requestedInsert by mutableStateOf<InsertRequest?>(null) private var requestedInsert by mutableStateOf<InsertRequest?>(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
// 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
// An external "edit this event" (ACTION_EDIT on content://.../events/<id>): // An external "edit this event" (ACTION_EDIT on content://.../events/<id>):
// opens the occurrence in the edit form. Same occurrence-key shape as the // opens the occurrence in the edit form. Same occurrence-key shape as the
// detail channel; consumed once by CalendarHost. // detail channel; consumed once by CalendarHost.
@@ -111,9 +130,25 @@ class MainActivity : AppCompatActivity() {
return 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 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 = when (cachedTheme) {
null, ThemeMode.SYSTEM -> systemDark
ThemeMode.LIGHT -> false
ThemeMode.DARK, ThemeMode.BLACK -> true
}
applyEdgeToEdge() applyEdgeToEdge()
lifecycleScope.launch {
settingsPrefs.themeMode.collect { mode ->
WindowThemeCache.write(this@MainActivity, mode)
window.setBackgroundDrawableResource(mode.windowBackgroundRes() ?: R.color.window_background)
}
}
// Android hands the intent that started the task back to onCreate every // 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 // 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 // the system reclaimed the process. Re-running a launch that opens one
@@ -124,7 +159,8 @@ class MainActivity : AppCompatActivity() {
// //
// Only those channels are held back. An .ics import or a prefilled // 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 // 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() val replaying = savedInstanceState != null || intent.isRelaunch()
if (!replaying) { if (!replaying) {
requestedDetailKey = intent.detailKeyOrNull() ?: intent.viewEventKeyOrNull() requestedDetailKey = intent.detailKeyOrNull() ?: intent.viewEventKeyOrNull()
@@ -133,7 +169,11 @@ class MainActivity : AppCompatActivity() {
requestedNav = intent.navRequestOrNull() requestedNav = intent.navRequestOrNull()
?.takeUnless { replaying && it is WidgetNavRequest.OpenEvent } ?.takeUnless { replaying && it is WidgetNavRequest.OpenEvent }
requestedImportUri = intent.importUriOrNull() requestedImportUri = intent.importUriOrNull()
requestedInsert = intent.insertRequestOrNull() val insertOpenBefore = savedInstanceState?.getBoolean(KEY_INSERT_FORM_OPEN) == true
requestedInsert = intent.createRequestOrNull()?.takeIf { !replaying || insertOpenBefore }
insertFormOpen = requestedInsert != null
launchedForInsert = savedInstanceState?.getBoolean(KEY_LAUNCHED_FOR_INSERT)
?: (requestedInsert != null)
if (CrashReporter.shouldPrompt(this)) pendingCrashReport = CrashReporter.pendingReport(this) if (CrashReporter.shouldPrompt(this)) pendingCrashReport = CrashReporter.pendingReport(this)
setContent { setContent {
// One activity-scoped SettingsViewModel drives both the theme here // One activity-scoped SettingsViewModel drives both the theme here
@@ -143,7 +183,7 @@ class MainActivity : AppCompatActivity() {
val darkTheme = when (settings.themeMode) { val darkTheme = when (settings.themeMode) {
ThemeMode.SYSTEM -> isSystemInDarkTheme() ThemeMode.SYSTEM -> isSystemInDarkTheme()
ThemeMode.LIGHT -> false ThemeMode.LIGHT -> false
ThemeMode.DARK -> true ThemeMode.DARK, ThemeMode.BLACK -> true
} }
// onCreate can only see the night resource qualifier, not the in-app // onCreate can only see the night resource qualifier, not the in-app
// override — re-apply from the resolved theme so the bar icons follow // override — re-apply from the resolved theme so the bar icons follow
@@ -183,6 +223,7 @@ class MainActivity : AppCompatActivity() {
CalendulaTheme( CalendulaTheme(
darkTheme = darkTheme, darkTheme = darkTheme,
dynamicColor = settings.dynamicColor, dynamicColor = settings.dynamicColor,
pureBlack = settings.themeMode == ThemeMode.BLACK,
typography = typography, typography = typography,
) { ) {
Box(modifier = Modifier.fillMaxSize()) { Box(modifier = Modifier.fillMaxSize()) {
@@ -204,6 +245,10 @@ class MainActivity : AppCompatActivity() {
requestedInsertForm = requestedInsert?.form, requestedInsertForm = requestedInsert?.form,
requestedInsertSource = requestedInsert?.source ?: ImportSource.Insert, requestedInsertSource = requestedInsert?.source ?: ImportSource.Insert,
onInsertConsumed = { requestedInsert = null }, onInsertConsumed = { requestedInsert = null },
onExternalFormClosed = {
insertFormOpen = false
if (launchedForInsert) finish()
},
requestedEditKey = requestedEditKey, requestedEditKey = requestedEditKey,
onEditKeyConsumed = { requestedEditKey = null }, onEditKeyConsumed = { requestedEditKey = null },
) )
@@ -245,18 +290,33 @@ class MainActivity : AppCompatActivity() {
) )
} }
override fun onStart() {
super.onStart()
// Changes made while we were away may never have notified us (#364).
calendarRepository.refresh()
}
override fun onResume() { override fun onResume() {
super.onResume() super.onResume()
// Reaching a running UI means startup succeeded; reset the loop trail. // Reaching a running UI means startup succeeded; reset the loop trail.
CrashReporter.markHealthy(this) CrashReporter.markHealthy(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) { override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent) super.onNewIntent(intent)
(intent.detailKeyOrNull() ?: intent.viewEventKeyOrNull())?.let { requestedDetailKey = it } (intent.detailKeyOrNull() ?: intent.viewEventKeyOrNull())?.let { requestedDetailKey = it }
intent.navRequestOrNull()?.let { requestedNav = it } intent.navRequestOrNull()?.let { requestedNav = it }
intent.importUriOrNull()?.let { requestedImportUri = it } intent.importUriOrNull()?.let { requestedImportUri = it }
intent.insertRequestOrNull()?.let { requestedInsert = it } intent.createRequestOrNull()?.let {
requestedInsert = it
insertFormOpen = true
}
intent.editEventKeyOrNull()?.let { requestedEditKey = it } intent.editEventKeyOrNull()?.let { requestedEditKey = it }
} }
@@ -278,7 +338,9 @@ class MainActivity : AppCompatActivity() {
private fun Intent.importUriOrNull(): Uri? { private fun Intent.importUriOrNull(): Uri? {
val uri = when (action) { val uri = when (action) {
Intent.ACTION_VIEW -> data Intent.ACTION_VIEW -> data
// Plain text is a create (#306), never a file to import.
Intent.ACTION_SEND -> IntentCompat.getParcelableExtra(this, Intent.EXTRA_STREAM, Uri::class.java) Intent.ACTION_SEND -> IntentCompat.getParcelableExtra(this, Intent.EXTRA_STREAM, Uri::class.java)
.takeUnless { type == SHARED_TEXT_TYPE }
else -> null else -> null
} ?: return null } ?: return null
// The calendar "view time" Uri (a date tap) is also ACTION_VIEW/content; // The calendar "view time" Uri (a date tap) is also ACTION_VIEW/content;
@@ -323,6 +385,36 @@ class MainActivity : AppCompatActivity() {
return InsertRequest(form, if (namesEnd) ImportSource.Insert else ImportSource.InsertOpenEnded) 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) {
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)
}
/** A Long extra's value, or null when the extra is absent. */ /** A Long extra's value, or null when the extra is absent. */
private fun Intent.longExtraOrNull(key: String): Long? = private fun Intent.longExtraOrNull(key: String): Long? =
if (hasExtra(key)) getLongExtra(key, 0L) else null if (hasExtra(key)) getLongExtra(key, 0L) else null
@@ -448,6 +540,9 @@ class MainActivity : AppCompatActivity() {
// The calendar provider's authority/host. A date tap arrives as // The calendar provider's authority/host. A date tap arrives as
// ACTION_VIEW on content://com.android.calendar/time/<epochMillis>. // ACTION_VIEW on content://com.android.calendar/time/<epochMillis>.
private const val CALENDAR_PROVIDER_HOST = "com.android.calendar" private const val CALENDAR_PROVIDER_HOST = "com.android.calendar"
private const val SHARED_TEXT_TYPE = "text/plain"
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_EVENT_ID = "de.jeanlucmakiola.calendula.extra.EVENT_ID"
private const val EXTRA_BEGIN_MILLIS = "de.jeanlucmakiola.calendula.extra.BEGIN" private const val EXTRA_BEGIN_MILLIS = "de.jeanlucmakiola.calendula.extra.BEGIN"
@@ -5,12 +5,10 @@ import android.app.NotificationChannel
import android.app.NotificationManager import android.app.NotificationManager
import android.app.PendingIntent import android.app.PendingIntent
import android.content.Context import android.content.Context
import android.content.pm.PackageManager
import android.os.Build import android.os.Build
import android.util.Log import android.util.Log
import androidx.core.app.NotificationCompat import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import androidx.core.net.toUri import androidx.core.net.toUri
import androidx.work.CoroutineWorker import androidx.work.CoroutineWorker
import androidx.work.ExistingPeriodicWorkPolicy import androidx.work.ExistingPeriodicWorkPolicy
@@ -28,6 +26,7 @@ import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
import de.jeanlucmakiola.calendula.data.ics.IcsExporter import de.jeanlucmakiola.calendula.data.ics.IcsExporter
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.domain.ics.IcsWriter import de.jeanlucmakiola.calendula.domain.ics.IcsWriter
import de.jeanlucmakiola.floret.android.hasPermission
import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.first
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import kotlin.time.Clock import kotlin.time.Clock
@@ -133,8 +132,7 @@ class BackupWorker(
private fun notifyFailure(context: Context) { private fun notifyFailure(context: Context) {
val canPost = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || val canPost = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == context.hasPermission(Manifest.permission.POST_NOTIFICATIONS)
PackageManager.PERMISSION_GRANTED
if (!canPost) return if (!canPost) return
val manager = NotificationManagerCompat.from(context) val manager = NotificationManagerCompat.from(context)
manager.createNotificationChannel( manager.createNotificationChannel(
@@ -1,13 +1,12 @@
package de.jeanlucmakiola.calendula.data.calendar package de.jeanlucmakiola.calendula.data.calendar
import de.jeanlucmakiola.floret.time.toEpochMillis import de.jeanlucmakiola.floret.android.hasPermission
import de.jeanlucmakiola.floret.time.toKotlinInstantFromEpochMillis import de.jeanlucmakiola.floret.time.toKotlinInstantFromEpochMillis
import android.Manifest import android.Manifest
import android.content.ContentResolver import android.content.ContentResolver
import android.content.ContentUris import android.content.ContentUris
import android.content.ContentValues import android.content.ContentValues
import android.content.Context import android.content.Context
import android.content.pm.PackageManager
import android.database.ContentObserver import android.database.ContentObserver
import android.database.Cursor import android.database.Cursor
import android.net.Uri import android.net.Uri
@@ -15,7 +14,6 @@ import android.os.Handler
import android.os.Looper import android.os.Looper
import android.provider.CalendarContract import android.provider.CalendarContract
import android.util.Log import android.util.Log
import androidx.core.content.ContextCompat
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.calendula.domain.Attendee import de.jeanlucmakiola.calendula.domain.Attendee
import de.jeanlucmakiola.calendula.domain.AttendeeRelationship import de.jeanlucmakiola.calendula.domain.AttendeeRelationship
@@ -28,7 +26,6 @@ import de.jeanlucmakiola.calendula.domain.curatedForPicker
import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.domain.EventSearch import de.jeanlucmakiola.calendula.domain.EventSearch
import de.jeanlucmakiola.calendula.domain.EventStatus
import de.jeanlucmakiola.calendula.domain.Reminder import de.jeanlucmakiola.calendula.domain.Reminder
import de.jeanlucmakiola.calendula.domain.SearchCandidate import de.jeanlucmakiola.calendula.domain.SearchCandidate
import de.jeanlucmakiola.calendula.domain.contacts.MANAGED_UID_PREFIX import de.jeanlucmakiola.calendula.domain.contacts.MANAGED_UID_PREFIX
@@ -36,7 +33,10 @@ import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
import de.jeanlucmakiola.calendula.domain.ics.IcsEvent import de.jeanlucmakiola.calendula.domain.ics.IcsEvent
import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent
import de.jeanlucmakiola.calendula.domain.ics.semanticReminderMinutes import de.jeanlucmakiola.calendula.domain.ics.semanticReminderMinutes
import de.jeanlucmakiola.calendula.domain.ics.parseRfc2445DurationMillis
import de.jeanlucmakiola.calendula.domain.rruleTruncatedAt import de.jeanlucmakiola.calendula.domain.rruleTruncatedAt
import de.jeanlucmakiola.calendula.domain.toEditForm
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toJavaLocalDate import kotlinx.datetime.toJavaLocalDate
import java.time.Instant import java.time.Instant
import java.time.LocalDate import java.time.LocalDate
@@ -238,8 +238,10 @@ interface CalendarDataSource {
* and cancelled occurrences) to [targetCalendarId], returning the new * and cancelled occurrences) to [targetCalendarId], returning the new
* `Events._ID`. `CALENDAR_ID` is sync-adapter-owned and can't be updated in * `Events._ID`. `CALENDAR_ID` is sync-adapter-owned and can't be updated in
* place, so this is copy+delete: the row is re-inserted on the target (its * place, so this is copy+delete: the row is re-inserted on the target (its
* `UID_2445` preserved), its exceptions, reminders and editable guests * `UID_2445` preserved), its reminders and editable guests copied, its
* replayed, the [original]→[updated] field edits applied, then the source * exceptions turned into EXDATEs (modified ones also into standalone events,
* as the new row has no `_sync_id` to attach them to), the
* [original]→[updated] field edits applied, then the source
* deleted. The source is removed only once the copy fully succeeds; a failure * deleted. The source is removed only once the copy fully succeeds; a failure
* before that rolls the new event back, leaving the original untouched. * before that rolls the new event back, leaving the original untouched.
* [allDayReminderTimeMinutes]: see [insertEvent]. * [allDayReminderTimeMinutes]: see [insertEvent].
@@ -323,8 +325,7 @@ class AndroidCalendarDataSource @Inject constructor(
private val registeredObservers = mutableSetOf<ContentObserver>() private val registeredObservers = mutableSetOf<ContentObserver>()
private fun hasCalendarPermission(): Boolean = private fun hasCalendarPermission(): Boolean =
ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CALENDAR) == context.hasPermission(Manifest.permission.READ_CALENDAR)
PackageManager.PERMISSION_GRANTED
/** /**
* Attach any not-yet-registered observers to the provider, but only once the * Attach any not-yet-registered observers to the provider, but only once the
@@ -460,8 +461,7 @@ class AndroidCalendarDataSource @Inject constructor(
} }
override fun canWriteCalendars(): Boolean = override fun canWriteCalendars(): Boolean =
ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_CALENDAR) == context.hasPermission(Manifest.permission.WRITE_CALENDAR)
PackageManager.PERMISSION_GRANTED
override fun createManagedCalendar(displayName: String, color: Int, type: SpecialDateType): Long { override fun createManagedCalendar(displayName: String, color: Int, type: SpecialDateType): Long {
val name = displayName.trim() val name = displayName.trim()
@@ -610,8 +610,11 @@ class AndroidCalendarDataSource @Inject constructor(
// cancelled exception for the one instance (#47). A NULL status is a // cancelled exception for the one instance (#47). A NULL status is a
// normal, un-cancelled event, so it must survive the filter — a bare // normal, un-cancelled event, so it must survive the filter — a bare
// `!= CANCELED` would drop it (NULL != 2 is NULL, not true). // `!= CANCELED` would drop it (NULL != 2 is NULL, not true).
"${CalendarContract.Instances.STATUS} IS NULL OR " + // DELETED = 0: a provider that soft-deletes may keep the row's
"${CalendarContract.Instances.STATUS} != ${CalendarContract.Events.STATUS_CANCELED}", // instances until a purge (#364).
"(${CalendarContract.Instances.STATUS} IS NULL OR " +
"${CalendarContract.Instances.STATUS} != ${CalendarContract.Events.STATUS_CANCELED}) AND " +
"${CalendarContract.Events.DELETED} = 0",
null, null,
CalendarContract.Instances.BEGIN + " ASC", CalendarContract.Instances.BEGIN + " ASC",
)?.use { c -> c.mapAllNotNull { CursorColumnReader(c).toEventInstance() } } ?: emptyList() )?.use { c -> c.mapAllNotNull { CursorColumnReader(c).toEventInstance() } } ?: emptyList()
@@ -1070,10 +1073,11 @@ class AndroidCalendarDataSource @Inject constructor(
buildMovedMasterValues(master.event, targetCalendarId, uid).toContentValues(), buildMovedMasterValues(master.event, targetCalendarId, uid).toContentValues(),
)?.let(ContentUris::parseId) )?.let(ContentUris::parseId)
?: throw WriteFailedException("insert moved event into calendar id=$targetCalendarId") ?: throw WriteFailedException("insert moved event into calendar id=$targetCalendarId")
val detached = mutableListOf<Long>()
try { try {
copyReminderRows(fromEventId = eventId, toEventId = newEventId) copyReminderRows(fromEventId = eventId, toEventId = newEventId)
insertAttendees(newEventId, editableAttendees(eventId)) insertAttendees(newEventId, editableAttendees(eventId))
copyExceptions(fromEventId = eventId, toEventId = newEventId) copyExceptions(eventId, newEventId, targetCalendarId, allDayReminderTimeMinutes, detached)
// Apply the user's field edits exactly as a same-calendar "all // Apply the user's field edits exactly as a same-calendar "all
// events" save would: the moved master carries the source's values, // events" save would: the moved master carries the source's values,
// so the dirty diff against [original] writes only what changed // so the dirty diff against [original] writes only what changed
@@ -1083,6 +1087,7 @@ class AndroidCalendarDataSource @Inject constructor(
// Undo the partial copy so a failed move leaves nothing behind; the // Undo the partial copy so a failed move leaves nothing behind; the
// source is still intact (it's deleted only past this point). // source is still intact (it's deleted only past this point).
runCatching { deleteEvent(newEventId) } runCatching { deleteEvent(newEventId) }
detached.forEach(::rollBackDetached)
throw t throw t
} }
deleteEvent(eventId) deleteEvent(eventId)
@@ -1159,44 +1164,47 @@ class AndroidCalendarDataSource @Inject constructor(
} }
/** /**
* Replay every exception of the series [fromEventId] against the moved series * Carry every exception of the series [fromEventId] over to the moved series
* [toEventId]. The copy preserved the recurrence skeleton, so each occurrence * [toEventId]. The moved row has no `_sync_id` yet, so exception rows would
* time still resolves: a cancelled occurrence is re-hidden with a cancelled * never attach to it ([deleteOccurrence], [detachOccurrence]): a cancelled
* exception, a modified one is re-inserted with its fields (then its reminders * occurrence becomes an EXDATE, a modified one an EXDATE plus a standalone
* reconciled and editable guests copied). No-op for a non-recurring event. * event on [targetCalendarId], its id added to [detached] for rollback.
*/ */
private fun copyExceptions(fromEventId: Long, toEventId: Long) { private fun copyExceptions(
queryExceptionRows(fromEventId).forEach { ex -> fromEventId: Long,
if (ex.isCancelled) { toEventId: Long,
val values = ContentValues().apply { targetCalendarId: Long,
put(CalendarContract.Events.ORIGINAL_INSTANCE_TIME, ex.originalInstanceMillis) allDayReminderTimeMinutes: Int,
put(CalendarContract.Events.STATUS, CalendarContract.Events.STATUS_CANCELED) detached: MutableList<Long>,
} ) {
resolver.insert( val exceptions = queryExceptionRows(fromEventId)
ContentUris.withAppendedId( if (exceptions.isEmpty()) return
CalendarContract.Events.CONTENT_EXCEPTION_URI, toEventId, val zone = TimeZone.currentSystemDefault()
), exceptions.filterNot { it.isCancelled }.forEach { ex ->
values, val detail = eventDetail(ex.exceptionEventId, allDayReminderTimeMinutes)
) ?: throw WriteFailedException("copy cancelled occurrence to event id=$toEventId") ?: throw WriteFailedException("read modified occurrence id=${ex.exceptionEventId}")
} else { val endMillis = ex.dtEndMillis ?: (ex.dtStartMillis + parseRfc2445DurationMillis(ex.duration))
val uri = resolver.insert( val form = detail.toEditForm(ex.dtStartMillis, endMillis, zone)
ContentUris.withAppendedId( .copy(calendarId = targetCalendarId)
CalendarContract.Events.CONTENT_EXCEPTION_URI, toEventId, .toDetachedOccurrence()
), detached += insertEvent(form, allDayReminderTimeMinutes)
buildCopiedExceptionValues(ex).toContentValues(),
) ?: throw WriteFailedException("copy modified occurrence to event id=$toEventId")
val newExceptionId = ContentUris.parseId(uri)
// The provider may clone the parent's reminders onto the new
// exception; reconcile to the source exception's exact set so
// they neither double nor drop. Same DTSTART → same all-day
// encoding, so the stored offsets match directly.
reconcileReminders(
newExceptionId,
queryReminders(ex.exceptionEventId).map { it.minutes },
)
insertAttendees(newExceptionId, editableAttendees(ex.exceptionEventId))
}
} }
val row = querySeriesRow(toEventId)
val values = buildOccurrencesExdateValues(
existingExdate = row.exdate,
occurrences = exceptions.map { it.originalInstanceMillis },
dtStartMillis = row.dtStartMillis,
rrule = row.rrule,
rdate = row.rdate,
duration = row.duration,
timezone = row.timezone,
allDay = row.allDay,
)
val updated = resolver.update(
ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, toEventId),
values.toContentValues(), null, null,
)
if (updated == 0) throw WriteFailedException("exdate moved exceptions event id=$toEventId")
} }
/** The series' exception rows (modified + cancelled), oldest occurrence first. */ /** The series' exception rows (modified + cancelled), oldest occurrence first. */
@@ -1215,18 +1223,10 @@ class AndroidCalendarDataSource @Inject constructor(
exceptionEventId = r.getLong(ExceptionProjection.IDX_ID), exceptionEventId = r.getLong(ExceptionProjection.IDX_ID),
originalInstanceMillis = r.getLong(ExceptionProjection.IDX_ORIGINAL_INSTANCE_TIME), originalInstanceMillis = r.getLong(ExceptionProjection.IDX_ORIGINAL_INSTANCE_TIME),
isCancelled = status == CalendarContract.Events.STATUS_CANCELED, isCancelled = status == CalendarContract.Events.STATUS_CANCELED,
status = status,
title = r.getString(ExceptionProjection.IDX_TITLE).orEmpty(),
isAllDay = r.getInt(ExceptionProjection.IDX_ALL_DAY) != 0,
dtStartMillis = r.getLong(ExceptionProjection.IDX_DTSTART), dtStartMillis = r.getLong(ExceptionProjection.IDX_DTSTART),
dtEndMillis = r.getLong(ExceptionProjection.IDX_DTEND) dtEndMillis = r.getLong(ExceptionProjection.IDX_DTEND)
.takeUnless { r.isNull(ExceptionProjection.IDX_DTEND) }, .takeUnless { r.isNull(ExceptionProjection.IDX_DTEND) },
duration = r.getString(ExceptionProjection.IDX_DURATION), duration = r.getString(ExceptionProjection.IDX_DURATION),
timezone = r.getString(ExceptionProjection.IDX_EVENT_TIMEZONE),
availability = r.getInt(ExceptionProjection.IDX_AVAILABILITY),
accessLevel = r.getInt(ExceptionProjection.IDX_ACCESS_LEVEL),
location = r.getString(ExceptionProjection.IDX_LOCATION),
description = r.getString(ExceptionProjection.IDX_DESCRIPTION),
) )
} }
} ?: emptyList() } ?: emptyList()
@@ -15,6 +15,9 @@ import kotlin.time.Instant
interface CalendarRepository { interface CalendarRepository {
fun calendars(): Flow<List<CalendarSource>> fun calendars(): Flow<List<CalendarSource>>
fun instances(range: ClosedRange<Instant>): Flow<List<EventInstance>> fun instances(range: ClosedRange<Instant>): Flow<List<EventInstance>>
/** Re-query every open [calendars] / [instances] flow. */
fun refresh()
suspend fun eventDetail(eventId: Long): EventDetail suspend fun eventDetail(eventId: Long): EventDetail
/** /**
@@ -1,8 +1,8 @@
package de.jeanlucmakiola.calendula.data.calendar package de.jeanlucmakiola.calendula.data.calendar
import android.util.Log import android.util.Log
import de.jeanlucmakiola.floret.di.IoDispatcher
import de.jeanlucmakiola.floret.time.toEpochMillis 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.CalendarPrefs
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.CalendarSource
@@ -14,6 +14,7 @@ import de.jeanlucmakiola.calendula.domain.SearchCandidate
import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary
import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.combine
@@ -51,21 +52,37 @@ class CalendarRepositoryImpl @Inject constructor(
private suspend fun allDayReminderTimeMinutes(): Int = private suspend fun allDayReminderTimeMinutes(): Int =
settingsPrefs.allDayReminderTimeMinutes.first() settingsPrefs.allDayReminderTimeMinutes.first()
// DROP_OLDEST: tryEmit never fails, so a tick that lands while a subscriber
// still holds the previous one is never lost (#364).
private val ticks = MutableSharedFlow<Unit>( private val ticks = MutableSharedFlow<Unit>(
replay = 0, replay = 0,
extraBufferCapacity = 1, extraBufferCapacity = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST,
) )
/** /**
* Bumped on every provider notification, so one tick's calendar read can be * Bumped on every [refresh], so one tick's calendar read can be
* shared by everything that needs it (see [calendarsSnapshot]). * shared by everything that needs it (see [calendarsSnapshot]).
*/ */
private val generation = AtomicLong(0L) private val generation = AtomicLong(0L)
init { init {
dataSource.registerChangeListener { dataSource.registerChangeListener(::refresh)
generation.incrementAndGet() }
ticks.tryEmit(Unit)
// Writes re-query on their own too: some providers never notify the
// observer, which left every view stale until a restart (#364).
override fun refresh() {
generation.incrementAndGet()
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) {
try {
block()
} finally {
refresh()
} }
} }
@@ -181,7 +198,7 @@ class CalendarRepositoryImpl @Inject constructor(
displayName: String, displayName: String,
color: Int, color: Int,
description: String?, description: String?,
): Long = withContext(io) { ): Long = write {
dataSource.createLocalCalendar(displayName, color, description) dataSource.createLocalCalendar(displayName, color, description)
} }
@@ -190,13 +207,13 @@ class CalendarRepositoryImpl @Inject constructor(
displayName: String, displayName: String,
color: Int, color: Int,
description: String?, description: String?,
) = withContext(io) { dataSource.updateCalendar(id, displayName, color, description) } ) = write { dataSource.updateCalendar(id, displayName, color, description) }
override suspend fun deleteCalendar(id: Long) = override suspend fun deleteCalendar(id: Long) =
withContext(io) { dataSource.deleteCalendar(id) } write { dataSource.deleteCalendar(id) }
override suspend fun setCalendarsVisible(ids: Collection<Long>, visible: Boolean) = override suspend fun setCalendarsVisible(ids: Collection<Long>, visible: Boolean) =
withContext(io) { write {
if (dataSource.canWriteCalendars()) { if (dataSource.canWriteCalendars()) {
ids.forEach { dataSource.setCalendarVisible(it, visible) } ids.forEach { dataSource.setCalendarVisible(it, visible) }
// Nothing of ours is left waiting for the provider once the // Nothing of ours is left waiting for the provider once the
@@ -217,7 +234,7 @@ class CalendarRepositoryImpl @Inject constructor(
override suspend fun importEvents( override suspend fun importEvents(
targetCalendarId: Long, targetCalendarId: Long,
events: List<ParsedIcsEvent>, events: List<ParsedIcsEvent>,
): IcsImportSummary = withContext(io) { ): IcsImportSummary = write {
val existing = dataSource.existingUids(targetCalendarId) val existing = dataSource.existingUids(targetCalendarId)
// Both are per-calendar, not per-event: looking them up once keeps a // Both are per-calendar, not per-event: looking them up once keeps a
// thousand-event restore to two extra queries. The palette is the // thousand-event restore to two extra queries. The palette is the
@@ -268,7 +285,7 @@ class CalendarRepositoryImpl @Inject constructor(
) )
} }
override suspend fun createEvent(form: EventForm): Long = withContext(io) { override suspend fun createEvent(form: EventForm): Long = write {
dataSource.insertEvent(form, allDayReminderTimeMinutes()) dataSource.insertEvent(form, allDayReminderTimeMinutes())
} }
@@ -276,11 +293,11 @@ class CalendarRepositoryImpl @Inject constructor(
eventId: Long, eventId: Long,
original: EventForm, original: EventForm,
updated: EventForm, updated: EventForm,
) = withContext(io) { ) = write {
dataSource.updateEvent(eventId, original, updated, allDayReminderTimeMinutes()) dataSource.updateEvent(eventId, original, updated, allDayReminderTimeMinutes())
} }
override suspend fun deleteEvent(eventId: Long) = withContext(io) { override suspend fun deleteEvent(eventId: Long) = write {
dataSource.deleteEvent(eventId) dataSource.deleteEvent(eventId)
} }
@@ -289,7 +306,7 @@ class CalendarRepositoryImpl @Inject constructor(
targetCalendarId: Long, targetCalendarId: Long,
original: EventForm, original: EventForm,
updated: EventForm, updated: EventForm,
): Long = withContext(io) { ): Long = write {
dataSource.moveEvent( dataSource.moveEvent(
eventId, targetCalendarId, original, updated, allDayReminderTimeMinutes(), eventId, targetCalendarId, original, updated, allDayReminderTimeMinutes(),
) )
@@ -300,7 +317,7 @@ class CalendarRepositoryImpl @Inject constructor(
beginMillis: Long, beginMillis: Long,
original: EventForm, original: EventForm,
form: EventForm, form: EventForm,
): Long = withContext(io) { ): Long = write {
dataSource.updateOccurrence( dataSource.updateOccurrence(
eventId, beginMillis, original, form, allDayReminderTimeMinutes(), eventId, beginMillis, original, form, allDayReminderTimeMinutes(),
) )
@@ -311,20 +328,20 @@ class CalendarRepositoryImpl @Inject constructor(
beginMillis: Long, beginMillis: Long,
original: EventForm, original: EventForm,
updated: EventForm, updated: EventForm,
): Long = withContext(io) { ): Long = write {
dataSource.updateEventFromOccurrence( dataSource.updateEventFromOccurrence(
eventId, beginMillis, original, updated, allDayReminderTimeMinutes(), eventId, beginMillis, original, updated, allDayReminderTimeMinutes(),
) )
} }
override suspend fun deleteOccurrence(eventId: Long, beginMillis: Long) = withContext(io) { override suspend fun deleteOccurrence(eventId: Long, beginMillis: Long) = write {
dataSource.deleteOccurrence(eventId, beginMillis) dataSource.deleteOccurrence(eventId, beginMillis)
} }
override suspend fun deleteEventFromOccurrence( override suspend fun deleteEventFromOccurrence(
eventId: Long, eventId: Long,
beginMillis: Long, beginMillis: Long,
) = withContext(io) { ) = write {
dataSource.deleteEventFromOccurrence(eventId, beginMillis) dataSource.deleteEventFromOccurrence(eventId, beginMillis)
} }
@@ -4,15 +4,15 @@ import android.Manifest
import android.content.Context import android.content.Context
import android.content.pm.PackageManager import android.content.pm.PackageManager
import android.util.Log import android.util.Log
import androidx.core.content.ContextCompat
import dagger.hilt.EntryPoint import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent import dagger.hilt.components.SingletonComponent
import de.jeanlucmakiola.calendula.data.di.IoDispatcher
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
import de.jeanlucmakiola.calendula.domain.calendarVisibilityPlan import de.jeanlucmakiola.calendula.domain.calendarVisibilityPlan
import de.jeanlucmakiola.calendula.domain.hasSystemHiddenCalendars 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.CoroutineDispatcher
import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
@@ -47,7 +47,7 @@ class CalendarVisibilityReconciler @Inject constructor(
// Settled ahead of the permission gate, so an update installed // Settled ahead of the permission gate, so an update installed
// before the first grant can't later look like an upgrade. // before the first grant can't later look like an upgrade.
if (!isUpgradeInstall()) settleNoticeOnce(pending = false) 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 pending = prefs.pendingDisabledCalendarIds.first()
val noticeSettled = prefs.visibilityNoticePending.first() != null val noticeSettled = prefs.visibilityNoticePending.first() != null
if (pending.isEmpty() && noticeSettled) return@withContext 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. // Both decisions below are one-way, so leave them to the next run.
if (calendars.isEmpty()) return@withContext if (calendars.isEmpty()) return@withContext
settleNoticeOnce(hasSystemHiddenCalendars(calendars, pending)) settleNoticeOnce(hasSystemHiddenCalendars(calendars, pending))
if (pending.isEmpty() || !hasPermission(Manifest.permission.WRITE_CALENDAR)) { if (pending.isEmpty() || !context.hasPermission(Manifest.permission.WRITE_CALENDAR)) {
return@withContext return@withContext
} }
val plan = calendarVisibilityPlan(calendars, pending) val plan = calendarVisibilityPlan(calendars, pending)
@@ -97,9 +97,6 @@ class CalendarVisibilityReconciler @Inject constructor(
false false
} }
private fun hasPermission(permission: String): Boolean =
ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
/** Lets non-injectable entry points (the Application) reach the reconciler. */ /** Lets non-injectable entry points (the Application) reach the reconciler. */
@EntryPoint @EntryPoint
@InstallIn(SingletonComponent::class) @InstallIn(SingletonComponent::class)
@@ -1,15 +1,19 @@
package de.jeanlucmakiola.calendula.data.calendar package de.jeanlucmakiola.calendula.data.calendar
import de.jeanlucmakiola.calendula.domain.instantIn
import kotlinx.datetime.toKotlinTimeZone
import android.provider.CalendarContract import android.provider.CalendarContract
import de.jeanlucmakiola.calendula.domain.AccessLevel import de.jeanlucmakiola.calendula.domain.AccessLevel
import de.jeanlucmakiola.calendula.domain.Availability import de.jeanlucmakiola.calendula.domain.Availability
import de.jeanlucmakiola.calendula.domain.EventColorOption import de.jeanlucmakiola.calendula.domain.EventColorOption
import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.FormTime
import de.jeanlucmakiola.calendula.domain.EventStatus import de.jeanlucmakiola.calendula.domain.EventStatus
import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent
import de.jeanlucmakiola.calendula.domain.nearestTo import de.jeanlucmakiola.calendula.domain.nearestTo
import kotlinx.datetime.toJavaLocalDate import kotlinx.datetime.toJavaLocalDate
import kotlinx.datetime.toJavaLocalDateTime import kotlinx.datetime.toJavaLocalDateTime
import kotlinx.datetime.toJavaZoneOffset
import java.time.Duration import java.time.Duration
import java.time.Instant import java.time.Instant
import java.time.ZoneId import java.time.ZoneId
@@ -48,8 +52,8 @@ internal fun EventForm.toWriteTimes(zone: ZoneId): EventWriteTimes = if (isAllDa
} else { } else {
val writeZone = writeZone(zone) val writeZone = writeZone(zone)
EventWriteTimes( EventWriteTimes(
dtStartMillis = start.toJavaLocalDateTime().atZone(writeZone).toInstant().toEpochMilli(), dtStartMillis = start.instantIn(writeZone.toKotlinTimeZone()).toEpochMilliseconds(),
dtEndMillis = end.toJavaLocalDateTime().atZone(writeZone).toInstant().toEpochMilli(), dtEndMillis = end.instantIn(writeZone.toKotlinTimeZone()).toEpochMilliseconds(),
timezone = writeZone.id, timezone = writeZone.id,
) )
} }
@@ -75,7 +79,7 @@ private fun EventForm.writeZone(deviceZone: ZoneId): ZoneId = if (isAllDay) {
private fun EventForm.anchorLocal(): JavaLocalDateTime = if (isAllDay) { private fun EventForm.anchorLocal(): JavaLocalDateTime = if (isAllDay) {
start.date.toJavaLocalDate().atStartOfDay() start.date.toJavaLocalDate().atStartOfDay()
} else { } else {
start.toJavaLocalDateTime() start.dateTime.toJavaLocalDateTime()
} }
/** /**
@@ -181,7 +185,8 @@ internal fun buildEventUpdateValues(
// A zone change counts as a time change even when the wall-clock is // 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 // 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 || val timesChanged = updated.start != original.start ||
updated.end != original.end || updated.end != original.end ||
updated.isAllDay != original.isAllDay || updated.isAllDay != original.isAllDay ||
@@ -209,15 +214,23 @@ internal fun buildEventUpdateValues(
// is a different offset from the series anchor's whenever a DST boundary // 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 // sits between them, or whenever the zone itself changed. Working in wall
// clock keeps "09:00" meaning 09:00 at both ends. // clock keeps "09:00" meaning 09:00 at both ends.
val seriesLocal = Instant.ofEpochMilli(seriesDtStartMillis) val seriesZoned = Instant.ofEpochMilli(seriesDtStartMillis).atZone(original.writeZone(zone))
.atZone(original.writeZone(zone)).toLocalDateTime() val seriesLocal = seriesZoned.toLocalDateTime()
val wallClockShift = Duration.between(original.anchorLocal(), updated.anchorLocal()) val wallClockShift = Duration.between(original.anchorLocal(), updated.anchorLocal())
val shifted = seriesLocal.plus(wallClockShift) val shifted = seriesLocal.plus(wallClockShift)
// An all-day series anchor must sit on a UTC midnight. A pure day move // 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 // already lands there (both ends are midnights), but *switching* a
// recurring event to all-day shifts by a time-of-day too, so snap. // 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 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.DTSTART, newSeriesStart.toInstant().toEpochMilli())
put(CalendarContract.Events.DTEND, null) put(CalendarContract.Events.DTEND, null)
put(CalendarContract.Events.RRULE, updated.rrule) put(CalendarContract.Events.RRULE, updated.rrule)
@@ -359,48 +372,11 @@ internal data class ExceptionRowSnapshot(
val exceptionEventId: Long, val exceptionEventId: Long,
val originalInstanceMillis: Long, val originalInstanceMillis: Long,
val isCancelled: Boolean, val isCancelled: Boolean,
val status: Int?,
val title: String,
val isAllDay: Boolean,
val dtStartMillis: Long, val dtStartMillis: Long,
val dtEndMillis: Long?, val dtEndMillis: Long?,
val duration: String?, 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 * Column values for a *cancelled*-occurrence exception row ("delete only this
* event"): inserting them at `Events.CONTENT_EXCEPTION_URI/<id>` makes the * event"): inserting them at `Events.CONTENT_EXCEPTION_URI/<id>` makes the
@@ -466,9 +442,24 @@ internal fun buildOccurrenceExdateValues(
duration: String?, duration: String?,
timezone: String?, timezone: String?,
allDay: Int, 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( ): Map<String, Any?> = mapOf(
CalendarContract.Events.EXDATE to CalendarContract.Events.EXDATE to occurrences.fold(existingExdate) { exdate, millis ->
mergedExdate(existingExdate, occurrenceMillis, allDay != 0, timezone), mergedExdate(exdate, millis, allDay != 0, timezone)
},
CalendarContract.Events.DTSTART to dtStartMillis, CalendarContract.Events.DTSTART to dtStartMillis,
CalendarContract.Events.RRULE to rrule, CalendarContract.Events.RRULE to rrule,
CalendarContract.Events.RDATE to rdate, CalendarContract.Events.RDATE to rdate,
@@ -251,40 +251,26 @@ internal object MoveMasterProjection {
/** /**
* The exception rows of a recurring series (`ORIGINAL_ID` = the series), read to * 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 * 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 { internal object ExceptionProjection {
val COLUMNS: Array<String> = arrayOf( val COLUMNS: Array<String> = arrayOf(
CalendarContract.Events._ID, CalendarContract.Events._ID,
CalendarContract.Events.ORIGINAL_INSTANCE_TIME, CalendarContract.Events.ORIGINAL_INSTANCE_TIME,
CalendarContract.Events.STATUS, CalendarContract.Events.STATUS,
CalendarContract.Events.TITLE,
CalendarContract.Events.ALL_DAY,
CalendarContract.Events.DTSTART, CalendarContract.Events.DTSTART,
CalendarContract.Events.DTEND, CalendarContract.Events.DTEND,
CalendarContract.Events.DURATION, 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_ID = 0
const val IDX_ORIGINAL_INSTANCE_TIME = 1 const val IDX_ORIGINAL_INSTANCE_TIME = 1
const val IDX_STATUS = 2 const val IDX_STATUS = 2
const val IDX_TITLE = 3 const val IDX_DTSTART = 3
const val IDX_ALL_DAY = 4 const val IDX_DTEND = 4
const val IDX_DTSTART = 5 const val IDX_DURATION = 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
} }
internal object AttendeeProjection { internal object AttendeeProjection {
@@ -2,16 +2,15 @@ package de.jeanlucmakiola.calendula.data.contacts
import android.Manifest import android.Manifest
import android.content.Context import android.content.Context
import android.content.pm.PackageManager
import android.provider.ContactsContract import android.provider.ContactsContract
import android.provider.ContactsContract.CommonDataKinds.Event import android.provider.ContactsContract.CommonDataKinds.Event
import android.util.Log import android.util.Log
import androidx.core.content.ContextCompat
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.calendula.domain.contacts.ContactSpecialDate import de.jeanlucmakiola.calendula.domain.contacts.ContactSpecialDate
import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
import de.jeanlucmakiola.calendula.domain.contacts.managedUid import de.jeanlucmakiola.calendula.domain.contacts.managedUid
import de.jeanlucmakiola.calendula.domain.contacts.parseContactEventDate import de.jeanlucmakiola.calendula.domain.contacts.parseContactEventDate
import de.jeanlucmakiola.floret.android.hasPermission
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
@@ -31,8 +30,7 @@ interface ContactSpecialDatesDataSource {
/** Whether `READ_CONTACTS` is granted — the gate for every contacts read. */ /** Whether `READ_CONTACTS` is granted — the gate for every contacts read. */
fun Context.hasContactsPermission(): Boolean = fun Context.hasContactsPermission(): Boolean =
ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == hasPermission(Manifest.permission.READ_CONTACTS)
PackageManager.PERMISSION_GRANTED
/** Map a `ContactsContract` event `TYPE` to our calendar bucket. */ /** Map a `ContactsContract` event `TYPE` to our calendar bucket. */
internal fun specialDateTypeForRawEventType(type: Int): SpecialDateType = when (type) { 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.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.domain.Availability import de.jeanlucmakiola.calendula.domain.Availability
import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.FormTime
import de.jeanlucmakiola.calendula.domain.RecurrenceFreq import de.jeanlucmakiola.calendula.domain.RecurrenceFreq
import de.jeanlucmakiola.calendula.domain.SimpleRecurrence import de.jeanlucmakiola.calendula.domain.SimpleRecurrence
import de.jeanlucmakiola.calendula.domain.contacts.ContactSpecialDate import de.jeanlucmakiola.calendula.domain.contacts.ContactSpecialDate
@@ -212,8 +213,8 @@ class SpecialDatesSyncEngine @Inject constructor(
calendarId = calendarId, calendarId = calendarId,
title = title, title = title,
isAllDay = true, isAllDay = true,
start = start, start = FormTime(start),
end = start, end = FormTime(start),
reminders = reminderCtx.resolveAllDay(calendarId), reminders = reminderCtx.resolveAllDay(calendarId),
availability = Availability.Free, availability = Availability.Free,
rrule = YEARLY_RRULE, rrule = YEARLY_RRULE,
@@ -20,8 +20,10 @@ import de.jeanlucmakiola.calendula.data.contacts.ContactSpecialDatesDataSource
import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesCalendarSpec import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesCalendarSpec
import de.jeanlucmakiola.calendula.data.reminders.ProviderReminderInstanceSource import de.jeanlucmakiola.calendula.data.reminders.ProviderReminderInstanceSource
import de.jeanlucmakiola.calendula.data.reminders.ReminderInstanceSource import de.jeanlucmakiola.calendula.data.reminders.ReminderInstanceSource
import kotlinx.coroutines.CoroutineDispatcher import de.jeanlucmakiola.calendula.data.time.AndroidTodaySource
import kotlinx.coroutines.Dispatchers import de.jeanlucmakiola.calendula.data.time.AndroidZoneSource
import de.jeanlucmakiola.calendula.data.time.TodaySource
import de.jeanlucmakiola.calendula.data.time.ZoneSource
import javax.inject.Singleton import javax.inject.Singleton
private val Context.calendulaDataStore: DataStore<Preferences> by preferencesDataStore( private val Context.calendulaDataStore: DataStore<Preferences> by preferencesDataStore(
@@ -61,6 +63,18 @@ abstract class DataBindModule {
abstract fun bindSpecialDatesCalendarSpec( abstract fun bindSpecialDatesCalendarSpec(
impl: AndroidSpecialDatesCalendarSpec, impl: AndroidSpecialDatesCalendarSpec,
): SpecialDatesCalendarSpec ): SpecialDatesCalendarSpec
@Binds
@Singleton
abstract fun bindTodaySource(
impl: AndroidTodaySource,
): TodaySource
@Binds
@Singleton
abstract fun bindZoneSource(
impl: AndroidZoneSource,
): ZoneSource
} }
@Module @Module
@@ -71,8 +85,4 @@ object DataProvideModule {
@Singleton @Singleton
fun provideDataStore(@ApplicationContext context: Context): DataStore<Preferences> = fun provideDataStore(@ApplicationContext context: Context): DataStore<Preferences> =
context.calendulaDataStore context.calendulaDataStore
@Provides
@IoDispatcher
fun provideIoDispatcher(): CoroutineDispatcher = Dispatchers.IO
} }
@@ -1,7 +0,0 @@
package de.jeanlucmakiola.calendula.data.di
import javax.inject.Qualifier
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class IoDispatcher
@@ -7,11 +7,11 @@ import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.longPreferencesKey import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
import de.jeanlucmakiola.floret.reminders.ReminderOverride import de.jeanlucmakiola.floret.reminders.ReminderOverride
import de.jeanlucmakiola.floret.reminders.ReminderOverrideCodec import de.jeanlucmakiola.floret.reminders.ReminderOverrideCodec
import de.jeanlucmakiola.floret.reminders.applyReminderOverride import de.jeanlucmakiola.floret.reminders.applyReminderOverride
import de.jeanlucmakiola.floret.reminders.normalizeReminders import de.jeanlucmakiola.floret.reminders.normalizeReminders
import de.jeanlucmakiola.floret.reminders.reminderOverrideFor
import de.jeanlucmakiola.calendula.domain.EventFormField import de.jeanlucmakiola.calendula.domain.EventFormField
import de.jeanlucmakiola.calendula.domain.FontRole import de.jeanlucmakiola.calendula.domain.FontRole
import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType
@@ -31,18 +31,19 @@ import de.jeanlucmakiola.calendula.widget.WidgetSize
import java.time.ZoneId import java.time.ZoneId
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.datetime.DayOfWeek import kotlinx.datetime.DayOfWeek
import java.time.temporal.WeekFields import java.time.temporal.WeekFields
import java.util.Locale import java.util.Locale
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
/** Light/dark override. SYSTEM follows the device setting. */ /**
enum class ThemeMode { SYSTEM, LIGHT, DARK } * Light/dark override. SYSTEM follows the device setting; BLACK is dark with
* pure-black surfaces, for AMOLED screens (#181).
*/
enum class ThemeMode { SYSTEM, LIGHT, DARK, BLACK }
/** /**
* Week-start override. [Auto] derives the first day from the active locale; * Week-start override. [Auto] derives the first day from the active locale;
@@ -102,9 +103,8 @@ fun WeekStartPref.resolveFirstDay(locale: Locale): DayOfWeek = when (this) {
fun SettingsPrefs.firstDayOfWeek(scope: CoroutineScope): StateFlow<DayOfWeek> = fun SettingsPrefs.firstDayOfWeek(scope: CoroutineScope): StateFlow<DayOfWeek> =
weekStart weekStart
.map { it.resolveFirstDay(Locale.getDefault()) } .map { it.resolveFirstDay(Locale.getDefault()) }
.stateIn( .stateWhileSubscribed(
scope = scope, scope = scope,
started = SharingStarted.WhileSubscribed(5_000L),
// Seed with the locale convention rather than a hardcoded weekday, so // Seed with the locale convention rather than a hardcoded weekday, so
// the first frame is already right for everyone still on Auto. // the first frame is already right for everyone still on Auto.
initialValue = WeekStartPref.Auto.resolveFirstDay(Locale.getDefault()), initialValue = WeekStartPref.Auto.resolveFirstDay(Locale.getDefault()),
@@ -346,6 +346,19 @@ class SettingsPrefs @Inject constructor(
store.edit { it[DRAG_TO_RESCHEDULE_KEY] = enabled } store.edit { it[DRAG_TO_RESCHEDULE_KEY] = enabled }
} }
/**
* Whether tapping an event in the calendar views opens the edit form instead
* of the detail screen (#178). Defaults to OFF; read-only events and
* reminder notifications always open the detail screen.
*/
val tapOpensEditor: Flow<Boolean> = store.data.map { prefs ->
prefs[TAP_OPENS_EDITOR_KEY] ?: false
}
suspend fun setTapOpensEditor(enabled: Boolean) {
store.edit { it[TAP_OPENS_EDITOR_KEY] = enabled }
}
/** /**
* How far ahead the in-app Agenda screen shows events (v2.11). Defaults to * How far ahead the in-app Agenda screen shows events (v2.11). Defaults to
* [AgendaRange.Month] — a month of upcoming events. Independent of the * [AgendaRange.Month] — a month of upcoming events. Independent of the
@@ -436,10 +449,6 @@ class SettingsPrefs @Inject constructor(
parseQuickSwitch(prefs[QUICK_SWITCH_VIEWS_KEY]) parseQuickSwitch(prefs[QUICK_SWITCH_VIEWS_KEY])
} }
suspend fun setQuickSwitchConfig(config: QuickSwitchConfig) {
store.edit { it[QUICK_SWITCH_VIEWS_KEY] = serializeQuickSwitch(config) }
}
/** /**
* Atomic read-modify-write of the quick-switch config: [transform] sees the * Atomic read-modify-write of the quick-switch config: [transform] sees the
* value currently stored, parsed inside the edit block, not the async-echoed * value currently stored, parsed inside the edit block, not the async-echoed
@@ -1019,6 +1028,7 @@ class SettingsPrefs @Inject constructor(
internal val TIMELINE_SCALE_KEY = stringPreferencesKey("timeline_scale") internal val TIMELINE_SCALE_KEY = stringPreferencesKey("timeline_scale")
internal val TODAY_BUTTON_IN_TOOLBAR_KEY = booleanPreferencesKey("today_button_in_toolbar") internal val TODAY_BUTTON_IN_TOOLBAR_KEY = booleanPreferencesKey("today_button_in_toolbar")
internal val DRAG_TO_RESCHEDULE_KEY = booleanPreferencesKey("drag_to_reschedule") internal val DRAG_TO_RESCHEDULE_KEY = booleanPreferencesKey("drag_to_reschedule")
internal val TAP_OPENS_EDITOR_KEY = booleanPreferencesKey("tap_opens_editor")
internal val DEFAULT_VIEW_KEY = stringPreferencesKey("default_view") internal val DEFAULT_VIEW_KEY = stringPreferencesKey("default_view")
internal val QUICK_SWITCH_VIEWS_KEY = stringPreferencesKey("quick_switch_views") internal val QUICK_SWITCH_VIEWS_KEY = stringPreferencesKey("quick_switch_views")
internal val DRAWER_VIEW_ORDER_KEY = stringPreferencesKey("drawer_view_order") internal val DRAWER_VIEW_ORDER_KEY = stringPreferencesKey("drawer_view_order")
@@ -6,11 +6,8 @@ import android.content.Intent
import androidx.core.net.toUri import androidx.core.net.toUri
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import kotlinx.coroutines.CoroutineScope import de.jeanlucmakiola.floret.android.goAsync
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import javax.inject.Inject import javax.inject.Inject
/** /**
@@ -44,27 +41,17 @@ class ReminderActionReceiver : BroadcastReceiver() {
// Cancel now so the notification doesn't linger until the alarm; // Cancel now so the notification doesn't linger until the alarm;
// the snooze delay read is the only async work. // the snooze delay read is the only async work.
notifier.cancel(alert) notifier.cancel(alert)
val pendingResult = goAsync() goAsync {
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { val minutes = settingsPrefs.snoozeMinutes.first()
try { val triggerAt = System.currentTimeMillis() + minutes * 60_000L
val minutes = settingsPrefs.snoozeMinutes.first() scheduler.schedule(alert, triggerAt)
val triggerAt = System.currentTimeMillis() + minutes * 60_000L
scheduler.schedule(alert, triggerAt)
} finally {
pendingResult.finish()
}
} }
} }
ACTION_SHOW -> { ACTION_SHOW -> {
val pendingResult = goAsync() goAsync {
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { if (settingsPrefs.remindersEnabled.first() && notifier.canPost()) {
try { notifier.post(alert)
if (settingsPrefs.remindersEnabled.first() && notifier.canPost()) {
notifier.post(alert)
}
} finally {
pendingResult.finish()
} }
} }
} }
@@ -4,20 +4,12 @@ import android.app.AlarmManager
import android.app.PendingIntent import android.app.PendingIntent
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.os.Build
import androidx.core.content.getSystemService import androidx.core.content.getSystemService
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.floret.android.setWakeup
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton 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 * 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 * 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) { fun scheduleScan(triggerAtMillis: Long) {
val alarmManager = context.getSystemService<AlarmManager>() ?: return val alarmManager = context.getSystemService<AlarmManager>() ?: return
val pendingIntent = scanPendingIntent(PendingIntent.FLAG_UPDATE_CURRENT) alarmManager.setWakeup(triggerAtMillis, scanPendingIntent(PendingIntent.FLAG_UPDATE_CURRENT))
if (alarmManager.canScheduleExactCompat()) {
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent,
)
} else {
alarmManager.setAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent,
)
}
} }
/** Drop the pending wake-up — reminders are off, or there is nothing to wait for. */ /** Drop the pending wake-up — reminders are off, or there is nothing to wait for. */
@@ -5,12 +5,10 @@ import android.app.NotificationChannel
import android.app.NotificationManager import android.app.NotificationManager
import android.app.PendingIntent import android.app.PendingIntent
import android.content.Context import android.content.Context
import android.content.pm.PackageManager
import android.os.Build import android.os.Build
import android.util.Log import android.util.Log
import androidx.core.app.NotificationCompat import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.calendula.MainActivity import de.jeanlucmakiola.calendula.MainActivity
import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.R
@@ -19,6 +17,7 @@ import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.data.prefs.is24Hour import de.jeanlucmakiola.calendula.data.prefs.is24Hour
import de.jeanlucmakiola.calendula.data.prefs.resolveFirstDay import de.jeanlucmakiola.calendula.data.prefs.resolveFirstDay
import de.jeanlucmakiola.floret.android.hasPermission
import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.first
import kotlinx.datetime.isoDayNumber import kotlinx.datetime.isoDayNumber
import java.time.DayOfWeek import java.time.DayOfWeek
@@ -48,8 +47,7 @@ class ReminderNotifier @Inject constructor(
/** False when the user declined `POST_NOTIFICATIONS` or muted the app. */ /** False when the user declined `POST_NOTIFICATIONS` or muted the app. */
fun canPost(): Boolean { fun canPost(): Boolean {
val granted = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || val granted = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == context.hasPermission(Manifest.permission.POST_NOTIFICATIONS)
PackageManager.PERMISSION_GRANTED
return granted && NotificationManagerCompat.from(context).areNotificationsEnabled() return granted && NotificationManagerCompat.from(context).areNotificationsEnabled()
} }
@@ -63,13 +61,9 @@ class ReminderNotifier @Inject constructor(
calendarId in calendarPrefs.pendingDisabledCalendarIds.first() || calendarId in calendarPrefs.pendingDisabledCalendarIds.first() ||
calendarDataSource.isCalendarVisible(calendarId) == false calendarDataSource.isCalendarVisible(calendarId) == false
/** /** Post [alert], unless its calendar is switched off. */
* Post [alert], unless its calendar is switched off. Returns whether the suspend fun post(alert: ReminderAlert) {
* notification was put up, which the snooze re-show path uses to tell a if (isSilenced(alert.calendarId)) return
* silenced reminder from a delivered one.
*/
suspend fun post(alert: ReminderAlert): Boolean {
if (isSilenced(alert.calendarId)) return false
ensureChannel() ensureChannel()
val title = alert.title.ifBlank { context.getString(R.string.event_untitled) } val title = alert.title.ifBlank { context.getString(R.string.event_untitled) }
val is24Hour = settingsPrefs.timeFormat.first() val is24Hour = settingsPrefs.timeFormat.first()
@@ -122,8 +116,6 @@ class ReminderNotifier @Inject constructor(
// POST_NOTIFICATIONS was revoked between canPost() and here. // POST_NOTIFICATIONS was revoked between canPost() and here.
Log.w(TAG, "Could not post reminder for event ${alert.eventId}", e) 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 a posted reminder (snooze re-shows it later; dismiss is final). */
@@ -2,19 +2,18 @@ package de.jeanlucmakiola.calendula.data.reminders
import android.Manifest import android.Manifest
import android.content.Context import android.content.Context
import android.content.pm.PackageManager
import android.util.Log import android.util.Log
import androidx.core.content.ContextCompat
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource
import de.jeanlucmakiola.calendula.data.calendar.withoutProviderDefaults import de.jeanlucmakiola.calendula.data.calendar.withoutProviderDefaults
import de.jeanlucmakiola.calendula.data.di.IoDispatcher
import de.jeanlucmakiola.calendula.data.prefs.ReminderStatePrefs import de.jeanlucmakiola.calendula.data.prefs.ReminderStatePrefs
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.domain.reminders.planReminders import de.jeanlucmakiola.calendula.domain.reminders.planReminders
import de.jeanlucmakiola.calendula.domain.reminders.reminderQueryHorizon import de.jeanlucmakiola.calendula.domain.reminders.reminderQueryHorizon
import de.jeanlucmakiola.calendula.domain.reminders.reminderWatermark import de.jeanlucmakiola.calendula.domain.reminders.reminderWatermark
import de.jeanlucmakiola.calendula.domain.reminders.scheduleReminders 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.CoroutineScope
import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.SupervisorJob
@@ -113,9 +112,7 @@ class ReminderScanner @Inject constructor(
alarms.scheduleScan(schedule.nextAlarmMillis) alarms.scheduleScan(schedule.nextAlarmMillis)
} }
private fun hasReadCalendar(): Boolean = ContextCompat.checkSelfPermission( private fun hasReadCalendar(): Boolean = context.hasPermission(Manifest.permission.READ_CALENDAR)
context, Manifest.permission.READ_CALENDAR,
) == PackageManager.PERMISSION_GRANTED
/** /**
* Re-scan when the provider changes, so a saved or deleted event re-arms the * Re-scan when the provider changes, so a saved or deleted event re-arms the
@@ -4,10 +4,7 @@ import android.content.BroadcastReceiver
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope import de.jeanlucmakiola.floret.android.goAsync
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import javax.inject.Inject import javax.inject.Inject
/** /**
@@ -29,14 +26,7 @@ class ReminderScheduleReceiver : BroadcastReceiver() {
// exported and the broadcasts it takes are protected, so any other // exported and the broadcasts it takes are protected, so any other
// action did not come from where it claims to. // action did not come from where it claims to.
if (intent.action !in HANDLED_ACTIONS) return if (intent.action !in HANDLED_ACTIONS) return
val pendingResult = goAsync() goAsync { scanner.scan() }
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
try {
scanner.scan()
} finally {
pendingResult.finish()
}
}
} }
companion object { companion object {
@@ -3,9 +3,9 @@ package de.jeanlucmakiola.calendula.data.reminders
import android.app.AlarmManager import android.app.AlarmManager
import android.app.PendingIntent import android.app.PendingIntent
import android.content.Context import android.content.Context
import android.os.Build
import androidx.core.content.getSystemService import androidx.core.content.getSystemService
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.floret.android.setWakeup
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
@@ -31,24 +31,6 @@ class ReminderSnoozeScheduler @Inject constructor(
ReminderActionReceiver.intent(context, ReminderActionReceiver.ACTION_SHOW, alert), ReminderActionReceiver.intent(context, ReminderActionReceiver.ACTION_SHOW, alert),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
) )
if (canScheduleExact(alarmManager)) { alarmManager.setWakeup(triggerAtMillis, pendingIntent)
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,
)
}
} }
/**
* 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()
} }
@@ -0,0 +1,45 @@
package de.jeanlucmakiola.calendula.data.time
import android.content.Context
import android.content.Intent
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.floret.android.broadcastTicks
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
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.
*/
@OptIn(ExperimentalCoroutinesApi::class)
class AndroidTodaySource @Inject constructor(
@ApplicationContext private val context: Context,
) : 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()
}
private const val MINUTE_MILLIS = 60_000L
fun currentDate(): LocalDate = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).date
@@ -0,0 +1,36 @@
package de.jeanlucmakiola.calendula.data.time
import android.content.Context
import android.content.Intent
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.floret.android.broadcastTicks
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
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. */
class AndroidZoneSource @Inject constructor(
@ApplicationContext private val context: Context,
) : ZoneSource {
override val zone: Flow<TimeZone> = context.broadcastTicks(Intent.ACTION_TIMEZONE_CHANGED)
.map { current() }
.distinctUntilChanged()
override fun current(): TimeZone = TimeZone.currentSystemDefault()
}
@@ -4,7 +4,7 @@ import kotlinx.datetime.LocalDate
import kotlinx.datetime.LocalDateTime import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.LocalTime import kotlinx.datetime.LocalTime
import kotlinx.datetime.TimeZone import kotlinx.datetime.TimeZone
import kotlinx.datetime.toInstant import kotlinx.datetime.UtcOffset
import kotlinx.datetime.toLocalDateTime import kotlinx.datetime.toLocalDateTime
import kotlin.time.Instant import kotlin.time.Instant
@@ -17,8 +17,8 @@ data class EventForm(
val calendarId: Long?, val calendarId: Long?,
val title: String = "", val title: String = "",
val isAllDay: Boolean = false, val isAllDay: Boolean = false,
val start: LocalDateTime, val start: FormTime,
val end: LocalDateTime, val end: FormTime,
/** /**
* The zone [start]/[end] are wall-clock values in, or null to follow the * 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 * device — null is not "no zone", it is "whichever zone the device is in
@@ -70,6 +70,19 @@ data class EventForm(
val attendees: List<EventAttendee> = emptyList(), 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 * 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 * write on), an optional display [name], and whether they're [optional] rather
@@ -145,16 +158,15 @@ fun EventDetail.toEditForm(beginMillis: Long, endMillis: Long, zone: TimeZone):
?.takeIf { runCatching { TimeZone.of(it) }.isSuccess } ?.takeIf { runCatching { TimeZone.of(it) }.isSuccess }
} }
val formZone = pinnedZone?.let { TimeZone.of(it) } ?: zone val formZone = pinnedZone?.let { TimeZone.of(it) } ?: zone
val begin = Instant.fromEpochMilliseconds(beginMillis)
val finish = Instant.fromEpochMilliseconds(endMillis)
val (start, end) = if (instance.isAllDay) { val (start, end) = if (instance.isAllDay) {
val startDate = Instant.fromEpochMilliseconds(beginMillis) val startDate = begin.toLocalDateTime(TimeZone.UTC).date
.toLocalDateTime(TimeZone.UTC).date val endExclusive = finish.toLocalDateTime(TimeZone.UTC).date
val endExclusive = Instant.fromEpochMilliseconds(endMillis)
.toLocalDateTime(TimeZone.UTC).date
val endDate = maxOf(startDate, LocalDate.fromEpochDays(endExclusive.toEpochDays() - 1)) val endDate = maxOf(startDate, LocalDate.fromEpochDays(endExclusive.toEpochDays() - 1))
LocalDateTime(startDate, LocalTime(9, 0)) to LocalDateTime(endDate, LocalTime(10, 0)) FormTime(LocalDateTime(startDate, LocalTime(9, 0))) to FormTime(LocalDateTime(endDate, LocalTime(10, 0)))
} else { } else {
Instant.fromEpochMilliseconds(beginMillis).toLocalDateTime(formZone) to begin.toFormTime(formZone) to finish.toFormTime(formZone)
Instant.fromEpochMilliseconds(endMillis).toLocalDateTime(formZone)
} }
return EventForm( return EventForm(
calendarId = instance.calendarId, calendarId = instance.calendarId,
@@ -221,20 +233,18 @@ 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 * Whether this form's times mean something else in [target] — a timed event
* actually means where the user is standing. Null when there's nothing to * pinned to another zone. False when there's nothing to disambiguate: an
* disambiguate: an unpinned event (already in [target]), one pinned to [target] * unpinned event (already in [target]), one pinned to [target] itself, an
* itself, an all-day event (no zone), or an unparseable pinned zone. * 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 * The form edits a pinned event in its own zone, so this is what tells the UI
* show the other side of the pair rather than making the user do the arithmetic. * to show the other side of the pair rather than making the user do the arithmetic.
*/ */
fun EventForm.timesIn(target: TimeZone): Pair<LocalDateTime, LocalDateTime>? { fun EventForm.isPinnedAwayFrom(target: TimeZone): Boolean {
if (isAllDay) return null if (isAllDay) return false
val pinned = timezone?.let { runCatching { TimeZone.of(it) }.getOrNull() } ?: return null val pinned = timezone?.let { runCatching { TimeZone.of(it) }.getOrNull() } ?: return false
if (pinned.id == target.id) return null return pinned.id != target.id
return start.toInstant(pinned).toLocalDateTime(target) to
end.toInstant(pinned).toLocalDateTime(target)
} }
/** /**
@@ -254,9 +264,19 @@ fun EventForm.populatedFields(): Set<EventFormField> = buildSet {
if (attendees.isNotEmpty()) add(EventFormField.Attendees) 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) 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) if (endsTooEarly) add(EventFormProblem.EndBeforeStart)
// An UNTIL before the first day would make the provider generate zero // An UNTIL before the first day would make the provider generate zero
// occurrences — the event would silently vanish from every view. // occurrences — the event would silently vanish from every view.
@@ -265,3 +285,20 @@ fun EventForm.problems(): Set<EventFormProblem> = buildSet {
add(EventFormProblem.RecurrenceEndsBeforeStart) 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 kept only when [canModify], otherwise the id is
* cleared so the create resolves to a writable calendar, which lets a read-only
* event be copied into an editable one. [instance]'s own times carry over.
*/
fun EventDetail.toDuplicateForm(canModify: Boolean, zone: TimeZone): EventForm =
toEditForm(
beginMillis = instance.start.toEpochMilliseconds(),
endMillis = instance.end.toEpochMilliseconds(),
zone = zone,
).copy(
rrule = null,
calendarId = instance.calendarId.takeIf { canModify },
)
@@ -162,16 +162,20 @@ object EventSearch {
val title = candidate.title?.takeIf { it.isNotBlank() } val title = candidate.title?.takeIf { it.isNotBlank() }
val location = candidate.event.location?.takeIf { it.isNotBlank() } val location = candidate.event.location?.takeIf { it.isNotBlank() }
// Collapsed so a multi-line description matches the way it is drawn. // 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, " ") ?.replace(WHITESPACE, " ")
?.trim() ?.trim()
?.takeIf { it.isNotEmpty() } ?.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". // Mid-word counts: "termin" has to keep finding "Zahnarzttermin".
val present = { token: String -> val present = { token: String ->
title?.contains(token, ignoreCase = true) == true || title?.contains(token, ignoreCase = true) == true ||
location?.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 if (!tokens.all(present)) return null
@@ -3,10 +3,19 @@ package de.jeanlucmakiola.calendula.domain
import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.LocalDateTime import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.TimeZone import kotlinx.datetime.TimeZone
import kotlinx.datetime.UtcOffset
import kotlinx.datetime.offsetAt
import kotlinx.datetime.plus import kotlinx.datetime.plus
import kotlinx.datetime.toInstant 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 kotlinx.datetime.toLocalDateTime
import java.time.ZonedDateTime
import kotlin.time.Instant import kotlin.time.Instant
import kotlin.time.toJavaInstant
import kotlin.time.toKotlinInstant
/** /**
* The zone this form's wall-clock times mean, matching what the data layer * The zone this form's wall-clock times mean, matching what the data layer
@@ -15,6 +24,114 @@ import kotlin.time.Instant
fun EventForm.resolvedZone(deviceZone: TimeZone): TimeZone = fun EventForm.resolvedZone(deviceZone: TimeZone): TimeZone =
timezone?.let { runCatching { TimeZone.of(it) }.getOrNull() } ?: deviceZone timezone?.let { runCatching { TimeZone.of(it) }.getOrNull() } ?: 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 — * The form moved so it starts at [newStart], keeping its **instant** duration —
* a recurring event's length travels to the provider as `DURATION`, so keeping * a recurring event's length travels to the provider as `DURATION`, so keeping
@@ -26,11 +143,8 @@ fun EventForm.resolvedZone(deviceZone: TimeZone): TimeZone =
fun EventForm.shiftedTo(newStart: Instant, deviceZone: TimeZone): EventForm { fun EventForm.shiftedTo(newStart: Instant, deviceZone: TimeZone): EventForm {
if (isAllDay) return this if (isAllDay) return this
val zone = resolvedZone(deviceZone) val zone = resolvedZone(deviceZone)
val span = end.toInstant(zone) - start.toInstant(zone) val span = endInstant(zone) - startInstant(zone)
return copy( return withTimes(newStart, newStart + span, zone)
start = newStart.toLocalDateTime(zone),
end = (newStart + span).toLocalDateTime(zone),
)
} }
/** /**
@@ -43,11 +157,21 @@ fun EventForm.shiftedByDays(days: Int, deviceZone: TimeZone): EventForm {
val newStart = LocalDateTime(start.date.plus(days, DateTimeUnit.DAY), start.time) val newStart = LocalDateTime(start.date.plus(days, DateTimeUnit.DAY), start.time)
if (isAllDay) { if (isAllDay) {
return copy( return copy(
start = newStart, start = FormTime(newStart),
end = LocalDateTime(end.date.plus(days, DateTimeUnit.DAY), end.time), end = FormTime(LocalDateTime(end.date.plus(days, DateTimeUnit.DAY), end.time)),
) )
} }
val zone = resolvedZone(deviceZone) val zone = resolvedZone(deviceZone)
val span = end.toInstant(zone) - start.toInstant(zone) val span = endInstant(zone) - startInstant(zone)
return copy(start = newStart, end = (newStart.toInstant(zone) + span).toLocalDateTime(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. All-day is untouched. */
fun EventForm.resizedTo(newStart: Instant, newEnd: Instant, deviceZone: TimeZone): EventForm {
if (isAllDay) return this
return withTimes(newStart, newEnd, resolvedZone(deviceZone))
} }
@@ -0,0 +1,387 @@
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
}
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
}
/** 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))
}
}
@@ -4,7 +4,6 @@ import kotlinx.datetime.LocalDate
import kotlinx.datetime.LocalDateTime import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.LocalTime import kotlinx.datetime.LocalTime
import kotlinx.datetime.TimeZone import kotlinx.datetime.TimeZone
import kotlinx.datetime.toInstant
import kotlinx.datetime.toLocalDateTime import kotlinx.datetime.toLocalDateTime
import kotlin.time.Duration.Companion.hours import kotlin.time.Duration.Companion.hours
import kotlin.time.Instant import kotlin.time.Instant
@@ -25,13 +24,13 @@ import kotlin.time.Instant
* the extras lives in `MainActivity.insertFormOrNull`. * the extras lives in `MainActivity.insertFormOrNull`.
*/ */
fun buildInsertEventForm( fun buildInsertEventForm(
beginMillis: Long?, beginMillis: Long? = null,
endMillis: Long?, endMillis: Long? = null,
isAllDay: Boolean, isAllDay: Boolean = false,
title: String?, title: String?,
description: String?, description: String?,
location: String?, location: String? = null,
rrule: String?, rrule: String? = null,
zone: TimeZone, zone: TimeZone,
now: Instant, now: Instant,
): EventForm { ): EventForm {
@@ -46,16 +45,12 @@ fun buildInsertEventForm(
?.let { Instant.fromEpochMilliseconds(it).toLocalDateTime(TimeZone.UTC).date } ?.let { Instant.fromEpochMilliseconds(it).toLocalDateTime(TimeZone.UTC).date }
?.let { exclusive -> maxOf(startDate, LocalDate.fromEpochDays(exclusive.toEpochDays() - 1)) } ?.let { exclusive -> maxOf(startDate, LocalDate.fromEpochDays(exclusive.toEpochDays() - 1)) }
?: startDate ?: startDate
LocalDateTime(startDate, LocalTime(9, 0)) to LocalDateTime(endDate, LocalTime(10, 0)) FormTime(LocalDateTime(startDate, LocalTime(9, 0))) to FormTime(LocalDateTime(endDate, LocalTime(10, 0)))
} else { } else {
val startTime = beginMillis val startAt = beginMillis?.let(Instant::fromEpochMilliseconds) ?: nextFullHour(now)
?.let { Instant.fromEpochMilliseconds(it).toLocalDateTime(zone) } val endAt = endMillis?.let(Instant::fromEpochMilliseconds)?.takeIf { it >= startAt }
?: nextFullHour(now, zone) ?: (startAt + 1.hours)
val endTime = endMillis startAt.toFormTime(zone) to endAt.toFormTime(zone)
?.let { Instant.fromEpochMilliseconds(it).toLocalDateTime(zone) }
?.takeIf { it >= startTime }
?: (startTime.toInstant(zone) + 1.hours).toLocalDateTime(zone)
startTime to endTime
} }
return EventForm( return EventForm(
calendarId = null, calendarId = null,
@@ -71,8 +66,34 @@ fun buildInsertEventForm(
) )
} }
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 hourMillis = 3_600_000L
val rounded = (now.toEpochMilliseconds() / hourMillis + 1) * hourMillis return Instant.fromEpochMilliseconds((now.toEpochMilliseconds() / hourMillis + 1) * hourMillis)
return Instant.fromEpochMilliseconds(rounded).toLocalDateTime(zone) }
/** 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)
} }
@@ -165,6 +165,17 @@ data class EventDetail(
val isException: Boolean = false, 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 * One selectable event colour published by a calendar's account
* (`CalendarContract.Colors`, `TYPE_EVENT`): [key] is the account-scoped * (`CalendarContract.Colors`, `TYPE_EVENT`): [key] is the account-scoped
@@ -157,14 +157,36 @@ fun timeZoneOptionOf(
* the offset isn't stated twice in ICU's spelling and ours. * the offset isn't stated twice in ICU's spelling and ours.
*/ */
fun zoneDescriptor(option: TimeZoneOption): String { fun zoneDescriptor(option: TimeZoneOption): String {
val abbrev = option.shortName val name = zoneAbbreviation(option)
return when { val statesOffset = option.shortName == "UTC" || option.shortName.startsWith("GMT")
abbrev == "UTC" -> "UTC" return if (statesOffset) name else "$name · ${formatGmtOffset(option.offsetMinutes)}"
abbrev.startsWith("GMT") -> formatGmtOffset(option.offsetMinutes)
else -> "$abbrev · ${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 * [options] matching [query], best matches first; a blank query returns the list
* unchanged. Matching is accent- and case-insensitive and treats underscores as * unchanged. Matching is accent- and case-insensitive and treats underscores as
@@ -1,6 +1,8 @@
package de.jeanlucmakiola.calendula.domain.ics package de.jeanlucmakiola.calendula.domain.ics
import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.FormTime
import de.jeanlucmakiola.calendula.domain.toFormTime
import kotlinx.datetime.LocalDate import kotlinx.datetime.LocalDate
import kotlinx.datetime.LocalDateTime import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.LocalTime import kotlinx.datetime.LocalTime
@@ -24,9 +26,9 @@ fun ParsedIcsEvent.toEventForm(zone: TimeZone): EventForm {
val startDate = this.start.toLocalDateTime(TimeZone.UTC).date val startDate = this.start.toLocalDateTime(TimeZone.UTC).date
val endExclusive = this.end.toLocalDateTime(TimeZone.UTC).date val endExclusive = this.end.toLocalDateTime(TimeZone.UTC).date
val endDate = maxOf(startDate, LocalDate.fromEpochDays(endExclusive.toEpochDays() - 1)) val endDate = maxOf(startDate, LocalDate.fromEpochDays(endExclusive.toEpochDays() - 1))
LocalDateTime(startDate, LocalTime(9, 0)) to LocalDateTime(endDate, LocalTime(10, 0)) FormTime(LocalDateTime(startDate, LocalTime(9, 0))) to FormTime(LocalDateTime(endDate, LocalTime(10, 0)))
} else { } else {
this.start.toLocalDateTime(zone) to this.end.toLocalDateTime(zone) this.start.toFormTime(zone) to this.end.toFormTime(zone)
} }
return EventForm( return EventForm(
calendarId = null, calendarId = null,
@@ -19,6 +19,7 @@ import androidx.compose.material3.Scaffold
import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberDrawerState import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.CompositionLocalProvider
@@ -29,6 +30,7 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.listSaver import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import de.jeanlucmakiola.calendula.ui.common.screen import de.jeanlucmakiola.calendula.ui.common.screen
import de.jeanlucmakiola.calendula.ui.common.ViewScreen import de.jeanlucmakiola.calendula.ui.common.ViewScreen
@@ -55,7 +57,13 @@ import de.jeanlucmakiola.floret.identity.fadeThrough
import de.jeanlucmakiola.floret.identity.predictiveBackExit import de.jeanlucmakiola.floret.identity.predictiveBackExit
import de.jeanlucmakiola.floret.identity.rememberReduceMotion import de.jeanlucmakiola.floret.identity.rememberReduceMotion
import de.jeanlucmakiola.calendula.ui.common.CalendarView 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.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.rememberWriteGateOr
import de.jeanlucmakiola.calendula.ui.common.EventMoveScope import de.jeanlucmakiola.calendula.ui.common.EventMoveScope
import de.jeanlucmakiola.calendula.ui.common.LocalEventMove import de.jeanlucmakiola.calendula.ui.common.LocalEventMove
import de.jeanlucmakiola.calendula.ui.common.LocalManageCalendars import de.jeanlucmakiola.calendula.ui.common.LocalManageCalendars
@@ -76,6 +84,7 @@ import de.jeanlucmakiola.calendula.ui.common.rememberCalendarSlideSpec
import de.jeanlucmakiola.calendula.ui.common.selectView import de.jeanlucmakiola.calendula.ui.common.selectView
import de.jeanlucmakiola.calendula.ui.common.viewBaseStack import de.jeanlucmakiola.calendula.ui.common.viewBaseStack
import de.jeanlucmakiola.calendula.ui.detail.EventDetailScreen 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.EventEditScreen
import de.jeanlucmakiola.calendula.ui.edit.ImportSource import de.jeanlucmakiola.calendula.ui.edit.ImportSource
import de.jeanlucmakiola.calendula.ui.imports.ImportScreen import de.jeanlucmakiola.calendula.ui.imports.ImportScreen
@@ -91,6 +100,7 @@ import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime import kotlinx.datetime.toLocalDateTime
import kotlin.coroutines.cancellation.CancellationException import kotlin.coroutines.cancellation.CancellationException
import kotlin.time.Clock import kotlin.time.Clock
import kotlin.time.Instant
/** /**
* Holds the top-level view back stack (spec M1) and swaps between the calendar * Holds the top-level view back stack (spec M1) and swaps between the calendar
@@ -126,6 +136,7 @@ fun CalendarHost(
requestedInsertForm: EventForm? = null, requestedInsertForm: EventForm? = null,
requestedInsertSource: ImportSource = ImportSource.Insert, requestedInsertSource: ImportSource = ImportSource.Insert,
onInsertConsumed: () -> Unit = {}, onInsertConsumed: () -> Unit = {},
onExternalFormClosed: () -> Unit = {},
requestedEditKey: LongArray? = null, requestedEditKey: LongArray? = null,
onEditKeyConsumed: () -> Unit = {}, onEditKeyConsumed: () -> Unit = {},
viewModel: CalendarHostViewModel = hiltViewModel(), viewModel: CalendarHostViewModel = hiltViewModel(),
@@ -146,14 +157,27 @@ fun CalendarHost(
mutableStateOf(listOf(defaultView)) mutableStateOf(listOf(defaultView))
} }
var navigationVersion by remember { mutableIntStateOf(0) } 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() val view = viewStack.last()
// The date every view opens on and carries along (#184); tapping a day // The date every view opens on and carries along (#184); tapping a day
// anywhere focuses it and opens the day view there. // anywhere focuses it and opens the day view there.
val focus = rememberSaveable(saver = ViewFocusSaver) { ViewFocus(localToday()) } val focus = rememberSaveable(saver = ViewFocusSaver) { ViewFocus(localToday()) }
// 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 switchScope = rememberCoroutineScope()
val switchTo: ((List<CalendarView>) -> List<CalendarView>) -> Unit = { move -> val switchTo: ((List<CalendarView>) -> List<CalendarView>) -> Unit = { move ->
navigationVersion++ navigationVersion++
returnedFromDay = false
viewStack = move(viewStack) viewStack = move(viewStack)
} }
val onSelectView: (CalendarView) -> Unit = { target -> switchTo { it.selectView(target) } } val onSelectView: (CalendarView) -> Unit = { target -> switchTo { it.selectView(target) } }
@@ -175,7 +199,7 @@ fun CalendarHost(
// placeholder — so the destination never loads a bogus id=0 on first frame. // placeholder — so the destination never loads a bogus id=0 on first frame.
var detailKey by rememberSaveable { mutableStateOf<LongArray?>(null) } var detailKey by rememberSaveable { mutableStateOf<LongArray?>(null) }
var heldKey by remember { mutableStateOf<LongArray?>(null) } var heldKey by remember { mutableStateOf<LongArray?>(null) }
val onEventClick: (EventInstance) -> Unit = { event -> val onOpenDetail: (EventInstance) -> Unit = { event ->
val key = longArrayOf( val key = longArrayOf(
event.eventId, event.eventId,
event.start.toEpochMilliseconds(), event.start.toEpochMilliseconds(),
@@ -222,11 +246,23 @@ fun CalendarHost(
var heldCreateIso by remember { mutableStateOf<String?>(null) } var heldCreateIso by remember { mutableStateOf<String?>(null) }
var createStartMinutes by rememberSaveable { mutableStateOf<Int?>(null) } var createStartMinutes by rememberSaveable { mutableStateOf<Int?>(null) }
var heldCreateMinutes by remember { mutableStateOf<Int?>(null) } var heldCreateMinutes by remember { mutableStateOf<Int?>(null) }
val onCreateEvent: (LocalDate, Int?) -> Unit = { date, startMinutes -> // 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).
var createDraftMillis by rememberSaveable { mutableStateOf<LongArray?>(null) }
var heldCreateDraftMillis by remember { mutableStateOf<LongArray?>(null) }
fun openCreate(date: LocalDate, startMinutes: Int?, draftMillis: LongArray?) {
heldCreateIso = date.toString() heldCreateIso = date.toString()
createDateIso = date.toString() createDateIso = date.toString()
heldCreateMinutes = startMinutes heldCreateMinutes = startMinutes
createStartMinutes = startMinutes createStartMinutes = startMinutes
heldCreateDraftMillis = draftMillis
createDraftMillis = draftMillis
}
val onCreateEvent: (LocalDate, Int?) -> Unit = { date, startMinutes -> openCreate(date, startMinutes, null) }
val onCreateDraft: (Instant, Instant) -> Unit = { start, end ->
val date = start.toLocalDateTime(TimeZone.currentSystemDefault()).date
openCreate(date, null, longArrayOf(start.toEpochMilliseconds(), end.toEpochMilliseconds()))
} }
// Edit form (v1.3) — reuses the detail screen's occurrence key; for // Edit form (v1.3) — reuses the detail screen's occurrence key; for
@@ -246,6 +282,34 @@ fun CalendarHost(
// Which channel filled [importForm]: an .ics file (prompt to apply the default // Which channel filled [importForm]: an .ics file (prompt to apply the default
// reminder) or an ACTION_INSERT intent (apply it automatically) — #49. // reminder) or an ACTION_INSERT intent (apply it automatically) — #49.
var importFormSource by remember { mutableStateOf(ImportSource.File) } var importFormSource by remember { mutableStateOf(ImportSource.File) }
// Bumped per open, so even an equal prefill starts a fresh form.
var importFormId by remember { 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 importViewModel: EventEditViewModel = hiltViewModel(key = "import")
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
onExternalFormClosed()
}
}
}
// A restore (in-app "Restore from .ics" button) always runs the full import // 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 // 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 // is "restore a backup", not "add this one event". An externally opened .ics
@@ -275,8 +339,11 @@ fun CalendarHost(
// reveals on top of whatever was open without extra dismissal. // reveals on top of whatever was open without extra dismissal.
LaunchedEffect(requestedInsertForm) { LaunchedEffect(requestedInsertForm) {
if (requestedInsertForm != null) { if (requestedInsertForm != null) {
importFormSource = requestedInsertSource if (importForm == null) {
importForm = requestedInsertForm openImportForm(requestedInsertForm, requestedInsertSource, fromRequest = true)
} else {
pendingInsert = requestedInsertForm to requestedInsertSource
}
onInsertConsumed() onInsertConsumed()
} }
} }
@@ -292,6 +359,9 @@ fun CalendarHost(
editKey = null editKey = null
importUri = null importUri = null
importForm = null importForm = null
importFromRequest = false
pendingInsert = null
importViewModel.reset()
} }
// An external "edit this event" (ACTION_EDIT, e.g. an assistant/task app or // An external "edit this event" (ACTION_EDIT, e.g. an assistant/task app or
@@ -313,7 +383,10 @@ fun CalendarHost(
// [requestedDetailKey]. Date/event opens root the stack in the widget's own // [requestedDetailKey]. Date/event opens root the stack in the widget's own
// view so backing out returns there (then home), not to the default. // view so backing out returns there (then home), not to the default.
LaunchedEffect(widgetNavRequest) { LaunchedEffect(widgetNavRequest) {
if (widgetNavRequest != null) navigationVersion++ if (widgetNavRequest != null) {
navigationVersion++
returnedFromDay = false
}
when (val req = widgetNavRequest) { when (val req = widgetNavRequest) {
is WidgetNavRequest.OpenDate -> { is WidgetNavRequest.OpenDate -> {
// Drill the day view in over the widget's view: drop any overlay // Drill the day view in over the widget's view: drop any overlay
@@ -360,6 +433,8 @@ fun CalendarHost(
createDateIso = iso createDateIso = iso
heldCreateMinutes = null heldCreateMinutes = null
createStartMinutes = null createStartMinutes = null
heldCreateDraftMillis = null
createDraftMillis = null
onWidgetNavConsumed() onWidgetNavConsumed()
} }
null -> {} null -> {}
@@ -370,6 +445,9 @@ fun CalendarHost(
// survives view switches; the calendar surfaces read it out of LocalEventMove. // survives view switches; the calendar surfaces read it out of LocalEventMove.
val reschedule: RescheduleViewModel = hiltViewModel() val reschedule: RescheduleViewModel = hiltViewModel()
val movableCalendarIds by reschedule.movableCalendarIds.collectAsStateWithLifecycle() val movableCalendarIds by reschedule.movableCalendarIds.collectAsStateWithLifecycle()
val eventActions: EventActionsViewModel = hiltViewModel()
val moveOutcome by reschedule.outcome.collectAsStateWithLifecycle()
val selectionFailure by eventActions.failure.collectAsStateWithLifecycle()
val onEditEvent: (EventInstance) -> Unit = { event -> val onEditEvent: (EventInstance) -> Unit = { event ->
val key = longArrayOf( val key = longArrayOf(
event.eventId, event.eventId,
@@ -379,6 +457,28 @@ fun CalendarHost(
heldEditKey = key heldEditKey = key
editKey = key editKey = key
} }
// 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
val requireWriteOr = rememberWriteGateOr()
// A refused write upgrade is asked once; later taps just open the details.
var tapWriteRefused by rememberSaveable { mutableStateOf(false) }
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 -> requireWriteOr({ onEditEvent(event) }) {
tapWriteRefused = true
onOpenDetail(event)
}
}
}
}
// Off by preference (#173) switches off the gesture, not the scope: blocks // 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. // register no drag, while the edit form and its TalkBack action stay put.
val dragToReschedule = viewModel.dragToReschedule.collectAsStateWithLifecycle().value val dragToReschedule = viewModel.dragToReschedule.collectAsStateWithLifecycle().value
@@ -415,11 +515,14 @@ fun CalendarHost(
if (reduceMotion) { if (reduceMotion) {
BackHandler(enabled = viewBackEnabled) { BackHandler(enabled = viewBackEnabled) {
navigationVersion++ navigationVersion++
returnedFromDay = viewStack.last() == CalendarView.Day
viewStack = viewStack.dropLast(1) viewStack = viewStack.dropLast(1)
} }
} else { } else {
PredictiveBackHandler(enabled = viewBackEnabled) { events -> PredictiveBackHandler(enabled = viewBackEnabled) { events ->
val previous = viewStack[viewStack.size - 2] val previous = viewStack[viewStack.size - 2]
// Set before the seek, which already composes the previous view.
returnedFromDay = viewStack.last() == CalendarView.Day
try { try {
events.collect { viewTransition.seekTo(it.progress, targetState = previous) } events.collect { viewTransition.seekTo(it.progress, targetState = previous) }
navigationVersion++ navigationVersion++
@@ -508,7 +611,24 @@ fun CalendarHost(
showTodayButton = todayInToolbar, 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,
onDismissChip = {
reschedule.consumeOutcome()
eventActions.consumeFailure()
},
)
CalendarFab(chromeHost, todayInToolbar, fabSelection)
},
) { innerPadding -> ) { innerPadding ->
SharedTransitionLayout( SharedTransitionLayout(
Modifier Modifier
@@ -539,6 +659,7 @@ fun CalendarHost(
onOpenDay = onOpenDay, onOpenDay = onOpenDay,
onEventClick = onEventClick, onEventClick = onEventClick,
onCreateEvent = onCreateEvent, onCreateEvent = onCreateEvent,
onCreateDraft = onCreateDraft,
) )
ViewScreen.Month -> MonthScreen( ViewScreen.Month -> MonthScreen(
onOpenDay = onOpenDay, onOpenDay = onOpenDay,
@@ -551,6 +672,7 @@ fun CalendarHost(
onEventClick = onEventClick, onEventClick = onEventClick,
onCreateEvent = onCreateEvent, onCreateEvent = onCreateEvent,
quickSwitchViews = quickSwitchViews, quickSwitchViews = quickSwitchViews,
restorePosition = returnedFromDay,
) )
} }
} }
@@ -562,7 +684,15 @@ fun CalendarHost(
// Scope prompt + confirmation/undo snackbar for a dropped event, declared // Scope prompt + confirmation/undo snackbar for a dropped event, declared
// right after the calendar views so later overlays cover it. // right after the calendar views so later overlays cover it.
EventMoveHost(reschedule, modifier = Modifier.fillMaxSize()) EventMoveHost(
reschedule,
modifier = Modifier.fillMaxSize(),
actionFailure = eventActionFailureMessage(selectionFailure),
onActionFailureShown = eventActions::consumeFailure,
)
// 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 // 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. // detail screen draws on top, and closing it returns to the results.
@@ -599,8 +729,7 @@ fun CalendarHost(
// Reuse the prefilled-create overlay: a duplicate is a // Reuse the prefilled-create overlay: a duplicate is a
// fresh event, so it applies the default reminder like an // fresh event, so it applies the default reminder like an
// in-app new event (#52). // in-app new event (#52).
importFormSource = ImportSource.Insert openImportForm(form, ImportSource.Insert)
importForm = form
detailKey = null detailKey = null
}, },
visible = detailKey != null, visible = detailKey != null,
@@ -618,10 +747,12 @@ fun CalendarHost(
EventEditScreen( EventEditScreen(
initialDateIso = iso, initialDateIso = iso,
initialStartMinutes = createStartMinutes ?: heldCreateMinutes, initialStartMinutes = createStartMinutes ?: heldCreateMinutes,
initialDraft = createDraftMillis ?: heldCreateDraftMillis,
onClose = { createDateIso = null }, onClose = { createDateIso = null },
onSaved = { createDateIso = null }, onSaved = { createDateIso = null },
onManageCalendars = { showCalendars = true }, onManageCalendars = { showCalendars = true },
visible = createDateIso != null, visible = createDateIso != null,
viewModel = hiltViewModel(key = "create"),
) )
} }
} }
@@ -642,7 +773,20 @@ fun CalendarHost(
detailKey = null detailKey = null
}, },
onManageCalendars = { showCalendars = true }, 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) {
heldKey = key
detailKey = key
}
},
visible = editKey != null, visible = editKey != null,
viewModel = hiltViewModel(key = "edit"),
) )
} }
} }
@@ -688,20 +832,24 @@ fun CalendarHost(
importUri = null importUri = null
calendarsAfterImport = false calendarsAfterImport = false
backupAfterImport = false backupAfterImport = false
importFormSource = ImportSource.File openImportForm(form, ImportSource.File)
importForm = form
}, },
) )
} }
importForm?.let { form -> importForm?.let { form ->
EventEditScreen( key(importFormId) {
initialDateIso = null, EventEditScreen(
initialForm = form, initialDateIso = null,
initialFormSource = importFormSource, initialForm = form,
onClose = { importForm = null }, initialFormSource = importFormSource,
onSaved = { importForm = null }, onClose = ::closeImportForm,
onManageCalendars = { showCalendars = true }, 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, // Declared last so it covers every overlay that can open it: Settings,
@@ -4,12 +4,15 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.lifecycle.HiltViewModel
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs 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.CalendarView
import de.jeanlucmakiola.calendula.ui.common.IMPLEMENTED_VIEWS 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.StateFlow
import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.first
import kotlinx.datetime.LocalDate
import javax.inject.Inject import javax.inject.Inject
/** /**
@@ -21,36 +24,39 @@ import javax.inject.Inject
@HiltViewModel @HiltViewModel
class CalendarHostViewModel @Inject constructor( class CalendarHostViewModel @Inject constructor(
prefs: SettingsPrefs, prefs: SettingsPrefs,
todaySource: TodaySource,
) : ViewModel() { ) : 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, scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = null, initialValue = null,
) )
/** Views the top-bar quick-switch pill cycles through, in the user's order (#24). */ /** Views the top-bar quick-switch pill cycles through, in the user's order (#24). */
val quickSwitchViews: StateFlow<List<CalendarView>> = prefs.quickSwitchConfig val quickSwitchViews: StateFlow<List<CalendarView>> = prefs.quickSwitchConfig
.map { it.cycle } .map { it.cycle }
.stateIn( .stateWhileSubscribed(
scope = viewModelScope, scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = IMPLEMENTED_VIEWS, initialValue = IMPLEMENTED_VIEWS,
) )
/** Order of the views in the navigation drawer (#24); every view always shown. */ /** Order of the views in the navigation drawer (#24); every view always shown. */
val drawerViewOrder: StateFlow<List<CalendarView>> = prefs.drawerViewOrder val drawerViewOrder: StateFlow<List<CalendarView>> = prefs.drawerViewOrder
.stateIn( .stateWhileSubscribed(
scope = viewModelScope, scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = IMPLEMENTED_VIEWS, initialValue = IMPLEMENTED_VIEWS,
) )
/** Whether each view's jump-to-today control lives in the top bar, not the FAB (#60). */ /** Whether each view's jump-to-today control lives in the top bar, not the FAB (#60). */
val todayButtonInToolbar: StateFlow<Boolean> = prefs.todayButtonInToolbar val todayButtonInToolbar: StateFlow<Boolean> = prefs.todayButtonInToolbar
.stateIn( .stateWhileSubscribed(
scope = viewModelScope, scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = false, initialValue = false,
) )
@@ -62,9 +68,13 @@ class CalendarHostViewModel @Inject constructor(
* switched off to be rid of. * switched off to be rid of.
*/ */
val dragToReschedule: StateFlow<Boolean> = prefs.dragToReschedule val dragToReschedule: StateFlow<Boolean> = prefs.dragToReschedule
.stateIn( .stateWhileSubscribed(
scope = viewModelScope, scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = false, 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()
} }
@@ -1,7 +1,6 @@
package de.jeanlucmakiola.calendula.ui package de.jeanlucmakiola.calendula.ui
import android.Manifest import android.Manifest
import android.content.pm.PackageManager
import androidx.compose.animation.AnimatedContent import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut import androidx.compose.animation.fadeOut
@@ -20,7 +19,6 @@ import androidx.compose.ui.platform.LocalContext
import androidx.hilt.navigation.compose.hiltViewModel import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.core.content.ContextCompat
import androidx.lifecycle.Lifecycle import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.LifecycleEventObserver
import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesScheduler import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesScheduler
@@ -31,6 +29,7 @@ import de.jeanlucmakiola.calendula.ui.onboarding.OnboardingSteps
import de.jeanlucmakiola.calendula.ui.onboarding.OnboardingViewModel import de.jeanlucmakiola.calendula.ui.onboarding.OnboardingViewModel
import de.jeanlucmakiola.calendula.ui.onboarding.onboardingSlideTransition import de.jeanlucmakiola.calendula.ui.onboarding.onboardingSlideTransition
import de.jeanlucmakiola.calendula.ui.onboarding.rememberOnboardingSlideSpec import de.jeanlucmakiola.calendula.ui.onboarding.rememberOnboardingSlideSpec
import de.jeanlucmakiola.floret.android.hasPermission
import de.jeanlucmakiola.floret.identity.rememberReduceMotion import de.jeanlucmakiola.floret.identity.rememberReduceMotion
/** What the root is showing: a wizard step, the app, or neither yet. */ /** What the root is showing: a wizard step, the app, or neither yet. */
@@ -54,14 +53,14 @@ fun RootScreen(
requestedInsertSource: de.jeanlucmakiola.calendula.ui.edit.ImportSource = requestedInsertSource: de.jeanlucmakiola.calendula.ui.edit.ImportSource =
de.jeanlucmakiola.calendula.ui.edit.ImportSource.Insert, de.jeanlucmakiola.calendula.ui.edit.ImportSource.Insert,
onInsertConsumed: () -> Unit = {}, onInsertConsumed: () -> Unit = {},
onExternalFormClosed: () -> Unit = {},
requestedEditKey: LongArray? = null, requestedEditKey: LongArray? = null,
onEditKeyConsumed: () -> Unit = {}, onEditKeyConsumed: () -> Unit = {},
) { ) {
val context = LocalContext.current val context = LocalContext.current
var hasPermission by remember { var hasPermission by remember {
mutableStateOf( mutableStateOf(
ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CALENDAR) context.hasPermission(Manifest.permission.READ_CALENDAR)
== PackageManager.PERMISSION_GRANTED
) )
} }
@@ -73,9 +72,7 @@ fun RootScreen(
DisposableEffect(lifecycle) { DisposableEffect(lifecycle) {
val obs = LifecycleEventObserver { _, event -> val obs = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME) { if (event == Lifecycle.Event.ON_RESUME) {
hasPermission = ContextCompat.checkSelfPermission( hasPermission = context.hasPermission(Manifest.permission.READ_CALENDAR)
context, Manifest.permission.READ_CALENDAR
) == PackageManager.PERMISSION_GRANTED
// Refresh the contact special-dates mirror on foreground (the // Refresh the contact special-dates mirror on foreground (the
// worker is debounced and no-ops when the feature is off). Gated // worker is debounced and no-ops when the feature is off). Gated
// on the permission so users without the opt-in never enqueue it. // on the permission so users without the opt-in never enqueue it.
@@ -155,6 +152,7 @@ fun RootScreen(
requestedInsertForm = requestedInsertForm, requestedInsertForm = requestedInsertForm,
requestedInsertSource = requestedInsertSource, requestedInsertSource = requestedInsertSource,
onInsertConsumed = onInsertConsumed, onInsertConsumed = onInsertConsumed,
onExternalFormClosed = onExternalFormClosed,
requestedEditKey = requestedEditKey, requestedEditKey = requestedEditKey,
onEditKeyConsumed = onEditKeyConsumed, onEditKeyConsumed = onEditKeyConsumed,
) )
@@ -2,7 +2,6 @@ package de.jeanlucmakiola.calendula.ui.agenda
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.clickable import androidx.compose.foundation.clickable
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
@@ -35,10 +34,10 @@ import de.jeanlucmakiola.calendula.ui.common.declinedTitle
import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors
import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat
import de.jeanlucmakiola.calendula.ui.common.eventAccent 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.formatTimeOfDay
import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.GroupedRow
import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.Position
import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme
import de.jeanlucmakiola.floret.locale.currentLocale import de.jeanlucmakiola.floret.locale.currentLocale
import de.jeanlucmakiola.floret.locale.localizedDateFormatter import de.jeanlucmakiola.floret.locale.localizedDateFormatter
import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.DateTimeUnit
@@ -127,7 +126,7 @@ internal fun AgendaEventRow(
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
onClick: () -> Unit, onClick: () -> Unit,
) { ) {
val dark = isSystemInDarkTheme() val dark = LocalFloretDarkTheme.current
val soften = LocalSoftenColors.current val soften = LocalSoftenColors.current
val title = event.title.ifBlank { stringResource(R.string.event_untitled) } val title = event.title.ifBlank { stringResource(R.string.event_untitled) }
GroupedRow( GroupedRow(
@@ -5,7 +5,6 @@ import de.jeanlucmakiola.calendula.ui.common.ScreenActions
import de.jeanlucmakiola.calendula.ui.common.ScreenBody import de.jeanlucmakiola.calendula.ui.common.ScreenBody
import de.jeanlucmakiola.calendula.ui.common.ScreenChrome import de.jeanlucmakiola.calendula.ui.common.ScreenChrome
import de.jeanlucmakiola.calendula.ui.common.LocalViewFocus import de.jeanlucmakiola.calendula.ui.common.LocalViewFocus
import de.jeanlucmakiola.calendula.ui.common.EnterOnFocus
import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.drop
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
@@ -38,7 +37,16 @@ import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect 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.derivedStateOf
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
@@ -53,7 +61,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay
import de.jeanlucmakiola.calendula.domain.EventInstance 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.AgendaRangePicker
import de.jeanlucmakiola.calendula.ui.common.AppBarSpacing import de.jeanlucmakiola.calendula.ui.common.AppBarSpacing
import de.jeanlucmakiola.calendula.ui.common.QuickSwitchConfig import de.jeanlucmakiola.calendula.ui.common.QuickSwitchConfig
@@ -82,11 +90,23 @@ fun AgendaScreen(
onCreateEvent: (LocalDate, Int?) -> Unit, onCreateEvent: (LocalDate, Int?) -> Unit,
quickSwitchViews: List<CalendarView> = IMPLEMENTED_VIEWS, quickSwitchViews: List<CalendarView> = IMPLEMENTED_VIEWS,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
restorePosition: Boolean = false,
viewModel: AgendaViewModel = hiltViewModel(), 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 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 state by viewModel.state.collectAsStateWithLifecycle()
val anchor by viewModel.anchor.collectAsStateWithLifecycle() val anchor by viewModel.anchor.collectAsStateWithLifecycle()
val pastDisplay by viewModel.pastEventDisplay.collectAsStateWithLifecycle() val pastDisplay by viewModel.pastEventDisplay.collectAsStateWithLifecycle()
@@ -106,20 +126,19 @@ fun AgendaScreen(
// list scroll, not an anchor change — "today" has to bring the list back to // 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). // the top as well, and stay offered while it is scrolled away (#305).
val listState = rememberLazyListState() 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 { val scrolledAway by remember {
derivedStateOf { 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 = { 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. // 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() viewModel.goToToday()
(state as? AgendaUiState.Success)?.today?.let { focus?.date = it } (state as? AgendaUiState.Success)?.today?.let { focus?.date = it }
} }
@@ -188,11 +207,17 @@ fun AgendaScreen(
pastDisplay = pastDisplay, pastDisplay = pastDisplay,
showToday = showToday, showToday = showToday,
listState = listState, listState = listState,
anchorIndex = anchorIndex,
initialTopDate = restoreTop,
onLoadEarlier = viewModel::loadEarlier,
onRetry = viewModel::goToToday, onRetry = viewModel::goToToday,
onEventClick = onEventClick, onEventClick = onEventClick,
onOpenDay = onOpenDay, onOpenDay = onOpenDay,
onTopDay = if (successState?.anchor == anchor) { onTopDay = if (successState?.anchor == anchor) {
{ focus?.date = it } {
focus?.date = it
viewModel.rememberTopDay(it)
}
} else null, } else null,
modifier = Modifier modifier = Modifier
.weight(1f) .weight(1f)
@@ -294,6 +319,9 @@ internal fun AgendaContent(
onOpenDay: (LocalDate) -> Unit, onOpenDay: (LocalDate) -> Unit,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
listState: LazyListState = rememberLazyListState(), listState: LazyListState = rememberLazyListState(),
anchorIndex: MutableIntState = remember { mutableIntStateOf(0) },
initialTopDate: LocalDate? = null,
onLoadEarlier: () -> Unit = {},
onTopDay: ((LocalDate) -> Unit)? = null, onTopDay: ((LocalDate) -> Unit)? = null,
) { ) {
when (state) { when (state) {
@@ -308,28 +336,34 @@ internal fun AgendaContent(
// away (or fade) as they end while the screen stays open. // away (or fade) as they end while the screen stays open.
val filtered = if (pastDisplay == PastEventDisplay.HIDE) { val filtered = if (pastDisplay == PastEventDisplay.HIDE) {
state.days.mapNotNull { day -> 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) if (remaining.isEmpty()) null else day.copy(events = remaining)
} }
} else { } else {
state.days state.days
} }
// Anchor today with a "nothing left today" placeholder — but only when // 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 // the agenda actually opens on today; a jumped-to date has no today
// it, so anchoring there would be misleading (#35). // in it, so anchoring there would be misleading (#35).
val days = anchorTodayIfMissing( val days = anchorTodayIfMissing(
days = filtered, days = filtered,
today = state.today, today = state.today,
enabled = showToday && state.anchor == 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 // Nothing to scroll: drop the position a previous list left, so
// the today FAB doesn't linger over an empty screen. // the today FAB doesn't linger over an empty screen.
LaunchedEffect(Unit) { listState.scrollToItem(0) } LaunchedEffect(Unit) { listState.scrollToItem(0) }
SideEffect { anchorIndex.intValue = 0 }
AgendaEmpty(modifier) AgendaEmpty(modifier)
} else { } else {
AgendaList( AgendaList(
days = days, days = days,
anchor = state.anchor,
anchorIndex = anchorIndex,
initialTopDate = initialTopDate,
onLoadEarlier = onLoadEarlier,
today = state.today, today = state.today,
zone = state.zone, zone = state.zone,
listState = listState, listState = listState,
@@ -349,6 +383,10 @@ internal fun AgendaContent(
@Composable @Composable
private fun AgendaList( private fun AgendaList(
days: List<AgendaDay>, days: List<AgendaDay>,
anchor: LocalDate,
anchorIndex: MutableIntState,
initialTopDate: LocalDate?,
onLoadEarlier: () -> Unit,
today: LocalDate, today: LocalDate,
zone: TimeZone, zone: TimeZone,
listState: LazyListState, listState: LazyListState,
@@ -359,19 +397,49 @@ private fun AgendaList(
onTopDay: ((LocalDate) -> Unit)?, onTopDay: ((LocalDate) -> Unit)?,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
) { ) {
val itemDates = agendaItemDates(days)
val anchorRow = itemDates.indexOfFirst { it >= anchor }.coerceAtLeast(0)
SideEffect { anchorIndex.intValue = anchorRow }
// A new anchor opens the list on its row from the first frame, with past
// days above. 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. The first run
// may restore a remembered day instead.
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) { if (onTopDay != null) {
val itemDates by rememberUpdatedState(agendaItemDates(days)) val currentItemDates by rememberUpdatedState(itemDates)
val currentOnTopDay by rememberUpdatedState(onTopDay) val currentOnTopDay by rememberUpdatedState(onTopDay)
// The day the list opened on is where the view already is; only a // The day the list opened on is where the view already is; only a
// scroll moves it on. // scroll moves it on.
LaunchedEffect(listState) { LaunchedEffect(listState) {
snapshotFlow { listState.firstVisibleItemIndex } snapshotFlow { listState.firstVisibleItemIndex }
.drop(1) .drop(1)
.collect { index -> itemDates.getOrNull(index)?.let(currentOnTopDay) } .collect { index -> currentItemDates.getOrNull(index)?.let(currentOnTopDay) }
} }
} }
LazyColumn( LazyColumn(
modifier = modifier, modifier = modifier.nestedScroll(loadOnScrollUp),
state = listState, state = listState,
// Bottom inset clears the FAB stack so the last row stays tappable. // 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 = 96.dp),
@@ -401,7 +469,7 @@ private fun AgendaList(
day = day.date, day = day.date,
zone = zone, zone = zone,
position = positionOf(index, day.events.size), position = positionOf(index, day.events.size),
dimmed = dimPast && event.hasEnded(now), dimmed = dimPast && event.isPastOn(day.date, now, zone),
modifier = animateItemMotion().morphEvent(ViewMorphKey.event(event, day.date)), modifier = animateItemMotion().morphEvent(ViewMorphKey.event(event, day.date)),
onClick = { onEventClick(event) }, onClick = { onEventClick(event) },
) )
@@ -412,6 +480,9 @@ private fun AgendaList(
} }
} }
/** 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. */ /** The day of each item [AgendaList] lays out for [days], in its order. */
internal fun agendaItemDates(days: List<AgendaDay>): List<LocalDate> = internal fun agendaItemDates(days: List<AgendaDay>): List<LocalDate> =
days.flatMap { day -> days.flatMap { day ->
@@ -93,22 +93,21 @@ fun groupAgendaDays(
} }
/** /**
* Ensure [today] surfaces as the first agenda day even when it carries no * Ensure [today] surfaces in the agenda even when it carries no (remaining)
* (remaining) events, by prepending an empty-event [AgendaDay] the agenda widget * 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 * 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 * when today already has its own day in [days]. Keeps today anchored so a glance
* so a glance tells today's events apart from a future day's (issue #35). * tells today's events apart from a future day's (issue #35).
*/ */
fun anchorTodayIfMissing( fun anchorTodayIfMissing(
days: List<AgendaDay>, days: List<AgendaDay>,
today: LocalDate, today: LocalDate,
enabled: Boolean, enabled: Boolean,
): List<AgendaDay> = ): List<AgendaDay> {
if (enabled && days.none { it.date == today }) { if (!enabled || days.any { it.date == today }) return days
listOf(AgendaDay(today, emptyList())) + days val at = days.indexOfFirst { it.date > today }.let { if (it < 0) days.size else it }
} else { return days.take(at) + AgendaDay(today, emptyList()) + days.drop(at)
days }
}
/** /**
* State for the Agenda view: a flat, forward-looking list of upcoming events * State for the Agenda view: a flat, forward-looking list of upcoming events
@@ -118,8 +117,10 @@ sealed interface AgendaUiState {
data object Loading : AgendaUiState data object Loading : AgendaUiState
data class Failure(val reason: FailureReason) : AgendaUiState data class Failure(val reason: FailureReason) : AgendaUiState
data class Success( 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, val anchor: LocalDate,
/** First loaded day, before [anchor] once past days are loaded (#367). */
val windowStart: LocalDate,
val today: LocalDate, val today: LocalDate,
val days: List<AgendaDay>, val days: List<AgendaDay>,
/** The range currently in effect — the saved default or a session override. */ /** The range currently in effect — the saved default or a session override. */
@@ -4,14 +4,17 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.lifecycle.HiltViewModel
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository 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.PastEventDisplay
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.data.prefs.firstDayOfWeek 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.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.domain.FailureReason import de.jeanlucmakiola.calendula.domain.FailureReason
import de.jeanlucmakiola.calendula.domain.calendarListFailure import de.jeanlucmakiola.calendula.domain.calendarListFailure
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
import de.jeanlucmakiola.floret.di.IoDispatcher
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
@@ -21,6 +24,8 @@ import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.stateIn
import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.DayOfWeek import kotlinx.datetime.DayOfWeek
@@ -28,10 +33,9 @@ import kotlinx.datetime.LocalDate
import kotlinx.datetime.TimeZone import kotlinx.datetime.TimeZone
import kotlinx.datetime.atStartOfDayIn import kotlinx.datetime.atStartOfDayIn
import kotlinx.datetime.atTime import kotlinx.datetime.atTime
import kotlinx.datetime.minus
import kotlinx.datetime.plus import kotlinx.datetime.plus
import kotlinx.datetime.toInstant import kotlinx.datetime.toInstant
import kotlinx.datetime.toLocalDateTime
import kotlin.time.Clock
import kotlin.time.Instant import kotlin.time.Instant
import javax.inject.Inject import javax.inject.Inject
@@ -40,6 +44,7 @@ import javax.inject.Inject
class AgendaViewModel @Inject constructor( class AgendaViewModel @Inject constructor(
private val repository: CalendarRepository, private val repository: CalendarRepository,
settingsPrefs: SettingsPrefs, settingsPrefs: SettingsPrefs,
todaySource: TodaySource,
@IoDispatcher private val io: CoroutineDispatcher, @IoDispatcher private val io: CoroutineDispatcher,
) : ViewModel() { ) : ViewModel() {
@@ -62,9 +67,8 @@ class AgendaViewModel @Inject constructor(
* the screen combines it with a per-minute "now" to fade or drop past rows. * the screen combines it with a per-minute "now" to fade or drop past rows.
*/ */
val pastEventDisplay: StateFlow<PastEventDisplay> = settingsPrefs.pastEventDisplay val pastEventDisplay: StateFlow<PastEventDisplay> = settingsPrefs.pastEventDisplay
.stateIn( .stateWhileSubscribed(
scope = viewModelScope, scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = PastEventDisplay.SHOW, initialValue = PastEventDisplay.SHOW,
) )
@@ -75,19 +79,42 @@ class AgendaViewModel @Inject constructor(
* alongside the data state like [pastEventDisplay] rather than re-querying. * alongside the data state like [pastEventDisplay] rather than re-querying.
*/ */
val showToday: StateFlow<Boolean> = settingsPrefs.agendaShowToday val showToday: StateFlow<Boolean> = settingsPrefs.agendaShowToday
.stateIn( .stateWhileSubscribed(
scope = viewModelScope, scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = true, initialValue = true,
) )
private val zone = TimeZone.currentSystemDefault() private val zone = TimeZone.currentSystemDefault()
private val todayDate: LocalDate private val todayDate: LocalDate
get() = Clock.System.now().toLocalDateTime(zone).date get() = currentDate()
private val _anchor = MutableStateFlow(todayDate) // The anchor and how many days before it are loaded, moved together so a
val anchor: StateFlow<LocalDate> = _anchor // 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
private var lastToday = todayDate
/**
* 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
.onEach { date ->
val old = lastToday
lastToday = date
if (old != date && _window.value.anchor == old) {
_window.value = _window.value.copy(anchor = date)
}
}
.stateWhileSubscribed(viewModelScope, todayDate)
// A transient, in-view override of the saved agenda range. Held in memory // A transient, in-view override of the saved agenda range. Held in memory
// (not persisted), so it survives view switches and rotation within the // (not persisted), so it survives view switches and rotation within the
@@ -95,9 +122,17 @@ class AgendaViewModel @Inject constructor(
private val _rangeOverride = MutableStateFlow<AgendaRange?>(null) private val _rangeOverride = MutableStateFlow<AgendaRange?>(null)
val state: StateFlow<AgendaUiState> = 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( 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, range = override ?: settings.range,
rangeIsOverride = override != null && override != settings.range, rangeIsOverride = override != null && override != settings.range,
weekStart = weekStart, weekStart = weekStart,
@@ -106,32 +141,50 @@ class AgendaViewModel @Inject constructor(
} }
.flatMapLatest { params -> .flatMapLatest { params ->
val window = agendaRange( val window = agendaRange(
params.anchor, params.windowStart,
params.range.dayCount(params.anchor, params.weekStart) - 1, params.pastDays + params.range.dayCount(params.anchor, params.weekStart) - 1,
zone, zone,
) )
combine( combine(
repository.calendars(), repository.calendars(),
repository.instances(window), repository.instances(window),
) { calendars, instances -> today,
buildState(params, calendars, instances) ) { calendars, instances, today ->
buildState(params, calendars, instances, today)
} }
} }
.catch { emit(AgendaUiState.Failure(FailureReason.ProviderUnavailable)) } .catch { emit(AgendaUiState.Failure(FailureReason.ProviderUnavailable)) }
.flowOn(io) .flowOn(io)
.stateIn( .stateWhileSubscribed(
scope = viewModelScope, scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = AgendaUiState.Loading, initialValue = AgendaUiState.Loading,
) )
fun goToToday() { fun goToToday() {
_anchor.value = todayDate goToDate(todayDate)
} }
/** Jump the agenda window to start on a specific date (drawer jump-to-date). */ /** Jump the agenda window to start on a specific date (drawer jump-to-date). */
fun goToDate(date: LocalDate) { 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 [PAST_CHUNK_DAYS] further back (#367). Ignored while the
* previous extension is still loading, so a scroll that keeps asking only
* moves one chunk at a time.
*/
fun loadEarlier() {
val loaded = (state.value as? AgendaUiState.Success)?.windowStart ?: return
val window = _window.value
if (loaded != window.start) return
_window.value = window.copy(pastDays = window.pastDays + PAST_CHUNK_DAYS)
}
fun rememberTopDay(date: LocalDate) {
lastTopDate = date
} }
/** Temporarily override the agenda range for this session (the bottom-left pill). */ /** Temporarily override the agenda range for this session (the bottom-left pill). */
@@ -144,18 +197,26 @@ class AgendaViewModel @Inject constructor(
val showBar: Boolean, 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( private data class AgendaParams(
val anchor: LocalDate, val anchor: LocalDate,
val pastDays: Int,
val range: AgendaRange, val range: AgendaRange,
val rangeIsOverride: Boolean, val rangeIsOverride: Boolean,
val weekStart: DayOfWeek, val weekStart: DayOfWeek,
val showRangeBar: Boolean, val showRangeBar: Boolean,
) ) {
val windowStart: LocalDate get() = anchor.minus(pastDays, DateTimeUnit.DAY)
}
private fun buildState( private fun buildState(
params: AgendaParams, params: AgendaParams,
calendars: List<CalendarSource>, calendars: List<CalendarSource>,
instances: List<EventInstance>, instances: List<EventInstance>,
today: LocalDate,
): AgendaUiState { ): AgendaUiState {
calendarListFailure(calendars)?.let { return AgendaUiState.Failure(it) } calendarListFailure(calendars)?.let { return AgendaUiState.Failure(it) }
val anchor = params.anchor val anchor = params.anchor
@@ -163,10 +224,11 @@ class AgendaViewModel @Inject constructor(
params.range.dayCount(anchor, params.weekStart) - 1, params.range.dayCount(anchor, params.weekStart) - 1,
DateTimeUnit.DAY, DateTimeUnit.DAY,
) )
val days = groupAgendaDays(anchor, rangeEnd, instances, zone) val days = groupAgendaDays(params.windowStart, rangeEnd, instances, zone)
return AgendaUiState.Success( return AgendaUiState.Success(
anchor = anchor, anchor = anchor,
today = todayDate, windowStart = params.windowStart,
today = today,
days = days, days = days,
range = params.range, range = params.range,
rangeIsOverride = params.rangeIsOverride, rangeIsOverride = params.rangeIsOverride,
@@ -177,6 +239,9 @@ class AgendaViewModel @Inject constructor(
} }
} }
/** How many days each scroll back into the past loads (#367). */
internal const val PAST_CHUNK_DAYS = 30
/** Inclusive instant range from the start of [anchor] through [days] days ahead. */ /** Inclusive instant range from the start of [anchor] through [days] days ahead. */
internal fun agendaRange(anchor: LocalDate, days: Int, zone: TimeZone): ClosedRange<Instant> { internal fun agendaRange(anchor: LocalDate, days: Int, zone: TimeZone): ClosedRange<Instant> {
val from = anchor.atStartOfDayIn(zone) val from = anchor.atStartOfDayIn(zone)
@@ -6,8 +6,8 @@ import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.Dp
import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay
import de.jeanlucmakiola.calendula.ui.common.ScaledViewPreview
import de.jeanlucmakiola.calendula.ui.common.sampleAgendaEvents import de.jeanlucmakiola.calendula.ui.common.sampleAgendaEvents
import de.jeanlucmakiola.floret.components.ScaledViewPreview
import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.LocalDate import kotlinx.datetime.LocalDate
import kotlinx.datetime.TimeZone 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) val windowEnd = today.plus(PREVIEW_WINDOW_DAYS, DateTimeUnit.DAY)
return AgendaUiState.Success( return AgendaUiState.Success(
anchor = today, anchor = today,
windowStart = today,
today = today, today = today,
days = groupAgendaDays(today, windowEnd, sampleAgendaEvents(today, zone), zone), days = groupAgendaDays(today, windowEnd, sampleAgendaEvents(today, zone), zone),
range = AgendaRange.Custom(PREVIEW_WINDOW_DAYS), range = AgendaRange.Custom(PREVIEW_WINDOW_DAYS),
@@ -1,7 +1,6 @@
package de.jeanlucmakiola.calendula.ui.calendars package de.jeanlucmakiola.calendula.ui.calendars
import android.net.Uri import android.net.Uri
import android.text.format.DateUtils
import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
@@ -58,9 +57,12 @@ import de.jeanlucmakiola.floret.components.CollapsingScaffold
import de.jeanlucmakiola.floret.components.DialogAmountField import de.jeanlucmakiola.floret.components.DialogAmountField
import de.jeanlucmakiola.floret.components.DialogUnitDropdown import de.jeanlucmakiola.floret.components.DialogUnitDropdown
import de.jeanlucmakiola.floret.components.FullScreenPicker import de.jeanlucmakiola.floret.components.FullScreenPicker
import de.jeanlucmakiola.floret.components.GroupedHint
import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.GroupedRow
import de.jeanlucmakiola.floret.components.GroupedSectionHeader
import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.Position
import de.jeanlucmakiola.floret.components.positionOf import de.jeanlucmakiola.floret.components.positionOf
import de.jeanlucmakiola.floret.locale.relativeTimeAgo
import java.time.LocalDate import java.time.LocalDate
// SAF mime filter for the restore picker. Source apps hand `.ics` files out // SAF mime filter for the restore picker. Source apps hand `.ics` files out
@@ -222,8 +224,8 @@ private fun BackupContent(
val onRestoreClick = if (canImport) onRestore else (manageCalendars ?: onRestore) val onRestoreClick = if (canImport) onRestore else (manageCalendars ?: onRestore)
if (exportable.isEmpty()) { if (exportable.isEmpty()) {
SectionHeader(stringResource(R.string.calendars_restore_header)) GroupedSectionHeader(stringResource(R.string.calendars_restore_header))
HintText(restoreSummary) GroupedHint(restoreSummary, style = MaterialTheme.typography.bodySmall)
GroupedRow( GroupedRow(
title = stringResource(R.string.calendars_restore_action), title = stringResource(R.string.calendars_restore_action),
position = Position.Alone, position = Position.Alone,
@@ -233,7 +235,7 @@ private fun BackupContent(
return return
} }
HintText(stringResource(R.string.calendars_backup_hint)) GroupedHint(stringResource(R.string.calendars_backup_hint), style = MaterialTheme.typography.bodySmall)
GroupedRow( GroupedRow(
title = stringResource(R.string.calendars_backup_action), title = stringResource(R.string.calendars_backup_action),
position = Position.Top, position = Position.Top,
@@ -272,7 +274,7 @@ private fun BackupContent(
position = Position.Bottom, position = Position.Bottom,
onClick = onEditInterval, onClick = onEditInterval,
) )
HintText(backupStatusText(autoBackup.status)) GroupedHint(backupStatusText(autoBackup.status), style = MaterialTheme.typography.bodySmall)
} }
} }
@@ -309,8 +311,9 @@ private fun ExportCalendarPicker(
FullScreenPicker( FullScreenPicker(
title = stringResource(R.string.calendars_export_title), title = stringResource(R.string.calendars_export_title),
onDismiss = onDismiss, onDismiss = onDismiss,
predictiveBack = true,
) { ) {
HintText(stringResource(R.string.calendars_export_hint)) GroupedHint(stringResource(R.string.calendars_export_hint), style = MaterialTheme.typography.bodySmall)
calendars.forEachIndexed { index, calendar -> calendars.forEachIndexed { index, calendar ->
val isSelected = calendar.id in selected val isSelected = calendar.id in selected
GroupedRow( GroupedRow(
@@ -376,9 +379,7 @@ private fun backupIntervalLabel(minutes: Long): String {
@Composable @Composable
private fun backupStatusText(status: BackupStatus): String { private fun backupStatusText(status: BackupStatus): String {
if (status.lastRun == 0L) return stringResource(R.string.calendars_auto_backup_status_never) if (status.lastRun == 0L) return stringResource(R.string.calendars_auto_backup_status_never)
val relative = DateUtils.getRelativeTimeSpanString( val relative = relativeTimeAgo(status.lastRun)
status.lastRun, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS,
).toString()
return if (status.lastSuccess) { return if (status.lastSuccess) {
stringResource(R.string.calendars_auto_backup_status_ok, relative) stringResource(R.string.calendars_auto_backup_status_ok, relative)
} else { } else {
@@ -6,34 +6,27 @@ import android.content.Intent
import android.provider.Settings import android.provider.Settings
import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight 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.automirrored.filled.OpenInNew
import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Backup import androidx.compose.material.icons.filled.Backup
import androidx.compose.material.icons.filled.CalendarMonth 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.Delete
import androidx.compose.material.icons.filled.Info import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.MoreVert 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.PhoneAndroid
import androidx.compose.material.icons.filled.Visibility import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff import androidx.compose.material.icons.filled.VisibilityOff
@@ -41,20 +34,15 @@ import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch import androidx.compose.material3.Switch
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
@@ -95,10 +83,12 @@ import de.jeanlucmakiola.calendula.ui.common.LeadingAvatar
import de.jeanlucmakiola.calendula.ui.common.SourceLogo import de.jeanlucmakiola.calendula.ui.common.SourceLogo
import de.jeanlucmakiola.calendula.ui.common.curatedSourcePackage import de.jeanlucmakiola.calendula.ui.common.curatedSourcePackage
import de.jeanlucmakiola.floret.components.CollapsingScaffold import de.jeanlucmakiola.floret.components.CollapsingScaffold
import de.jeanlucmakiola.floret.components.GroupedHint
import de.jeanlucmakiola.floret.components.GroupedSectionHeader
import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme
import de.jeanlucmakiola.floret.identity.collapseExit import de.jeanlucmakiola.floret.identity.collapseExit
import de.jeanlucmakiola.floret.identity.expandEnter import de.jeanlucmakiola.floret.identity.expandEnter
import de.jeanlucmakiola.floret.identity.predictiveBack import de.jeanlucmakiola.floret.identity.predictiveBack
import de.jeanlucmakiola.floret.components.GroupedListInset
import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.GroupedRow
import de.jeanlucmakiola.floret.components.InlineTextField import de.jeanlucmakiola.floret.components.InlineTextField
import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.Position
@@ -224,7 +214,7 @@ private fun CalendarsList(
visible = visible, visible = visible,
) { ) {
// What the per-calendar / per-account switches below actually do. // 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 // Local (device-only) calendars — one collapsible group. The header's
// "+" adds a calendar; the switch enables/disables them all at once; // "+" adds a calendar; the switch enables/disables them all at once;
@@ -245,7 +235,7 @@ private fun CalendarsList(
onToggleAll = { enabled -> onSetAccountVisible(local.map { it.id }, enabled) }, onToggleAll = { enabled -> onSetAccountVisible(local.map { it.id }, enabled) },
) { ) {
if (local.isEmpty()) { if (local.isEmpty()) {
HintText(stringResource(R.string.calendars_local_empty)) GroupedHint(stringResource(R.string.calendars_local_empty), style = MaterialTheme.typography.bodySmall)
} else { } else {
local.forEachIndexed { index, calendar -> local.forEachIndexed { index, calendar ->
val disabled = !calendar.isVisibleInSystem val disabled = !calendar.isVisibleInSystem
@@ -291,8 +281,8 @@ private fun CalendarsList(
// Synced calendars — read-only, grouped by account. Each account is a // Synced calendars — read-only, grouped by account. Each account is a
// collapsible group whose header opens the source app (icon) and toggles // collapsible group whose header opens the source app (icon) and toggles
// all of its calendars at once (switch). // all of its calendars at once (switch).
SectionHeader(stringResource(R.string.calendars_synced_header)) GroupedSectionHeader(stringResource(R.string.calendars_synced_header))
HintText(stringResource(R.string.calendars_synced_hint)) GroupedHint(stringResource(R.string.calendars_synced_hint), style = MaterialTheme.typography.bodySmall)
synced synced
.groupByAccount() .groupByAccount()
.forEach { group -> .forEach { group ->
@@ -478,7 +468,7 @@ private fun CalendarNameField(
onNameChange: (String) -> Unit, onNameChange: (String) -> Unit,
onImeAction: () -> Unit, onImeAction: () -> Unit,
) { ) {
val dark = isSystemInDarkTheme() val dark = LocalFloretDarkTheme.current
val soften = LocalSoftenColors.current val soften = LocalSoftenColors.current
GroupedSurface(position = Position.Alone, modifier = Modifier.padding(horizontal = 16.dp)) { GroupedSurface(position = Position.Alone, modifier = Modifier.padding(horizontal = 16.dp)) {
Row( Row(
@@ -522,7 +512,7 @@ private fun CalendarNameField(
*/ */
@Composable @Composable
private fun CalendarColorGrid(selected: Int, onSelect: (Int) -> Unit) { private fun CalendarColorGrid(selected: Int, onSelect: (Int) -> Unit) {
val dark = isSystemInDarkTheme() val dark = LocalFloretDarkTheme.current
val soften = LocalSoftenColors.current val soften = LocalSoftenColors.current
GroupedSurface(position = Position.Alone, modifier = Modifier.padding(horizontal = 16.dp)) { GroupedSurface(position = Position.Alone, modifier = Modifier.padding(horizontal = 16.dp)) {
Column( Column(
@@ -841,33 +831,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 * Pick the app to open for managing a synced calendar's account. The account's
* own authenticator package (resolved from [AccountManager], no permission * own authenticator package (resolved from [AccountManager], no permission
@@ -9,16 +9,16 @@ import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.calendula.data.backup.BackupScheduler import de.jeanlucmakiola.calendula.data.backup.BackupScheduler
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
import de.jeanlucmakiola.calendula.data.di.IoDispatcher
import de.jeanlucmakiola.calendula.data.ics.IcsExporter import de.jeanlucmakiola.calendula.data.ics.IcsExporter
import de.jeanlucmakiola.calendula.data.prefs.BackupStatus import de.jeanlucmakiola.calendula.data.prefs.BackupStatus
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.FailureReason import de.jeanlucmakiola.calendula.domain.FailureReason
import de.jeanlucmakiola.calendula.domain.ics.IcsWriter import de.jeanlucmakiola.calendula.domain.ics.IcsWriter
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
import de.jeanlucmakiola.floret.di.IoDispatcher
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.catch
@@ -26,7 +26,6 @@ import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import kotlin.coroutines.cancellation.CancellationException import kotlin.coroutines.cancellation.CancellationException
@@ -52,9 +51,8 @@ class CalendarsViewModel @Inject constructor(
repository.calendars() repository.calendars()
.catch { emit(emptyList()) } .catch { emit(emptyList()) }
.flowOn(io) .flowOn(io)
.stateIn( .stateWhileSubscribed(
scope = viewModelScope, scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = emptyList(), initialValue = emptyList(),
) )
@@ -68,9 +66,8 @@ class CalendarsViewModel @Inject constructor(
.map { backupUiState(it) } .map { backupUiState(it) }
.catch { emit(BackupUiState.Failure(FailureReason.ProviderUnavailable)) } .catch { emit(BackupUiState.Failure(FailureReason.ProviderUnavailable)) }
.flowOn(io) .flowOn(io)
.stateIn( .stateWhileSubscribed(
scope = viewModelScope, scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = BackupUiState.Loading, initialValue = BackupUiState.Loading,
) )
@@ -84,9 +81,8 @@ class CalendarsViewModel @Inject constructor(
AutoBackupUiState(enabled, interval, folder, status) AutoBackupUiState(enabled, interval, folder, status)
} }
.flowOn(io) .flowOn(io)
.stateIn( .stateWhileSubscribed(
scope = viewModelScope, scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = AutoBackupUiState(), initialValue = AutoBackupUiState(),
) )
@@ -103,9 +99,8 @@ class CalendarsViewModel @Inject constructor(
if (!enabled) emptySet() else sources.filter { it.isManaged }.map { it.id }.toSet() if (!enabled) emptySet() else sources.filter { it.isManaged }.map { it.id }.toSet()
} }
.flowOn(io) .flowOn(io)
.stateIn( .stateWhileSubscribed(
scope = viewModelScope, scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = emptySet(), initialValue = emptySet(),
) )
@@ -278,12 +278,23 @@ data class BlockPlacement(val xFraction: Float, val widthFraction: Float, val y:
* A pinch-zoom rewrites the hour height every pointer frame, and the gutter and * A pinch-zoom rewrites the hour height every pointer frame, and the gutter and
* grid lines follow it instantly — so the tween stands down for the gesture * grid lines follow it instantly — so the tween stands down for the gesture
* rather than leaving the blocks trailing the ruler they are measured against. * rather than leaving the blocks trailing the ruler they are measured against.
* A [landing] block, under a dropped copy, moves without the spring's bounce.
*/ */
@OptIn(ExperimentalMaterial3ExpressiveApi::class) @OptIn(ExperimentalMaterial3ExpressiveApi::class)
@Composable @Composable
fun animatedBlockPlacement(xFraction: Float, widthFraction: Float, y: Dp, height: Dp): BlockPlacement { fun animatedBlockPlacement(
xFraction: Float,
widthFraction: Float,
y: Dp,
height: Dp,
landing: Boolean = false,
): BlockPlacement {
val still = rememberReduceMotion() || LocalTimelineZoom.current.isPinching val still = rememberReduceMotion() || LocalTimelineZoom.current.isPinching
val dpSpec: FiniteAnimationSpec<Dp> = if (still) snap() else MaterialTheme.motionScheme.fastSpatialSpec() val dpSpec: FiniteAnimationSpec<Dp> = when {
still -> snap()
landing -> MaterialTheme.motionScheme.fastEffectsSpec()
else -> MaterialTheme.motionScheme.fastSpatialSpec()
}
val shareSpec: FiniteAnimationSpec<Float> = if (still) snap() else MaterialTheme.motionScheme.fastSpatialSpec() val shareSpec: FiniteAnimationSpec<Float> = if (still) snap() else MaterialTheme.motionScheme.fastSpatialSpec()
val animatedX by animateFloatAsState(xFraction, shareSpec, label = "block-x") val animatedX by animateFloatAsState(xFraction, shareSpec, label = "block-x")
val animatedWidth by animateFloatAsState(widthFraction, shareSpec, label = "block-width") val animatedWidth by animateFloatAsState(widthFraction, shareSpec, label = "block-width")
@@ -1,5 +1,14 @@
package de.jeanlucmakiola.calendula.ui.common package de.jeanlucmakiola.calendula.ui.common
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.animation.togetherWith
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.PaddingValues
@@ -16,6 +25,9 @@ import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.Immutable import androidx.compose.runtime.Immutable
import androidx.compose.runtime.SideEffect import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.Stable import androidx.compose.runtime.Stable
@@ -24,6 +36,7 @@ import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.domain.EventInstance
import kotlinx.datetime.LocalDate import kotlinx.datetime.LocalDate
/** /**
@@ -53,12 +66,39 @@ class ScreenActions(
val onCreate: () -> Unit, val onCreate: () -> Unit,
) )
/**
* An event a long press left selected (#141), which the host answers with the
* action bar in place of the FAB. [dismiss] clears it on the screen that owns it.
* [create] is set for a block drafted on an empty slot (#153), which has no
* event yet, so the bar offers to create one.
*/
@Stable
class EventSelection(
val event: EventInstance,
val dismiss: () -> Unit,
val create: (() -> Unit)? = null,
/** The event at the times an ongoing move or resize would give it, else null. */
val preview: () -> EventInstance? = { null },
)
/** The screen on show's [ScreenChrome] and [ScreenActions], for the host to draw. */ /** The screen on show's [ScreenChrome] and [ScreenActions], for the host to draw. */
@Stable @Stable
class ChromeHost { class ChromeHost {
var chrome by mutableStateOf<ScreenChrome?>(null) var chrome by mutableStateOf<ScreenChrome?>(null)
private set private set
var selection by mutableStateOf<EventSelection?>(null)
internal set
/** Whether the selected event is being dragged or resized right now. */
var selectionBusy by mutableStateOf(false)
internal set
/** Whether the bar would cover the selected event, and so draws compact. */
var selectionCompact by mutableStateOf(false)
internal set
var actions: ScreenActions? = null var actions: ScreenActions? = null
private set private set
@@ -80,8 +120,54 @@ fun PublishChrome(chrome: ScreenChrome, actions: ScreenActions) {
if (slot.current) SideEffect { slot.host.publish(chrome, actions) } if (slot.current) SideEffect { slot.host.publish(chrome, actions) }
} }
/** The top bar every calendar screen shares. */ /** Hands the screen's selected [event] to the host, for as long as it stays selected. */
@OptIn(ExperimentalMaterial3Api::class) @Composable
fun PublishSelection(
event: EventInstance?,
busy: Boolean,
compact: Boolean,
onDismiss: () -> Unit,
onCreate: (() -> Unit)? = null,
preview: () -> EventInstance? = { null },
) {
val slot = LocalChromeSlot.current ?: return
val currentDismiss by rememberUpdatedState(onDismiss)
val currentCreate by rememberUpdatedState(onCreate)
val currentPreview by rememberUpdatedState(preview)
val drafted = onCreate != null
val selection = remember(event, drafted) {
event?.let {
EventSelection(
event = it,
dismiss = { currentDismiss() },
create = if (drafted) ({ currentCreate?.invoke() }) else null,
preview = { currentPreview() },
)
}
}
val host = slot.host
val current = slot.current
DisposableEffect(host, selection, current) {
if (current) host.selection = selection
onDispose {
if (host.selection === selection) host.selection = null
// Left mid-drag, nothing else would clear these for the other views.
host.selectionBusy = false
host.selectionCompact = false
}
}
if (current) {
SideEffect {
host.selectionBusy = busy && selection != null
host.selectionCompact = compact && selection != null
}
}
}
/**
* The top bar every calendar screen shares — or, while an event is selected,
* the selection's own bar in its place (#141).
*/
@Composable @Composable
fun CalendarTopBar( fun CalendarTopBar(
host: ChromeHost, host: ChromeHost,
@@ -91,6 +177,43 @@ fun CalendarTopBar(
onOpenDrawer: () -> Unit, onOpenDrawer: () -> Unit,
onOpenSearch: () -> Unit, onOpenSearch: () -> Unit,
showTodayButton: Boolean, showTodayButton: Boolean,
) {
val effects = MaterialTheme.motionScheme.fastEffectsSpec<Float>()
AnimatedContent(
targetState = host.selection,
contentKey = { it != null },
transitionSpec = {
(fadeIn(effects) + slideInVertically { -it / 4 })
.togetherWith(fadeOut(effects) + slideOutVertically { -it / 4 })
},
label = "top-bar",
) { selection ->
if (selection != null) {
SelectionTopBar(selection)
} else {
ViewTopBar(
host = host,
selectedView = selectedView,
quickSwitchViews = quickSwitchViews,
onCycleView = onCycleView,
onOpenDrawer = onOpenDrawer,
onOpenSearch = onOpenSearch,
showTodayButton = showTodayButton,
)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun ViewTopBar(
host: ChromeHost,
selectedView: CalendarView,
quickSwitchViews: List<CalendarView>,
onCycleView: () -> Unit,
onOpenDrawer: () -> Unit,
onOpenSearch: () -> Unit,
showTodayButton: Boolean,
) { ) {
val chrome = host.chrome val chrome = host.chrome
TopAppBar( TopAppBar(
@@ -136,16 +259,26 @@ fun CalendarTopBar(
) )
} }
/** The FAB column every calendar screen shares. */ /**
* The FAB column every calendar screen shares. While an event is selected the
* FAB is [selection]'s toggle instead, and it steps aside mid-gesture.
*/
@Composable @Composable
fun CalendarFab(host: ChromeHost, todayInToolbar: Boolean) { fun CalendarFab(host: ChromeHost, todayInToolbar: Boolean, selection: FabSelection? = null) {
val chrome = host.chrome ?: return val chrome = host.chrome ?: return
CalendarFabColumn( AnimatedVisibility(
todayVisible = chrome.awayFromToday && !todayInToolbar, visible = !host.selectionBusy,
todayText = chrome.todayText, enter = scaleIn(MaterialTheme.motionScheme.fastSpatialSpec()) + fadeIn(),
onToday = { host.actions?.onToday?.invoke() }, exit = scaleOut(MaterialTheme.motionScheme.fastSpatialSpec()) + fadeOut(),
onCreate = { host.actions?.onCreate?.invoke() }, ) {
) CalendarFabColumn(
todayVisible = chrome.awayFromToday && !todayInToolbar,
todayText = chrome.todayText,
onToday = { host.actions?.onToday?.invoke() },
onCreate = { host.actions?.onCreate?.invoke() },
selection = selection,
)
}
} }
/** /**
@@ -1,7 +1,6 @@
package de.jeanlucmakiola.calendula.ui.common package de.jeanlucmakiola.calendula.ui.common
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CircleShape
@@ -14,6 +13,7 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme
/** /**
* Leading avatar for a calendar: a neutral chip holding a calendar glyph tinted * Leading avatar for a calendar: a neutral chip holding a calendar glyph tinted
@@ -23,7 +23,7 @@ import androidx.compose.ui.unit.dp
*/ */
@Composable @Composable
fun CalendarColorChip(color: Int, modifier: Modifier = Modifier) { fun CalendarColorChip(color: Int, modifier: Modifier = Modifier) {
val dark = isSystemInDarkTheme() val dark = LocalFloretDarkTheme.current
val soften = LocalSoftenColors.current val soften = LocalSoftenColors.current
Box( Box(
modifier = modifier modifier = modifier
@@ -1,11 +1,20 @@
package de.jeanlucmakiola.calendula.ui.common package de.jeanlucmakiola.calendula.ui.common
import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.expandHorizontally
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut import androidx.compose.animation.scaleOut
import androidx.compose.animation.shrinkHorizontally
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.height
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Refresh import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
@@ -15,15 +24,38 @@ import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.R
/** The standard FAB's size, shared by the selection bar that unrolls from it (#141). */
val FabSize = 56.dp
/** What the FAB is while an event is selected (#141): the toggle for its action bar. */
@Stable
class FabSelection(
val expanded: Boolean,
val onToggle: () -> Unit,
val bar: @Composable () -> Unit,
)
/** /**
* The FAB stack shared by the three calendar views: a persistent "+" to * The FAB stack shared by the three calendar views: a persistent "+" to
* create an event, with the jump-to-today pill appearing above it whenever * create an event, with the jump-to-today pill appearing above it whenever
* the view isn't anchored on today. * the view isn't anchored on today. While an event is selected the same FAB,
* in the same spot, opens and folds the selection's action bar, which unrolls
* from it towards the start.
*/ */
@OptIn(ExperimentalMaterial3ExpressiveApi::class) @OptIn(ExperimentalMaterial3ExpressiveApi::class)
@Composable @Composable
@@ -32,13 +64,14 @@ fun CalendarFabColumn(
todayText: String, todayText: String,
onToday: () -> Unit, onToday: () -> Unit,
onCreate: () -> Unit, onCreate: () -> Unit,
selection: FabSelection? = null,
) { ) {
Column( Column(
horizontalAlignment = Alignment.End, horizontalAlignment = Alignment.End,
verticalArrangement = Arrangement.spacedBy(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp),
) { ) {
AnimatedVisibility( AnimatedVisibility(
visible = todayVisible, visible = todayVisible && selection == null,
enter = scaleIn(MaterialTheme.motionScheme.fastSpatialSpec()), enter = scaleIn(MaterialTheme.motionScheme.fastSpatialSpec()),
exit = scaleOut(MaterialTheme.motionScheme.fastSpatialSpec()), exit = scaleOut(MaterialTheme.motionScheme.fastSpatialSpec()),
) { ) {
@@ -48,11 +81,71 @@ fun CalendarFabColumn(
text = { Text(todayText) }, text = { Text(todayText) },
) )
} }
FloatingActionButton(onClick = onCreate) { // Held past the selection clearing, so the bar has something to fold away.
Icon( val heldBar = remember { mutableStateOf<(@Composable () -> Unit)?>(null) }
imageVector = Icons.Default.Add, if (selection != null && heldBar.value !== selection.bar) heldBar.value = selection.bar
contentDescription = stringResource(R.string.event_edit_new_title), // Held at the FAB's height so the taller bar can't shift the FAB.
Row(
modifier = Modifier.height(FabSize),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
AnimatedVisibility(
visible = selection?.expanded == true,
enter = expandHorizontally(
animationSpec = MaterialTheme.motionScheme.fastSpatialSpec(),
expandFrom = Alignment.End,
) + fadeIn(),
exit = shrinkHorizontally(
animationSpec = MaterialTheme.motionScheme.fastSpatialSpec(),
shrinkTowards = Alignment.End,
) + fadeOut(),
) {
heldBar.value?.invoke()
}
val label = stringResource(
when {
selection == null -> R.string.event_edit_new_title
selection.expanded -> R.string.event_selection_hide
else -> R.string.event_selection_actions
},
) )
FloatingActionButton(
onClick = selection?.onToggle ?: onCreate,
modifier = Modifier.semantics { contentDescription = label },
) {
FabGlyph(selecting = selection != null, expanded = selection?.expanded == true)
}
} }
} }
} }
/** "+", or with an event selected a chevron that turns to open and fold the bar. */
@Composable
private fun FabGlyph(selecting: Boolean, expanded: Boolean) {
val spatial = MaterialTheme.motionScheme.fastSpatialSpec<Float>()
val swap by animateFloatAsState(if (selecting) 1f else 0f, spatial, label = "fab-swap")
val turn by animateFloatAsState(if (expanded) 0f else 180f, spatial, label = "fab-turn")
Box(contentAlignment = Alignment.Center) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = null,
modifier = Modifier.graphicsLayer {
rotationZ = 90f * swap
scaleX = 1f - 0.5f * swap
scaleY = 1f - 0.5f * swap
alpha = (1f - swap).coerceIn(0f, 1f)
},
)
Icon(
imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight,
contentDescription = null,
modifier = Modifier.graphicsLayer {
rotationZ = turn - 90f * (1f - swap)
scaleX = 0.5f + 0.5f * swap
scaleY = 0.5f + 0.5f * swap
alpha = swap.coerceIn(0f, 1f)
},
)
}
}
@@ -34,7 +34,6 @@ import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.GroupedRow
import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.Position
import de.jeanlucmakiola.floret.components.SelectedCheck
/** /**
* The app's single "which calendar" selection list, shared by the event editor * The app's single "which calendar" selection list, shared by the event editor
@@ -114,17 +113,11 @@ private fun CalendarPickerGroup(
leading = leading, leading = leading,
) )
calendars.forEachIndexed { index, calendar -> calendars.forEachIndexed { index, calendar ->
val isSelected = calendar.id == selectedId
GroupedRow( GroupedRow(
title = calendar.displayName.ifBlank { stringResource(R.string.calendar_unnamed) }, title = calendar.displayName.ifBlank { stringResource(R.string.calendar_unnamed) },
position = if (index == calendars.lastIndex) Position.Bottom else Position.Middle, position = if (index == calendars.lastIndex) Position.Bottom else Position.Middle,
selected = isSelected, checked = calendar.id == selectedId,
leading = { CalendarColorChip(calendar.color) }, leading = { CalendarColorChip(calendar.color) },
trailing = if (isSelected) {
{ SelectedCheck() }
} else {
null
},
onClick = { onSelect(calendar.id) }, onClick = { onSelect(calendar.id) },
) )
} }
@@ -2,14 +2,16 @@ package de.jeanlucmakiola.calendula.ui.common
import android.content.ClipData import android.content.ClipData
import android.os.Build import android.os.Build
import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.hapticfeedback.HapticFeedbackType import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.ClipEntry import androidx.compose.ui.platform.ClipEntry
import androidx.compose.ui.platform.LocalClipboard import androidx.compose.ui.platform.LocalClipboard
@@ -67,9 +69,12 @@ fun rememberFieldCopier(snackbarHostState: SnackbarHostState): FieldCopier {
* *
* [onTap] carries a field's existing tap action through, announced as * [onTap] carries a field's existing tap action through, announced as
* [onTapLabel]; a field without one stays unclickable rather than growing a * [onTapLabel]; a field without one stays unclickable rather than growing a
* ripple that leads nowhere, and gets its long press announced through semantics instead. That branch merges the * ripple that leads nowhere. The long press is announced through semantics,
* node it sits on, so a screen reader lands on the field itself and finds the * merging the node it sits on, so a screen reader lands on the field itself
* action there — a bare container is never focused. * and finds the action there — a bare container is never focused.
*
* The press is caught ahead of the field's children, so a long press on a
* link inside the text copies too instead of leaving that stretch dead.
*/ */
@Composable @Composable
fun Modifier.copyOnLongPress( fun Modifier.copyOnLongPress(
@@ -80,27 +85,45 @@ fun Modifier.copyOnLongPress(
onTapLabel: String? = null, onTapLabel: String? = null,
): Modifier { ): Modifier {
val actionLabel = stringResource(R.string.field_copy_action) val actionLabel = stringResource(R.string.field_copy_action)
return if (onTap != null) { val haptics = LocalHapticFeedback.current
combinedClickable( return longPressAheadOfChildren(label, text, copy) {
onClick = onTap, haptics.performHapticFeedback(HapticFeedbackType.LongPress)
onClickLabel = onTapLabel, copy(label, text)
onLongClickLabel = actionLabel, }
onLongClick = { copy(label, text) }, .then(if (onTap != null) Modifier.clickable(onClickLabel = onTapLabel, onClick = onTap) else Modifier)
) .semantics(mergeDescendants = true) {
} else {
val haptics = LocalHapticFeedback.current
pointerInput(label, text, copy) {
detectTapGestures(
onLongPress = {
haptics.performHapticFeedback(HapticFeedbackType.LongPress)
copy(label, text)
},
)
}.semantics(mergeDescendants = true) {
onLongClick(actionLabel) { onLongClick(actionLabel) {
copy(label, text) copy(label, text)
true true
} }
} }
}
} }
/**
* Run [onLongPress] once a press has held still for the long-press timeout,
* watching on the initial pass — before the children see the events — and
* then swallow the rest of that press, so neither a link under the finger nor
* a tap handler fires on release.
*/
private fun Modifier.longPressAheadOfChildren(vararg keys: Any?, onLongPress: () -> Unit): Modifier =
pointerInput(*keys) {
awaitEachGesture {
val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)
val endedEarly = withTimeoutOrNull(viewConfiguration.longPressTimeoutMillis) {
while (true) {
val change = awaitPointerEvent(PointerEventPass.Initial).changes
.firstOrNull { it.id == down.id }
val moved = change != null &&
(change.position - down.position).getDistance() > viewConfiguration.touchSlop
if (change == null || !change.pressed || moved) break
}
true
}
if (endedEarly != null) return@awaitEachGesture
onLongPress()
do {
val event = awaitPointerEvent(PointerEventPass.Initial)
event.changes.forEach { it.consume() }
} while (event.changes.any { it.pressed })
}
}
@@ -0,0 +1,201 @@
package de.jeanlucmakiola.calendula.ui.common
import android.Manifest
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.Log
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.material3.AlertDialog
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
import de.jeanlucmakiola.calendula.data.calendar.NoSuchEventException
import de.jeanlucmakiola.calendula.data.ics.IcsExporter
import de.jeanlucmakiola.calendula.domain.EventDetail
import de.jeanlucmakiola.calendula.domain.RecurringWriteScope
import de.jeanlucmakiola.calendula.domain.ics.IcsWriter
import de.jeanlucmakiola.calendula.domain.ics.toShareIcsEvent
import de.jeanlucmakiola.floret.android.hasPermission
import de.jeanlucmakiola.floret.components.OptionCard
import kotlin.coroutines.cancellation.CancellationException
import kotlin.time.Clock
/**
* Serialise [detail] to a cache `.ics` and return a shareable content Uri for an
* `ACTION_SEND`, or null when the write fails. Exported as a one-off (see
* [toShareIcsEvent]). Blocking — call it off the main thread.
*/
fun IcsExporter.stageEventShare(detail: EventDetail): Uri? = runCatching {
val ics = IcsWriter().writeCalendar(
events = listOf(detail.toShareIcsEvent()),
dtStamp = Clock.System.now(),
)
stageShareFile(shareFileName(detail.instance.title), ics)
}.getOrNull()
/** Open the system chooser for a staged `.ics`; false when nothing could take it. */
fun Context.sendEventShare(uri: Uri, chooserTitle: String): Boolean = runCatching {
val send = Intent(Intent.ACTION_SEND).apply {
type = "text/calendar"
putExtra(Intent.EXTRA_STREAM, uri)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
startActivity(Intent.createChooser(send, chooserTitle))
}.isSuccess
/** Delete an event, or as much of its series as [scope] reaches from the occurrence at [beginMillis]. */
suspend fun CalendarRepository.deleteEvent(
eventId: Long,
beginMillis: Long,
scope: RecurringWriteScope,
) = when (scope) {
RecurringWriteScope.AllEvents -> deleteEvent(eventId)
RecurringWriteScope.ThisEvent -> deleteOccurrence(eventId, beginMillis)
RecurringWriteScope.ThisAndFollowing -> deleteEventFromOccurrence(eventId, beginMillis)
}
/** How a [tryDeleteEvent] ended. */
enum class DeleteOutcome { Deleted, Gone, NeedsPermission, Failed }
/** Whether this install may write to the calendar; v1.0 installs only hold read access. */
fun Context.canWriteCalendar(): Boolean =
hasPermission(Manifest.permission.WRITE_CALENDAR)
/** [deleteEvent], with the provider's failures mapped to a [DeleteOutcome]. */
suspend fun CalendarRepository.tryDeleteEvent(
eventId: Long,
beginMillis: Long,
scope: RecurringWriteScope,
): DeleteOutcome = try {
deleteEvent(eventId, beginMillis, scope)
DeleteOutcome.Deleted
} catch (e: CancellationException) {
throw e
} catch (e: SecurityException) {
DeleteOutcome.NeedsPermission
} catch (e: NoSuchEventException) {
DeleteOutcome.Gone
} catch (e: Exception) {
Log.w("EventActions", "Delete failed (scope=$scope, eventId=$eventId)", e)
DeleteOutcome.Failed
}
/**
* Runs an action that writes to the calendar, asking for `WRITE_CALENDAR` first
* where the install only holds read access (v1.0 installs). A grant continues
* straight into the action that asked for it.
*/
@Composable
fun rememberWriteGate(): (() -> Unit) -> Unit {
val gate = rememberWriteGateOr()
return { action -> gate(action) {} }
}
/** [rememberWriteGate], running the fallback instead when the user refuses. */
@Composable
fun rememberWriteGateOr(): (action: () -> Unit, fallback: () -> Unit) -> Unit {
val context = LocalContext.current
var pending by remember { mutableStateOf<Pair<() -> Unit, () -> Unit>?>(null) }
val launcher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestPermission(),
) { granted ->
pending?.let { (action, fallback) -> if (granted) action() else fallback() }
pending = null
}
return { action, fallback ->
if (context.canWriteCalendar()) {
action()
} else {
pending = action to fallback
launcher.launch(Manifest.permission.WRITE_CALENDAR)
}
}
}
/**
* Delete confirmation. Recurring events choose between cancelling just the
* tapped occurrence (default), truncating the series from it onwards, and
* removing the whole series.
*/
@Composable
fun DeleteEventDialog(
isRecurring: Boolean,
onConfirm: (RecurringWriteScope) -> Unit,
onDismiss: () -> Unit,
) {
var scope by rememberSaveable { mutableStateOf(RecurringWriteScope.ThisEvent) }
AlertDialog(
onDismissRequest = onDismiss,
title = {
Text(
stringResource(
if (isRecurring) R.string.event_delete_recurring_title
else R.string.event_delete_title,
),
)
},
text = {
if (isRecurring) {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
OptionCard(
label = stringResource(R.string.event_delete_option_occurrence),
onClick = { scope = RecurringWriteScope.ThisEvent },
selected = scope == RecurringWriteScope.ThisEvent,
)
OptionCard(
label = stringResource(R.string.event_delete_option_following),
onClick = { scope = RecurringWriteScope.ThisAndFollowing },
selected = scope == RecurringWriteScope.ThisAndFollowing,
)
OptionCard(
label = stringResource(R.string.event_delete_option_series),
onClick = { scope = RecurringWriteScope.AllEvents },
selected = scope == RecurringWriteScope.AllEvents,
)
}
} else {
Text(stringResource(R.string.event_delete_body))
}
},
confirmButton = {
TextButton(
onClick = { onConfirm(if (isRecurring) scope else RecurringWriteScope.AllEvents) },
) {
Text(
text = stringResource(R.string.event_detail_delete),
color = MaterialTheme.colorScheme.error,
)
}
},
dismissButton = {
TextButton(onClick = onDismiss) {
Text(stringResource(R.string.dialog_cancel))
}
},
)
}
/** A filesystem-safe `.ics` file name from an event title (or a fallback). */
private fun shareFileName(title: String): String {
val base = title.trim()
.replace(Regex("""[^\p{L}\p{Nd} _-]"""), "")
.replace(' ', '_')
.take(40)
.ifBlank { "event" }
return "$base.ics"
}
@@ -0,0 +1,137 @@
package de.jeanlucmakiola.calendula.ui.common
import android.net.Uri
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.calendar.NoSuchEventException
import de.jeanlucmakiola.calendula.data.ics.IcsExporter
import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.EventDetail
import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.domain.RecurringWriteScope
import de.jeanlucmakiola.calendula.domain.atOccurrence
import de.jeanlucmakiola.calendula.domain.toDuplicateForm
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
import de.jeanlucmakiola.floret.di.IoDispatcher
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.datetime.TimeZone
import kotlin.coroutines.cancellation.CancellationException
import javax.inject.Inject
/** A delete waiting on its confirmation dialog. */
data class DeletePrompt(val event: EventInstance, val isRecurring: Boolean)
/** How an action on a selected event ended, when it has something to say. */
enum class EventActionFailure { LoadFailed, ShareFailed, DeleteFailed, WriteDenied, Gone }
/** Duplicate, share and delete for a selected event (#141), loading it on demand. */
@HiltViewModel
class EventActionsViewModel @Inject constructor(
private val repository: CalendarRepository,
private val icsExporter: IcsExporter,
@IoDispatcher private val io: CoroutineDispatcher,
) : ViewModel() {
/** Every calendar by id, for what a selected event's bar may offer. */
val calendars: StateFlow<Map<Long, CalendarSource>> = repository.calendars()
.map { list -> list.associateBy { it.id } }
.catch { emit(emptyMap()) }
.flowOn(io)
.stateWhileSubscribed(
scope = viewModelScope,
initialValue = emptyMap(),
)
private val _deletePrompt = MutableStateFlow<DeletePrompt?>(null)
val deletePrompt: StateFlow<DeletePrompt?> = _deletePrompt.asStateFlow()
private val _failure = MutableStateFlow<EventActionFailure?>(null)
val failure: StateFlow<EventActionFailure?> = _failure.asStateFlow()
/** A create form copying [event], or null when it can't be read. */
suspend fun duplicateForm(event: EventInstance): EventForm? {
val detail = load(event) ?: return null
val canModify = calendars.value[event.calendarId]?.canModifyContents == true
return detail.toDuplicateForm(canModify, TimeZone.currentSystemDefault())
}
/** A staged `.ics` for [event], or null — reported — when it can't be built. */
suspend fun shareUri(event: EventInstance): Uri? {
val uri = load(event)?.let { withContext(io) { icsExporter.stageEventShare(it) } }
if (uri == null && _failure.value == null) _failure.value = EventActionFailure.ShareFailed
return uri
}
/** Ask to delete [event]; the dialog it needs depends on whether it recurs. */
fun requestDelete(event: EventInstance) {
viewModelScope.launch {
val detail = load(event) ?: return@launch
_deletePrompt.value = DeletePrompt(event, isRecurring = !detail.rrule.isNullOrBlank())
}
}
fun confirmDelete(scope: RecurringWriteScope) {
val prompt = _deletePrompt.value ?: return
_deletePrompt.value = null
viewModelScope.launch {
val event = prompt.event
_failure.value = when (repository.tryDeleteEvent(event.eventId, event.start.toEpochMilliseconds(), scope)) {
DeleteOutcome.Deleted -> null
DeleteOutcome.Gone -> EventActionFailure.Gone
DeleteOutcome.NeedsPermission -> EventActionFailure.WriteDenied
DeleteOutcome.Failed -> EventActionFailure.DeleteFailed
}
}
}
fun cancelDelete() {
_deletePrompt.value = null
}
/** The chooser itself couldn't open — nothing on the device takes an `.ics`. */
fun reportShareFailed() {
_failure.value = EventActionFailure.ShareFailed
}
fun consumeFailure() {
_failure.value = null
}
/** Whether [calendarId] takes writes, asking the provider while [calendars] hasn't loaded yet. */
suspend fun canModify(calendarId: Long): Boolean {
val calendar = calendars.value[calendarId] ?: try {
repository.calendars().first().firstOrNull { it.id == calendarId }
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
null
}
return calendar?.canModifyContents == true
}
private suspend fun load(event: EventInstance): EventDetail? = try {
// The row holds the series start; the actions work on this occurrence.
repository.eventDetail(event.eventId)
.atOccurrence(event.start.toEpochMilliseconds(), event.end.toEpochMilliseconds())
} catch (e: CancellationException) {
throw e
} catch (e: NoSuchEventException) {
_failure.value = EventActionFailure.Gone
null
} catch (e: Exception) {
_failure.value = EventActionFailure.LoadFailed
null
}
}
@@ -24,38 +24,57 @@ import androidx.compose.ui.unit.dp
/** How far the finger may wander during the hold — well under touch slop. */ /** How far the finger may wander during the hold — well under touch slop. */
private val PICKUP_TOLERANCE = 6.dp private val PICKUP_TOLERANCE = 6.dp
/** What a long press on a block turned into. */
enum class PickUp {
/** Nothing to pick up; the gesture is left alone. */
None,
/** Lifted and following the finger. */
Drag,
/** Held but not movable — the gesture is swallowed until the finger lifts. */
Hold,
}
/** /**
* Pick an event block up with a long press and drag it, without * Pick an event block up with a long press and drag it, without
* `detectDragGesturesAfterLongPress`: the stock detector cancels as soon as an * `detectDragGesturesAfterLongPress`: the stock detector cancels as soon as an
* ancestor consumes or the finger leaves the block, which a * ancestor consumes or the finger leaves the block, which a
* `MIN_EVENT_FRACTION`-tall block loses immediately. Movement before the timeout * `MIN_EVENT_FRACTION`-tall block loses immediately. Movement before the timeout
* is deliberately not consumed, so a scroll starting on top of a block survives. * is deliberately not consumed, so a scroll starting on top of a block survives.
*
* [onRelease] is the long press that never moved: the finger lifted within touch
* slop of where it was picked up, or a [PickUp.Hold] ended. Without it, such a
* release is a drop like any other. [immediate] also lifts the block as soon as
* the finger moves past touch slop, with no hold — for a block already selected.
*/ */
@Composable @Composable
fun rememberEventDragSource( fun rememberEventDragSource(
enabled: Boolean, enabled: Boolean,
key: Any?, key: Any?,
onPickUp: (pointerInRoot: Offset, blockInRoot: Offset, size: IntSize) -> Unit, onPickUp: (pointerInRoot: Offset, blockInRoot: Offset, size: IntSize) -> PickUp,
onMove: (pointerInRoot: Offset) -> Unit, onMove: (pointerInRoot: Offset) -> Unit,
onDrop: () -> Unit, onDrop: () -> Unit,
onCancel: () -> Unit, onCancel: () -> Unit,
): Modifier = rememberDragSurface( onRelease: (() -> Unit)? = null,
immediate: Boolean = false,
): Modifier = rememberPickUpSurface(
enabled = enabled, enabled = enabled,
key = key, key = key,
onPickUp = { _, pointerInRoot, nodeInRoot, size -> immediate = immediate,
onPickUp(pointerInRoot, nodeInRoot, size) onPickUp = { _, pointerInRoot, nodeInRoot, size -> onPickUp(pointerInRoot, nodeInRoot, size) },
true
},
onMove = onMove, onMove = onMove,
onDrop = onDrop, onDrop = onDrop,
onCancel = onCancel, onCancel = onCancel,
onRelease = onRelease,
) )
/** /**
* The same pickup, for a surface that carries many draggable pieces rather than * The same pickup, for a surface that carries many draggable pieces rather than
* being one itself — the month grid, whose chips are covered by a full-bleed tap * being one itself — the month grid, whose chips are covered by a full-bleed tap
* layer. [onPickUp] receives the press position local to this node and answers * layer. [onPickUp] receives the press position local to this node and answers
* whether anything is there; false abandons the gesture. * whether anything is there; false abandons the gesture. [skipClaimedDown] leaves
* a press a descendant already consumed alone.
*/ */
@Composable @Composable
fun rememberDragSurface( fun rememberDragSurface(
@@ -65,6 +84,33 @@ fun rememberDragSurface(
onMove: (pointerInRoot: Offset) -> Unit, onMove: (pointerInRoot: Offset) -> Unit,
onDrop: () -> Unit, onDrop: () -> Unit,
onCancel: () -> Unit, onCancel: () -> Unit,
onRelease: (() -> Unit)? = null,
skipClaimedDown: Boolean = false,
): Modifier = rememberPickUpSurface(
enabled = enabled,
key = key,
immediate = false,
onPickUp = { local, pointer, node, size ->
if (onPickUp(local, pointer, node, size)) PickUp.Drag else PickUp.None
},
onMove = onMove,
onDrop = onDrop,
onCancel = onCancel,
onRelease = onRelease,
skipClaimedDown = skipClaimedDown,
)
@Composable
private fun rememberPickUpSurface(
enabled: Boolean,
key: Any?,
immediate: Boolean,
onPickUp: (local: Offset, pointerInRoot: Offset, nodeInRoot: Offset, size: IntSize) -> PickUp,
onMove: (pointerInRoot: Offset) -> Unit,
onDrop: () -> Unit,
onCancel: () -> Unit,
onRelease: (() -> Unit)?,
skipClaimedDown: Boolean = false,
): Modifier { ): Modifier {
if (!enabled) return Modifier if (!enabled) return Modifier
val holdMillis = LocalViewConfiguration.current.longPressTimeoutMillis val holdMillis = LocalViewConfiguration.current.longPressTimeoutMillis
@@ -74,27 +120,44 @@ fun rememberDragSurface(
val currentMove by rememberUpdatedState(onMove) val currentMove by rememberUpdatedState(onMove)
val currentDrop by rememberUpdatedState(onDrop) val currentDrop by rememberUpdatedState(onDrop)
val currentCancel by rememberUpdatedState(onCancel) val currentCancel by rememberUpdatedState(onCancel)
val currentRelease by rememberUpdatedState(onRelease)
// Not a key: the pickup changes it, and a restart would cancel the drag.
val currentImmediate by rememberUpdatedState(immediate)
return Modifier return Modifier
.onGloballyPositioned { coordinates[0] = it } .onGloballyPositioned { coordinates[0] = it }
.pointerInput(key) { .pointerInput(key) {
val slop = viewConfiguration.touchSlop
awaitEachGesture { awaitEachGesture {
val down = awaitFirstDown(requireUnconsumed = false) val down = awaitFirstDown(requireUnconsumed = false)
// A child that took the press, such as a resize handle, keeps it.
if (skipClaimedDown && down.isConsumed) return@awaitEachGesture
val origin = down.position val origin = down.position
val heldStill = withTimeoutOrNull(holdMillis) { val immediate = currentImmediate
while (true) { // Null: held still. True: an immediate pickup past slop. False: abandoned.
val outcome = withTimeoutOrNull(holdMillis) {
var result: Boolean? = null
while (result == null) {
val main = awaitPointerEvent() val main = awaitPointerEvent()
val change = main.changes.firstOrNull { it.id == down.id } ?: break val change = main.changes.firstOrNull { it.id == down.id }
if (!change.pressed) break val distance = change?.let { (it.position - origin).getDistance() } ?: 0f
if (main.changes.count { it.pressed } > 1) break result = when {
if ((change.position - origin).getDistance() > tolerance) break change == null || !change.pressed -> false
// An ancestor's claim only becomes visible once the whole main.changes.count { it.pressed } > 1 -> false
// main pass has run, so look again on the final pass. immediate && distance > slop && !change.isConsumed -> {
val final = awaitPointerEvent(PointerEventPass.Final) change.consume()
if (final.changes.any { it.isConsumed }) break true
}
!immediate && distance > tolerance -> false
// An ancestor's claim only becomes visible once the
// whole main pass has run, so look again on the final pass.
awaitPointerEvent(PointerEventPass.Final).changes.any { it.isConsumed } -> false
else -> null
}
} }
} == null result
if (!heldStill) return@awaitEachGesture }
if (outcome == false) return@awaitEachGesture
val layout = coordinates[0]?.takeIf { it.isAttached } ?: return@awaitEachGesture val layout = coordinates[0]?.takeIf { it.isAttached } ?: return@awaitEachGesture
val took = currentPickUp( val took = currentPickUp(
@@ -103,8 +166,11 @@ fun rememberDragSurface(
layout.positionInRoot(), layout.positionInRoot(),
layout.size, layout.size,
) )
if (!took) return@awaitEachGesture if (took == PickUp.None) return@awaitEachGesture
// Moved already, for an immediate pickup: it can't be a release.
var moved = outcome == true
var dropped = false var dropped = false
var released = false
try { try {
// Driven on the initial pass, which runs parent → child: an // Driven on the initial pass, which runs parent → child: an
// ancestor that outranks us (the pinch) has already consumed // ancestor that outranks us (the pinch) has already consumed
@@ -116,28 +182,51 @@ fun rememberDragSurface(
if (change.isConsumed) break if (change.isConsumed) break
if (!change.pressed) { if (!change.pressed) {
change.consume() change.consume()
dropped = true if (took == PickUp.Hold || (!moved && currentRelease != null)) {
released = true
} else {
dropped = true
}
break break
} }
if (event.changes.count { it.pressed } > 1) break if (event.changes.count { it.pressed } > 1) break
change.consume() change.consume()
if (took == PickUp.Hold) continue
if ((change.position - origin).getDistance() > slop) moved = true
coordinates[0]?.takeIf { it.isAttached } coordinates[0]?.takeIf { it.isAttached }
?.let { currentMove(it.localToRoot(change.position)) } ?.let { currentMove(it.localToRoot(change.position)) }
} }
} finally { } finally {
// Also reached when the pointer node is disposed mid-drag — // Also reached when the pointer node is disposed mid-drag —
// a cancel, not a drop, and must never write. // a cancel, not a drop, and must never write.
if (dropped) currentDrop() else currentCancel() when {
released -> {
if (took == PickUp.Drag) currentCancel()
currentRelease?.invoke()
}
dropped -> currentDrop()
took == PickUp.Drag -> currentCancel()
}
} }
} }
} }
} }
/** A lift on pickup, then a tick every time the drop target snaps to a new slot. */ /**
* A lift on pickup, a tick every time the drop target snaps to a new slot, and a
* confirm each time [drops] counts a real drop.
*/
@Composable @Composable
fun DragSnapHaptics(slot: Any?) { fun DragSnapHaptics(slot: Any?, drops: Int) {
val haptics = LocalHapticFeedback.current val haptics = LocalHapticFeedback.current
val previous = remember { arrayOfNulls<Any>(1) } val previous = remember { arrayOfNulls<Any>(1) }
val dropsSeen = remember { intArrayOf(drops) }
LaunchedEffect(drops) {
if (drops != dropsSeen[0]) {
dropsSeen[0] = drops
haptics.performHapticFeedback(HapticFeedbackType.Confirm)
}
}
LaunchedEffect(slot) { LaunchedEffect(slot) {
val had = previous[0] val had = previous[0]
previous[0] = slot previous[0] = slot
@@ -48,7 +48,12 @@ private val FAB_BAND = 88.dp
* a pill on the FAB's band, leaving the calendar visible behind it. * a pill on the FAB's band, leaving the calendar visible behind it.
*/ */
@Composable @Composable
fun EventMoveHost(viewModel: RescheduleViewModel, modifier: Modifier = Modifier) { fun EventMoveHost(
viewModel: RescheduleViewModel,
modifier: Modifier = Modifier,
actionFailure: String? = null,
onActionFailureShown: () -> Unit = {},
) {
val prompt by viewModel.scopePrompt.collectAsStateWithLifecycle() val prompt by viewModel.scopePrompt.collectAsStateWithLifecycle()
val outcome by viewModel.outcome.collectAsStateWithLifecycle() val outcome by viewModel.outcome.collectAsStateWithLifecycle()
val undoTick by viewModel.undoStarted.collectAsStateWithLifecycle() val undoTick by viewModel.undoStarted.collectAsStateWithLifecycle()
@@ -58,7 +63,9 @@ fun EventMoveHost(viewModel: RescheduleViewModel, modifier: Modifier = Modifier)
prompt?.let { pending -> prompt?.let { pending ->
RecurringScopeDialog( RecurringScopeDialog(
title = stringResource(R.string.event_move_recurring_title), title = stringResource(
if (pending.resize) R.string.event_resize_recurring_title else R.string.event_move_recurring_title,
),
onSelect = viewModel::moveWithScope, onSelect = viewModel::moveWithScope,
onDismiss = viewModel::cancelScope, onDismiss = viewModel::cancelScope,
allowSeries = !pending.occurrenceOnly, allowSeries = !pending.occurrenceOnly,
@@ -69,9 +76,17 @@ fun EventMoveHost(viewModel: RescheduleViewModel, modifier: Modifier = Modifier)
val moved = outcome as? MoveOutcome.Moved val moved = outcome as? MoveOutcome.Moved
val movedLabel = moved?.let { formatMovedTo(it.startMillis, it.isAllDay, use24Hour, locale) } val movedLabel = moved?.let { formatMovedTo(it.startMillis, it.isAllDay, use24Hour, locale) }
val resizedLabel = moved?.endMillis?.let { end ->
"$movedLabel–${formatTime(end, use24Hour, locale)}"
}
// A failed selection action (#141) shares the chip rather than stacking on it.
val message = when (outcome) { val message = when (outcome) {
null -> null null -> actionFailure
is MoveOutcome.Moved -> stringResource(R.string.event_move_done, movedLabel.orEmpty()) is MoveOutcome.Moved -> if (resizedLabel != null) {
stringResource(R.string.event_resize_done, resizedLabel)
} else {
stringResource(R.string.event_move_done, movedLabel.orEmpty())
}
MoveOutcome.Undone -> stringResource(R.string.event_move_undone) MoveOutcome.Undone -> stringResource(R.string.event_move_undone)
MoveOutcome.WriteDenied -> stringResource(R.string.event_move_write_denied) MoveOutcome.WriteDenied -> stringResource(R.string.event_move_write_denied)
MoveOutcome.Gone -> stringResource(R.string.event_move_gone) MoveOutcome.Gone -> stringResource(R.string.event_move_gone)
@@ -96,6 +111,12 @@ fun EventMoveHost(viewModel: RescheduleViewModel, modifier: Modifier = Modifier)
delay(if (outcome == MoveOutcome.Undone) UNDONE_CHIP_MILLIS else CHIP_MILLIS) delay(if (outcome == MoveOutcome.Undone) UNDONE_CHIP_MILLIS else CHIP_MILLIS)
viewModel.consumeOutcome() viewModel.consumeOutcome()
} }
// A failure waits for the chip to be free, then has its own turn.
LaunchedEffect(actionFailure, outcome == null) {
if (actionFailure == null || outcome != null) return@LaunchedEffect
delay(CHIP_MILLIS)
onActionFailureShown()
}
BoxWithConstraints(modifier = modifier.fillMaxSize()) { BoxWithConstraints(modifier = modifier.fillMaxSize()) {
val chipMaxWidth = maxWidth - FAB_BAND val chipMaxWidth = maxWidth - FAB_BAND
@@ -113,7 +134,7 @@ fun EventMoveHost(viewModel: RescheduleViewModel, modifier: Modifier = Modifier)
// write anyway, so offering it would be a button that does nothing. // write anyway, so offering it would be a button that does nothing.
val undo = content.undo?.takeIf { !writeInFlight } val undo = content.undo?.takeIf { !writeInFlight }
SnackChip( SnackChip(
visible = outcome != null, visible = outcome != null || actionFailure != null,
message = content.message, message = content.message,
maxWidth = chipMaxWidth, maxWidth = chipMaxWidth,
actionLabel = stringResource(R.string.event_move_undo).takeIf { undo != null }, actionLabel = stringResource(R.string.event_move_undo).takeIf { undo != null },
@@ -142,3 +163,7 @@ private fun formatMovedTo(
return localizedDateFormatter(locale, skeleton) return localizedDateFormatter(locale, skeleton)
.format(Instant.ofEpochMilli(startMillis).atZone(zone)) .format(Instant.ofEpochMilli(startMillis).atZone(zone))
} }
/** "10:30" — the end of a resized event, read in the device zone like its start. */
private fun formatTime(millis: Long, use24Hour: Boolean, locale: Locale): String =
timeOfDayFormatter(use24Hour, locale).format(Instant.ofEpochMilli(millis).atZone(ZoneId.systemDefault()))
@@ -131,6 +131,13 @@ fun eventDragAllowed(event: EventInstance): Boolean {
return move.dragEnabled && move.allows(event) return move.dragEnabled && move.allows(event)
} }
/**
* Whether a long press may select events at all (#141) — the gesture setting,
* whatever the event's calendar allows. A read-only event is selected but stays put.
*/
@Composable
fun eventSelectAllowed(): Boolean = LocalEventMove.current?.dragEnabled == true
/** /**
* A TalkBack action that opens [event] in the edit form, so rescheduling isn't * A TalkBack action that opens [event] in the edit form, so rescheduling isn't
* pointer-only. Null when this event can't be moved. * pointer-only. Null when this event can't be moved.
@@ -0,0 +1,82 @@
package de.jeanlucmakiola.calendula.ui.common
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import de.jeanlucmakiola.calendula.R
/** The selected event's action bar (#141); Edit and Delete only where its calendar allows. */
@Composable
fun EventSelectionBar(
canEdit: Boolean,
canDelete: Boolean,
onEdit: () -> Unit,
onDuplicate: () -> Unit,
onShare: () -> Unit,
onDelete: () -> Unit,
modifier: Modifier = Modifier,
) {
// The FAB's height and colours, so the two read as one control.
Surface(
shape = CircleShape,
color = MaterialTheme.colorScheme.primaryContainer,
contentColor = MaterialTheme.colorScheme.onPrimaryContainer,
shadowElevation = 6.dp,
modifier = modifier.height(FabSize),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(horizontal = 4.dp),
) {
if (canEdit) BarAction(Icons.Default.Edit, R.string.event_detail_edit, onEdit)
BarAction(Icons.Default.ContentCopy, R.string.event_detail_duplicate, onDuplicate)
BarAction(Icons.Default.Share, R.string.event_detail_share, onShare)
if (canDelete) BarAction(Icons.Default.Delete, R.string.event_detail_delete, onDelete)
}
}
}
/** A drafted block's bar (#153): create the event, or let the draft go. */
@Composable
fun DraftSelectionBar(onCreate: () -> Unit, onDiscard: () -> Unit, modifier: Modifier = Modifier) {
Surface(
shape = CircleShape,
color = MaterialTheme.colorScheme.primaryContainer,
contentColor = MaterialTheme.colorScheme.onPrimaryContainer,
shadowElevation = 6.dp,
modifier = modifier.height(FabSize),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(horizontal = 4.dp),
) {
BarAction(Icons.Default.Close, R.string.event_draft_discard, onDiscard)
BarAction(Icons.Default.Check, R.string.event_draft_create, onCreate)
}
}
}
@Composable
private fun BarAction(icon: ImageVector, label: Int, onClick: () -> Unit) {
IconButton(onClick = onClick) {
Icon(imageVector = icon, contentDescription = stringResource(label))
}
}
@@ -0,0 +1,134 @@
package de.jeanlucmakiola.calendula.ui.common
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.floret.components.SnackChipMargin
import kotlinx.coroutines.launch
/** The bottom band the selection bar and FAB cover, margin included. */
val SelectionBarClearance = FabSize + SnackChipMargin
/** The FAB's role while an event is selected (#141): its action bar's toggle. Null otherwise. */
@Composable
fun rememberFabSelection(
host: ChromeHost,
viewModel: EventActionsViewModel,
onEdit: (EventInstance) -> Unit,
onDuplicate: (EventForm) -> Unit,
chipShown: Boolean,
onDismissChip: () -> Unit,
): FabSelection? {
val calendars by viewModel.calendars.collectAsStateWithLifecycle()
val context = LocalContext.current
val scope = rememberCoroutineScope()
val requireWrite = rememberWriteGate()
val chooserTitle = stringResource(R.string.event_share_chooser_title)
// What the FAB has been told for this selection, over what the coverage says.
var chosen by remember(host.selection?.event) { mutableStateOf<Boolean?>(null) }
// Folded while a chip is up, which then sits beside the FAB as usual.
val expanded = !chipShown && (chosen ?: !host.selectionCompact)
val currentEdit by rememberUpdatedState(onEdit)
val currentDuplicate by rememberUpdatedState(onDuplicate)
val currentDismissChip by rememberUpdatedState(onDismissChip)
val currentWrite by rememberUpdatedState(requireWrite)
val selection = host.selection ?: return null
selection.create?.let { create ->
return remember(selection, expanded, chipShown) {
FabSelection(
expanded = expanded,
onToggle = {
if (chipShown) currentDismissChip()
chosen = !expanded
},
bar = {
DraftSelectionBar(
onCreate = { currentWrite { create() } },
onDiscard = selection.dismiss,
)
},
)
}
}
val event = selection.event
val calendar = calendars[event.calendarId]
val canEdit = calendar?.canModifyContents == true
val canDelete = canEdit && calendar?.isManaged == false
return remember(selection, expanded, chipShown, canEdit, canDelete) {
FabSelection(
expanded = expanded,
onToggle = {
if (chipShown) currentDismissChip()
chosen = !expanded
},
bar = {
EventSelectionBar(
canEdit = canEdit,
canDelete = canDelete,
onEdit = {
currentWrite {
selection.dismiss()
currentEdit(event)
}
},
onDuplicate = {
currentWrite {
scope.launch {
val form = viewModel.duplicateForm(event) ?: return@launch
selection.dismiss()
currentDuplicate(form)
}
}
},
onShare = {
scope.launch {
val uri = viewModel.shareUri(event) ?: return@launch
if (!context.sendEventShare(uri, chooserTitle)) viewModel.reportShareFailed()
}
},
onDelete = { currentWrite { viewModel.requestDelete(event) } },
)
},
)
}
}
/** What a failed action on a selected event says, for the move host's chip to show (#141). */
@Composable
fun eventActionFailureMessage(failure: EventActionFailure?): String? = when (failure) {
null -> null
EventActionFailure.LoadFailed -> stringResource(R.string.event_action_load_failed)
EventActionFailure.ShareFailed -> stringResource(R.string.event_share_failed)
EventActionFailure.DeleteFailed -> stringResource(R.string.event_delete_failed)
EventActionFailure.WriteDenied -> stringResource(R.string.event_delete_write_denied)
EventActionFailure.Gone -> stringResource(R.string.event_move_gone)
}
/** The delete confirmation a selected event's Delete brings up (#141). */
@Composable
fun EventSelectionHost(host: ChromeHost, viewModel: EventActionsViewModel) {
val deletePrompt by viewModel.deletePrompt.collectAsStateWithLifecycle()
deletePrompt?.let { prompt ->
DeleteEventDialog(
isRecurring = prompt.isRecurring,
onConfirm = { writeScope ->
host.selection?.takeIf { it.event == prompt.event }?.dismiss()
viewModel.confirmDelete(writeScope)
},
onDismiss = viewModel::cancelDelete,
)
}
}
@@ -19,12 +19,15 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import de.jeanlucmakiola.calendula.ui.week.MINUTES_PER_DAY
import de.jeanlucmakiola.floret.locale.currentLocale import de.jeanlucmakiola.floret.locale.currentLocale
/** Width of the hour gutter down the start edge of the day and week timelines. */ /** Width of the hour gutter down the start edge of the day and week timelines. */
@@ -67,7 +70,7 @@ fun HourGutter(
val locale = currentLocale() val locale = currentLocale()
// Derived: the drag is rewritten every frame, its snapped start once a slot. // Derived: the drag is rewritten every frame, its snapped start once a slot.
val dragStartMin by remember(dragController) { val dragStartMin by remember(dragController) {
derivedStateOf { dragController.drag?.startMin } derivedStateOf { dragController.drag?.markerMin }
} }
val hourAlpha by animateFloatAsState( val hourAlpha by animateFloatAsState(
targetValue = if (dragStartMin != null) DIMMED_HOUR_ALPHA else 1f, targetValue = if (dragStartMin != null) DIMMED_HOUR_ALPHA else 1f,
@@ -107,12 +110,25 @@ fun HourGutter(
} }
} }
} }
dragStartMin?.let { startMin -> // Held while it fades, so it goes out where it was rather than blinking off.
val badgeMin = remember { mutableStateOf<Int?>(null) }
dragStartMin?.let { badgeMin.value = it }
val badgeIn by animateFloatAsState(
targetValue = if (dragStartMin != null) 1f else 0f,
animationSpec = MaterialTheme.motionScheme.fastEffectsSpec(),
label = "gutterBadge",
)
badgeMin.value?.takeIf { badgeIn > 0f }?.let { startMin ->
val top = (hourHeight * (startMin / 60f) - BADGE_HEIGHT / 2).coerceAtLeast(0.dp) val top = (hourHeight * (startMin / 60f) - BADGE_HEIGHT / 2).coerceAtLeast(0.dp)
Box( Box(
modifier = Modifier modifier = Modifier
.align(Alignment.TopCenter) .align(Alignment.TopCenter)
.offset(y = top) .offset(y = top)
.graphicsLayer {
alpha = badgeIn
scaleX = 0.8f + 0.2f * badgeIn
scaleY = 0.8f + 0.2f * badgeIn
}
.height(BADGE_HEIGHT) .height(BADGE_HEIGHT)
.background(MaterialTheme.colorScheme.primary, CircleShape) .background(MaterialTheme.colorScheme.primary, CircleShape)
.padding(horizontal = 4.dp) .padding(horizontal = 4.dp)
@@ -121,7 +137,8 @@ fun HourGutter(
contentAlignment = Alignment.Center, contentAlignment = Alignment.Center,
) { ) {
Text( Text(
text = formatGutterTime(startMin, use24Hour, locale), // A resized end can sit on midnight: 00:00, not a clamped 23:59.
text = formatGutterTime(startMin % MINUTES_PER_DAY, use24Hour, locale),
style = MaterialTheme.typography.labelSmall, style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onPrimary, color = MaterialTheme.colorScheme.onPrimary,
maxLines = 1, maxLines = 1,
@@ -195,15 +195,20 @@ class OutOfViewEdges internal constructor(
} }
} }
/** Whether a press at [y] (content px) lands on an edge bar (#153). */
fun covers(y: Float): Boolean = edgeAt(y) != null
private fun edgeAt(y: Float) = tappedEdge(
events = events,
y = y,
viewportTop = scrollState.value.toFloat(),
viewportPx = scrollState.viewportSize,
reachPx = reachPx,
)
/** Reveals the hidden event if a tap at [y] (content px) lands on a bar. */ /** Reveals the hidden event if a tap at [y] (content px) lands on a bar. */
fun tap(y: Float): Boolean { fun tap(y: Float): Boolean {
val edge = tappedEdge( val edge = edgeAt(y) ?: return false
events = events,
y = y,
viewportTop = scrollState.value.toFloat(),
viewportPx = scrollState.viewportSize,
reachPx = reachPx,
) ?: return false
reveal(edge) reveal(edge)
return true return true
} }
@@ -1,10 +1,10 @@
package de.jeanlucmakiola.calendula.ui.common package de.jeanlucmakiola.calendula.ui.common
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.plus import kotlinx.coroutines.plus
@@ -45,7 +45,7 @@ class PageStateCache<K, S>(
return entries.getOrPut(key) { return entries.getOrPut(key) {
val job = SupervisorJob(scope.coroutineContext[Job]) val job = SupervisorJob(scope.coroutineContext[Job])
Entry( Entry(
state = load(key).stateIn(scope + job, SharingStarted.WhileSubscribed(5_000L), initial), state = load(key).stateWhileSubscribed(scope + job, initial),
job = job, job = job,
) )
}.state }.state
@@ -5,6 +5,11 @@ import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.text.style.TextDecoration
import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.domain.hasEnded
import kotlinx.datetime.LocalDate
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime
import kotlin.time.Instant import kotlin.time.Instant
/** /**
@@ -16,6 +21,17 @@ import kotlin.time.Instant
*/ */
val LocalDimCutoff = compositionLocalOf<Instant?> { null } val LocalDimCutoff = compositionLocalOf<Instant?> { null }
/**
* Whether [this] counts as past where it's drawn on [day]: once it has ended,
* or on any day before the one [now] falls in, so a multi-day event still
* running doesn't stay undimmed on the days already behind it.
*/
fun EventInstance.isPastOn(
day: LocalDate,
now: Instant,
zone: TimeZone = TimeZone.currentSystemDefault(),
): Boolean = hasEnded(now) || day < now.toLocalDateTime(zone).date
/** Opacity applied to a completed/past event chip when it is dimmed. */ /** Opacity applied to a completed/past event chip when it is dimmed. */
const val EventDimAlpha = 0.4f const val EventDimAlpha = 0.4f
@@ -1,14 +1,8 @@
package de.jeanlucmakiola.calendula.ui.common package de.jeanlucmakiola.calendula.ui.common
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material3.Checkbox import androidx.compose.material3.Checkbox
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
@@ -22,17 +16,16 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.floret.components.CustomAmountEditor import de.jeanlucmakiola.floret.components.CustomAmountEditor
import de.jeanlucmakiola.floret.components.CustomExpandRow
import de.jeanlucmakiola.floret.components.FullScreenPicker import de.jeanlucmakiola.floret.components.FullScreenPicker
import de.jeanlucmakiola.floret.components.GroupedListInset import de.jeanlucmakiola.floret.components.GroupedHint
import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.GroupedRow
import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.Position
import de.jeanlucmakiola.floret.components.SelectedCheck
import de.jeanlucmakiola.floret.components.positionOf import de.jeanlucmakiola.floret.components.positionOf
import de.jeanlucmakiola.floret.identity.collapseExit
import de.jeanlucmakiola.floret.identity.expandEnter
import de.jeanlucmakiola.floret.locale.currentLocale import de.jeanlucmakiola.floret.locale.currentLocale
import de.jeanlucmakiola.floret.reminders.ReminderOverride import de.jeanlucmakiola.floret.reminders.ReminderOverride
import de.jeanlucmakiola.floret.reminders.ReminderUnit import de.jeanlucmakiola.floret.reminders.ReminderUnit
import de.jeanlucmakiola.floret.reminders.minutesOrEmpty
import de.jeanlucmakiola.floret.reminders.reminderOverrideForMinutes import de.jeanlucmakiola.floret.reminders.reminderOverrideForMinutes
import de.jeanlucmakiola.calendula.ui.agenda.AgendaRange import de.jeanlucmakiola.calendula.ui.agenda.AgendaRange
import de.jeanlucmakiola.calendula.ui.agenda.agendaRangeWindowSummary import de.jeanlucmakiola.calendula.ui.agenda.agendaRangeWindowSummary
@@ -90,7 +83,7 @@ fun ReminderDefaultPicker(
} }
val inherits = current is ReminderOverride.Inherit val inherits = current is ReminderOverride.Inherit
val isNone = current is ReminderOverride.None val isNone = current is ReminderOverride.None
val selectedMinutes = (current as? ReminderOverride.Minutes)?.minutes.orEmpty() val selectedMinutes = current.minutesOrEmpty()
// Custom (non-preset) lead times seen this session, so unchecking one keeps // Custom (non-preset) lead times seen this session, so unchecking one keeps
// its row (unchecked) until the picker closes instead of vanishing mid-tap, // its row (unchecked) until the picker closes instead of vanishing mid-tap,
// which would strand a hand-entered value with no way to re-check it. // which would strand a hand-entered value with no way to re-check it.
@@ -121,24 +114,14 @@ fun ReminderDefaultPicker(
GroupedRow( GroupedRow(
title = stringResource(R.string.reminder_use_default), title = stringResource(R.string.reminder_use_default),
position = Position.Top, position = Position.Top,
selected = inherits, checked = inherits,
trailing = if (inherits) {
{ SelectedCheck() }
} else {
null
},
onClick = { apply(ReminderOverride.Inherit) }, onClick = { apply(ReminderOverride.Inherit) },
) )
} }
GroupedRow( GroupedRow(
title = stringResource(R.string.reminder_none), title = stringResource(R.string.reminder_none),
position = if (allowInherit) Position.Bottom else Position.Alone, position = if (allowInherit) Position.Bottom else Position.Alone,
selected = isNone, checked = isNone,
trailing = if (isNone) {
{ SelectedCheck() }
} else {
null
},
onClick = { apply(ReminderOverride.None) }, onClick = { apply(ReminderOverride.None) },
) )
Spacer(Modifier.height(24.dp)) Spacer(Modifier.height(24.dp))
@@ -154,17 +137,11 @@ fun ReminderDefaultPicker(
onClick = { toggle(minute) }, onClick = { toggle(minute) },
) )
} }
// When expanded, the Custom row connects downward into the editor card CustomExpandRow(
// so the two read as one grouped container (the per-calendar pattern).
GroupedRow(
title = stringResource(R.string.event_edit_reminder_custom), title = stringResource(R.string.event_edit_reminder_custom),
position = if (customExpanded) Position.Top else positionOf(rows.size, rowCount), position = positionOf(rows.size, rowCount),
onClick = { customExpanded = !customExpanded }, expanded = customExpanded,
) onExpandedChange = { customExpanded = it },
AnimatedVisibility(
visible = customExpanded,
enter = expandEnter(),
exit = collapseExit(),
) { ) {
CustomReminderEditor( CustomReminderEditor(
amountText = amountText, amountText = amountText,
@@ -212,19 +189,6 @@ private fun CustomReminderEditor(
) )
} }
/** A short explanatory paragraph shown under a picker's title, above the rows,
* on the same left margin as the rows themselves. */
@Composable
internal fun PickerDescription(text: String) {
Text(
text = text,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = GroupedListInset, vertical = 8.dp),
)
}
/** /**
* Agenda-range picker, full-screen. Two grouped lists — the calendar-aligned * Agenda-range picker, full-screen. Two grouped lists — the calendar-aligned
* options (today / this week / this month) and the rolling windows (next 7 / 30 * options (today / this week / this month) and the rolling windows (next 7 / 30
@@ -265,17 +229,11 @@ fun AgendaRangePicker(
} }
val rangeRow: @Composable (AgendaRange, Position) -> Unit = { option, position -> val rangeRow: @Composable (AgendaRange, Position) -> Unit = { option, position ->
val isSelected = option == selected
GroupedRow( GroupedRow(
title = agendaRangeLabel(option), title = agendaRangeLabel(option),
summary = windowSummary(option), summary = windowSummary(option),
position = position, position = position,
selected = isSelected, checked = option == selected,
trailing = if (isSelected) {
{ SelectedCheck() }
} else {
null
},
onClick = { onClick = {
onSelect(option) onSelect(option)
onDismiss() onDismiss()
@@ -284,7 +242,7 @@ fun AgendaRangePicker(
} }
FullScreenPicker(title = title, onDismiss = onDismiss) { FullScreenPicker(title = title, onDismiss = onDismiss) {
PickerDescription(description) GroupedHint(description, verticalPadding = 8.dp)
// Calendar-aligned windows. // Calendar-aligned windows.
calendarAligned.forEachIndexed { index, option -> calendarAligned.forEachIndexed { index, option ->
@@ -297,7 +255,7 @@ fun AgendaRangePicker(
rolling.forEachIndexed { index, option -> rolling.forEachIndexed { index, option ->
rangeRow(option, positionOf(index, rollingRowCount)) rangeRow(option, positionOf(index, rollingRowCount))
} }
GroupedRow( CustomExpandRow(
title = if (customSelected) { title = if (customSelected) {
agendaRangeLabel(selected) agendaRangeLabel(selected)
} else { } else {
@@ -306,19 +264,10 @@ fun AgendaRangePicker(
// An unset custom window has no day count yet, so the row stays // An unset custom window has no day count yet, so the row stays
// single-line until it does. // single-line until it does.
summary = if (customSelected) windowSummary(selected) else null, summary = if (customSelected) windowSummary(selected) else null,
position = if (customExpanded) Position.Top else positionOf(rolling.size, rollingRowCount), position = positionOf(rolling.size, rollingRowCount),
selected = customSelected, expanded = customExpanded,
trailing = if (customSelected) { onExpandedChange = { customExpanded = it },
{ SelectedCheck() } checked = customSelected,
} else {
null
},
onClick = { customExpanded = !customExpanded },
)
AnimatedVisibility(
visible = customExpanded,
enter = expandEnter(),
exit = collapseExit(),
) { ) {
CustomDaysEditor( CustomDaysEditor(
amountText = amountText, amountText = amountText,
@@ -396,17 +345,12 @@ fun DurationPicker(
} }
FullScreenPicker(title = title, onDismiss = onDismiss, predictiveBack = true) { FullScreenPicker(title = title, onDismiss = onDismiss, predictiveBack = true) {
if (description != null) PickerDescription(description) if (description != null) GroupedHint(description, verticalPadding = 8.dp)
if (inheritLabel != null) { if (inheritLabel != null) {
GroupedRow( GroupedRow(
title = inheritLabel, title = inheritLabel,
position = Position.Alone, position = Position.Alone,
selected = inherits, checked = inherits,
trailing = if (inherits) {
{ SelectedCheck() }
} else {
null
},
onClick = { onClick = {
onSelect(null) onSelect(null)
onDismiss() onDismiss()
@@ -415,39 +359,22 @@ fun DurationPicker(
Spacer(Modifier.height(24.dp)) Spacer(Modifier.height(24.dp))
} }
presets.forEachIndexed { index, minute -> presets.forEachIndexed { index, minute ->
val isSelected = minute == selected
GroupedRow( GroupedRow(
title = label(minute), title = label(minute),
position = positionOf(index, rowCount), position = positionOf(index, rowCount),
selected = isSelected, checked = minute == selected,
trailing = if (isSelected) {
{ SelectedCheck() }
} else {
null
},
onClick = { onClick = {
onSelect(minute) onSelect(minute)
onDismiss() onDismiss()
}, },
) )
} }
// The Custom row connects downward into the editor card when expanded, so CustomExpandRow(
// the two read as one grouped container (the shared custom-expand pattern).
GroupedRow(
title = custom?.let { label(it) } ?: stringResource(R.string.event_edit_reminder_custom), title = custom?.let { label(it) } ?: stringResource(R.string.event_edit_reminder_custom),
position = if (customExpanded) Position.Top else positionOf(presets.size, rowCount), position = positionOf(presets.size, rowCount),
selected = custom != null, expanded = customExpanded,
trailing = if (custom != null) { onExpandedChange = { customExpanded = it },
{ SelectedCheck() } checked = custom != null,
} else {
null
},
onClick = { customExpanded = !customExpanded },
)
AnimatedVisibility(
visible = customExpanded,
enter = expandEnter(),
exit = collapseExit(),
) { ) {
CustomDurationEditor( CustomDurationEditor(
amountText = amountText, amountText = amountText,
@@ -3,9 +3,9 @@ package de.jeanlucmakiola.calendula.ui.common
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.lifecycle.HiltViewModel
import de.jeanlucmakiola.calendula.data.time.ZoneSource
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
import de.jeanlucmakiola.calendula.data.calendar.NoSuchEventException import de.jeanlucmakiola.calendula.data.calendar.NoSuchEventException
import de.jeanlucmakiola.calendula.data.di.IoDispatcher
import de.jeanlucmakiola.calendula.domain.EventDetail import de.jeanlucmakiola.calendula.domain.EventDetail
import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.EventFormProblem import de.jeanlucmakiola.calendula.domain.EventFormProblem
@@ -15,26 +15,28 @@ import de.jeanlucmakiola.calendula.domain.allowsEventMove
import de.jeanlucmakiola.calendula.domain.parseSimpleRecurrence import de.jeanlucmakiola.calendula.domain.parseSimpleRecurrence
import de.jeanlucmakiola.calendula.domain.problems import de.jeanlucmakiola.calendula.domain.problems
import de.jeanlucmakiola.calendula.domain.realignRecurrence import de.jeanlucmakiola.calendula.domain.realignRecurrence
import de.jeanlucmakiola.calendula.domain.resizedTo
import de.jeanlucmakiola.calendula.domain.endInstant
import de.jeanlucmakiola.calendula.domain.startInstant
import de.jeanlucmakiola.calendula.domain.resolvedZone import de.jeanlucmakiola.calendula.domain.resolvedZone
import de.jeanlucmakiola.calendula.domain.shiftedByDays import de.jeanlucmakiola.calendula.domain.shiftedByDays
import de.jeanlucmakiola.calendula.domain.shiftedTo import de.jeanlucmakiola.calendula.domain.shiftedTo
import de.jeanlucmakiola.calendula.domain.toEditForm import de.jeanlucmakiola.calendula.domain.toEditForm
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
import de.jeanlucmakiola.floret.di.IoDispatcher
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.LocalDate import kotlinx.datetime.LocalDate
import kotlinx.datetime.TimeZone import kotlinx.datetime.TimeZone
import kotlinx.datetime.atStartOfDayIn import kotlinx.datetime.atStartOfDayIn
import kotlinx.datetime.plus import kotlinx.datetime.plus
import kotlinx.datetime.toInstant
import kotlinx.datetime.toLocalDateTime import kotlinx.datetime.toLocalDateTime
import kotlin.coroutines.cancellation.CancellationException import kotlin.coroutines.cancellation.CancellationException
import kotlin.time.Instant import kotlin.time.Instant
@@ -54,6 +56,9 @@ sealed interface MoveTarget {
* disagree by a day over which zone the event's first day is resolved in. * disagree by a day over which zone the event's first day is resolved in.
*/ */
data class ByDays(val days: Int) : MoveTarget data class ByDays(val days: Int) : MoveTarget
/** New start and end instants — a timeline resize, which changes the length. */
data class Span(val start: Instant, val end: Instant) : MoveTarget
} }
/** /**
@@ -74,7 +79,7 @@ data class MoveRequest(
* re-derive (`BYDAY=MO,WE`, `2TH`, …), or the shift wouldn't carry the anchor * re-derive (`BYDAY=MO,WE`, `2TH`, …), or the shift wouldn't carry the anchor
* across the same midnights the occurrence crossed. * across the same midnights the occurrence crossed.
*/ */
data class MoveScopePrompt(val occurrenceOnly: Boolean) data class MoveScopePrompt(val occurrenceOnly: Boolean, val resize: Boolean = false)
/** The inverse of a completed move, for the undo action. */ /** The inverse of a completed move, for the undo action. */
data class MoveUndo( data class MoveUndo(
@@ -88,12 +93,14 @@ data class MoveUndo(
sealed interface MoveOutcome { sealed interface MoveOutcome {
/** /**
* Written. [startMillis] is where the dragged occurrence now begins, for the * Written. [startMillis] is where the dragged occurrence now begins, for the
* confirmation message; [undo] is null when the write has no clean inverse. * confirmation message, and [endMillis] where it ends — set only for a resize,
* whose message names both; [undo] is null when the write has no clean inverse.
*/ */
data class Moved( data class Moved(
val startMillis: Long, val startMillis: Long,
val isAllDay: Boolean, val isAllDay: Boolean,
val undo: MoveUndo?, val undo: MoveUndo?,
val endMillis: Long? = null,
) : MoveOutcome ) : MoveOutcome
data object Undone : MoveOutcome data object Undone : MoveOutcome
@@ -122,6 +129,7 @@ sealed interface MoveOutcome {
class RescheduleViewModel @Inject constructor( class RescheduleViewModel @Inject constructor(
private val repository: CalendarRepository, private val repository: CalendarRepository,
@IoDispatcher private val io: CoroutineDispatcher, @IoDispatcher private val io: CoroutineDispatcher,
private val zoneSource: ZoneSource,
) : ViewModel() { ) : ViewModel() {
private val _scopePrompt = MutableStateFlow<MoveScopePrompt?>(null) private val _scopePrompt = MutableStateFlow<MoveScopePrompt?>(null)
@@ -179,9 +187,8 @@ class RescheduleViewModel @Inject constructor(
.map { calendars -> calendars.filter { it.allowsEventMove }.map { it.id }.toSet() } .map { calendars -> calendars.filter { it.allowsEventMove }.map { it.id }.toSet() }
.catch { emit(emptySet<Long>()) } .catch { emit(emptySet<Long>()) }
.flowOn(io) .flowOn(io)
.stateIn( .stateWhileSubscribed(
scope = viewModelScope, scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = emptySet(), initialValue = emptySet(),
) )
@@ -226,7 +233,10 @@ class RescheduleViewModel @Inject constructor(
} else { } else {
// Still busy: the scope dialog is now the thing in flight. // Still busy: the scope dialog is now the thing in flight.
pending = prepared pending = prepared
_scopePrompt.value = MoveScopePrompt(occurrenceOnly = !prepared.canRealign) _scopePrompt.value = MoveScopePrompt(
occurrenceOnly = !prepared.canRealign,
resize = request.target is MoveTarget.Span,
)
} }
} }
return true return true
@@ -308,18 +318,19 @@ class RescheduleViewModel @Inject constructor(
return null return null
} }
val zone = TimeZone.currentSystemDefault() val zone = zoneSource.current()
val original = detail.toEditForm(request.beginMillis, request.endMillis, zone) val original = detail.toEditForm(request.beginMillis, request.endMillis, zone)
val shifted = when (val target = request.target) { val shifted = when (val target = request.target) {
is MoveTarget.Start -> original.shiftedTo(target.instant, zone) is MoveTarget.Start -> original.shiftedTo(target.instant, zone)
is MoveTarget.ByDays -> original.shiftedByDays(target.days, zone) is MoveTarget.ByDays -> original.shiftedByDays(target.days, zone)
is MoveTarget.Span -> original.resizedTo(target.start, target.end, zone)
} }
// A zero-distance drop is not a write. // A zero-distance drop is not a write.
if (shifted == original) return null if (shifted == original) return null
// The UNTIL check is deferred to the write, which knows how far the move // The UNTIL check is deferred to the write, which knows how far the move
// reaches and so which date has to clear it. // reaches and so which date has to clear it.
if ((shifted.problems() - EventFormProblem.RecurrenceEndsBeforeStart).isNotEmpty()) { if ((shifted.problems(zone) - EventFormProblem.RecurrenceEndsBeforeStart).isNotEmpty()) {
_outcome.value = MoveOutcome.Failed _outcome.value = MoveOutcome.Failed
return null return null
} }
@@ -396,6 +407,7 @@ class RescheduleViewModel @Inject constructor(
startMillis = movedStartMillis(prepared), startMillis = movedStartMillis(prepared),
isAllDay = prepared.updated.isAllDay, isAllDay = prepared.updated.isAllDay,
undo = undoFor(prepared, scope), undo = undoFor(prepared, scope),
endMillis = resizedEndMillis(prepared),
) )
} catch (e: CancellationException) { } catch (e: CancellationException) {
throw e throw e
@@ -480,6 +492,13 @@ class RescheduleViewModel @Inject constructor(
null null
} }
/** Where a resized occurrence now ends; null for a move, which keeps its length. */
private fun resizedEndMillis(prepared: PreparedMove): Long? {
if (prepared.request.target !is MoveTarget.Span) return null
val form = prepared.updated
return form.endInstant(form.resolvedZone(zoneSource.current())).toEpochMilliseconds()
}
/** /**
* Where the dragged occurrence now begins, in the same anchoring the views * Where the dragged occurrence now begins, in the same anchoring the views
* read dates back in: UTC midnight for an all-day event. * read dates back in: UTC midnight for an all-day event.
@@ -489,8 +508,7 @@ class RescheduleViewModel @Inject constructor(
return if (form.isAllDay) { return if (form.isAllDay) {
form.start.date.atStartOfDayIn(TimeZone.UTC).toEpochMilliseconds() form.start.date.atStartOfDayIn(TimeZone.UTC).toEpochMilliseconds()
} else { } else {
form.start.toInstant(form.resolvedZone(TimeZone.currentSystemDefault())) form.startInstant(form.resolvedZone(zoneSource.current())).toEpochMilliseconds()
.toEpochMilliseconds()
} }
} }
@@ -0,0 +1,102 @@
package de.jeanlucmakiola.calendula.ui.common
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.LayoutCoordinates
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.unit.dp
/** The handle's touch target, centred on the edge it moves. */
val ResizeHandleTarget = 48.dp
private val HANDLE_DOT = 16.dp
private val HANDLE_RING = 2.dp
/**
* A grip on one edge of a selected event (#141), dragged without a hold. No
* semantics: TalkBack resizes through the event's edit action.
*/
@Composable
fun ResizeHandle(
color: Color,
enabled: Boolean,
onStart: (pointerInRoot: Offset) -> Unit,
onMove: (pointerInRoot: Offset) -> Unit,
onEnd: () -> Unit,
onCancel: () -> Unit,
modifier: Modifier = Modifier,
) {
val coordinates = remember { arrayOfNulls<LayoutCoordinates>(1) }
val currentStart by rememberUpdatedState(onStart)
val currentMove by rememberUpdatedState(onMove)
val currentEnd by rememberUpdatedState(onEnd)
val currentCancel by rememberUpdatedState(onCancel)
// Not a key: turning it off mid-resize must not cancel that resize.
val currentEnabled by rememberUpdatedState(enabled)
Box(
contentAlignment = Alignment.Center,
modifier = modifier
.size(ResizeHandleTarget)
.clearAndSetSemantics { }
.onGloballyPositioned { coordinates[0] = it }
.pointerInput(Unit) {
awaitEachGesture {
val down = awaitFirstDown()
if (!currentEnabled) return@awaitEachGesture
down.consume()
var started = false
var ended = false
try {
while (true) {
val event = awaitPointerEvent()
val change = event.changes.firstOrNull { it.id == down.id } ?: break
// Claimed by an ancestor that outranks us — the pinch.
if (change.isConsumed) break
if (event.changes.count { it.pressed } > 1) break
change.consume()
if (!change.pressed) {
ended = started
break
}
val root = coordinates[0]?.takeIf { it.isAttached }
?.localToRoot(change.position) ?: break
if (started) {
currentMove(root)
} else {
started = true
currentStart(root)
}
}
} finally {
when {
ended -> currentEnd()
started -> currentCancel()
}
}
}
},
) {
Box(
Modifier
.size(HANDLE_DOT)
.background(color, CircleShape)
.border(HANDLE_RING, MaterialTheme.colorScheme.surface, CircleShape),
)
}
}
@@ -0,0 +1,96 @@
package de.jeanlucmakiola.calendula.ui.common
import androidx.compose.foundation.layout.Column
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.floret.locale.currentLocale
import de.jeanlucmakiola.floret.locale.localizedDateFormatter
import java.time.ZoneId
import java.util.Locale
import kotlin.time.toJavaInstant
/**
* The top bar while an event is selected (#141): says which, and when, with a
* way out — the selection otherwise only shows on the grid and in the FAB.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SelectionTopBar(selection: EventSelection) {
val event = selection.event
// Follows a move or resize, so the times stay readable under the finger.
val preview by remember(selection) { derivedStateOf { selection.preview() } }
val shown = preview ?: event
val use24Hour = LocalUse24HourFormat.current
val locale = currentLocale()
val whenText = remember(shown.start, shown.end, use24Hour, locale) {
formatSelectionWhen(shown, use24Hour, locale)
}
TopAppBar(
navigationIcon = {
IconButton(onClick = selection.dismiss) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = stringResource(
if (selection.create != null) R.string.event_draft_discard else R.string.event_selection_close,
),
)
}
},
title = {
Column {
Text(
text = event.title.ifBlank { stringResource(R.string.event_untitled) },
style = MaterialTheme.typography.titleMedium,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
text = whenText,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
},
// The header's own surface, as the view's bar has (#186).
colors = TopAppBarDefaults.topAppBarColors(
containerColor = MaterialTheme.colorScheme.surface,
scrolledContainerColor = MaterialTheme.colorScheme.surface,
),
)
}
/**
* "Fri, 9 Oct · 09:00–10:00", or with both days named for an event that runs
* into another: "Fri, 9 Oct, 22:00 – Sat, 10 Oct, 02:00".
*/
private fun formatSelectionWhen(event: EventInstance, use24Hour: Boolean, locale: Locale): String {
val zone = ZoneId.systemDefault()
val start = event.start.toJavaInstant().atZone(zone)
val end = event.end.toJavaInstant().atZone(zone)
val day = localizedDateFormatter(locale, "EEEdMMM")
val time = timeOfDayFormatter(use24Hour, locale)
val endsSameDay = end.toLocalDate() == start.toLocalDate() ||
(end.toLocalTime().toSecondOfDay() == 0 && end.toLocalDate() == start.toLocalDate().plusDays(1))
return if (endsSameDay) {
"${day.format(start)} · ${time.format(start)}–${time.format(end)}"
} else {
"${day.format(start)}, ${time.format(start)} – ${day.format(end)}, ${time.format(end)}"
}
}
@@ -1,7 +1,12 @@
package de.jeanlucmakiola.calendula.ui.common package de.jeanlucmakiola.calendula.ui.common
import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.runtime.staticCompositionLocalOf
import de.jeanlucmakiola.calendula.domain.inRepeatedHour
import de.jeanlucmakiola.calendula.domain.zoneAbbreviationAt
import kotlinx.datetime.TimeZone
import java.time.LocalTime import java.time.LocalTime
import kotlin.time.Instant
import kotlin.time.toJavaInstant
import java.time.format.DateTimeFormatter import java.time.format.DateTimeFormatter
import java.util.Locale import java.util.Locale
@@ -68,3 +73,15 @@ fun formatHourLabel(hour: Int, is24Hour: Boolean, locale: Locale): String =
} }
private const val MINUTES_PER_DAY = 1_440 private const val MINUTES_PER_DAY = 1_440
/**
* [formatted] — [instant]'s time in [zone] — with the zone's abbreviation after
* it ("2:30 AM CEST") when the fall-back hour repeats that time, the one case
* where the time alone doesn't say which instant it is (#387).
*/
fun withRepeatedHourZone(formatted: String, instant: Instant, zone: TimeZone, locale: Locale): String {
if (!instant.inRepeatedHour(zone)) return formatted
val abbreviation = zoneAbbreviationAt(zone.id, locale, instant.toJavaInstant(), ::icuTimeZoneRegion)
?: return formatted
return "$formatted $abbreviation"
}
@@ -1,6 +1,5 @@
package de.jeanlucmakiola.calendula.ui.common package de.jeanlucmakiola.calendula.ui.common
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
@@ -39,11 +38,10 @@ import de.jeanlucmakiola.calendula.domain.timeZoneOptionOf
import de.jeanlucmakiola.calendula.domain.timeZoneOptions import de.jeanlucmakiola.calendula.domain.timeZoneOptions
import de.jeanlucmakiola.calendula.domain.zoneDescriptor import de.jeanlucmakiola.calendula.domain.zoneDescriptor
import de.jeanlucmakiola.floret.components.FullScreenPicker import de.jeanlucmakiola.floret.components.FullScreenPicker
import de.jeanlucmakiola.floret.components.GroupedListInset
import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.GroupedRow
import de.jeanlucmakiola.floret.components.GroupedSectionHeader
import de.jeanlucmakiola.floret.components.InlineTextField import de.jeanlucmakiola.floret.components.InlineTextField
import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.Position
import de.jeanlucmakiola.floret.components.SelectedCheck
import de.jeanlucmakiola.floret.components.positionOf import de.jeanlucmakiola.floret.components.positionOf
import de.jeanlucmakiola.floret.locale.currentLocale import de.jeanlucmakiola.floret.locale.currentLocale
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
@@ -118,19 +116,14 @@ fun TimeZonePickerDialog(
title = stringResource(R.string.event_edit_timezone_device), title = stringResource(R.string.event_edit_timezone_device),
summary = deviceSummary, summary = deviceSummary,
position = Position.Alone, position = Position.Alone,
selected = selected == null, checked = selected == null,
leading = { Icon(Icons.Default.Public, contentDescription = null) }, leading = { Icon(Icons.Default.Public, contentDescription = null) },
trailing = if (selected == null) {
{ SelectedCheck() }
} else {
null
},
onClick = { choose(null) }, onClick = { choose(null) },
) )
} }
if (recentZones.isNotEmpty()) { if (recentZones.isNotEmpty()) {
item(key = "recent_header") { item(key = "recent_header") {
SectionHeader(stringResource(R.string.event_edit_timezone_recent)) GroupedSectionHeader(stringResource(R.string.event_edit_timezone_recent))
} }
itemsIndexed( itemsIndexed(
items = recentZones, items = recentZones,
@@ -145,7 +138,7 @@ fun TimeZonePickerDialog(
} }
} }
item(key = "all_header") { item(key = "all_header") {
SectionHeader(stringResource(R.string.event_edit_timezone_all)) GroupedSectionHeader(stringResource(R.string.event_edit_timezone_all))
} }
} }
@@ -234,23 +227,6 @@ private fun SearchField(
} }
} }
/** A small primary-coloured group label, matching the settings screens. */
@Composable
private fun SectionHeader(text: String) {
Text(
text = text,
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary,
modifier = Modifier.padding(
start = GroupedListInset,
end = GroupedListInset,
top = 16.dp,
bottom = 4.dp,
),
)
}
@Composable @Composable
private fun ZoneRow( private fun ZoneRow(
zone: TimeZoneOption, zone: TimeZoneOption,
@@ -262,12 +238,7 @@ private fun ZoneRow(
title = zone.label, title = zone.label,
summary = zoneDescriptor(zone), summary = zoneDescriptor(zone),
position = position, position = position,
selected = selected, checked = selected,
trailing = if (selected) {
{ SelectedCheck() }
} else {
null
},
onClick = onClick, onClick = onClick,
) )
} }
@@ -1,11 +1,10 @@
package de.jeanlucmakiola.calendula.ui.common package de.jeanlucmakiola.calendula.ui.common
import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.tween import androidx.compose.animation.core.tween
import androidx.compose.foundation.ScrollState import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.MutatePriority import androidx.compose.foundation.MutatePriority
import androidx.compose.foundation.background
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
@@ -19,7 +18,10 @@ import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable import androidx.compose.runtime.Stable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
@@ -27,6 +29,7 @@ import androidx.compose.runtime.withFrameNanos
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.TransformOrigin import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.layout.LayoutCoordinates
@@ -35,14 +38,25 @@ import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInRoot import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalViewConfiguration
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.domain.instantIn
import de.jeanlucmakiola.calendula.domain.repeatedHourOffsetAt
import de.jeanlucmakiola.calendula.domain.repicked
import de.jeanlucmakiola.calendula.domain.toFormTime
import de.jeanlucmakiola.calendula.domain.resolveIn
import de.jeanlucmakiola.calendula.ui.week.MINUTES_PER_DAY import de.jeanlucmakiola.calendula.ui.week.MINUTES_PER_DAY
import de.jeanlucmakiola.calendula.ui.week.TimedBlock import de.jeanlucmakiola.calendula.ui.week.TimedBlock
import de.jeanlucmakiola.calendula.ui.week.minutesPast
import de.jeanlucmakiola.calendula.ui.week.wallClockEndMinutes
import de.jeanlucmakiola.calendula.ui.week.wallClockMinutes
import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme
import de.jeanlucmakiola.floret.identity.rememberReduceMotion import de.jeanlucmakiola.floret.identity.rememberReduceMotion
import de.jeanlucmakiola.floret.locale.currentLocale import de.jeanlucmakiola.floret.locale.currentLocale
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
@@ -50,13 +64,15 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.LocalDate import kotlinx.datetime.LocalDate
import kotlinx.datetime.atStartOfDayIn import kotlinx.datetime.atStartOfDayIn
import kotlinx.datetime.UtcOffset
import kotlinx.datetime.plus import kotlinx.datetime.plus
import kotlinx.datetime.LocalDateTime import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.LocalTime import kotlinx.datetime.LocalTime
import kotlinx.datetime.TimeZone import kotlinx.datetime.TimeZone
import kotlinx.datetime.toInstant
import kotlinx.datetime.toLocalDateTime import kotlinx.datetime.toLocalDateTime
import kotlin.math.roundToInt import kotlin.math.roundToInt
import kotlin.time.Duration
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Instant import kotlin.time.Instant
/** Start granularity a dragged block snaps to, matching the big calendar apps. */ /** Start granularity a dragged block snaps to, matching the big calendar apps. */
@@ -97,11 +113,28 @@ data class TimelineDrag(
* drop lands, so it is dropped once the gesture ends ([finish]). * drop lands, so it is dropped once the gesture ends ([finish]).
*/ */
val edgeOnly: Boolean = false, val edgeOnly: Boolean = false,
/**
* The minute of its day the gutter badge names — the top edge, or for a
* bottom-edge resize the end being dragged (#141).
*/
val markerMin: Int = startMin,
) { ) {
/** What the snap haptics key off: one tick per changed slot, not per frame. */ /**
val slot: Pair<LocalDate, Int> get() = date to startMin * What the snap haptics key off: one tick per changed slot, not per frame.
* Carries the length, which is all a bottom-edge resize changes.
*/
val slot: Triple<LocalDate, Int, Int> get() = Triple(date, startMin, eventSpanMin)
} }
/** The event a long press left selected (#141). */
data class TimelineSelection(
val event: EventInstance,
/** Set from a move or resize of it until the grid shows where it landed. */
val moved: Boolean = false,
/** Selected by letting go of a lifted block, which then keeps that lift as it is. */
val fromLift: Boolean = false,
)
/** /**
* One day column's share of a dragged event, ready to draw. Both halves of an * One day column's share of a dragged event, ready to draw. Both halves of an
* event crossing midnight are previewed, whichever half the finger picked up: * event crossing midnight are previewed, whichever half the finger picked up:
@@ -248,6 +281,139 @@ data class TimelineDrop(
val clipOffsetMin: Int = 0, val clipOffsetMin: Int = 0,
) )
/** The id a drafted block's stand-in event carries, which no provider row has (#153). */
private const val DRAFT_ID = Long.MIN_VALUE
/** Whether this is the stand-in for a block drafted on an empty slot, not a real event. */
val EventInstance.isDraft: Boolean get() = instanceId == DRAFT_ID
/** A drafted block's stand-in event, [minutes] long from [start]. */
fun draftEvent(title: String, color: Int, start: Instant, minutes: Int): EventInstance = EventInstance(
instanceId = DRAFT_ID,
eventId = DRAFT_ID,
calendarId = DRAFT_ID,
title = title,
start = start,
end = start + minutes.minutes,
isAllDay = false,
color = color,
location = null,
)
/** Where a long press [minutes] down the column starts its draft, snapped down to the slot. */
internal fun draftStartMin(minutes: Float): Int =
(minutes / DRAG_SNAP_MINUTES).toInt().times(DRAG_SNAP_MINUTES)
.coerceIn(0, MINUTES_PER_DAY - DRAG_SNAP_MINUTES)
/** The part of [draft] on [date] as a full-width block, or null if none of it falls there. */
internal fun draftBlock(draft: EventInstance, date: LocalDate, zone: TimeZone): TimedBlock? {
// Clipped to the day the way the grid lays out events, so it's drawn the same across a DST change (#387).
// The end is exclusive, so a draft ending at midnight belongs to the day before.
val start = maxOf(draft.start, date.atStartOfDayIn(zone))
val end = minOf(draft.end, date.plus(1, DateTimeUnit.DAY).atStartOfDayIn(zone))
if (end <= start) return null
val startMin = wallClockMinutes(start, date, zone)
val endMin = wallClockEndMinutes(startMin, start, end, date, zone).coerceAtMost(MINUTES_PER_DAY)
return TimedBlock(draft, startMin, endMin, lane = 0, laneCount = 1)
}
/** Which end of an event a resize handle moves (#141). */
enum class ResizeEdge { Top, Bottom }
/** Where a finished resize asks its event to begin and end. */
data class TimelineResizeDrop(val event: EventInstance, val start: Instant, val end: Instant)
/**
* [event] resized by its [edge] to the span [startMin]..+[spanMin] from [date]'s
* midnight. Only the held edge moves. The other keeps its own instant rather than
* a round trip through the grid, where an end in the fall-back hour's repeat is
* drawn to that hour's end, not at its own time (#387). In a repeated hour, the
* held edge takes the pass that matches the direction it was dragged from where
* it was drawn (see [repicked]). An end takes a pass the grid draws at the drop
* point, so the block settles under the finger.
*/
internal fun resizedDrop(
event: EventInstance,
edge: ResizeEdge?,
date: LocalDate,
startMin: Int,
spanMin: Int,
zone: TimeZone,
): TimelineResizeDrop {
val drawn = wallClockSpan(event, zone)
return TimelineResizeDrop(
event = event,
start = if (edge == ResizeEdge.Top) {
event.start.toFormTime(zone).repicked(
wallClockTime(date, startMin),
zone,
shownAt = wallClockTime(drawn.day, drawn.startMin),
notAfter = event.end,
).instantIn(zone)
} else {
event.start
},
end = if (edge == ResizeEdge.Bottom) {
val picked = wallClockTime(date, startMin + spanMin)
val pickedMin = (picked.date.toEpochDays() - drawn.day.toEpochDays()).toInt() * MINUTES_PER_DAY +
picked.time.toSecondOfDay() / 60
event.end.toFormTime(zone).repicked(
picked,
zone,
shownAt = wallClockTime(drawn.day, drawn.endMin),
notBefore = event.start,
drawable = { wallClockEndMinutes(drawn.startMin, event.start, it, drawn.day, zone) == pickedMin },
).instantIn(zone)
} else {
event.end
},
)
}
/**
* The span after dragging [edge] to [edgeMin] in day [edgeDay], in minutes from the
* start day's midnight. Snapped, and at least one snap step long.
*/
internal fun resizedSpan(
edge: ResizeEdge,
startMin: Int,
endMin: Int,
edgeMin: Float,
edgeDay: Int? = null,
): Pair<Int, Int> {
// An edge dragged into a day past the other end changes nothing.
if (edgeDay != null) {
val endDay = (endMin - 1).floorDiv(MINUTES_PER_DAY).coerceAtLeast(0)
val wrongWay = when (edge) {
ResizeEdge.Top -> edgeDay > endDay
ResizeEdge.Bottom -> edgeDay < startMin.floorDiv(MINUTES_PER_DAY)
}
if (wrongWay) return startMin to endMin
}
val snapped = (edgeMin / DRAG_SNAP_MINUTES).roundToInt() * DRAG_SNAP_MINUTES
return when (edge) {
ResizeEdge.Top -> minOf(snapped, endMin - DRAG_SNAP_MINUTES) to endMin
ResizeEdge.Bottom -> startMin to maxOf(snapped, startMin + DRAG_SNAP_MINUTES)
}
}
/** [minutes] snapped, kept at [held] until three quarters of a step away. */
internal fun stickySnap(minutes: Float, held: Int?): Int {
if (held != null && kotlin.math.abs(minutes - held) < DRAG_SNAP_MINUTES * 0.75f) return held
return (minutes / DRAG_SNAP_MINUTES).roundToInt() * DRAG_SNAP_MINUTES
}
/** How far past its column's side the finger has to go before a resize changes day. */
private const val COLUMN_HYSTERESIS = 0.25f
/** The column under [position], kept at [held] until [COLUMN_HYSTERESIS] into another. */
internal fun stickyColumn(position: Float, held: Int?, lastIndex: Int): Int {
val under = position.toInt().coerceIn(0, lastIndex)
if (held == null) return under
val stays = position >= held - COLUMN_HYSTERESIS && position < held + 1 + COLUMN_HYSTERESIS
return if (stays) held else under
}
/** /**
* The timeline's live geometry, republished on every layout. Plain fields rather * The timeline's live geometry, republished on every layout. Plain fields rather
* than snapshot state: it changes on every scroll frame, and the drag loop reads * than snapshot state: it changes on every scroll frame, and the drag loop reads
@@ -302,6 +468,10 @@ class TimelineDragController {
var settling: TimelineDrag? by mutableStateOf(null) var settling: TimelineDrag? by mutableStateOf(null)
private set private set
/** How many real drops this controller has handed back. */
var drops by mutableIntStateOf(0)
private set
/** /**
* Which block is lifted, and whether anything is. Separate snapshot state * Which block is lifted, and whether anything is. Separate snapshot state
* from [drag], which changes every frame, so blocks that only need "am I the * from [drag], which changes every frame, so blocks that only need "am I the
@@ -320,10 +490,92 @@ class TimelineDragController {
*/ */
private var settledOrigin: Pair<Long, Instant>? by mutableStateOf(null) private var settledOrigin: Pair<Long, Instant>? by mutableStateOf(null)
/** How long a block drafted on an empty slot starts out, in minutes (#153). */
var draftMinutes: Int = SettingsPrefs.DEFAULT_EVENT_DURATION
/** The selected event, if any — see [TimelineSelection]. */
var selection: TimelineSelection? by mutableStateOf(null)
private set
fun select(event: EventInstance, moved: Boolean = false, fromLift: Boolean = false) {
if (selection?.event?.instanceId != event.instanceId) selectionCovered = false
selection = TimelineSelection(event, moved, fromLift)
}
fun deselect() {
if (selection?.event?.isDraft == true && settling?.event?.isDraft == true) release()
selection = null
selectionCovered = false
}
/** The events of the blocks on screen that show the selection; none for a while ends it. */
val selectedCandidates = mutableStateListOf<EventInstance>()
fun noteSelectedBlock(event: EventInstance, shown: Boolean) {
if (shown) selectedCandidates.add(event) else selectedCandidates.remove(event)
}
/**
* Once a move of the selected event has settled, point the selection at the
* row it landed as. A new event id wins: a single moved occurrence is written
* as an exception, and another occurrence of its series may share its time.
*/
fun settleMovedSelection() {
val current = selection?.takeIf { it.moved } ?: return
if (isDragging || settling != null) return
val landed = selectedCandidates.filter { it.instanceId != current.event.instanceId }
// Only the original row left: the move was abandoned, and it still stands.
val chosen = landed.firstOrNull { it.eventId != current.event.eventId }
?: landed.firstOrNull() ?: selectedCandidates.firstOrNull() ?: return
selection = current.copy(event = chosen, moved = false)
}
/** Whether the selected block's bottom sits where the action bar would cover it. */
var selectionCovered: Boolean by mutableStateOf(false)
private set
/**
* Whether [block] is the selected event: by instance, by series and start, and
* just after a move by title and times, since a moved occurrence gets new ids.
*/
fun isSelected(block: TimedBlock): Boolean {
val current = selection ?: return false
val selected = current.event
val event = block.event
return event.instanceId == selected.instanceId ||
(event.eventId == selected.eventId && event.start == selected.start) ||
(
current.moved &&
event.calendarId == selected.calendarId &&
event.title.isNotBlank() &&
event.title == selected.title &&
event.start == selected.start &&
event.end == selected.end
)
}
/** Point the selection at [block]'s event, so the bar acts on the row now there. */
fun adoptSelection(block: TimedBlock) {
val current = selection?.takeIf { !it.moved } ?: return
if (current.event != block.event) selection = current.copy(event = block.event)
}
/** Whether a finger is on a block right now — [settling] is not dragging. */ /** Whether a finger is on a block right now — [settling] is not dragging. */
var isDragging: Boolean by mutableStateOf(false) var isDragging: Boolean by mutableStateOf(false)
private set private set
/** Whether the finger has moved since the pickup; only then may the view auto-scroll. */
var pointerMoved: Boolean by mutableStateOf(false)
private set
/** Touch slop, past which the finger counts as having moved. */
var slopPx: Float = 0f
private var pickupPointer = Offset.Zero
/** The end a settling resize asked for, which the grid has to show before it settles. */
private var settledEnd: Instant? = null
/** /**
* Whether the grid itself now draws the settled drop at its landing slot. * Whether the grid itself now draws the settled drop at its landing slot.
* The copy may only be handed back once this is true, or the source ghost * The copy may only be handed back once this is true, or the source ghost
@@ -332,6 +584,10 @@ class TimelineDragController {
var settledOnGrid: Boolean by mutableStateOf(false) var settledOnGrid: Boolean by mutableStateOf(false)
private set private set
/** Whether the settling drop is the selected event, whose block lands still lifted. */
var settlingSelected: Boolean = false
private set
/** /**
* The abandoned-move counter, read at the drop so the mark can't be a * The abandoned-move counter, read at the drop so the mark can't be a
* composition behind the tick it is compared against. * composition behind the tick it is compared against.
@@ -353,6 +609,10 @@ class TimelineDragController {
* finger is on; this is what turns where it lands back into an event start. * finger is on; this is what turns where it lands back into an event start.
*/ */
private var clipOffsetMin = 0 private var clipOffsetMin = 0
private var dragZone: TimeZone? = null
private var dragDuration = Duration.ZERO
/** The dragged event's pass of a repeated hour, worked out once per drag (#387). */
private var dragKept: UtcOffset? = null
/** What the picked-up block drew its title over — see [TimelineDrag.titleLines]. */ /** What the picked-up block drew its title over — see [TimelineDrag.titleLines]. */
private var titleLines = 0 private var titleLines = 0
@@ -361,44 +621,93 @@ class TimelineDragController {
* The slot the block already occupied when it was picked up — not the same * The slot the block already occupied when it was picked up — not the same
* as its start, since the target snaps to the grid (09:07 lifts to 09:00). * as its start, since the target snaps to the grid (09:07 lifts to 09:00).
*/ */
private var originSlot: Pair<LocalDate, Int>? = null private var originSlot: Triple<LocalDate, Int, Int>? = null
/** The edge a resize is dragging, or null for a plain drag (#141). */
private var resizeEdge: ResizeEdge? = null
/** The day the resized event starts on; its edges are minutes from that midnight. */
private var resizeDay: LocalDate? = null
private var resizeStartMin = 0
private var resizeEndMin = 0
/** How far the finger sits past the edge it grabbed, so the edge doesn't jump to it. */
private var resizeGrabMin = 0f
/** The column the resized edge is in, held until the finger is well into another. */
private var resizeColumn: Int? = null
/** The slot the resized edge sits on, held against a finger trembling between two. */
private var resizeSlot: Int? = null
/** The day, counted from the event's start day, the finger is resizing in. */
private var resizeEdgeDay = 0
fun begin( fun begin(
block: TimedBlock, block: TimedBlock,
clipOffsetMin: Int, clipOffsetMin: Int,
zone: TimeZone,
titleLines: Int, titleLines: Int,
pointerInRoot: Offset, pointerInRoot: Offset,
blockInRoot: Offset, blockInRoot: Offset,
) { ) {
// The selected event keeps its selection through a drag; any other ends it.
if (!isSelected(block)) deselect()
source = block source = block
this.clipOffsetMin = clipOffsetMin this.clipOffsetMin = clipOffsetMin
dragZone = zone
dragDuration = (block.event.end - block.event.start).coerceAtLeast(Duration.ZERO)
dragKept = zone.repeatedHourOffsetAt(block.event.start)
this.titleLines = titleLines this.titleLines = titleLines
settling = null settling = null
isDragging = true isDragging = true
liftedInstanceId = block.event.instanceId liftedInstanceId = block.event.instanceId
grab = pointerInRoot - blockInRoot grab = pointerInRoot - blockInRoot
pointer = pointerInRoot pointer = pointerInRoot
pickupPointer = pointerInRoot
pointerMoved = false
originSlot = null originSlot = null
recompute() recompute()
originSlot = drag?.slot originSlot = drag?.slot
} }
/**
* Draft a block on an empty slot and lift it at once (#153). It is selected
* from the start, so it keeps its handles and bar once the finger lets go.
*/
fun beginDraft(block: TimedBlock, zone: TimeZone, pointerInRoot: Offset, blockInRoot: Offset) {
deselect()
select(block.event)
begin(block, clipOffsetMin = 0, zone, titleLines = 1, pointerInRoot = pointerInRoot, blockInRoot = blockInRoot)
}
fun move(pointerInRoot: Offset) { fun move(pointerInRoot: Offset) {
pointer = pointerInRoot pointer = pointerInRoot
if (!pointerMoved && (pointerInRoot - pickupPointer).getDistance() > slopPx) pointerMoved = true
recompute() recompute()
} }
fun cancel() { fun cancel() {
resizeEdge = null
resizeDay = null
resizeColumn = null
resizeSlot = null
source = null source = null
clipOffsetMin = 0 clipOffsetMin = 0
dragZone = null
dragDuration = Duration.ZERO
dragKept = null
titleLines = 0 titleLines = 0
isDragging = false isDragging = false
pointerMoved = false
liftedInstanceId = null liftedInstanceId = null
originSlot = null originSlot = null
drag = null drag = null
settling = null settling = null
settledOnGrid = false settledOnGrid = false
settledOrigin = null settledOrigin = null
settledEnd = null
settlingSelected = false
} }
/** /**
@@ -429,8 +738,11 @@ class TimelineDragController {
val offset = (date.toEpochDays() - landed.date.toEpochDays()).toInt() val offset = (date.toEpochDays() - landed.date.toEpochDays()).toInt()
val slice = dragSlices(landed.eventStartMin, landed.eventSpanMin, offset..offset) val slice = dragSlices(landed.eventStartMin, landed.eventSpanMin, offset..offset)
.firstOrNull() ?: return .firstOrNull() ?: return
val end = settledEnd
settledOnGrid = blocks.any { block -> settledOnGrid = blocks.any { block ->
block.startMin == slice.startMin && block.startMin == slice.startMin &&
// A resize may keep its start, so its end has to have landed too.
(end == null || block.event.end == end) &&
( (
block.event.eventId == landed.event.eventId || block.event.eventId == landed.event.eventId ||
( (
@@ -452,6 +764,9 @@ class TimelineDragController {
val clipOffset = clipOffsetMin val clipOffset = clipOffsetMin
cancel() cancel()
if (landed == null || landed.slot == origin) return null if (landed == null || landed.slot == origin) return null
// A draft dropped on a day off screen would vanish, so it stays where it was (#153).
if (landed.edgeOnly && landed.event.isDraft) return null
settlingSelected = selection?.event?.instanceId == landed.event.instanceId
// An edge piece is a hint for the finger, not a preview of the landing // An edge piece is a hint for the finger, not a preview of the landing
// slot: the event belongs to a day this timeline has no column for, so // slot: the event belongs to a day this timeline has no column for, so
// [noteGrid] can never seat it and it would sit at the top of today for // [noteGrid] can never seat it and it would sit at the top of today for
@@ -460,9 +775,165 @@ class TimelineDragController {
liftedInstanceId = landed.event.instanceId liftedInstanceId = landed.event.instanceId
settledOrigin = landed.event.eventId to landed.event.start settledOrigin = landed.event.eventId to landed.event.start
settledAbandonedMark = abandonedTicks?.value ?: 0 settledAbandonedMark = abandonedTicks?.value ?: 0
drops++
return TimelineDrop(landed.event, landed.date, landed.startMin, clipOffset) return TimelineDrop(landed.event, landed.date, landed.startMin, clipOffset)
} }
/**
* Grab one edge of [block] to resize it (#141). The edge follows the finger
* across days as a drag does; the other stays where it is.
*/
fun beginResize(
block: TimedBlock,
edge: ResizeEdge,
zone: TimeZone,
titleLines: Int,
pointerInRoot: Offset,
) {
val span = wallClockSpan(block.event, zone)
source = block
resizeEdge = edge
resizeDay = span.day
resizeStartMin = span.startMin
resizeEndMin = span.endMin
clipOffsetMin = 0
this.titleLines = titleLines
settling = null
isDragging = true
pointerMoved = true
liftedInstanceId = block.event.instanceId
pointer = pointerInRoot
// Measured from the edge's own column: the handle overhangs into the next.
val edgeDay = if (edge == ResizeEdge.Top) 0 else (resizeEndMin - 1).floorDiv(MINUTES_PER_DAY).coerceAtLeast(0)
val edgeIndex = geometry.days.indexOf(span.day.plus(edgeDay, DateTimeUnit.DAY))
resizeColumn = edgeIndex.takeIf { it >= 0 }
?.let { if (geometry.isRtl) geometry.days.lastIndex - it else it }
resizeGrabMin = (pointerResizeMinutes() ?: 0f) -
if (edge == ResizeEdge.Top) resizeStartMin else resizeEndMin
originSlot = null
recompute()
originSlot = drag?.slot
}
/** The slot the gesture would land on, changing once per snap rather than per frame. */
private val landingSlot by derivedStateOf { drag?.slot }
/**
* The dragged event at the times letting go now would give it, worked out as
* [finish] and [finishResize] do. Null while it is still on its own slot (#141).
*/
fun preview(zone: TimeZone): EventInstance? {
val (date, startMin, spanMin) = landingSlot?.takeIf { it != originSlot } ?: return null
val event = source?.event ?: return null
val edge = resizeEdge
if (edge != null) {
val drop = resizedDrop(event, edge, date, startMin, spanMin, zone)
return event.copy(start = drop.start, end = drop.end)
}
val start = TimelineDrop(event, date, startMin, clipOffsetMin).startInstant(zone)
return event.copy(start = start, end = start + dragDuration)
}
/**
* End a resize, handing back the event's new span — null when it never
* resolved or came back to the length it started at. Settles as [finish] does.
*/
fun finishResize(zone: TimeZone): TimelineResizeDrop? {
val landed = drag
val origin = originSlot
val edge = resizeEdge
cancel()
if (landed == null || landed.slot == origin) return null
val drop = resizedDrop(landed.event, edge, landed.date, landed.eventStartMin, landed.eventSpanMin, zone)
settlingSelected = selection?.event?.instanceId == landed.event.instanceId
settling = if (landed.edgeOnly) landed.copy(pieces = emptyList()) else landed
liftedInstanceId = landed.event.instanceId
settledOrigin = landed.event.eventId to landed.event.start
settledAbandonedMark = abandonedTicks?.value ?: 0
settledEnd = drop.end
drops++
return drop
}
/**
* Where the finger is, in minutes from the resized event's start day —
* past 1440 in a later column, negative in an earlier one.
*/
private fun pointerResizeMinutes(): Float? {
val grid = geometry.grid?.takeIf { it.isAttached } ?: return null
val day = resizeDay ?: return null
val hourPx = geometry.hourPx
val columnPx = geometry.columnWidthPx
val days = geometry.days
if (hourPx <= 0f || columnPx <= 0f || days.isEmpty()) return null
val origin = grid.positionInRoot()
val column = stickyColumn(
position = (pointer.x - origin.x) / columnPx,
held = resizeColumn,
lastIndex = days.lastIndex,
)
resizeColumn = column
val dayIndex = if (geometry.isRtl) days.lastIndex - column else column
val dayOffset = (days[dayIndex].toEpochDays() - day.toEpochDays()).toInt()
resizeEdgeDay = dayOffset
return dayOffset * MINUTES_PER_DAY + (pointer.y - origin.y) / hourPx * 60f
}
private fun recomputeResize(edge: ResizeEdge) {
val block = source ?: return
val day = resizeDay ?: return
val raw = pointerResizeMinutes() ?: return
val slot = stickySnap(raw - resizeGrabMin, resizeSlot)
resizeSlot = slot
val (start, end) = resizedSpan(edge, resizeStartMin, resizeEndMin, slot.toFloat(), resizeEdgeDay)
val days = geometry.days
val hourPx = geometry.hourPx
val columnPx = geometry.columnWidthPx
val origin = geometry.grid?.takeIf { it.isAttached }?.positionInRoot() ?: return
// Which column the start day sits in, possibly off either end of the view.
val startIndex = (day.toEpochDays() - days.first().toEpochDays()).toInt()
val visible = -startIndex..days.lastIndex - startIndex
val slices = dragSlices(start, end - start, within = visible)
drag = TimelineDrag(
event = block.event,
date = day,
startMin = start,
eventStartMin = start,
eventSpanMin = end - start,
titleLines = titleLines,
pieces = slices.map { slice ->
val dayIndex = startIndex + slice.dayOffset
val col = if (geometry.isRtl) days.lastIndex - dayIndex else dayIndex
val bounds = dragPieceBounds(slice, hourPx, geometry.blockInsetPx)
TimelineDragPiece(
topLeftInRoot = Offset(x = origin.x + col * columnPx, y = origin.y + bounds.top),
sizePx = IntSize(
(columnPx - geometry.columnGapPx).roundToInt(),
bounds.height.roundToInt(),
),
continuesBefore = slice.continuesBefore,
continuesAfter = slice.continuesAfter,
)
},
edgeOnly = slices.isEmpty(),
markerMin = if (edge == ResizeEdge.Top) {
start.mod(MINUTES_PER_DAY)
} else {
end - (end - 1).floorDiv(MINUTES_PER_DAY) * MINUTES_PER_DAY
},
)
}
/** Note whether the action bar would cover the selected block's bottom handle (#141). */
fun noteSelectedBottom(block: LayoutCoordinates, extraPx: Float, clearancePx: Float) {
val viewport = geometry.viewport?.takeIf { it.isAttached } ?: return
if (!block.isAttached) return
val port = viewport.boundsInRoot()
val bottom = block.positionInRoot().y + block.size.height + extraPx
val covered = bottom > port.bottom - clearancePx
if (covered != selectionCovered) selectionCovered = covered
}
/** /**
* Stop ghosting the source — the grid draws the drop itself by now — while * Stop ghosting the source — the grid draws the drop itself by now — while
* the copy is still dissolving. Un-ghosting at [release] instead would leave * the copy is still dissolving. Un-ghosting at [release] instead would leave
@@ -477,6 +948,8 @@ class TimelineDragController {
fun release() { fun release() {
settling = null settling = null
settledOnGrid = false settledOnGrid = false
settledEnd = null
settlingSelected = false
handOver() handOver()
} }
@@ -486,6 +959,10 @@ class TimelineDragController {
* no move events while auto-scroll walks the content underneath it. * no move events while auto-scroll walks the content underneath it.
*/ */
fun recompute() { fun recompute() {
resizeEdge?.let {
recomputeResize(it)
return
}
val block = source ?: return val block = source ?: return
val grid = geometry.grid?.takeIf { it.isAttached } ?: return val grid = geometry.grid?.takeIf { it.isAttached } ?: return
val hourPx = geometry.hourPx val hourPx = geometry.hourPx
@@ -496,13 +973,22 @@ class TimelineDragController {
val origin = grid.positionInRoot() val origin = grid.positionInRoot()
val rawMinutes = (pointer.y - grab.y - origin.y) / hourPx * 60f val rawMinutes = (pointer.y - grab.y - origin.y) / hourPx * 60f
val snapped = (rawMinutes / DRAG_SNAP_MINUTES).roundToInt() * DRAG_SNAP_MINUTES val snapped = (rawMinutes / DRAG_SNAP_MINUTES).roundToInt() * DRAG_SNAP_MINUTES
val eventSpan = (block.event.end - block.event.start).inWholeMinutes.toInt() val zone = dragZone ?: return
.coerceAtLeast(0)
val floor = dragFloorMin(clipOffsetMin, eventSpan)
val startMin = snapped.coerceIn(floor, MINUTES_PER_DAY - DRAG_SNAP_MINUTES)
val eventStartMin = startMin - clipOffsetMin
val column = ((pointer.x - origin.x) / columnPx).toInt().coerceIn(0, days.lastIndex) val column = ((pointer.x - origin.x) / columnPx).toInt().coerceIn(0, days.lastIndex)
val dayIndex = if (geometry.isRtl) days.lastIndex - column else column val dayIndex = if (geometry.isRtl) days.lastIndex - column else column
val target = days[dayIndex]
val keep = dragKept
// Measured where it would land: the drop keeps the real duration, which in
// wall clock gains or loses the hour of a DST change it crosses (#387).
val floor = dragFloorMin(
clipOffsetMin,
wallClockSpanMinutes(target, snapped - clipOffsetMin, dragDuration, zone, keep),
)
val held = snapped.coerceIn(floor, MINUTES_PER_DAY - DRAG_SNAP_MINUTES) - clipOffsetMin
// A start in the spring-forward gap lands an hour on; show it there.
val eventStartMin = wallClockInstant(target, held, zone, keep).minutesPast(target, zone)
val startMin = (eventStartMin + clipOffsetMin).coerceAtMost(MINUTES_PER_DAY - DRAG_SNAP_MINUTES)
val eventSpan = wallClockSpanMinutes(target, eventStartMin, dragDuration, zone, keep)
val visible = -dayIndex..days.lastIndex - dayIndex val visible = -dayIndex..days.lastIndex - dayIndex
val onGrid = dragSlices(eventStartMin, eventSpan, within = visible) val onGrid = dragSlices(eventStartMin, eventSpan, within = visible)
val slices = onGrid.ifEmpty { val slices = onGrid.ifEmpty {
@@ -577,6 +1063,7 @@ fun rememberTimelineDragController(): TimelineDragController {
val density = LocalDensity.current val density = LocalDensity.current
controller.geometry.edgePx = with(density) { AUTO_SCROLL_EDGE.toPx() } controller.geometry.edgePx = with(density) { AUTO_SCROLL_EDGE.toPx() }
controller.geometry.stepPx = with(density) { AUTO_SCROLL_STEP.toPx() } controller.geometry.stepPx = with(density) { AUTO_SCROLL_STEP.toPx() }
controller.slopPx = LocalViewConfiguration.current.touchSlop
controller.abandonedTicks = LocalEventMove.current?.abandoned controller.abandonedTicks = LocalEventMove.current?.abandoned
return controller return controller
} }
@@ -589,10 +1076,7 @@ fun rememberTimelineDragController(): TimelineDragController {
* so the offset has to come back off at the drop (#253). * so the offset has to come back off at the drop (#253).
*/ */
fun TimedBlock.clipOffsetMinutes(day: LocalDate, zone: TimeZone): Int { fun TimedBlock.clipOffsetMinutes(day: LocalDate, zone: TimeZone): Int {
val start = event.start.toLocalDateTime(zone) return (startMin - event.start.minutesPast(day, zone)).coerceAtLeast(0)
val days = (day.toEpochDays() - start.date.toEpochDays()).toInt()
val minutes = days * MINUTES_PER_DAY + startMin - start.time.toSecondOfDay() / 60
return minutes.coerceAtLeast(0)
} }
/** /**
@@ -613,15 +1097,58 @@ fun TimedBlock.continuesAfter(day: LocalDate, zone: TimeZone): Boolean =
* of its own; `toInstant` resolves it forward by the missing hour, and the block * of its own; `toInstant` resolves it forward by the missing hour, and the block
* visibly settles there. * visibly settles there.
*/ */
fun TimelineDrop.startInstant(zone: TimeZone): Instant { fun TimelineDrop.startInstant(zone: TimeZone): Instant =
// Wall clock throughout, and past this day at either end: a block's top edge wallClockInstant(date, startMin - clipOffsetMin, zone, kept = zone.repeatedHourOffsetAt(event.start))
// can be dragged above its midnight and a tail's below the next one, so the
// start is resolved as a day plus a minute of it rather than as an offset /**
// from an instant — which would shift by an hour across a DST boundary. * The wall-clock minutes an event lasting [duration] covers when it starts
val fromMidnight = startMin - clipOffsetMin * [startMin] past [date]'s midnight in [zone] — its real length, give or take a
val day = date.plus(fromMidnight.floorDiv(MINUTES_PER_DAY), DateTimeUnit.DAY) * DST change in between (#387).
val minute = fromMidnight.mod(MINUTES_PER_DAY) */
return LocalDateTime(day, LocalTime(minute / 60, minute % 60)).toInstant(zone) internal fun wallClockSpanMinutes(
date: LocalDate,
startMin: Int,
duration: Duration,
zone: TimeZone,
kept: UtcOffset? = null,
): Int {
val start = wallClockInstant(date, startMin, zone, kept)
return wallClockEndMinutes(startMin, start, start + duration, date, zone) - startMin
}
/**
* [minutes] past [date]'s midnight, either way past it, as wall clock in [zone]
* (DST-safe). A time the fall-back hour repeats lands on its earlier pass, unless
* [kept] is its later one: an event there stays on it (#387). Pass
* [repeatedHourOffsetAt] of the event's time, which is null outside the hour —
* such an instant says nothing about which pass the grid slot means, so a drop
* never depends on the season the event came from.
*/
fun wallClockInstant(date: LocalDate, minutes: Int, zone: TimeZone, kept: UtcOffset? = null): Instant =
wallClockTime(date, minutes).resolveIn(zone, kept)
/** The wall-clock time [minutes] past [date]'s midnight, on a later day past 1440. */
fun wallClockTime(date: LocalDate, minutes: Int): LocalDateTime {
val day = date.plus(minutes.floorDiv(MINUTES_PER_DAY), DateTimeUnit.DAY)
val minute = minutes.mod(MINUTES_PER_DAY)
return LocalDateTime(day, LocalTime(minute / 60, minute % 60))
}
/** An event's span as wall-clock minutes from its start day's midnight. */
data class WallClockSpan(val day: LocalDate, val startMin: Int, val endMin: Int)
/**
* [event]'s [WallClockSpan], its end past 1440 when it ends on a later day
* (DST-safe). One ending in the fall-back hour's repeat ends where that hour does.
*/
fun wallClockSpan(event: EventInstance, zone: TimeZone): WallClockSpan {
val start = event.start.toLocalDateTime(zone)
val startMin = start.time.toSecondOfDay() / 60
return WallClockSpan(
start.date,
startMin,
wallClockEndMinutes(startMin, event.start, event.end, start.date, zone),
)
} }
/** /**
@@ -651,7 +1178,7 @@ const val SETTLE_FADE_MILLIS: Int = 250
fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier = Modifier) { fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier = Modifier) {
var origin by remember { mutableStateOf(Offset.Zero) } var origin by remember { mutableStateOf(Offset.Zero) }
val density = LocalDensity.current val density = LocalDensity.current
val dark = isSystemInDarkTheme() val dark = LocalFloretDarkTheme.current
val use24Hour = LocalUse24HourFormat.current val use24Hour = LocalUse24HourFormat.current
val locale = currentLocale() val locale = currentLocale()
val reduceMotion = rememberReduceMotion() val reduceMotion = rememberReduceMotion()
@@ -659,9 +1186,11 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
// Both live here rather than beside the controller: they read [drag], which // Both live here rather than beside the controller: they read [drag], which
// changes every frame, and this composable is the one that is meant to. // changes every frame, and this composable is the one that is meant to.
DragSnapHaptics(controller.drag?.slot) DragSnapHaptics(controller.drag?.slot, controller.drops)
LaunchedEffect(controller.isDragging) { // Only once the finger has moved: a long press held near an edge must not
if (controller.isDragging) controller.autoScroll() // scroll the drop target out from under a finger that only means to select.
LaunchedEffect(controller.isDragging && controller.pointerMoved) {
if (controller.isDragging && controller.pointerMoved) controller.autoScroll()
} }
// Hold the landed copy until the write is done — including the time a // Hold the landed copy until the write is done — including the time a
// recurring drop's scope dialog is up — and then until the grid draws the // recurring drop's scope dialog is up — and then until the grid draws the
@@ -693,7 +1222,8 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
// Landed: the copy sinks back to the grid's own plane while the write runs. // Landed: the copy sinks back to the grid's own plane while the write runs.
val landed = controller.drag == null val landed = controller.drag == null
val lift by animateFloatAsState( val lift by animateFloatAsState(
targetValue = if (landed || reduceMotion) 0f else 1f, // A selected event's block is lifted too: sinking first made it shrink, then grow back.
targetValue = if (reduceMotion || (landed && !controller.settlingSelected)) 0f else 1f,
label = "drag-lift", label = "drag-lift",
) )
val copyAlpha by animateFloatAsState( val copyAlpha by animateFloatAsState(
@@ -870,7 +1400,7 @@ private fun DragCopy(
Text( Text(
text = label, text = label,
// As the block it lifted off sets its own time (#219). // As the block it lifted off sets its own time (#219).
style = MaterialTheme.typography.labelSmall.asEventTime(), style = rememberPackedLines(MaterialTheme.typography.labelSmall.asEventTime()),
maxLines = timeMaxLines, maxLines = timeMaxLines,
overflow = overflow.overflow, overflow = overflow.overflow,
softWrap = overflow.softWrap, softWrap = overflow.softWrap,
@@ -880,3 +1410,30 @@ private fun DragCopy(
} }
} }
} }
/** How far a selected block is lifted, 0 to 1 (#141); [snap] takes it over at once. */
@Composable
fun selectionLift(selected: Boolean, snap: Boolean = false): Float {
val reduceMotion = rememberReduceMotion()
val spec = MaterialTheme.motionScheme.fastSpatialSpec<Float>()
val raise = remember { Animatable(if (selected) 1f else 0f) }
LaunchedEffect(selected) {
val target = if (selected) 1f else 0f
if (reduceMotion || (selected && snap)) raise.snapTo(target) else raise.animateTo(target, spec)
}
// The effect runs a frame late, and that frame would show the block unlifted.
return if (selected && snap) 1f else raise.value
}
/**
* A selected block raised off the grid, the way a dragged copy is: scaled from
* its top edge so the text doesn't creep, with a shadow in the block's shape.
*/
fun Modifier.selectionLift(raise: Float, shape: Shape): Modifier = graphicsLayer {
transformOrigin = TransformOrigin(0.5f, 0f)
scaleX = 1f + 0.02f * raise
scaleY = 1f + 0.02f * raise
shadowElevation = 6.dp.toPx() * raise
this.shape = shape
clip = false
}
@@ -16,8 +16,6 @@ data class TimelineHours(
val startHour: Int = DEFAULT_START_HOUR, val startHour: Int = DEFAULT_START_HOUR,
val endHour: Int = DEFAULT_END_HOUR, val endHour: Int = DEFAULT_END_HOUR,
) { ) {
val span: Int get() = endHour - startHour
companion object { companion object {
const val DEFAULT_START_HOUR = 7 const val DEFAULT_START_HOUR = 7
const val DEFAULT_END_HOUR = 22 const val DEFAULT_END_HOUR = 22
@@ -1,145 +0,0 @@
package de.jeanlucmakiola.calendula.ui.common
import androidx.compose.animation.Crossfade
import androidx.compose.animation.core.snap
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.layout
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import de.jeanlucmakiola.floret.components.GroupedListInset
import de.jeanlucmakiola.floret.identity.rememberReduceMotion
import kotlin.math.roundToInt
/**
* The viewport a view preview pretends to be: a phone's width by the height a
* calendar view gets under the top bar. Scaling every preview from one fixed
* height keeps them comparable — each shows the same slice of screen.
*/
internal val PREVIEW_VIEWPORT_HEIGHT = 440.dp
/**
* Renders [content] at a full phone viewport and shrinks the finished layout
* into a box [height] tall, for the settings and onboarding choosers. Callers
* pass the *real* view composables, so a preview cannot drift from what it
* depicts.
*
* The [layout] below ignores the incoming constraints so the view measures at a
* phone viewport, and a [graphicsLayer] scale shrinks the result.
* `Modifier.requiredSize` is the obvious alternative but *centres* content that
* overflows its constraints, leaving only the bottom-right corner in the clip.
*/
@Composable
internal fun ScaledViewPreview(
height: Dp,
modifier: Modifier = Modifier,
content: @Composable () -> Unit,
) {
val screenWidth = LocalConfiguration.current.screenWidthDp.dp
val scale = height.value / PREVIEW_VIEWPORT_HEIGHT.value
Box(
modifier = modifier
.clipToBounds()
.background(MaterialTheme.colorScheme.surface)
// A preview is a picture, not a control: swallow touches before the
// view's own clickables see them, and give screen readers one label
// instead of six weeks of day cells.
.pointerInput(Unit) {
awaitPointerEventScope {
while (true) {
awaitPointerEvent(PointerEventPass.Initial).changes
.forEach { it.consume() }
}
}
}
.clearAndSetSemantics { }
// Measure at a full phone viewport but report the scaled size, so the
// node occupies exactly what it draws.
.layout { measurable, _ ->
val fullWidth = screenWidth.roundToPx()
val fullHeight = PREVIEW_VIEWPORT_HEIGHT.roundToPx()
val placeable = measurable.measure(Constraints.fixed(fullWidth, fullHeight))
layout((fullWidth * scale).roundToInt(), (fullHeight * scale).roundToInt()) {
placeable.place(0, 0)
}
}
.graphicsLayer {
scaleX = scale
scaleY = scale
transformOrigin = TransformOrigin(0f, 0f)
},
) {
Column(Modifier.fillMaxSize()) { content() }
}
}
/**
* The stage every preview picker sets its preview on, cross-fading as [selected]
* changes. A preview draws the app's own surface, so a tonal plate gives it the
* edge it would otherwise lack on a chooser screen; the plate takes the width
* and outer radius of the grouped rows underneath so the two read as one stack.
*
* Only vertical spacing is the caller's to pass — the horizontal inset is the
* rows' own, and the alignment is the point.
*/
@Composable
internal fun <T> ViewPreviewFrame(
selected: T,
label: String,
modifier: Modifier = Modifier,
content: @Composable (T) -> Unit,
) {
val reduceMotion = rememberReduceMotion()
Box(
modifier = modifier
.fillMaxWidth()
.padding(horizontal = GroupedListInset)
.clip(FRAME_SHAPE)
.background(MaterialTheme.colorScheme.surfaceContainerHigh)
.padding(FRAME_INSET),
contentAlignment = Alignment.Center,
) {
Crossfade(
targetState = selected,
animationSpec = if (reduceMotion) snap() else tween(durationMillis = 250),
label = label,
) { shown ->
// Each preview renders the real view at phone size and scales it
// down, so its own corners are square — the plate rounds them.
Box(
modifier = Modifier
.clip(PREVIEW_SHAPE)
.background(MaterialTheme.colorScheme.surface)
.clipToBounds(),
) {
content(shown)
}
}
}
}
private val FRAME_INSET = 8.dp
/** The grouped rows' own outer radius, so the stack shares one silhouette. */
private val FRAME_SHAPE = RoundedCornerShape(22.dp)
private val PREVIEW_SHAPE = RoundedCornerShape(12.dp)
@@ -1,22 +0,0 @@
package de.jeanlucmakiola.calendula.ui.day
import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.LocalDate
import kotlinx.datetime.daysUntil
import kotlinx.datetime.plus
/** Pages the day pager spans — a little under four centuries, centred on [PAGE_EPOCH]. */
internal const val DAY_PAGE_COUNT: Int = 140_000
private const val EPOCH_PAGE = DAY_PAGE_COUNT / 2
/** The day at [EPOCH_PAGE]; any date works, it only has to stay fixed. */
private val PAGE_EPOCH = LocalDate(2000, 1, 1)
/** The day shown on pager [page]. */
internal fun dayForPage(page: Int): LocalDate =
PAGE_EPOCH.plus(page - EPOCH_PAGE, DateTimeUnit.DAY)
/** The pager page showing [date]. */
internal fun dayPageFor(date: LocalDate): Int =
(EPOCH_PAGE + PAGE_EPOCH.daysUntil(date)).coerceIn(0, DAY_PAGE_COUNT - 1)
@@ -1,19 +1,13 @@
package de.jeanlucmakiola.calendula.ui.detail package de.jeanlucmakiola.calendula.ui.detail
import android.Manifest
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri import android.net.Uri
import android.widget.Toast import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
@@ -22,7 +16,6 @@ import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
@@ -41,7 +34,6 @@ import androidx.compose.material.icons.filled.Public
import androidx.compose.material.icons.filled.Repeat import androidx.compose.material.icons.filled.Repeat
import androidx.compose.material.icons.filled.Schedule import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material.icons.filled.Share import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
@@ -51,7 +43,6 @@ import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface import androidx.compose.material3.Surface
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
@@ -65,19 +56,21 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.core.content.ContextCompat
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.LinkAnnotation import androidx.compose.ui.text.LinkAnnotation
import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextLinkStyles import androidx.compose.ui.text.TextLinkStyles
import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.BaselineShift
import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.em
import androidx.hilt.navigation.compose.hiltViewModel import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.R
@@ -90,24 +83,29 @@ import de.jeanlucmakiola.calendula.domain.Availability
import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.domain.EventStatus import de.jeanlucmakiola.calendula.domain.EventStatus
import de.jeanlucmakiola.calendula.domain.RecurringWriteScope import de.jeanlucmakiola.calendula.domain.InlineStyle
import de.jeanlucmakiola.calendula.domain.Reminder import de.jeanlucmakiola.calendula.domain.Reminder
import de.jeanlucmakiola.calendula.domain.RichText
import de.jeanlucmakiola.calendula.domain.TimeZoneOption import de.jeanlucmakiola.calendula.domain.TimeZoneOption
import de.jeanlucmakiola.calendula.domain.timeZoneOptionOf import de.jeanlucmakiola.calendula.domain.timeZoneOptionOf
import de.jeanlucmakiola.calendula.domain.zoneDescriptor import de.jeanlucmakiola.calendula.domain.zoneDescriptor
import de.jeanlucmakiola.floret.components.IconInfoCard
import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme
import de.jeanlucmakiola.floret.identity.predictiveBack import de.jeanlucmakiola.floret.identity.predictiveBack
import de.jeanlucmakiola.calendula.ui.common.CalendarFailure import de.jeanlucmakiola.calendula.ui.common.CalendarFailure
import de.jeanlucmakiola.calendula.ui.common.DeleteEventDialog
import de.jeanlucmakiola.calendula.ui.common.rememberWriteGate
import de.jeanlucmakiola.calendula.ui.common.sendEventShare
import de.jeanlucmakiola.calendula.ui.common.FieldCopier import de.jeanlucmakiola.calendula.ui.common.FieldCopier
import de.jeanlucmakiola.calendula.ui.common.copyOnLongPress import de.jeanlucmakiola.calendula.ui.common.copyOnLongPress
import de.jeanlucmakiola.calendula.ui.common.rememberFieldCopier import de.jeanlucmakiola.calendula.ui.common.rememberFieldCopier
import de.jeanlucmakiola.calendula.ui.common.icuTimeZoneRegion import de.jeanlucmakiola.calendula.ui.common.icuTimeZoneRegion
import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors
import de.jeanlucmakiola.calendula.ui.common.eventAccent import de.jeanlucmakiola.calendula.ui.common.eventAccent
import de.jeanlucmakiola.calendula.ui.common.eventFill
import de.jeanlucmakiola.floret.components.OptionCard
import de.jeanlucmakiola.floret.locale.currentLocale import de.jeanlucmakiola.floret.locale.currentLocale
import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat
import de.jeanlucmakiola.calendula.ui.common.timeOfDayFormatter import de.jeanlucmakiola.calendula.ui.common.timeOfDayFormatter
import de.jeanlucmakiola.calendula.ui.common.withRepeatedHourZone
import de.jeanlucmakiola.calendula.ui.common.recurrenceText import de.jeanlucmakiola.calendula.ui.common.recurrenceText
import de.jeanlucmakiola.calendula.ui.common.reminderLeadTimeLabel import de.jeanlucmakiola.calendula.ui.common.reminderLeadTimeLabel
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
@@ -162,43 +160,15 @@ fun EventDetailScreen(
val onShareClick = { val onShareClick = {
scope.launch { scope.launch {
val uri = viewModel.shareUri() val uri = viewModel.shareUri()
val sent = uri != null && runCatching { val sent = uri != null && context.sendEventShare(uri, shareChooserTitle)
val send = Intent(Intent.ACTION_SEND).apply {
type = "text/calendar"
putExtra(Intent.EXTRA_STREAM, uri)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
context.startActivity(Intent.createChooser(send, shareChooserTitle))
}.isSuccess
if (!sent) snackbarHostState.showSnackbar(shareFailedMessage) if (!sent) snackbarHostState.showSnackbar(shareFailedMessage)
} }
Unit Unit
} }
// v1.0 installs only hold READ_CALENDAR; the first write asks for the // v1.0 installs only hold READ_CALENDAR; the first write asks for the
// upgrade in place. Granting continues straight into the tapped action — // upgrade in place and continues straight into the tapped action.
// edit, delete, or duplicate — held here until the result comes back. val requireWrite = rememberWriteGate()
var pendingWrite by remember { mutableStateOf<(() -> Unit)?>(null) }
val writePermissionLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestPermission(),
) { granted ->
if (granted) pendingWrite?.invoke()
pendingWrite = null
}
val hasWritePermission = {
ContextCompat.checkSelfPermission(
context,
Manifest.permission.WRITE_CALENDAR,
) == PackageManager.PERMISSION_GRANTED
}
val requireWrite: (() -> Unit) -> Unit = { action ->
if (hasWritePermission()) {
action()
} else {
pendingWrite = action
writePermissionLauncher.launch(Manifest.permission.WRITE_CALENDAR)
}
}
val onDeleteClick = { requireWrite { showDeleteDialog = true } } val onDeleteClick = { requireWrite { showDeleteDialog = true } }
val onEditClick = { requireWrite(onEdit) } val onEditClick = { requireWrite(onEdit) }
// Duplicate reads the loaded detail into a create form and hands it up; the // Duplicate reads the loaded detail into a create form and hands it up; the
@@ -322,70 +292,6 @@ fun EventDetailScreen(
} }
} }
/**
* Delete confirmation. Recurring events choose between cancelling just the
* tapped occurrence (default), truncating the series from it onwards, and
* removing the whole series.
*/
@Composable
private fun DeleteEventDialog(
isRecurring: Boolean,
onConfirm: (RecurringWriteScope) -> Unit,
onDismiss: () -> Unit,
) {
var scope by rememberSaveable { mutableStateOf(RecurringWriteScope.ThisEvent) }
AlertDialog(
onDismissRequest = onDismiss,
title = {
Text(
stringResource(
if (isRecurring) R.string.event_delete_recurring_title
else R.string.event_delete_title,
),
)
},
text = {
if (isRecurring) {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
OptionCard(
label = stringResource(R.string.event_delete_option_occurrence),
onClick = { scope = RecurringWriteScope.ThisEvent },
selected = scope == RecurringWriteScope.ThisEvent,
)
OptionCard(
label = stringResource(R.string.event_delete_option_following),
onClick = { scope = RecurringWriteScope.ThisAndFollowing },
selected = scope == RecurringWriteScope.ThisAndFollowing,
)
OptionCard(
label = stringResource(R.string.event_delete_option_series),
onClick = { scope = RecurringWriteScope.AllEvents },
selected = scope == RecurringWriteScope.AllEvents,
)
}
} else {
Text(stringResource(R.string.event_delete_body))
}
},
confirmButton = {
TextButton(
onClick = { onConfirm(if (isRecurring) scope else RecurringWriteScope.AllEvents) },
) {
Text(
text = stringResource(R.string.event_detail_delete),
color = MaterialTheme.colorScheme.error,
)
}
},
dismissButton = {
TextButton(onClick = onDismiss) {
Text(stringResource(R.string.dialog_cancel))
}
},
)
}
@Composable @Composable
private fun EventDetailContent( private fun EventDetailContent(
state: EventDetailUiState.Success, state: EventDetailUiState.Success,
@@ -394,7 +300,7 @@ private fun EventDetailContent(
) { ) {
val detail = state.detail val detail = state.detail
val instance = detail.instance val instance = detail.instance
val dark = isSystemInDarkTheme() val dark = LocalFloretDarkTheme.current
val locale = currentDetailLocale() val locale = currentDetailLocale()
val accent = eventAccent(instance.color, dark, LocalSoftenColors.current) val accent = eventAccent(instance.color, dark, LocalSoftenColors.current)
@@ -409,15 +315,26 @@ private fun EventDetailContent(
// cancelled event strikes through its title. // cancelled event strikes through its title.
Row(verticalAlignment = Alignment.Top) { Row(verticalAlignment = Alignment.Top) {
val titleLabel = stringResource(R.string.event_detail_title) val titleLabel = stringResource(R.string.event_detail_title)
val titleDecoration = if (detail.status == EventStatus.Cancelled) {
TextDecoration.LineThrough
} else {
null
}
Text( Text(
text = instance.title.ifBlank { stringResource(R.string.event_untitled) }, // A phone number in the title ("Call Anna 0151 …") dials too.
text = if (instance.title.isBlank()) {
AnnotatedString(stringResource(R.string.event_untitled))
} else {
linkify(
instance.title,
state.phoneLinks.title,
MaterialTheme.colorScheme.primary,
titleDecoration,
)
},
style = MaterialTheme.typography.headlineMedium, style = MaterialTheme.typography.headlineMedium,
fontWeight = FontWeight.SemiBold, fontWeight = FontWeight.SemiBold,
textDecoration = if (detail.status == EventStatus.Cancelled) { textDecoration = titleDecoration,
TextDecoration.LineThrough
} else {
null
},
modifier = Modifier modifier = Modifier
.weight(1f) .weight(1f)
.then( .then(
@@ -464,8 +381,8 @@ private fun EventDetailContent(
val gap = 12.dp val gap = 12.dp
// "When" — date/all-day plus the time range. // "When" — date/all-day plus the time range.
val (whenPrimary, whenSecondary) = formatWhen(instance, TimeZone.currentSystemDefault(), locale) val (whenPrimary, whenSecondary) = rememberWhen(instance, TimeZone.currentSystemDefault(), locale)
DetailCard(icon = Icons.Default.Schedule, iconContentDescription = null) { IconInfoCard(icon = Icons.Default.Schedule, iconContentDescription = null) {
Text(text = whenPrimary, style = MaterialTheme.typography.titleMedium) Text(text = whenPrimary, style = MaterialTheme.typography.titleMedium)
if (whenSecondary != null) { if (whenSecondary != null) {
Spacer(Modifier.height(2.dp)) Spacer(Modifier.height(2.dp))
@@ -490,7 +407,7 @@ private fun EventDetailContent(
} }
foreignZone?.let { zoneOption -> foreignZone?.let { zoneOption ->
Spacer(Modifier.height(gap)) Spacer(Modifier.height(gap))
DetailCard( IconInfoCard(
icon = Icons.Default.Public, icon = Icons.Default.Public,
iconContentDescription = stringResource(R.string.event_detail_timezone), iconContentDescription = stringResource(R.string.event_detail_timezone),
) { ) {
@@ -504,7 +421,7 @@ private fun EventDetailContent(
// in the primary instead, so fall back to it. If the zone can't be // in the primary instead, so fall back to it. If the zone can't be
// read back at all, drop to just the abbreviation + offset. // read back at all, drop to just the abbreviation + offset.
val originalTime = runCatching { TimeZone.of(zoneOption.id) }.getOrNull() val originalTime = runCatching { TimeZone.of(zoneOption.id) }.getOrNull()
?.let { formatWhen(instance, it, locale) } ?.let { rememberWhen(instance, it, locale) }
?.let { (primary, secondary) -> secondary ?: primary } ?.let { (primary, secondary) -> secondary ?: primary }
Spacer(Modifier.height(2.dp)) Spacer(Modifier.height(2.dp))
Text( Text(
@@ -522,7 +439,7 @@ private fun EventDetailContent(
// Calendar — icon tinted in the calendar colour conveys identity, so no // Calendar — icon tinted in the calendar colour conveys identity, so no
// separate colour dot is needed. // separate colour dot is needed.
Spacer(Modifier.height(gap)) Spacer(Modifier.height(gap))
DetailCard( IconInfoCard(
icon = Icons.Default.CalendarMonth, icon = Icons.Default.CalendarMonth,
iconTint = accent, iconTint = accent,
iconContentDescription = stringResource(R.string.event_detail_calendar), iconContentDescription = stringResource(R.string.event_detail_calendar),
@@ -534,17 +451,18 @@ private fun EventDetailContent(
) )
} }
// Location (conditional). URLs open in the browser, the rest in maps. // Location (conditional). URLs open in the browser, phone numbers in the
// dialer, the rest in maps.
instance.location?.takeIf { it.isNotBlank() }?.let { location -> instance.location?.takeIf { it.isNotBlank() }?.let { location ->
val context = LocalContext.current val context = LocalContext.current
val locationLabel = stringResource(R.string.event_detail_location) val locationLabel = stringResource(R.string.event_detail_location)
Spacer(Modifier.height(gap)) Spacer(Modifier.height(gap))
DetailCard( IconInfoCard(
icon = Icons.Default.Place, icon = Icons.Default.Place,
iconContentDescription = locationLabel, iconContentDescription = locationLabel,
) { ) {
Text( Text(
text = linkifyUrls(location, MaterialTheme.colorScheme.primary), text = linkify(location, state.phoneLinks.location, MaterialTheme.colorScheme.primary),
style = MaterialTheme.typography.titleMedium, style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.primary, color = MaterialTheme.colorScheme.primary,
modifier = Modifier modifier = Modifier
@@ -561,20 +479,21 @@ private fun EventDetailContent(
} }
} }
// Description (conditional). URLs are auto-linked. // Description (conditional). HTML is rendered (#271); URLs and phone
detail.description?.takeIf { it.isNotBlank() }?.let { description -> // numbers are auto-linked.
state.description?.let { description ->
val descriptionLabel = stringResource(R.string.event_detail_description) val descriptionLabel = stringResource(R.string.event_detail_description)
Spacer(Modifier.height(gap)) Spacer(Modifier.height(gap))
DetailCard( IconInfoCard(
icon = Icons.AutoMirrored.Filled.Notes, icon = Icons.AutoMirrored.Filled.Notes,
iconContentDescription = descriptionLabel, iconContentDescription = descriptionLabel,
// The gesture sits on the card so the icon and padding answer // The gesture sits on the card so the icon and padding answer
// it too: every linkified URL owns the pointer over its own // it too: every linkified URL owns the pointer over its own
// glyphs, which leaves the text itself a patchy target. // glyphs, which leaves the text itself a patchy target.
modifier = Modifier.copyOnLongPress(descriptionLabel, description, copyField), modifier = Modifier.copyOnLongPress(descriptionLabel, description.copyText(), copyField),
) { ) {
Text( Text(
text = linkifyUrls(description, MaterialTheme.colorScheme.primary), text = linkify(description, state.phoneLinks.description, MaterialTheme.colorScheme.primary),
style = MaterialTheme.typography.bodyMedium, style = MaterialTheme.typography.bodyMedium,
) )
} }
@@ -584,7 +503,7 @@ private fun EventDetailContent(
// each attendee with their role and reply. // each attendee with their role and reply.
detail.attendees.takeIf { it.isNotEmpty() }?.let { attendees -> detail.attendees.takeIf { it.isNotEmpty() }?.let { attendees ->
Spacer(Modifier.height(gap)) Spacer(Modifier.height(gap))
DetailCard( IconInfoCard(
icon = Icons.Default.People, icon = Icons.Default.People,
iconContentDescription = stringResource(R.string.event_detail_attendees), iconContentDescription = stringResource(R.string.event_detail_attendees),
) { ) {
@@ -606,7 +525,7 @@ private fun EventDetailContent(
// Reminders (conditional) — list each lead time before the event. // Reminders (conditional) — list each lead time before the event.
detail.reminders.takeIf { it.isNotEmpty() }?.let { reminders -> detail.reminders.takeIf { it.isNotEmpty() }?.let { reminders ->
Spacer(Modifier.height(gap)) Spacer(Modifier.height(gap))
DetailCard( IconInfoCard(
icon = Icons.Default.Notifications, icon = Icons.Default.Notifications,
iconContentDescription = stringResource(R.string.event_detail_reminders), iconContentDescription = stringResource(R.string.event_detail_reminders),
) { ) {
@@ -626,7 +545,7 @@ private fun EventDetailContent(
// Recurrence (conditional) — humanised from the RRULE. // Recurrence (conditional) — humanised from the RRULE.
detail.rrule?.takeIf { it.isNotBlank() }?.let { rrule -> detail.rrule?.takeIf { it.isNotBlank() }?.let { rrule ->
Spacer(Modifier.height(gap)) Spacer(Modifier.height(gap))
DetailCard( IconInfoCard(
icon = Icons.Default.Repeat, icon = Icons.Default.Repeat,
iconContentDescription = stringResource(R.string.event_detail_recurrence), iconContentDescription = stringResource(R.string.event_detail_recurrence),
) { ) {
@@ -639,36 +558,6 @@ private fun EventDetailContent(
} }
} }
/** One info card: tonal container, leading icon in the gutter, value to the right. */
@Composable
private fun DetailCard(
icon: ImageVector,
iconContentDescription: String?,
modifier: Modifier = Modifier,
iconTint: Color = MaterialTheme.colorScheme.onSurfaceVariant,
content: @Composable ColumnScope.() -> Unit,
) {
Surface(
color = MaterialTheme.colorScheme.surfaceContainerHigh,
shape = RoundedCornerShape(16.dp),
modifier = modifier.fillMaxWidth(),
) {
Row(
modifier = Modifier.padding(16.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
imageVector = icon,
contentDescription = iconContentDescription,
tint = iconTint,
modifier = Modifier.size(24.dp),
)
Spacer(Modifier.width(16.dp))
Column(modifier = Modifier.weight(1f), content = content)
}
}
}
@Composable @Composable
private fun AttendeeRow(attendee: Attendee) { private fun AttendeeRow(attendee: Attendee) {
Row( Row(
@@ -847,45 +736,114 @@ private fun foreignTimeZone(
) )
} }
/** Wrap http(s) URLs in [text] as links tinted [linkColor] that open in the browser. */ /**
* Wrap http(s) URLs in [text] as links that open in the browser, and its
* [phoneLinks] as links that open the dialer, both tinted [linkColor]. A
* link's underline joins [textDecoration] rather than replacing it, so a
* cancelled title stays struck through across its links.
*/
@Composable @Composable
private fun linkifyUrls(text: String, linkColor: Color): AnnotatedString { private fun linkify(
text: String,
phoneLinks: List<PhoneLink>,
linkColor: Color,
textDecoration: TextDecoration? = null,
): AnnotatedString = linkify(RichText(text), phoneLinks, linkColor, textDecoration)
/**
* [linkify] for text rendered from HTML: its own formatting and `<a href>`
* links come along, and a URL or number already inside one isn't linked again.
*/
@Composable
private fun linkify(
text: RichText,
phoneLinks: List<PhoneLink>,
linkColor: Color,
textDecoration: TextDecoration? = null,
): AnnotatedString {
val context = LocalContext.current val context = LocalContext.current
return remember(text, linkColor, context) { return remember(text, phoneLinks, linkColor, textDecoration, context) {
val styles = TextLinkStyles( // Decorations go on separately so overlapping ones add up: a span's
style = SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline), // textDecoration replaces whatever sits under it.
) val styles = TextLinkStyles(style = SpanStyle(color = linkColor))
val decorations = mutableListOf<Triple<Int, Int, TextDecoration>>()
textDecoration?.let { decorations += Triple(0, text.text.length, it) }
for (range in text.styles) {
when (range.style) {
InlineStyle.Underline -> decorations += Triple(range.start, range.end, TextDecoration.Underline)
InlineStyle.Strikethrough -> decorations += Triple(range.start, range.end, TextDecoration.LineThrough)
else -> Unit
}
}
fun linked(start: Int, end: Int) = text.links.any { start < it.end && it.start < end }
buildAnnotatedString { buildAnnotatedString {
append(text) append(text.text)
for (link in findWebLinks(text)) { for (range in text.styles) range.style.toSpanStyle()?.let { addStyle(it, range.start, range.end) }
addLink( fun link(url: String, start: Int, end: Int, onClick: () -> Unit) {
LinkAnnotation.Url(link.url, styles) { openWebLink(context, link.url) }, addLink(LinkAnnotation.Url(url, styles) { onClick() }, start, end)
link.start, decorations += Triple(start, end, TextDecoration.Underline)
link.end, }
) for (link in text.links) {
if (link.url.startsWith("tel:")) {
link(link.url, link.start, link.end) { dial(context, Uri.decode(link.url.substring(4))) }
} else {
link(link.url, link.start, link.end) { openWebLink(context, link.url) }
}
}
for (link in findWebLinks(text.text)) {
if (linked(link.start, link.end)) continue
link(link.url, link.start, link.end) { openWebLink(context, link.url) }
}
for (link in phoneLinks) {
if (linked(link.start, link.end)) continue
link("tel:${link.number}", link.start, link.end) { dial(context, link.number) }
}
val bounds = decorations.flatMap { listOf(it.first, it.second) }.distinct().sorted()
for ((start, end) in bounds.zipWithNext()) {
val covering = decorations.filter { it.first <= start && end <= it.second }.map { it.third }.distinct()
if (covering.isNotEmpty()) addStyle(SpanStyle(textDecoration = TextDecoration.combine(covering)), start, end)
} }
} }
} }
} }
private fun InlineStyle.toSpanStyle(): SpanStyle? = when (this) {
InlineStyle.Bold -> SpanStyle(fontWeight = FontWeight.Bold)
InlineStyle.Italic -> SpanStyle(fontStyle = FontStyle.Italic)
InlineStyle.Superscript -> SpanStyle(baselineShift = BaselineShift.Superscript, fontSize = 0.75.em)
InlineStyle.Subscript -> SpanStyle(baselineShift = BaselineShift.Subscript, fontSize = 0.75.em)
InlineStyle.Monospace -> SpanStyle(fontFamily = FontFamily.Monospace)
InlineStyle.Underline, InlineStyle.Strikethrough -> null
}
/** /**
* Format an event's time into a primary line (date, or "All day") and an * Format an event's time into a primary line (date, or "All day") and an
* optional secondary line (time range). Multi-day timed events collapse into a * optional secondary line (time range). Multi-day timed events collapse into a
* single primary line spanning both ends. * single primary line spanning both ends.
*/ */
@Composable @Composable
private fun rememberWhen(instance: EventInstance, zone: TimeZone, locale: Locale): Pair<String, String?> {
val use24Hour = LocalUse24HourFormat.current
val allDayLabel = stringResource(R.string.event_detail_all_day)
// Remembered: a time in the repeated hour looks up its zone abbreviation (#387).
return remember(instance, zone, locale, use24Hour, allDayLabel) {
formatWhen(instance, zone, locale, use24Hour, allDayLabel)
}
}
private fun formatWhen( private fun formatWhen(
instance: EventInstance, instance: EventInstance,
zone: TimeZone, zone: TimeZone,
locale: Locale, locale: Locale,
use24Hour: Boolean,
allDayLabel: String,
): Pair<String, String?> { ): Pair<String, String?> {
val zid = ZoneId.of(zone.id) val zid = ZoneId.of(zone.id)
val dateFull = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).withLocale(locale) val dateFull = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).withLocale(locale)
val dateMedium = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(locale) val dateMedium = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(locale)
val timeShort = timeOfDayFormatter(LocalUse24HourFormat.current, locale) val timeShort = timeOfDayFormatter(use24Hour, locale)
val startLdt = instance.start.toJavaLocalDateTime(zid) val startLdt = instance.start.toJavaLocalDateTime(zid)
val allDayLabel = stringResource(R.string.event_detail_all_day)
if (instance.isAllDay) { if (instance.isAllDay) {
// All-day events live at UTC midnights with an exclusive end. Resolve // All-day events live at UTC midnights with an exclusive end. Resolve
@@ -905,12 +863,13 @@ private fun formatWhen(
} }
val endLdt = instance.end.toJavaLocalDateTime(zid) val endLdt = instance.end.toJavaLocalDateTime(zid)
val startTime = withRepeatedHourZone(timeShort.format(startLdt), instance.start, zone, locale)
val endTime = withRepeatedHourZone(timeShort.format(endLdt), instance.end, zone, locale)
return if (startLdt.toLocalDate() == endLdt.toLocalDate()) { return if (startLdt.toLocalDate() == endLdt.toLocalDate()) {
dateFull.format(startLdt.toLocalDate()) to dateFull.format(startLdt.toLocalDate()) to "$startTime – $endTime"
"${timeShort.format(startLdt)} – ${timeShort.format(endLdt)}"
} else { } else {
val start = "${dateMedium.format(startLdt.toLocalDate())} ${timeShort.format(startLdt)}" val start = "${dateMedium.format(startLdt.toLocalDate())} $startTime"
val end = "${dateMedium.format(endLdt.toLocalDate())} ${timeShort.format(endLdt)}" val end = "${dateMedium.format(endLdt.toLocalDate())} $endTime"
"$start – $end" to null "$start – $end" to null
} }
} }
@@ -920,7 +879,15 @@ private fun Instant.toJavaLocalDateTime(zid: ZoneId): java.time.LocalDateTime =
/** Open [url] in a browsable app, or say so when none can take it. */ /** Open [url] in a browsable app, or say so when none can take it. */
private fun openWebLink(context: Context, url: String) { private fun openWebLink(context: Context, url: String) {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)).addCategory(Intent.CATEGORY_BROWSABLE) startOrSayNoApp(context, Intent(Intent.ACTION_VIEW, Uri.parse(url)).addCategory(Intent.CATEGORY_BROWSABLE))
}
/** Open the dialer with [number] filled in, or say so when none can take it. */
private fun dial(context: Context, number: String) {
startOrSayNoApp(context, Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", number, null)))
}
private fun startOrSayNoApp(context: Context, intent: Intent) {
if (runCatching { context.startActivity(intent) }.isFailure) { if (runCatching { context.startActivity(intent) }.isFailure) {
Toast.makeText(context, R.string.link_open_failed, Toast.LENGTH_SHORT).show() Toast.makeText(context, R.string.link_open_failed, Toast.LENGTH_SHORT).show()
} }
@@ -2,6 +2,7 @@ package de.jeanlucmakiola.calendula.ui.detail
import de.jeanlucmakiola.calendula.domain.EventDetail import de.jeanlucmakiola.calendula.domain.EventDetail
import de.jeanlucmakiola.calendula.domain.FailureReason import de.jeanlucmakiola.calendula.domain.FailureReason
import de.jeanlucmakiola.calendula.domain.RichText
/** /**
* UI state for the event-detail screen (spec S4). * UI state for the event-detail screen (spec S4).
@@ -21,6 +22,10 @@ sealed interface EventDetailUiState {
* the sync would just resurrect it. Contact dates are removed at the source. * the sync would just resurrect it. Contact dates are removed at the source.
*/ */
val isManaged: Boolean = false, val isManaged: Boolean = false,
/** Phone numbers to link in the title, location and description. */
val phoneLinks: EventPhoneLinks = EventPhoneLinks(),
/** The description as drawn — HTML rendered (#271); null when there is none. */
val description: RichText? = null,
) : EventDetailUiState ) : EventDetailUiState
} }
@@ -6,20 +6,22 @@ import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.lifecycle.HiltViewModel
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
import de.jeanlucmakiola.calendula.data.calendar.NoSuchEventException import de.jeanlucmakiola.calendula.data.calendar.NoSuchEventException
import de.jeanlucmakiola.calendula.data.di.IoDispatcher
import de.jeanlucmakiola.calendula.data.ics.IcsExporter import de.jeanlucmakiola.calendula.data.ics.IcsExporter
import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.FailureReason import de.jeanlucmakiola.calendula.domain.FailureReason
import de.jeanlucmakiola.calendula.domain.RecurringWriteScope import de.jeanlucmakiola.calendula.domain.RecurringWriteScope
import de.jeanlucmakiola.calendula.domain.ics.IcsWriter import de.jeanlucmakiola.calendula.domain.atOccurrence
import de.jeanlucmakiola.calendula.domain.ics.toShareIcsEvent import de.jeanlucmakiola.calendula.domain.descriptionRichText
import de.jeanlucmakiola.calendula.domain.toEditForm import de.jeanlucmakiola.calendula.domain.toDuplicateForm
import de.jeanlucmakiola.calendula.ui.common.DeleteOutcome
import de.jeanlucmakiola.calendula.ui.common.tryDeleteEvent
import de.jeanlucmakiola.calendula.ui.common.stageEventShare
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
import de.jeanlucmakiola.floret.di.IoDispatcher
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import kotlin.time.Clock
import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.combine
@@ -28,11 +30,9 @@ import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.datetime.TimeZone import kotlinx.datetime.TimeZone
import kotlin.coroutines.cancellation.CancellationException import kotlin.coroutines.cancellation.CancellationException
import kotlin.time.Instant
import javax.inject.Inject import javax.inject.Inject
/** /**
@@ -75,9 +75,8 @@ class EventDetailViewModel @Inject constructor(
} }
} }
.flowOn(io) .flowOn(io)
.stateIn( .stateWhileSubscribed(
scope = viewModelScope, scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = EventDetailUiState.Loading, initialValue = EventDetailUiState.Loading,
) )
@@ -112,22 +111,11 @@ class EventDetailViewModel @Inject constructor(
if (_deleteState.value == DeleteUiState.Deleting) return if (_deleteState.value == DeleteUiState.Deleting) return
viewModelScope.launch { viewModelScope.launch {
_deleteState.value = DeleteUiState.Deleting _deleteState.value = DeleteUiState.Deleting
_deleteState.value = try { _deleteState.value = when (repository.tryDeleteEvent(target.eventId, target.beginMillis, scope)) {
when (scope) { // Already gone is what a delete wants anyway.
RecurringWriteScope.AllEvents -> DeleteOutcome.Deleted, DeleteOutcome.Gone -> DeleteUiState.Deleted
repository.deleteEvent(target.eventId) DeleteOutcome.NeedsPermission -> DeleteUiState.NeedsPermission
RecurringWriteScope.ThisEvent -> DeleteOutcome.Failed -> DeleteUiState.Failed
repository.deleteOccurrence(target.eventId, target.beginMillis)
RecurringWriteScope.ThisAndFollowing ->
repository.deleteEventFromOccurrence(target.eventId, target.beginMillis)
}
DeleteUiState.Deleted
} catch (e: CancellationException) {
throw e
} catch (e: SecurityException) {
DeleteUiState.NeedsPermission
} catch (e: Exception) {
DeleteUiState.Failed
} }
} }
} }
@@ -144,66 +132,46 @@ class EventDetailViewModel @Inject constructor(
*/ */
suspend fun shareUri(): Uri? { suspend fun shareUri(): Uri? {
val detail = (state.value as? EventDetailUiState.Success)?.detail ?: return null val detail = (state.value as? EventDetailUiState.Success)?.detail ?: return null
return runCatching { return withContext(io) { icsExporter.stageEventShare(detail) }
withContext(io) {
val ics = IcsWriter().writeCalendar(
events = listOf(detail.toShareIcsEvent()),
dtStamp = Clock.System.now(),
)
icsExporter.stageShareFile(shareFileName(detail.instance.title), ics)
}
}.getOrNull()
} }
/** /**
* Build a create form seeded from the open event so the user can save a * A create form seeded from the open event, to save a copy as a new event
* copy as a new, independent event (#52). Returns null when nothing is * (#52) — see [toDuplicateForm]. Null when nothing is loaded.
* loaded.
*
* The recurrence is dropped — a duplicate is a single event; anyone who
* wants a series can re-add one in the edit form that opens. The source
* calendar is kept only when it's writable, otherwise the id is cleared so
* the create resolves to the last-used/first-writable calendar — which lets
* a read-only event (a WebCal subscription, a birthday) be copied into an
* editable calendar. The occurrence's own times carry over unchanged.
*/ */
fun duplicateForm(): EventForm? { fun duplicateForm(): EventForm? {
val loaded = state.value as? EventDetailUiState.Success ?: return null val loaded = state.value as? EventDetailUiState.Success ?: return null
val detail = loaded.detail return loaded.detail.toDuplicateForm(loaded.canModify, TimeZone.currentSystemDefault())
return detail.toEditForm(
beginMillis = detail.instance.start.toEpochMilliseconds(),
endMillis = detail.instance.end.toEpochMilliseconds(),
zone = TimeZone.currentSystemDefault(),
).copy(
rrule = null,
calendarId = detail.instance.calendarId.takeIf { loaded.canModify },
)
} }
private suspend fun loadDetail(target: Target): EventDetailUiState = try { private suspend fun loadDetail(target: Target): EventDetailUiState = try {
val detail = repository.eventDetail(target.eventId) val detail = repository.eventDetail(target.eventId)
// The Events row holds the series start; replace it with this // An external "open event" that names no occurrence ([NO_OCCURRENCE_TIME] —
// occurrence's time so recurring events render correctly. An external // e.g. a bare content://.../events/<id> VIEW intent, issue #48) keeps the
// "open event" that names no occurrence ([NO_OCCURRENCE_TIME] — e.g. a // row's own DTSTART/DTEND instead of overriding it to the epoch.
// bare content://.../events/<id> VIEW intent, issue #48) keeps the row's
// own DTSTART/DTEND instead of overriding it to the epoch.
val corrected = if (target.beginMillis == NO_OCCURRENCE_TIME) { val corrected = if (target.beginMillis == NO_OCCURRENCE_TIME) {
detail detail
} else { } else {
detail.copy( detail.atOccurrence(target.beginMillis, target.endMillis)
instance = detail.instance.copy(
start = Instant.fromEpochMilliseconds(target.beginMillis),
end = Instant.fromEpochMilliseconds(target.endMillis),
),
)
} }
val calendar = repository.calendars().first() val calendar = repository.calendars().first()
.firstOrNull { it.id == corrected.instance.calendarId } .firstOrNull { it.id == corrected.instance.calendarId }
val description = corrected.description
?.let(::descriptionRichText)
?.takeIf { it.text.isNotBlank() }
EventDetailUiState.Success( EventDetailUiState.Success(
detail = corrected, detail = corrected,
calendarName = calendar?.displayName, calendarName = calendar?.displayName,
canModify = calendar?.canModifyContents == true, canModify = calendar?.canModifyContents == true,
isManaged = calendar?.isManaged == true, isManaged = calendar?.isManaged == true,
// Found here, off the main thread and once per load: the platform
// matcher loads its metadata on first use.
phoneLinks = findEventPhoneLinks(
title = corrected.instance.title,
location = corrected.instance.location,
description = description?.text,
),
description = description,
) )
} catch (e: CancellationException) { } catch (e: CancellationException) {
throw e throw e
@@ -228,13 +196,3 @@ class EventDetailViewModel @Inject constructor(
const val NO_OCCURRENCE_TIME: Long = Long.MIN_VALUE const val NO_OCCURRENCE_TIME: Long = Long.MIN_VALUE
} }
} }
/** A filesystem-safe `.ics` file name from an event title (or a fallback). */
private fun shareFileName(title: String): String {
val base = title.trim()
.replace(Regex("""[^\p{L}\p{Nd} _-]"""), "")
.replace(' ', '_')
.take(40)
.ifBlank { "event" }
return "$base.ics"
}
@@ -0,0 +1,202 @@
package de.jeanlucmakiola.calendula.ui.detail
import android.text.SpannableString
import android.text.style.URLSpan
import android.text.util.Linkify
/**
* A phone number found in free text, spanning [start] until [end] (exclusive).
* [number] is what the dialer gets: digits, a leading `+`, and any `,`/`#`
* dial-in suffix — the separators that only made it readable are gone.
*/
data class PhoneLink(val start: Int, val end: Int, val number: String)
/** The phone numbers in an event's free-text fields, each against its own text. */
data class EventPhoneLinks(
val title: List<PhoneLink> = emptyList(),
val location: List<PhoneLink> = emptyList(),
val description: List<PhoneLink> = emptyList(),
)
/** Where the platform matcher saw a phone number: [start] until [end] (exclusive). */
internal data class PhoneMatch(val start: Int, val end: Int)
// A conference dial-in's pauses and meeting id right after the number:
// "+16465588656,,85012345678#" or Zoom's ",,850…#,,,,*123456#". It opens on a
// double comma or closes on "#", so "030 1234567,0151 2345678" stays a list.
private val dialSuffixRegex = Regex("""^(?:,,+[\d*]+#?|,[\d*]+#)(?:,+[\d*]+#?)*""")
// Whitespace as invites write it: Java's \s misses the no-break space and the
// invisible direction marks Meet and Outlook wrap around numbers.
private const val GAP = """\s\u00A0\u200E\u200F\u202A-\u202E\u2066-\u2069"""
// A number right after one of these labels is an id to type in, not one to
// call. English and German cover the Zoom/Teams/Meet/Webex invites seen so far.
// "Conference number" is left out: invites use it for the dial-in itself.
private val notAPhoneLabelRegex = Regex(
"""(?:(?:meeting|webinar|besprechungs)[ -]?(?:id|number|nummer)|(?:conference|konferenz)[ -]?id|""" +
"""\bpin|passcode|password|passwort|kenncode|access code|zugangscode)[$GAP:#.()]*$""",
RegexOption.IGNORE_CASE,
)
// A day.month.year (or year-month-day, or US month/day/year) date: exactly
// three groups, so a French "01.23.45.67.89" chain doesn't read as one.
private val dateRegex = Regex("""(?<![\d./-])(\d{1,4})([./-])(\d{1,2})\2(\d{4}|\d{2})(?![\d]|[./-]\d)""")
// Thousands groups. A short lead ("1.250.000", "12 500 000") is an amount; a
// three-digit lead is one only beside a currency — "612 345 678" and
// "612.345.678" are Spanish mobiles, "125.000.000 €" a budget.
private val shortLeadAmountRegex = Regex("""[1-9]\d?(?:([. ])\d{3})(?:\1\d{3})*""")
private val amountRegex = Regex("""[1-9]\d{0,2}(?:([. ])\d{3})(?:\1\d{3})*""")
private val currencyBeforeRegex = Regex("""(?:[€$£]|\b(?:eur|euro|usd|chf|gbp))\s*$""", RegexOption.IGNORE_CASE)
private val currencyAfterRegex = Regex("""^\s*(?:[€$£]|(?:eur|euro|usd|chf|gbp)\b)""", RegexOption.IGNORE_CASE)
// A short group set off by a space after a long one, with a word straight
// after — "… 2345678 2 times" — is the prose's count, not the number's tail.
// Without the word ("030 123456 0") or after a short group ("0221 1234 56")
// it is the number's own.
private val strayTailRegex = Regex("""(?<=\d{6})\s+\d{1,2}$""")
private val wordAfterRegex = Regex("""[ \t\u00A0]+\p{L}""")
// "9.30 – 12.00", "10.00-11.30": times of day written the German way.
private val dottedTimesRegex = Regex("""(\d{1,2})\.(\d{2})(?:\s*[-–]\s*(\d{1,2})\.(\d{2}))?""")
// "ext. 567", "x567", "Durchwahl 567": the dialer reaches an extension after a pause.
private val extensionRegex = Regex("""\s*(?:ext\.?|extension|x|durchwahl|dw\.?)\s*(?=\d)""", RegexOption.IGNORE_CASE)
private val trunkPrefixRegex = Regex("""\(\s*0\s*\)""")
private val strandedCountryCodeRegex = Regex("""\+\d{1,3}\s*\(\s*0\s*\)\s*$""")
// Short local numbers exist, but in event text a 5- or 6-digit run is far more
// often a postcode, house number or booking reference.
private const val MIN_DIGITS = 7
/**
* Find the phone numbers in [text]. The platform's libphonenumber-backed
* matcher does the finding — it knows the device's region and real number
* lengths; [refinePhoneMatches] then fits what it found to an event's text.
* Call off the main thread: the matcher loads its metadata on first use.
* No match at all when the platform matcher fails.
*/
internal fun findPhoneLinks(text: String): List<PhoneLink> =
refinePhoneMatches(text, platformPhoneMatches(text), findWebLinks(text))
/** [findPhoneLinks] for each of an event's free-text fields. */
internal fun findEventPhoneLinks(title: String, location: String?, description: String?) = EventPhoneLinks(
title = findPhoneLinks(title),
location = location?.let(::findPhoneLinks).orEmpty(),
description = description?.let(::findPhoneLinks).orEmpty(),
)
// The matcher reads the region off the SIM, which throws on a device without
// telephony; a field then just goes without phone links.
private fun platformPhoneMatches(text: String): List<PhoneMatch> = runCatching {
val spannable = SpannableString(text)
if (!Linkify.addLinks(spannable, Linkify.PHONE_NUMBERS)) return emptyList()
spannable.getSpans(0, spannable.length, URLSpan::class.java)
.map { PhoneMatch(spannable.getSpanStart(it), spannable.getSpanEnd(it)) }
}.getOrDefault(emptyList())
/**
* Turn the platform's [matches] in [text] into dialable links. The matcher is
* lenient, so a match is dropped when it sits inside one of the [webLinks],
* follows a meeting id or PIN label, holds a date, reads as an amount or is
* too short. What's kept loses a stray count off its end, regains an
* international "+49 (0)" prefix the matcher left behind, and carries a
* conference dial-in suffix along.
*/
internal fun refinePhoneMatches(
text: String,
matches: List<PhoneMatch>,
webLinks: List<WebLink>,
): List<PhoneLink> {
val links = mutableListOf<PhoneLink>()
for (match in matches.sortedBy { it.start }) {
var start = match.start
var end = match.end
val matched = text.substring(start, end)
if (webLinks.any { start < it.end && it.start < end }) continue
if (gluedIntoAWord(text, start, end)) continue
val lineBefore = text.window(lineStart(text, start).coerceAtLeast(start - LOOK_BEHIND), start)
if (notAPhoneLabelRegex.containsMatchIn(lineBefore)) continue
if (dateRegex.findAll(matched).any { it.isDate() }) continue
if (isDottedTimes(matched)) continue
if (isAmount(text, start, end)) continue
strayTailRegex.find(matched)?.let { tail ->
if (wordAfterRegex.matchesAt(text, end)) end = start + tail.range.first
}
// "+49 (0)151 …": a matcher that stops at the "(0)" leaves the domestic
// tail, which would dial without the country code.
strandedCountryCodeRegex.find(text.window(start - LOOK_BEHIND, start))
?.let { start -= it.value.length }
val number = dialable(text.substring(start, end))
if (number.count { it.isDigit() } < MIN_DIGITS) continue
val suffix = dialSuffixRegex.find(text.window(end, end + LOOK_AHEAD))?.value.orEmpty()
// A suffix swallowed what the matcher saw as the next number.
if (links.lastOrNull()?.let { start < it.end } == true) continue
links += PhoneLink(start, end + suffix.length, number + dialable(suffix))
}
return links
}
// How far around a match the label, prefix, currency and suffix checks look.
// Enough for any of them, and it keeps a long invite from being re-read whole
// for every number in it.
private const val LOOK_BEHIND = 40
private const val LOOK_AHEAD = 60
private fun String.window(from: Int, to: Int): String =
substring(from.coerceAtLeast(0), to.coerceAtMost(length))
/**
* Digits run straight into a letter or a URL path — "zoom.us/j/850…" without
* its https:// — which no web link covered. A phone number stands apart.
*/
private fun gluedIntoAWord(text: String, start: Int, end: Int): Boolean {
val before = text.getOrNull(start - 1)
val after = text.getOrNull(end)
return (before != null && (before.isLetter() || before in "/=?&")) ||
(after != null && (after.isLetter() || after == '/'))
}
private fun isDottedTimes(matched: String): Boolean {
val times = dottedTimesRegex.matchEntire(matched) ?: return false
return times.groupValues.drop(1).chunked(2).all { (hour, minute) ->
hour.isEmpty() || (hour.toInt() in 0..24 && minute.toInt() in 0..59)
}
}
private fun isAmount(text: String, start: Int, end: Int): Boolean {
val matched = text.substring(start, end)
if (shortLeadAmountRegex.matches(matched)) return true
return amountRegex.matches(matched) &&
(currencyBeforeRegex.containsMatchIn(text.window(start - LOOK_BEHIND, start)) ||
currencyAfterRegex.containsMatchIn(text.window(end, end + LOOK_AHEAD)))
}
private fun MatchResult.isDate(): Boolean {
val (a, _, b, c) = destructured
val first = a.toInt()
val second = b.toInt()
val last = c.toInt()
return when {
a.length == 4 -> second in 1..12 && last in 1..31 && c.length <= 2
a.length > 2 -> false
// Day first (most of the world) or month first (US).
else -> (first in 1..31 && second in 1..12) || (first in 1..12 && second in 1..31)
}
}
private fun lineStart(text: String, index: Int): Int = text.lastIndexOf('\n', index - 1) + 1
/**
* Strip [raw] down to what a dialer takes. An international number's "(0)"
* trunk prefix — "+49 (0) 151 …" — is a domestic-only hint and would break the
* call, so it goes too; an extension becomes a pause.
*/
private fun dialable(raw: String): String {
val international = raw.trimStart('(').startsWith("+")
val withoutTrunk = if (international) raw.replace(trunkPrefixRegex, "") else raw
return withoutTrunk.replace(extensionRegex, ",")
.filter { it.isDigit() || it == '+' || it == ',' || it == '#' || it == '*' }
}
@@ -4,7 +4,6 @@ import android.Manifest
import android.app.Activity import android.app.Activity
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri import android.net.Uri
import android.provider.ContactsContract import android.provider.ContactsContract
import android.util.Patterns import android.util.Patterns
@@ -13,7 +12,6 @@ import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.clickable import androidx.compose.foundation.clickable
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.ColumnScope
@@ -31,11 +29,22 @@ import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Notes import androidx.compose.material.icons.automirrored.filled.Notes
import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Add
import de.jeanlucmakiola.floret.components.IconInfoCard
import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme
import kotlinx.coroutines.launch
import de.jeanlucmakiola.calendula.ui.common.sendEventShare
import de.jeanlucmakiola.calendula.ui.common.canWriteCalendar
import de.jeanlucmakiola.calendula.ui.common.rememberWriteGate
import de.jeanlucmakiola.calendula.ui.common.DeleteEventDialog
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.ArrowDropDown import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.CalendarMonth import androidx.compose.material.icons.filled.CalendarMonth
import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Close
@@ -86,8 +95,6 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.isSpecified
import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
@@ -106,7 +113,6 @@ import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import androidx.hilt.navigation.compose.hiltViewModel import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.R
@@ -116,10 +122,13 @@ import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.EventAttendee import de.jeanlucmakiola.calendula.domain.EventAttendee
import de.jeanlucmakiola.calendula.domain.EventColorOption import de.jeanlucmakiola.calendula.domain.EventColorOption
import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.startInstant
import de.jeanlucmakiola.calendula.domain.endInstant
import de.jeanlucmakiola.calendula.domain.resolvedZone
import de.jeanlucmakiola.calendula.domain.isPinnedAwayFrom
import de.jeanlucmakiola.calendula.domain.EventFormField import de.jeanlucmakiola.calendula.domain.EventFormField
import de.jeanlucmakiola.calendula.domain.zoneDescriptor import de.jeanlucmakiola.calendula.domain.zoneDescriptor
import de.jeanlucmakiola.calendula.domain.timeZoneOptionOf import de.jeanlucmakiola.calendula.domain.timeZoneOptionOf
import de.jeanlucmakiola.calendula.domain.timesIn
import de.jeanlucmakiola.calendula.domain.EventFormProblem import de.jeanlucmakiola.calendula.domain.EventFormProblem
import de.jeanlucmakiola.calendula.domain.RecurrenceEnd import de.jeanlucmakiola.calendula.domain.RecurrenceEnd
import de.jeanlucmakiola.calendula.domain.RecurrenceFreq import de.jeanlucmakiola.calendula.domain.RecurrenceFreq
@@ -148,12 +157,10 @@ import de.jeanlucmakiola.calendula.ui.common.eventFormFieldLabel
import de.jeanlucmakiola.floret.components.FullScreenPicker import de.jeanlucmakiola.floret.components.FullScreenPicker
import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.GroupedRow
import de.jeanlucmakiola.floret.components.GroupedSurface import de.jeanlucmakiola.floret.components.GroupedSurface
import de.jeanlucmakiola.calendula.ui.common.MILLIS_PER_DAY
import de.jeanlucmakiola.floret.components.InlineTextField import de.jeanlucmakiola.floret.components.InlineTextField
import de.jeanlucmakiola.floret.components.OptionCard import de.jeanlucmakiola.floret.components.OptionCard
import de.jeanlucmakiola.floret.components.OptionPicker import de.jeanlucmakiola.floret.components.OptionPicker
import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.Position
import de.jeanlucmakiola.floret.components.SelectedCheck
import de.jeanlucmakiola.floret.components.groupedShape as floretGroupedShape import de.jeanlucmakiola.floret.components.groupedShape as floretGroupedShape
import de.jeanlucmakiola.floret.components.positionOf import de.jeanlucmakiola.floret.components.positionOf
import de.jeanlucmakiola.calendula.ui.common.REMINDER_PRESETS import de.jeanlucmakiola.calendula.ui.common.REMINDER_PRESETS
@@ -162,6 +169,7 @@ import de.jeanlucmakiola.floret.reminders.ReminderUnit
import de.jeanlucmakiola.floret.locale.currentLocale import de.jeanlucmakiola.floret.locale.currentLocale
import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat
import de.jeanlucmakiola.calendula.ui.common.timeOfDayFormatter import de.jeanlucmakiola.calendula.ui.common.timeOfDayFormatter
import de.jeanlucmakiola.calendula.ui.common.withRepeatedHourZone
import de.jeanlucmakiola.calendula.ui.common.reminderLeadTimeLabel import de.jeanlucmakiola.calendula.ui.common.reminderLeadTimeLabel
import de.jeanlucmakiola.calendula.ui.common.reminderUnitLabel import de.jeanlucmakiola.calendula.ui.common.reminderUnitLabel
import de.jeanlucmakiola.calendula.ui.common.nextOccurrencesText import de.jeanlucmakiola.calendula.ui.common.nextOccurrencesText
@@ -169,12 +177,10 @@ import de.jeanlucmakiola.calendula.ui.common.recurrenceText
import kotlinx.datetime.DayOfWeek import kotlinx.datetime.DayOfWeek
import kotlinx.datetime.LocalDate import kotlinx.datetime.LocalDate
import kotlinx.datetime.LocalDateTime import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.LocalTime
import kotlinx.datetime.TimeZone import kotlinx.datetime.TimeZone
import kotlinx.datetime.isoDayNumber import kotlinx.datetime.isoDayNumber
import kotlinx.datetime.toJavaDayOfWeek import kotlinx.datetime.toJavaDayOfWeek
import kotlinx.datetime.toJavaLocalDate import kotlinx.datetime.toJavaLocalDate
import kotlinx.datetime.toInstant
import kotlinx.datetime.toJavaLocalTime import kotlinx.datetime.toJavaLocalTime
import kotlinx.datetime.toLocalDateTime import kotlinx.datetime.toLocalDateTime
import kotlin.time.toJavaInstant import kotlin.time.toJavaInstant
@@ -184,6 +190,7 @@ import java.time.format.FormatStyle
import java.time.format.TextStyle as JavaTextStyle import java.time.format.TextStyle as JavaTextStyle
import java.util.Locale import java.util.Locale
import kotlin.time.Clock import kotlin.time.Clock
import kotlin.time.Instant
/** /**
* Full-screen event form: create (v1.2, from the FAB's anchor date) and edit * Full-screen event form: create (v1.2, from the FAB's anchor date) and edit
@@ -192,6 +199,10 @@ import kotlin.time.Clock
* first asks how far the change reaches (this occurrence / this and * first asks how far the change reaches (this occurrence / this and
* following / whole series) — then closes. The calendar picker offers only * following / whole series) — then closes. The calendar picker offers only
* writable calendars; when editing, the calendar is fixed. * writable calendars; when editing, the calendar is fixed.
*
* Leaving with unsaved changes asks to save, discard or keep editing (#178).
* While editing, the overflow menu offers Duplicate (the form as it stands,
* handed to [onDuplicate] as a new event), Share and Delete.
*/ */
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
@@ -201,13 +212,21 @@ fun EventEditScreen(
onSaved: () -> Unit, onSaved: () -> Unit,
editKey: LongArray? = null, editKey: LongArray? = null,
initialStartMinutes: Int? = null, initialStartMinutes: Int? = null,
initialDraft: LongArray? = null,
initialForm: EventForm? = null, initialForm: EventForm? = null,
initialFormSource: ImportSource = ImportSource.File, initialFormSource: ImportSource = ImportSource.File,
onManageCalendars: (() -> Unit)? = null, onManageCalendars: (() -> Unit)? = null,
onDuplicate: ((EventForm) -> Unit)? = null,
onDeleted: () -> Unit = onSaved,
onLoadFailed: () -> Unit = onClose,
leaveRequested: Boolean = false,
onLeaveDeclined: () -> Unit = {},
visible: Boolean = true, visible: Boolean = true,
viewModel: EventEditViewModel = hiltViewModel(), viewModel: EventEditViewModel = hiltViewModel(),
) { ) {
LaunchedEffect(initialDateIso, editKey, initialForm) { // Keyed on every input that decides the form, so a second draft or slot on
// the same day opens its own form even when the composition is kept alive.
LaunchedEffect(initialDateIso, editKey, initialForm, initialDraft, initialStartMinutes) {
when { when {
// A prefilled open: a single-event .ics for review, or an external // A prefilled open: a single-event .ics for review, or an external
// ACTION_INSERT intent. The source drives how reminders are seeded. // ACTION_INSERT intent. The source drives how reminders are seeded.
@@ -217,9 +236,14 @@ fun EventEditScreen(
beginMillis = editKey[1], beginMillis = editKey[1],
endMillis = editKey[2], endMillis = editKey[2],
) )
// A block drafted on the timeline (#153): its own start and end.
initialDraft != null -> viewModel.openDraft(
start = Instant.fromEpochMilliseconds(initialDraft[0]),
end = Instant.fromEpochMilliseconds(initialDraft[1]),
)
else -> { else -> {
val date = initialDateIso?.let { runCatching { LocalDate.parse(it) }.getOrNull() } val date = initialDateIso?.let { runCatching { LocalDate.parse(it) }.getOrNull() }
?: Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).date ?: Clock.System.now().toLocalDateTime(viewModel.zone.value).date
viewModel.openNew(date, initialStartMinutes) viewModel.openNew(date, initialStartMinutes)
} }
} }
@@ -235,41 +259,91 @@ fun EventEditScreen(
viewModel.reset() viewModel.reset()
onClose() onClose()
} }
// The event vanished between the detail screen and the edit tap — fall val hasUnsavedChanges by viewModel.hasUnsavedChanges.collectAsStateWithLifecycle()
// back to the detail screen, which shows its own failure state. var showLeavePrompt by rememberSaveable { mutableStateOf(false) }
var showDeleteDialog by rememberSaveable { mutableStateOf(false) }
// A running save or delete can't be called back, so leaving waits for it;
// its result then closes the form or reports why it didn't.
val requestClose = {
when {
state?.saveState == SaveUiState.Saving -> Unit
hasUnsavedChanges -> showLeavePrompt = true
else -> close()
}
}
// Something else wants this form's place, e.g. a second share (#306).
LaunchedEffect(leaveRequested) {
if (leaveRequested) requestClose()
}
// The event vanished before the form could load it — fall back to the
// detail screen, which shows its own failure state.
LaunchedEffect(loadFailed) { LaunchedEffect(loadFailed) {
if (loadFailed) close() if (loadFailed) {
viewModel.reset()
onLoadFailed()
}
} }
val context = LocalContext.current val context = LocalContext.current
val snackbarHostState = remember { SnackbarHostState() } val snackbarHostState = remember { SnackbarHostState() }
// Contextual WRITE_CALENDAR upgrade for v1.0 installs, like delete. val scope = rememberCoroutineScope()
val writePermissionLauncher = rememberLauncherForActivityResult( val requireWrite = rememberWriteGate()
// Save keeps its own launcher: its result calls straight into the ViewModel,
// so a save waiting on the permission dialog survives a rotation.
val savePermissionLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestPermission(), contract = ActivityResultContracts.RequestPermission(),
) { granted -> ) { granted ->
if (granted) viewModel.save() if (granted) viewModel.save()
} }
val onSaveClick = { val onSaveClick = {
val granted = ContextCompat.checkSelfPermission( if (context.canWriteCalendar()) {
context,
Manifest.permission.WRITE_CALENDAR,
) == PackageManager.PERMISSION_GRANTED
if (granted) {
viewModel.save() viewModel.save()
} else { } else {
writePermissionLauncher.launch(Manifest.permission.WRITE_CALENDAR) savePermissionLauncher.launch(Manifest.permission.WRITE_CALENDAR)
}
}
val shareFailedMessage = stringResource(R.string.event_share_failed)
val shareChooserTitle = stringResource(R.string.event_share_chooser_title)
val onShareClick: () -> Unit = {
scope.launch {
val uri = viewModel.shareUri()
val sent = uri != null && context.sendEventShare(uri, shareChooserTitle)
if (!sent) snackbarHostState.showSnackbar(shareFailedMessage)
}
}
// The copy opens over this form; a form with nothing to lose steps aside.
val onDuplicateClick: () -> Unit = {
requireWrite {
viewModel.duplicateForm()?.let { form ->
onDuplicate?.invoke(form)
if (!hasUnsavedChanges) close()
}
} }
} }
val saveFailedMessage = stringResource(R.string.event_edit_save_failed) val saveFailedMessage = stringResource(R.string.event_edit_save_failed)
val writeDeniedMessage = stringResource(R.string.event_edit_write_denied) val writeDeniedMessage = stringResource(R.string.event_edit_write_denied)
val deleteFailedMessage = stringResource(R.string.event_delete_failed)
val deleteDeniedMessage = stringResource(R.string.event_delete_write_denied)
LaunchedEffect(state?.saveState) { LaunchedEffect(state?.saveState) {
when (state?.saveState) { when (state?.saveState) {
SaveUiState.Saved -> { SaveUiState.Saved -> {
viewModel.reset() viewModel.reset()
onSaved() onSaved()
} }
SaveUiState.Deleted -> {
viewModel.reset()
onDeleted()
}
SaveUiState.DeleteFailed -> {
viewModel.consumeSaveResult()
snackbarHostState.showSnackbar(deleteFailedMessage, duration = SnackbarDuration.Long)
}
SaveUiState.DeleteDenied -> {
viewModel.consumeSaveResult()
snackbarHostState.showSnackbar(deleteDeniedMessage, duration = SnackbarDuration.Long)
}
// A failed save leaves the form looking unchanged, so the snackbar is // A failed save leaves the form looking unchanged, so the snackbar is
// the only sign anything happened — long rather than the default // the only sign anything happened — long rather than the default
// flash (Codeberg #234: it read as "nothing happens at all"). // flash (Codeberg #234: it read as "nothing happens at all").
@@ -286,8 +360,11 @@ fun EventEditScreen(
} }
} }
// From the inputs, not the loaded state, so the label never flips mid-load.
val opensForEdit = initialForm == null && editKey != null
Scaffold( Scaffold(
modifier = Modifier.predictiveBack(onBack = close, visible = visible), modifier = Modifier.predictiveBack(onBack = requestClose, visible = visible),
snackbarHost = { SnackbarHost(snackbarHostState) }, snackbarHost = { SnackbarHost(snackbarHostState) },
topBar = { topBar = {
TopAppBar( TopAppBar(
@@ -295,7 +372,7 @@ fun EventEditScreen(
// matching the detail screen's bare top bar. // matching the detail screen's bare top bar.
title = {}, title = {},
navigationIcon = { navigationIcon = {
IconButton(onClick = close) { IconButton(onClick = requestClose) {
Icon( Icon(
imageVector = Icons.Default.Close, imageVector = Icons.Default.Close,
contentDescription = stringResource(R.string.event_edit_close), contentDescription = stringResource(R.string.event_edit_close),
@@ -303,12 +380,25 @@ fun EventEditScreen(
} }
}, },
actions = { actions = {
if (state?.isEditing == true) {
EditActionsMenu(
canDelete = state?.isManaged == false,
canDuplicate = onDuplicate != null,
onDuplicate = onDuplicateClick,
onShare = onShareClick,
onDelete = { requireWrite { showDeleteDialog = true } },
)
}
Button( Button(
onClick = onSaveClick, onClick = onSaveClick,
enabled = state != null && state?.saveState != SaveUiState.Saving, enabled = state != null && state?.saveState != SaveUiState.Saving,
modifier = Modifier.padding(end = 12.dp), modifier = Modifier.padding(end = 12.dp),
) { ) {
Text(stringResource(R.string.event_edit_save)) Text(
stringResource(
if (opensForEdit) R.string.event_edit_save else R.string.event_edit_create,
),
)
} }
}, },
colors = TopAppBarDefaults.topAppBarColors( colors = TopAppBarDefaults.topAppBarColors(
@@ -329,6 +419,35 @@ fun EventEditScreen(
} }
} }
if (showLeavePrompt) {
UnsavedChangesDialog(
onSave = {
showLeavePrompt = false
onSaveClick()
},
onDiscard = {
showLeavePrompt = false
close()
},
onDismiss = {
showLeavePrompt = false
if (leaveRequested) onLeaveDeclined()
},
)
}
val recurs = viewModel.editedEventRecurs()
if (showDeleteDialog && recurs != null) {
DeleteEventDialog(
isRecurring = recurs,
onConfirm = { deleteScope ->
showDeleteDialog = false
viewModel.delete(deleteScope)
},
onDismiss = { showDeleteDialog = false },
)
}
if (state?.saveState == SaveUiState.AwaitingScope) { if (state?.saveState == SaveUiState.AwaitingScope) {
SaveScopeDialog( SaveScopeDialog(
recurrenceChanged = state?.recurrenceChanged == true, recurrenceChanged = state?.recurrenceChanged == true,
@@ -373,6 +492,90 @@ fun EventEditScreen(
} }
} }
/** Duplicate, Share and Delete for the event being edited, behind an overflow button. */
@Composable
private fun EditActionsMenu(
canDelete: Boolean,
canDuplicate: Boolean,
onDuplicate: () -> Unit,
onShare: () -> Unit,
onDelete: () -> Unit,
) {
var open by remember { mutableStateOf(false) }
Box {
IconButton(onClick = { open = true }) {
Icon(
imageVector = Icons.Default.MoreVert,
contentDescription = stringResource(R.string.event_edit_more_actions),
)
}
DropdownMenu(expanded = open, onDismissRequest = { open = false }) {
if (canDuplicate) {
DropdownMenuItem(
text = { Text(stringResource(R.string.event_detail_duplicate)) },
leadingIcon = { Icon(Icons.Default.ContentCopy, contentDescription = null) },
onClick = {
open = false
onDuplicate()
},
)
}
DropdownMenuItem(
text = { Text(stringResource(R.string.event_detail_share)) },
leadingIcon = { Icon(Icons.Default.Share, contentDescription = null) },
onClick = {
open = false
onShare()
},
)
// Managed special-dates events have no delete, as on the detail screen.
if (canDelete) {
DropdownMenuItem(
text = { Text(stringResource(R.string.event_detail_delete)) },
leadingIcon = { Icon(Icons.Default.Delete, contentDescription = null) },
onClick = {
open = false
onDelete()
},
)
}
}
}
}
/**
* Asked when leaving the form with unsaved changes (#178). Dismissing keeps
* editing; a form with nothing changed closes without asking.
*/
@Composable
private fun UnsavedChangesDialog(
onSave: () -> Unit,
onDiscard: () -> Unit,
onDismiss: () -> Unit,
) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.event_edit_unsaved_title)) },
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
OptionCard(
label = stringResource(R.string.event_edit_unsaved_save),
onClick = onSave,
)
OptionCard(
label = stringResource(R.string.event_edit_unsaved_discard),
onClick = onDiscard,
)
}
},
confirmButton = {
TextButton(onClick = onDismiss) {
Text(stringResource(R.string.event_edit_unsaved_keep))
}
},
)
}
/** /**
* Offer to apply the settings default reminder to an event opened from a `.ics` * Offer to apply the settings default reminder to an event opened from a `.ics`
* file. The file's own reminders are kept unless the user accepts. A plain * file. The file's own reminders are kept unless the user accepts. A plain
@@ -501,8 +704,9 @@ private fun EventEditContent(
) { ) {
val form = state.form val form = state.form
val locale = currentLocale() val locale = currentLocale()
val deviceZone by viewModel.zone.collectAsStateWithLifecycle()
val firstDayOfWeek by viewModel.firstDayOfWeek.collectAsStateWithLifecycle() val firstDayOfWeek by viewModel.firstDayOfWeek.collectAsStateWithLifecycle()
val dark = isSystemInDarkTheme() val dark = LocalFloretDarkTheme.current
// The title, date and recurrence are managed by the special-dates sync, so // The title, date and recurrence are managed by the special-dates sync, so
// they're locked here; everything else (reminders, location, notes) is the // they're locked here; everything else (reminders, location, notes) is the
// user's to edit. // user's to edit.
@@ -640,7 +844,7 @@ private fun EventEditContent(
// "When" card: the icon centres on the all-day row (header); the // "When" card: the icon centres on the all-day row (header); the
// start/end rows continue below in the same text column. // start/end rows continue below in the same text column.
EditCard( IconInfoCard(
icon = Icons.Default.Schedule, icon = Icons.Default.Schedule,
iconContentDescription = null, iconContentDescription = null,
header = { header = {
@@ -662,9 +866,14 @@ private fun EventEditContent(
}, },
) { ) {
Spacer(Modifier.height(4.dp)) Spacer(Modifier.height(4.dp))
val formZone = remember(form.timezone, deviceZone) { form.resolvedZone(deviceZone) }
val startAt = remember(form.start, formZone) { form.startInstant(formZone) }
val endAt = remember(form.end, formZone) { form.endInstant(formZone) }
ScheduleRow( ScheduleRow(
label = stringResource(R.string.event_edit_starts), label = stringResource(R.string.event_edit_starts),
dateTime = form.start, dateTime = form.start.dateTime,
instant = startAt,
zone = formZone,
isAllDay = form.isAllDay, isAllDay = form.isAllDay,
locale = locale, locale = locale,
onDateClick = { picker = PickerTarget.StartDate }, onDateClick = { picker = PickerTarget.StartDate },
@@ -673,7 +882,9 @@ private fun EventEditContent(
) )
ScheduleRow( ScheduleRow(
label = stringResource(R.string.event_edit_ends), label = stringResource(R.string.event_edit_ends),
dateTime = form.end, dateTime = form.end.dateTime,
instant = endAt,
zone = formZone,
isAllDay = form.isAllDay, isAllDay = form.isAllDay,
locale = locale, locale = locale,
onDateClick = { picker = PickerTarget.EndDate }, onDateClick = { picker = PickerTarget.EndDate },
@@ -692,20 +903,20 @@ private fun EventEditContent(
// The rows above edit a pinned event in *its own* zone, which is the // The rows above edit a pinned event in *its own* zone, which is the
// time it was set at — but that says nothing about when it lands for // time it was set at — but that says nothing about when it lands for
// whoever is reading it. Spell the local equivalent out rather than // whoever is reading it. Spell the local equivalent out rather than
// leaving the user to do the offset arithmetic. Absent (null) unless // leaving the user to do the offset arithmetic. Absent unless the
// the event is pinned somewhere other than here. // event is pinned somewhere other than here.
// Keyed rather than recomputed: this sits in the same Column as the // Keyed rather than recomputed: this sits in the same Column as the
// title field, so it would otherwise re-parse the zone on every // title field, so it would otherwise re-parse the zone on every
// keystroke. // keystroke.
val localTimes = remember(form.timezone, form.start, form.end, form.isAllDay) { val pinnedAway = remember(form.timezone, form.isAllDay, deviceZone) {
form.timesIn(TimeZone.currentSystemDefault()) form.isPinnedAwayFrom(deviceZone)
} }
localTimes?.let { (localStart, localEnd) -> if (pinnedAway) {
Spacer(Modifier.height(2.dp)) Spacer(Modifier.height(2.dp))
Text( Text(
text = stringResource( text = stringResource(
R.string.event_edit_timezone_local_time, R.string.event_edit_timezone_local_time,
formatTimeRange(localStart, localEnd, locale), formatTimeRange(startAt, endAt, deviceZone, locale),
), ),
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
@@ -719,7 +930,7 @@ private fun EventEditContent(
// different one while editing *moves* the event (copy+delete on save, // different one while editing *moves* the event (copy+delete on save,
// since CALENDAR_ID can't be updated in place). Managed special-dates // since CALENDAR_ID can't be updated in place). Managed special-dates
// events stay locked: the contact sync owns their calendar. // events stay locked: the contact sync owns their calendar.
EditCard( IconInfoCard(
icon = Icons.Default.CalendarMonth, icon = Icons.Default.CalendarMonth,
iconContentDescription = stringResource(R.string.event_detail_calendar), iconContentDescription = stringResource(R.string.event_detail_calendar),
iconTint = accent, iconTint = accent,
@@ -750,7 +961,7 @@ private fun EventEditContent(
// rest unfold behind the "more fields" button below. // rest unfold behind the "more fields" button below.
OptionalFormSection(visible = EventFormField.Timezone in state.visibleFields) { OptionalFormSection(visible = EventFormField.Timezone in state.visibleFields) {
Spacer(Modifier.height(gap)) Spacer(Modifier.height(gap))
EditCard( IconInfoCard(
icon = Icons.Default.Public, icon = Icons.Default.Public,
iconContentDescription = null, iconContentDescription = null,
onClick = { showTimezonePicker = true }, onClick = { showTimezonePicker = true },
@@ -769,7 +980,7 @@ private fun EventEditContent(
timeZoneOptionOf( timeZoneOptionOf(
id, id,
locale, locale,
at = form.start.toInstant(zone).toJavaInstant(), at = form.startInstant(zone).toJavaInstant(),
regionOf = ::icuTimeZoneRegion, regionOf = ::icuTimeZoneRegion,
) )
} }
@@ -798,10 +1009,11 @@ private fun EventEditContent(
OptionalFormSection(visible = EventFormField.Location in state.visibleFields) { OptionalFormSection(visible = EventFormField.Location in state.visibleFields) {
Spacer(Modifier.height(gap)) Spacer(Modifier.height(gap))
EditCard( IconInfoCard(
icon = Icons.Default.Place, icon = Icons.Default.Place,
iconContentDescription = stringResource(R.string.event_detail_location), iconContentDescription = stringResource(R.string.event_detail_location),
iconAtTop = true, iconAlignment = Alignment.Top,
iconTopPadding = ((firstLineHeight() - 24.dp) / 2).coerceAtLeast(0.dp),
) { ) {
Row(verticalAlignment = Alignment.Top) { Row(verticalAlignment = Alignment.Top) {
Column(modifier = Modifier.weight(1f)) { Column(modifier = Modifier.weight(1f)) {
@@ -867,10 +1079,11 @@ private fun EventEditContent(
OptionalFormSection(visible = EventFormField.Description in state.visibleFields) { OptionalFormSection(visible = EventFormField.Description in state.visibleFields) {
Spacer(Modifier.height(gap)) Spacer(Modifier.height(gap))
EditCard( IconInfoCard(
icon = Icons.AutoMirrored.Filled.Notes, icon = Icons.AutoMirrored.Filled.Notes,
iconContentDescription = stringResource(R.string.event_detail_description), iconContentDescription = stringResource(R.string.event_detail_description),
iconAtTop = true, iconAlignment = Alignment.Top,
iconTopPadding = ((firstLineHeight() - 24.dp) / 2).coerceAtLeast(0.dp),
) { ) {
InlineField( InlineField(
value = form.description, value = form.description,
@@ -906,7 +1119,7 @@ private fun EventEditContent(
OptionalFormSection(visible = EventFormField.Recurrence in state.visibleFields) { OptionalFormSection(visible = EventFormField.Recurrence in state.visibleFields) {
Spacer(Modifier.height(gap)) Spacer(Modifier.height(gap))
EditCard( IconInfoCard(
icon = Icons.Default.Repeat, icon = Icons.Default.Repeat,
iconContentDescription = null, iconContentDescription = null,
onClick = if (locked) null else ({ showRecurrencePicker = true }), onClick = if (locked) null else ({ showRecurrencePicker = true }),
@@ -946,7 +1159,7 @@ private fun EventEditContent(
OptionalFormSection(visible = EventFormField.Availability in state.visibleFields) { OptionalFormSection(visible = EventFormField.Availability in state.visibleFields) {
Spacer(Modifier.height(gap)) Spacer(Modifier.height(gap))
EditCard( IconInfoCard(
icon = Icons.Default.EventAvailable, icon = Icons.Default.EventAvailable,
iconContentDescription = null, iconContentDescription = null,
header = { header = {
@@ -974,7 +1187,7 @@ private fun EventEditContent(
OptionalFormSection(visible = EventFormField.Visibility in state.visibleFields) { OptionalFormSection(visible = EventFormField.Visibility in state.visibleFields) {
Spacer(Modifier.height(gap)) Spacer(Modifier.height(gap))
EditCard( IconInfoCard(
icon = Icons.Default.Lock, icon = Icons.Default.Lock,
iconContentDescription = null, iconContentDescription = null,
onClick = { showVisibilityPicker = true }, onClick = { showVisibilityPicker = true },
@@ -1008,7 +1221,7 @@ private fun EventEditContent(
// The swatch the event will paint with: its own colour, else the // The swatch the event will paint with: its own colour, else the
// calendar's. The Palette icon takes that colour as a preview. // calendar's. The Palette icon takes that colour as a preview.
val swatch = form.color ?: selectedCalendar?.color val swatch = form.color ?: selectedCalendar?.color
EditCard( IconInfoCard(
icon = Icons.Default.Palette, icon = Icons.Default.Palette,
iconContentDescription = stringResource(R.string.event_edit_color), iconContentDescription = stringResource(R.string.event_edit_color),
iconTint = if (colorSupported && swatch != null) { iconTint = if (colorSupported && swatch != null) {
@@ -1461,12 +1674,7 @@ private fun RecurrencePickerDialog(
GroupedRow( GroupedRow(
title = stringResource(R.string.event_edit_recurrence_none), title = stringResource(R.string.event_edit_recurrence_none),
position = positionOf(0, rowCount), position = positionOf(0, rowCount),
selected = current == null, checked = current == null,
trailing = if (current == null) {
{ SelectedCheck() }
} else {
null
},
onClick = { onSelect(null) }, onClick = { onSelect(null) },
) )
RecurrenceFreq.entries.forEachIndexed { index, entry -> RecurrenceFreq.entries.forEachIndexed { index, entry ->
@@ -1474,24 +1682,14 @@ private fun RecurrencePickerDialog(
title = stringResource(recurrencePresetLabel(entry)), title = stringResource(recurrencePresetLabel(entry)),
summary = nextOccurrencesText(SimpleRecurrence(entry), startDate, locale), summary = nextOccurrencesText(SimpleRecurrence(entry), startDate, locale),
position = positionOf(index + 1, rowCount), position = positionOf(index + 1, rowCount),
selected = isPlainPreset && parsed?.freq == entry, checked = isPlainPreset && parsed?.freq == entry,
trailing = if (isPlainPreset && parsed?.freq == entry) {
{ SelectedCheck() }
} else {
null
},
onClick = { onSelect(SimpleRecurrence(entry).toRRule()) }, onClick = { onSelect(SimpleRecurrence(entry).toRRule()) },
) )
} }
GroupedRow( GroupedRow(
title = stringResource(R.string.event_edit_recurrence_custom), title = stringResource(R.string.event_edit_recurrence_custom),
position = positionOf(rowCount - 1, rowCount), position = positionOf(rowCount - 1, rowCount),
selected = current != null && !isPlainPreset, checked = current != null && !isPlainPreset,
trailing = if (current != null && !isPlainPreset) {
{ SelectedCheck() }
} else {
null
},
onClick = { customMode = true }, onClick = { customMode = true },
) )
} else { } else {
@@ -1620,24 +1818,14 @@ private fun RecurrencePickerDialog(
GroupedRow( GroupedRow(
title = stringResource(R.string.event_edit_recurrence_end_never), title = stringResource(R.string.event_edit_recurrence_end_never),
position = Position.Top, position = Position.Top,
selected = endMode == RecurrenceEndMode.Never, checked = endMode == RecurrenceEndMode.Never,
trailing = if (endMode == RecurrenceEndMode.Never) {
{ SelectedCheck() }
} else {
null
},
onClick = { endMode = RecurrenceEndMode.Never }, onClick = { endMode = RecurrenceEndMode.Never },
) )
GroupedRow( GroupedRow(
title = stringResource(R.string.event_edit_recurrence_end_until), title = stringResource(R.string.event_edit_recurrence_end_until),
summary = untilSummary, summary = untilSummary,
position = Position.Middle, position = Position.Middle,
selected = endMode == RecurrenceEndMode.Until, checked = endMode == RecurrenceEndMode.Until,
trailing = if (endMode == RecurrenceEndMode.Until) {
{ SelectedCheck() }
} else {
null
},
onClick = { onClick = {
endMode = RecurrenceEndMode.Until endMode = RecurrenceEndMode.Until
showUntilPicker = true showUntilPicker = true
@@ -1650,12 +1838,7 @@ private fun RecurrencePickerDialog(
} else { } else {
Position.Bottom Position.Bottom
}, },
selected = endMode == RecurrenceEndMode.Count, checked = endMode == RecurrenceEndMode.Count,
trailing = if (endMode == RecurrenceEndMode.Count) {
{ SelectedCheck() }
} else {
null
},
onClick = { endMode = RecurrenceEndMode.Count }, onClick = { endMode = RecurrenceEndMode.Count },
) )
// Animated for the same reason the weekday card is: this is the // Animated for the same reason the weekday card is: this is the
@@ -1694,9 +1877,8 @@ private fun RecurrencePickerDialog(
if (showUntilPicker) { if (showUntilPicker) {
CalendarDatePickerDialog( CalendarDatePickerDialog(
initial = untilDate ?: LocalDate.fromEpochDays( initial = untilDate
(Clock.System.now().toEpochMilliseconds() / MILLIS_PER_DAY).toInt(), ?: Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).date,
),
onConfirm = { onConfirm = {
untilIso = it.toString() untilIso = it.toString()
showUntilPicker = false showUntilPicker = false
@@ -1814,13 +1996,7 @@ private fun GroupedItemCard(
titleMaxLines: Int = Int.MAX_VALUE, titleMaxLines: Int = Int.MAX_VALUE,
trailing: @Composable (() -> Unit)? = null, trailing: @Composable (() -> Unit)? = null,
) { ) {
Surface( GroupedSurface(position = position) {
color = MaterialTheme.colorScheme.surfaceContainerHigh,
shape = groupedShape(position),
modifier = Modifier
.fillMaxWidth()
.then(groupedGap(position)),
) {
Row( Row(
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(start = 16.dp, end = 8.dp, top = 8.dp, bottom = 8.dp), modifier = Modifier.padding(start = 16.dp, end = 8.dp, top = 8.dp, bottom = 8.dp),
@@ -2091,7 +2267,7 @@ private fun ColorPickerDialog(
onClear: () -> Unit, onClear: () -> Unit,
onDismiss: () -> Unit, onDismiss: () -> Unit,
) { ) {
val dark = isSystemInDarkTheme() val dark = LocalFloretDarkTheme.current
FullScreenPicker( FullScreenPicker(
title = stringResource(R.string.event_edit_color), title = stringResource(R.string.event_edit_color),
onDismiss = onDismiss, onDismiss = onDismiss,
@@ -2172,97 +2348,23 @@ private fun accessLevelSummary(level: AccessLevel): Int = when (level) {
private fun reminderLabel(minutes: Int): String = reminderLeadTimeLabel(minutes) private fun reminderLabel(minutes: Int): String = reminderLeadTimeLabel(minutes)
/** /**
* One info card mirroring the detail screen's DetailCard: tonal container, * "2:00 PM – 3:00 PM" in [zone], honouring the user's 12/24-hour setting. Collapses
* leading icon in the gutter, value to the right. Optionally clickable as a * to one time for an instant event, which shouldn't read as a range against
* whole (calendar picker). * itself. Dates are deliberately absent — the rows above carry them.
*/ */
@Composable @Composable
private fun EditCard( private fun formatTimeRange(start: Instant, end: Instant, zone: TimeZone, locale: Locale): String {
icon: ImageVector,
iconContentDescription: String?,
iconTint: Color = MaterialTheme.colorScheme.onSurfaceVariant,
onClick: (() -> Unit)? = null,
// Multiline-input cards align the icon with the field's first text line.
iconAtTop: Boolean = false,
// Tall cards pass their first row here: the icon centres on it, and
// [content] continues below, indented to the same text column.
header: (@Composable ColumnScope.() -> Unit)? = null,
content: @Composable ColumnScope.() -> Unit,
) {
val shape = RoundedCornerShape(16.dp)
val color = MaterialTheme.colorScheme.surfaceContainerHigh
val inner: @Composable () -> Unit = {
if (header != null) {
Column(modifier = Modifier.padding(16.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
imageVector = icon,
contentDescription = iconContentDescription,
tint = iconTint,
modifier = Modifier.size(24.dp),
)
Spacer(Modifier.width(16.dp))
Column(modifier = Modifier.weight(1f), content = header)
}
Column(
modifier = Modifier.padding(start = 40.dp),
content = content,
)
}
} else {
Row(
modifier = Modifier.padding(16.dp),
verticalAlignment = if (iconAtTop) Alignment.Top else Alignment.CenterVertically,
) {
// A top-aligned icon centres on the first text line, whatever
// that line measures at the user's font scale.
val iconOffset = if (iconAtTop) {
((firstLineHeight() - 24.dp) / 2).coerceAtLeast(0.dp)
} else {
0.dp
}
Icon(
imageVector = icon,
contentDescription = iconContentDescription,
tint = iconTint,
modifier = Modifier
.padding(top = iconOffset)
.size(24.dp),
)
Spacer(Modifier.width(16.dp))
Column(modifier = Modifier.weight(1f), content = content)
}
}
}
if (onClick != null) {
Surface(
onClick = onClick,
color = color,
shape = shape,
modifier = Modifier.fillMaxWidth(),
) { inner() }
} else {
Surface(
color = color,
shape = shape,
modifier = Modifier.fillMaxWidth(),
) { inner() }
}
}
/**
* "2:00 PM – 3:00 PM", honouring the user's 12/24-hour setting. Collapses to one
* time when both land on the same minute (an instant event shouldn't read as a
* range against itself). Dates are deliberately absent — the rows above carry
* them.
*/
@Composable
private fun formatTimeRange(start: LocalDateTime, end: LocalDateTime, locale: Locale): String {
val use24Hour = LocalUse24HourFormat.current val use24Hour = LocalUse24HourFormat.current
val timeFormat = remember(locale, use24Hour) { timeOfDayFormatter(use24Hour, locale) } return remember(start, end, zone, locale, use24Hour) {
val from = timeFormat.format(start.time.toJavaLocalTime()) val timeFormat = timeOfDayFormatter(use24Hour, locale)
val to = timeFormat.format(end.time.toJavaLocalTime()) fun format(at: Instant) = withRepeatedHourZone(
return if (from == to) from else "$from – $to" timeFormat.format(at.toLocalDateTime(zone).time.toJavaLocalTime()),
at,
zone,
locale,
)
if (start == end) format(start) else "${format(start)} – ${format(end)}"
}
} }
/** /**
@@ -2344,6 +2446,8 @@ private fun firstLineHeight(
private fun ScheduleRow( private fun ScheduleRow(
label: String, label: String,
dateTime: LocalDateTime, dateTime: LocalDateTime,
instant: Instant,
zone: TimeZone,
isAllDay: Boolean, isAllDay: Boolean,
locale: Locale, locale: Locale,
onDateClick: () -> Unit, onDateClick: () -> Unit,
@@ -2385,8 +2489,11 @@ private fun ScheduleRow(
.padding(vertical = 8.dp, horizontal = 6.dp), .padding(vertical = 8.dp, horizontal = 6.dp),
) )
if (!isAllDay) { if (!isAllDay) {
val time = remember(dateTime, instant, zone, locale, timeFormat) {
withRepeatedHourZone(timeFormat.format(dateTime.time.toJavaLocalTime()), instant, zone, locale)
}
Text( Text(
text = timeFormat.format(dateTime.time.toJavaLocalTime()), text = time,
style = MaterialTheme.typography.titleMedium, style = MaterialTheme.typography.titleMedium,
color = valueColor, color = valueColor,
modifier = Modifier modifier = Modifier
@@ -77,6 +77,11 @@ sealed interface SaveUiState {
data object Gone : SaveUiState data object Gone : SaveUiState
data object Saving : SaveUiState data object Saving : SaveUiState
data object Saved : SaveUiState data object Saved : SaveUiState
/** The event was deleted from the form (#178). */
data object Deleted : SaveUiState
data object DeleteFailed : SaveUiState
/** WRITE_CALENDAR was revoked before a delete from the form. */
data object DeleteDenied : SaveUiState
/** WRITE_CALENDAR was revoked between the tap and the provider call. */ /** WRITE_CALENDAR was revoked between the tap and the provider call. */
data object NeedsPermission : SaveUiState data object NeedsPermission : SaveUiState
data object Failed : SaveUiState data object Failed : SaveUiState
@@ -1,14 +1,16 @@
package de.jeanlucmakiola.calendula.ui.edit package de.jeanlucmakiola.calendula.ui.edit
import android.net.Uri
import android.util.Log import android.util.Log
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.lifecycle.HiltViewModel
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
import de.jeanlucmakiola.calendula.data.calendar.NoSuchEventException import de.jeanlucmakiola.calendula.data.calendar.NoSuchEventException
import de.jeanlucmakiola.calendula.data.di.IoDispatcher import de.jeanlucmakiola.calendula.data.ics.IcsExporter
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.data.time.ZoneSource
import de.jeanlucmakiola.calendula.data.prefs.firstDayOfWeek import de.jeanlucmakiola.calendula.data.prefs.firstDayOfWeek
import de.jeanlucmakiola.calendula.data.prefs.resolveDefaultEventDuration import de.jeanlucmakiola.calendula.data.prefs.resolveDefaultEventDuration
import de.jeanlucmakiola.calendula.data.prefs.resolveDefaultReminder import de.jeanlucmakiola.calendula.data.prefs.resolveDefaultReminder
@@ -18,14 +20,29 @@ import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.EditSnapshot import de.jeanlucmakiola.calendula.domain.EditSnapshot
import de.jeanlucmakiola.calendula.domain.EventAttendee import de.jeanlucmakiola.calendula.domain.EventAttendee
import de.jeanlucmakiola.calendula.domain.EventColorOption import de.jeanlucmakiola.calendula.domain.EventColorOption
import de.jeanlucmakiola.calendula.domain.EventDetail
import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.EventForm
import de.jeanlucmakiola.calendula.domain.nextFullHour
import de.jeanlucmakiola.calendula.domain.toFormTime
import de.jeanlucmakiola.calendula.domain.resolvedZone
import de.jeanlucmakiola.calendula.domain.startInstant
import de.jeanlucmakiola.calendula.domain.withEnd
import de.jeanlucmakiola.calendula.domain.withStart
import de.jeanlucmakiola.calendula.domain.withTimes
import de.jeanlucmakiola.calendula.domain.withTimezone
import de.jeanlucmakiola.calendula.domain.EventFormField import de.jeanlucmakiola.calendula.domain.EventFormField
import de.jeanlucmakiola.calendula.domain.RecurringWriteScope import de.jeanlucmakiola.calendula.domain.RecurringWriteScope
import de.jeanlucmakiola.calendula.domain.atOccurrence
import de.jeanlucmakiola.calendula.domain.isEventTarget import de.jeanlucmakiola.calendula.domain.isEventTarget
import de.jeanlucmakiola.calendula.domain.populatedFields import de.jeanlucmakiola.calendula.domain.populatedFields
import de.jeanlucmakiola.calendula.domain.problems import de.jeanlucmakiola.calendula.domain.problems
import de.jeanlucmakiola.calendula.domain.toEditSnapshot import de.jeanlucmakiola.calendula.domain.toEditSnapshot
import de.jeanlucmakiola.calendula.ui.detail.EventDetailViewModel.Companion.NO_OCCURRENCE_TIME import de.jeanlucmakiola.calendula.ui.detail.EventDetailViewModel.Companion.NO_OCCURRENCE_TIME
import de.jeanlucmakiola.calendula.ui.common.DeleteOutcome
import de.jeanlucmakiola.calendula.ui.common.tryDeleteEvent
import de.jeanlucmakiola.calendula.ui.common.stageEventShare
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
import de.jeanlucmakiola.floret.di.IoDispatcher
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
@@ -132,9 +149,15 @@ class EventEditViewModel @Inject constructor(
private val repository: CalendarRepository, private val repository: CalendarRepository,
private val prefs: CalendarPrefs, private val prefs: CalendarPrefs,
private val settingsPrefs: SettingsPrefs, private val settingsPrefs: SettingsPrefs,
private val icsExporter: IcsExporter,
@IoDispatcher private val io: CoroutineDispatcher, @IoDispatcher private val io: CoroutineDispatcher,
private val zoneSource: ZoneSource,
) : ViewModel() { ) : ViewModel() {
/** The zone the form's unpinned times are read in, for the screen to show them in too. */
val zone: StateFlow<TimeZone> = zoneSource.zone
.stateIn(viewModelScope, SharingStarted.Eagerly, zoneSource.current())
private val _form = MutableStateFlow<EventForm?>(null) private val _form = MutableStateFlow<EventForm?>(null)
private val _saveState = MutableStateFlow<SaveUiState>(SaveUiState.Idle) private val _saveState = MutableStateFlow<SaveUiState>(SaveUiState.Idle)
// Problems stay hidden until the first save attempt, so a half-filled // Problems stay hidden until the first save attempt, so a half-filled
@@ -156,6 +179,11 @@ class EventEditViewModel @Inject constructor(
// A one-time offer, raised when a .ics import opens, to replace the file's // A one-time offer, raised when a .ics import opens, to replace the file's
// reminders with the settings default (#49). Null while there's nothing to ask. // reminders with the settings default (#49). Null while there's nothing to ask.
private val _importReminderPrompt = MutableStateFlow<ImportReminderPrompt?>(null) private val _importReminderPrompt = MutableStateFlow<ImportReminderPrompt?>(null)
// The form as the user received it: the loaded event, or a new form with its
// prefill and auto-applied defaults. Anything else is an unsaved change.
private val _baseline = MutableStateFlow<EventForm?>(null)
// Bumped by reset(), so work started for a closed form never lands on the next.
private var session = 0
/** True when the event to edit couldn't be loaded; the screen closes itself. */ /** True when the event to edit couldn't be loaded; the screen closes itself. */
val loadFailed: StateFlow<Boolean> = _loadFailed.asStateFlow() val loadFailed: StateFlow<Boolean> = _loadFailed.asStateFlow()
@@ -176,6 +204,8 @@ class EventEditViewModel @Inject constructor(
val beginMillis: Long, val beginMillis: Long,
val endMillis: Long, val endMillis: Long,
val zone: TimeZone, val zone: TimeZone,
/** The event as loaded, on the tapped occurrence's times — what Share exports. */
val detail: EventDetail,
) { ) {
val original: EventForm get() = snapshot.form val original: EventForm get() = snapshot.form
} }
@@ -289,7 +319,11 @@ class EventEditViewModel @Inject constructor(
EventEditUiState( EventEditUiState(
form = resolved, form = resolved,
calendars = pickerCalendars, calendars = pickerCalendars,
problems = if (local.showProblems) resolved.problems() else emptySet(), problems = if (local.showProblems) {
resolved.problems(zoneSource.current())
} else {
emptySet()
},
saveState = local.saveState, saveState = local.saveState,
visibleFields = visibleFields, visibleFields = visibleFields,
hiddenFields = (offerableFields - visibleFields).sorted(), hiddenFields = (offerableFields - visibleFields).sorted(),
@@ -305,12 +339,19 @@ class EventEditViewModel @Inject constructor(
allowColorOnUnsupportedCalendars = external.allowColorOnUnsupported, allowColorOnUnsupportedCalendars = external.allowColorOnUnsupported,
) )
} }
.stateIn( .stateWhileSubscribed(
scope = viewModelScope, scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = null, initialValue = null,
) )
/**
* Whether leaving now would lose something the user did (#178): the form
* differs from how it opened, counting the defaults it applied itself.
*/
val hasUnsavedChanges: StateFlow<Boolean> = combine(_form, _baseline) { form, baseline ->
form != null && form != baseline
}.stateIn(viewModelScope, SharingStarted.Eagerly, false)
/** /**
* First day of the week for ordering the recurrence weekday toggles — the * First day of the week for ordering the recurrence weekday toggles — the
* app's "week starts on" preference, matching the calendar views (Auto * app's "week starts on" preference, matching the calendar views (Auto
@@ -329,22 +370,32 @@ class EventEditViewModel @Inject constructor(
*/ */
fun openNew(date: LocalDate, startMinutes: Int? = null) { fun openNew(date: LocalDate, startMinutes: Int? = null) {
if (_form.value != null) return if (_form.value != null) return
val zone = TimeZone.currentSystemDefault() val zone = zoneSource.current()
val now = Clock.System.now() val now = Clock.System.now()
val start = when { val startAt = when {
startMinutes != null -> startMinutes != null ->
LocalDateTime(date, LocalTime(startMinutes / 60, startMinutes % 60)) LocalDateTime(date, LocalTime(startMinutes / 60, startMinutes % 60)).toInstant(zone)
date == now.toLocalDateTime(zone).date -> { date == now.toLocalDateTime(zone).date -> nextFullHour(now)
// Today: the next full hour (may roll into tomorrow before midnight). else -> LocalDateTime(date, LocalTime(9, 0)).toInstant(zone)
val hourMillis = 3_600_000L
val rounded = (now.toEpochMilliseconds() / hourMillis + 1) * hourMillis
Instant.fromEpochMilliseconds(rounded).toLocalDateTime(zone)
}
else -> LocalDateTime(date, LocalTime(9, 0))
} }
val end = (start.toInstant(zone) + SettingsPrefs.DEFAULT_EVENT_DURATION.minutes) val endAt = startAt + SettingsPrefs.DEFAULT_EVENT_DURATION.minutes
.toLocalDateTime(zone) open(EventForm(calendarId = null, start = startAt.toFormTime(zone), end = endAt.toFormTime(zone)))
_form.value = EventForm(calendarId = null, start = start, end = end) applyDefaultReminder()
applyDefaultDuration()
}
/**
* Initialise a fresh form for a block drafted on the timeline (#153), from
* [start] to [end]. These are the instants the block shows, so a time in the
* fall-back hour's repeat, or one moved out of the spring-forward gap, opens
* as drawn (#387). The user chose the length, so the default length doesn't
* apply. No-op when a form is already open, as [openNew].
*/
fun openDraft(start: Instant, end: Instant) {
if (_form.value != null) return
val zone = zoneSource.current()
open(EventForm(calendarId = null, start = start.toFormTime(zone), end = end.toFormTime(zone)))
_durationTouched.value = true
applyDefaultReminder() applyDefaultReminder()
applyDefaultDuration() applyDefaultDuration()
} }
@@ -377,7 +428,7 @@ class EventEditViewModel @Inject constructor(
fun openImported(form: EventForm, source: ImportSource) { fun openImported(form: EventForm, source: ImportSource) {
if (_form.value != null || _editTarget.value != null) return if (_form.value != null || _editTarget.value != null) return
_revealed.value = form.populatedFields() _revealed.value = form.populatedFields()
_form.value = form open(form)
if (source.ownsDuration) _durationTouched.value = true else applyDefaultDuration() if (source.ownsDuration) _durationTouched.value = true else applyDefaultDuration()
when (source) { when (source) {
ImportSource.Insert, ImportSource.InsertOpenEnded -> ImportSource.Insert, ImportSource.InsertOpenEnded ->
@@ -402,16 +453,18 @@ class EventEditViewModel @Inject constructor(
*/ */
private fun applyDefaultReminder(calendarId: Long? = null) { private fun applyDefaultReminder(calendarId: Long? = null) {
if (_editTarget.value != null || _remindersTouched.value) return if (_editTarget.value != null || _remindersTouched.value) return
val opened = session
viewModelScope.launch { viewModelScope.launch {
val defaults = reminderDefaults() val defaults = reminderDefaults()
val targetId = calendarId ?: resolvedCalendarId.first() val targetId = calendarId ?: resolvedCalendarId.first()
// Re-check after suspending: bail if the form closed or the user edited. // Re-check after suspending: bail if the form closed or the user edited.
if (opened != session) return@launch
val form = _form.value ?: return@launch val form = _form.value ?: return@launch
if (_editTarget.value != null || _remindersTouched.value) return@launch if (_editTarget.value != null || _remindersTouched.value) return@launch
val reminders = defaults.resolveFor(targetId, form.isAllDay) val reminders = defaults.resolveFor(targetId, form.isAllDay)
// Write through update(): the duration default resolves in parallel, // The duration default resolves in parallel, so both must compose
// so both must compose onto the current form, not a pre-suspend copy. // onto the current form, not a pre-suspend copy.
update { it.copy(reminders = reminders) } applyDefault { it.copy(reminders = reminders) }
// Surface the section so an auto-applied default is visible and // Surface the section so an auto-applied default is visible and
// removable, even when Reminders isn't a default-shown field. // removable, even when Reminders isn't a default-shown field.
if (reminders.isNotEmpty()) { if (reminders.isNotEmpty()) {
@@ -440,6 +493,7 @@ class EventEditViewModel @Inject constructor(
*/ */
private fun applyDefaultDuration(calendarId: Long? = null) { private fun applyDefaultDuration(calendarId: Long? = null) {
if (_editTarget.value != null || _durationTouched.value) return if (_editTarget.value != null || _durationTouched.value) return
val opened = session
viewModelScope.launch { viewModelScope.launch {
val global = settingsPrefs.defaultEventDurationMinutes.first() val global = settingsPrefs.defaultEventDurationMinutes.first()
val overrides = settingsPrefs.perCalendarEventDuration.first() val overrides = settingsPrefs.perCalendarEventDuration.first()
@@ -451,14 +505,14 @@ class EventEditViewModel @Inject constructor(
else -> calendarId ?: resolvedCalendarId.first() else -> calendarId ?: resolvedCalendarId.first()
} }
// Re-check after suspending: bail if the form closed or the user edited. // Re-check after suspending: bail if the form closed or the user edited.
if (opened != session) return@launch
if (_editTarget.value != null || _durationTouched.value) return@launch if (_editTarget.value != null || _durationTouched.value) return@launch
if (_form.value?.isAllDay != false) return@launch if (_form.value?.isAllDay != false) return@launch
val duration = resolveDefaultEventDuration(global, overrides, targetId) val duration = resolveDefaultEventDuration(global, overrides, targetId)
val zone = TimeZone.currentSystemDefault() applyDefault { form ->
update { form -> val zone = form.resolvedZone(zoneSource.current())
form.copy( val start = form.startInstant(zone)
end = (form.start.toInstant(zone) + duration.minutes).toLocalDateTime(zone), form.withTimes(start, start + duration.minutes, zone)
)
} }
} }
} }
@@ -471,10 +525,12 @@ class EventEditViewModel @Inject constructor(
* configured and it isn't already exactly what the file carried. * configured and it isn't already exactly what the file carried.
*/ */
private fun maybePromptImportedReminderDefault(form: EventForm) { private fun maybePromptImportedReminderDefault(form: EventForm) {
val opened = session
viewModelScope.launch { viewModelScope.launch {
val targetId = resolvedCalendarId.first() val targetId = resolvedCalendarId.first()
val default = reminderDefaults().resolveFor(targetId, form.isAllDay) val default = reminderDefaults().resolveFor(targetId, form.isAllDay)
// Bail if the form closed or became an edit while we resolved. // Bail if the form closed or became an edit while we resolved.
if (opened != session) return@launch
val current = _form.value ?: return@launch val current = _form.value ?: return@launch
if (_editTarget.value != null) return@launch if (_editTarget.value != null) return@launch
if (default.isEmpty() || default == current.reminders) return@launch if (default.isEmpty() || default == current.reminders) return@launch
@@ -490,7 +546,7 @@ class EventEditViewModel @Inject constructor(
val prompt = _importReminderPrompt.value ?: return val prompt = _importReminderPrompt.value ?: return
_importReminderPrompt.value = null _importReminderPrompt.value = null
// Already frozen as touched by openImported; this just swaps the values. // Already frozen as touched by openImported; this just swaps the values.
update { it.copy(reminders = prompt.defaultReminders) } edit { it.copy(reminders = prompt.defaultReminders) }
_revealed.value = _revealed.value + EventFormField.Reminders _revealed.value = _revealed.value + EventFormField.Reminders
} }
@@ -510,31 +566,35 @@ class EventEditViewModel @Inject constructor(
*/ */
fun openForEdit(eventId: Long, beginMillis: Long, endMillis: Long) { fun openForEdit(eventId: Long, beginMillis: Long, endMillis: Long) {
if (_form.value != null || _editTarget.value != null) return if (_form.value != null || _editTarget.value != null) return
val opened = session
viewModelScope.launch { viewModelScope.launch {
val detail = try { val detail = try {
repository.eventDetail(eventId) repository.eventDetail(eventId)
} catch (e: CancellationException) { } catch (e: CancellationException) {
throw e throw e
} catch (e: Exception) { } catch (e: Exception) {
_loadFailed.value = true if (opened == session) _loadFailed.value = true
return@launch return@launch
} }
val zone = TimeZone.currentSystemDefault() if (opened != session) return@launch
val zone = zoneSource.current()
val begin = beginMillis.takeUnless { it == NO_OCCURRENCE_TIME } val begin = beginMillis.takeUnless { it == NO_OCCURRENCE_TIME }
?: detail.instance.start.toEpochMilliseconds() ?: detail.instance.start.toEpochMilliseconds()
val end = endMillis.takeUnless { it == NO_OCCURRENCE_TIME } val end = endMillis.takeUnless { it == NO_OCCURRENCE_TIME }
?: detail.instance.end.toEpochMilliseconds() ?: detail.instance.end.toEpochMilliseconds()
val snapshot = detail.toEditSnapshot(begin, end, zone) val snapshot = detail.toEditSnapshot(begin, end, zone)
_editTarget.value = EditTarget(eventId, snapshot, begin, end, zone) _editTarget.value = EditTarget(eventId, snapshot, begin, end, zone, detail.atOccurrence(begin, end))
// Sections holding data must show even when not in the defaults. // Sections holding data must show even when not in the defaults.
_revealed.value = snapshot.form.populatedFields() _revealed.value = snapshot.form.populatedFields()
_form.value = snapshot.form open(snapshot.form)
} }
} }
/** Forget the open form; the next [openNew]/[openForEdit] starts clean. */ /** Forget the open form; the next [openNew]/[openForEdit] starts clean. */
fun reset() { fun reset() {
session++
_form.value = null _form.value = null
_baseline.value = null
_saveState.value = SaveUiState.Idle _saveState.value = SaveUiState.Idle
_showProblems.value = false _showProblems.value = false
_revealed.value = emptySet() _revealed.value = emptySet()
@@ -553,24 +613,28 @@ class EventEditViewModel @Inject constructor(
// The title field wraps (multi-line) so long titles stay visible (#33), but // The title field wraps (multi-line) so long titles stay visible (#33), but
// a title is one logical line: drop any newline the IME's Enter key or a // a title is one logical line: drop any newline the IME's Enter key or a
// paste would introduce, so it never reaches the provider's TITLE column. // paste would introduce, so it never reaches the provider's TITLE column.
fun setTitle(value: String) = update { fun setTitle(value: String) = edit {
val cleaned = value.replace("\n", "").replace("\r", "") val cleaned = value.replace("\n", "").replace("\r", "")
it.copy(title = capLength(cleaned, it.title)) it.copy(title = capLength(cleaned, it.title))
} }
// The location wraps too (#273) but is likewise one logical line. A pasted // The location wraps too (#273) but is likewise one logical line. A pasted
// multi-line address joins the way the contact picker's does (#146), so it // multi-line address joins the way the contact picker's does (#146), so it
// never runs together into "12 Main St10115 Berlin". // never runs together into "12 Main St10115 Berlin".
fun setLocation(value: String) = update { fun setLocation(value: String) = edit {
val cleaned = value.replace(LINE_BREAK, ", ") val cleaned = value.replace(LINE_BREAK, ", ")
it.copy(location = capLength(cleaned, it.location)) it.copy(location = capLength(cleaned, it.location))
} }
fun setDescription(value: String) = update { it.copy(description = value) } fun setDescription(value: String) = edit { it.copy(description = value) }
fun setAllDay(value: Boolean) { fun setAllDay(value: Boolean) {
// Going all-day drops any pinned zone: the times become bare dates that // Going all-day drops any pinned zone: the times become bare dates that
// the provider stores UTC-anchored, so a zone could only misrepresent // the provider stores UTC-anchored, so a zone could only misrepresent
// them. Coming back out of all-day leaves the event on the device zone, // them. Coming back out of all-day leaves the event on the device zone,
// which is the same thing a fresh event gets. // which is the same thing a fresh event gets.
update { it.copy(isAllDay = value, timezone = if (value) null else it.timezone) } // A kept pass of a repeated hour stays, so switching back out of all-day
// lands where the event was — unless dropping the pin changed the zone.
edit {
if (value) it.withTimezone(null, zoneSource.current()).copy(isAllDay = true) else it.copy(isAllDay = false)
}
// The default reminder differs for all-day vs timed; re-apply the // The default reminder differs for all-day vs timed; re-apply the
// type-appropriate default unless the user has hand-edited it (guarded). // type-appropriate default unless the user has hand-edited it (guarded).
applyDefaultReminder() applyDefaultReminder()
@@ -585,7 +649,7 @@ class EventEditViewModel @Inject constructor(
* time — only real picks are remembered, not the device fallback. * time — only real picks are remembered, not the device fallback.
*/ */
fun setTimezone(zoneId: String?) { fun setTimezone(zoneId: String?) {
update { it.copy(timezone = zoneId) } edit { it.withTimezone(zoneId, zoneSource.current()) }
if (zoneId != null) { if (zoneId != null) {
viewModelScope.launch { withContext(io) { settingsPrefs.addRecentTimeZone(zoneId) } } viewModelScope.launch { withContext(io) { settingsPrefs.addRecentTimeZone(zoneId) } }
} }
@@ -597,35 +661,35 @@ class EventEditViewModel @Inject constructor(
* The event falls back to the new calendar's colour until re-picked. * The event falls back to the new calendar's colour until re-picked.
*/ */
fun setCalendar(id: Long) { fun setCalendar(id: Long) {
update { it.copy(calendarId = id, colorKey = null, color = null) } edit { it.copy(calendarId = id, colorKey = null, color = null) }
// A fresh event re-inherits the new calendar's default reminder and // A fresh event re-inherits the new calendar's default reminder and
// length unless the user has already hand-edited them (guarded inside). // length unless the user has already hand-edited them (guarded inside).
applyDefaultReminder(id) applyDefaultReminder(id)
applyDefaultDuration(id) applyDefaultDuration(id)
} }
fun setAvailability(value: Availability) = update { it.copy(availability = value) } fun setAvailability(value: Availability) = edit { it.copy(availability = value) }
fun setAccessLevel(value: AccessLevel) = update { it.copy(accessLevel = value) } fun setAccessLevel(value: AccessLevel) = edit { it.copy(accessLevel = value) }
/** Pick a palette colour (round-trips via its key); [argb] is its swatch. */ /** Pick a palette colour (round-trips via its key); [argb] is its swatch. */
fun setColorKey(key: String, argb: Int) = update { it.copy(colorKey = key, color = argb) } fun setColorKey(key: String, argb: Int) = edit { it.copy(colorKey = key, color = argb) }
/** Pick a raw colour (local / opted-in calendars), clearing any palette key. */ /** Pick a raw colour (local / opted-in calendars), clearing any palette key. */
fun setColorRaw(argb: Int) = update { it.copy(colorKey = null, color = argb) } fun setColorRaw(argb: Int) = edit { it.copy(colorKey = null, color = argb) }
/** Clear the colour so the event inherits its calendar's. */ /** Clear the colour so the event inherits its calendar's. */
fun clearColor() = update { it.copy(colorKey = null, color = null) } fun clearColor() = edit { it.copy(colorKey = null, color = null) }
/** Bare RRULE value from the recurrence picker; null = does not repeat. */ /** Bare RRULE value from the recurrence picker; null = does not repeat. */
fun setRecurrence(rrule: String?) = update { it.copy(rrule = rrule) } fun setRecurrence(rrule: String?) = edit { it.copy(rrule = rrule) }
fun addReminder(minutes: Int) { fun addReminder(minutes: Int) {
_remindersTouched.value = true _remindersTouched.value = true
update { it.copy(reminders = (it.reminders + minutes).distinct().sorted()) } edit { it.copy(reminders = (it.reminders + minutes).distinct().sorted()) }
} }
fun removeReminder(minutes: Int) { fun removeReminder(minutes: Int) {
_remindersTouched.value = true _remindersTouched.value = true
update { it.copy(reminders = it.reminders - minutes) } edit { it.copy(reminders = it.reminders - minutes) }
} }
/** /**
@@ -636,7 +700,7 @@ class EventEditViewModel @Inject constructor(
fun addAttendee(email: String, name: String = "", optional: Boolean = false) { fun addAttendee(email: String, name: String = "", optional: Boolean = false) {
val trimmed = email.trim() val trimmed = email.trim()
if (trimmed.isEmpty()) return if (trimmed.isEmpty()) return
update { form -> edit { form ->
val attendee = EventAttendee(email = trimmed, name = name.trim(), optional = optional) val attendee = EventAttendee(email = trimmed, name = name.trim(), optional = optional)
val rest = form.attendees.filterNot { it.email.equals(trimmed, ignoreCase = true) } val rest = form.attendees.filterNot { it.email.equals(trimmed, ignoreCase = true) }
form.copy(attendees = rest + attendee) form.copy(attendees = rest + attendee)
@@ -644,10 +708,10 @@ class EventEditViewModel @Inject constructor(
} }
fun removeAttendee(attendee: EventAttendee) = fun removeAttendee(attendee: EventAttendee) =
update { it.copy(attendees = it.attendees.filterNot { a -> a.email.equals(attendee.email, ignoreCase = true) }) } edit { it.copy(attendees = it.attendees.filterNot { a -> a.email.equals(attendee.email, ignoreCase = true) }) }
/** Flip a guest between required and optional (the per-row role toggle). */ /** Flip a guest between required and optional (the per-row role toggle). */
fun setAttendeeOptional(attendee: EventAttendee, optional: Boolean) = update { form -> fun setAttendeeOptional(attendee: EventAttendee, optional: Boolean) = edit { form ->
form.copy( form.copy(
attendees = form.attendees.map { a -> attendees = form.attendees.map { a ->
if (a.email.equals(attendee.email, ignoreCase = true)) a.copy(optional = optional) else a if (a.email.equals(attendee.email, ignoreCase = true)) a.copy(optional = optional) else a
@@ -663,12 +727,12 @@ class EventEditViewModel @Inject constructor(
// default duration, so a later calendar switch keeps their span (#54). // default duration, so a later calendar switch keeps their span (#54).
fun setEndDate(date: LocalDate) { fun setEndDate(date: LocalDate) {
_durationTouched.value = true _durationTouched.value = true
update { it.copy(end = LocalDateTime(date, it.end.time)) } moveEnd { LocalDateTime(date, it.time) }
} }
fun setEndTime(time: LocalTime) { fun setEndTime(time: LocalTime) {
_durationTouched.value = true _durationTouched.value = true
update { it.copy(end = LocalDateTime(it.end.date, time)) } moveEnd { LocalDateTime(it.date, time) }
} }
/** /**
@@ -681,7 +745,7 @@ class EventEditViewModel @Inject constructor(
val current = state.value ?: return val current = state.value ?: return
if (current.saveState == SaveUiState.Saving) return if (current.saveState == SaveUiState.Saving) return
val form = current.form val form = current.form
if (form.problems().isNotEmpty()) { if (form.problems(zoneSource.current()).isNotEmpty()) {
_showProblems.value = true _showProblems.value = true
return return
} }
@@ -726,8 +790,13 @@ class EventEditViewModel @Inject constructor(
ignoreConflict: Boolean = false, ignoreConflict: Boolean = false,
) { ) {
val target = _editTarget.value val target = _editTarget.value
val opened = session
// A form closed mid-save drops the result rather than handing it to the next one.
fun settle(result: SaveUiState) {
if (opened == session) _saveState.value = result
}
viewModelScope.launch { viewModelScope.launch {
_saveState.value = SaveUiState.Saving settle(SaveUiState.Saving)
// No locking (plan 03, decision 5): right before writing, re-read // No locking (plan 03, decision 5): right before writing, re-read
// the event and compare against what the form loaded. An external // the event and compare against what the form loaded. An external
// change parks the save in a conflict dialog instead of silently // change parks the save in a conflict dialog instead of silently
@@ -739,18 +808,18 @@ class EventEditViewModel @Inject constructor(
} catch (e: CancellationException) { } catch (e: CancellationException) {
throw e throw e
} catch (e: NoSuchEventException) { } catch (e: NoSuchEventException) {
_saveState.value = SaveUiState.Gone settle(SaveUiState.Gone)
return@launch return@launch
} catch (e: Exception) { } catch (e: Exception) {
// Can't verify — proceed; a real problem fails the write itself. // Can't verify — proceed; a real problem fails the write itself.
null null
} }
if (fresh != null && fresh != target.snapshot) { if (fresh != null && fresh != target.snapshot) {
_saveState.value = SaveUiState.AwaitingConflict(scope) settle(SaveUiState.AwaitingConflict(scope))
return@launch return@launch
} }
} }
_saveState.value = try { val result = try {
if (target == null) { if (target == null) {
repository.createEvent(form) repository.createEvent(form)
prefs.setLastUsedCalendarId(requireNotNull(form.calendarId)) prefs.setLastUsedCalendarId(requireNotNull(form.calendarId))
@@ -801,6 +870,37 @@ class EventEditViewModel @Inject constructor(
Log.w(TAG, "Save failed (scope=$scope, eventId=${target?.eventId})", e) Log.w(TAG, "Save failed (scope=$scope, eventId=${target?.eventId})", e)
SaveUiState.Failed SaveUiState.Failed
} }
settle(result)
}
}
/** Whether the event being edited recurs; null while not editing. */
fun editedEventRecurs(): Boolean? = _editTarget.value?.let { !it.detail.rrule.isNullOrBlank() }
/** The form as it stands, as a fresh one-off event — Duplicate in the edit form (#178). */
fun duplicateForm(): EventForm? = state.value?.form?.copy(rrule = null)
/** A staged `.ics` of the event as saved, or null when it can't be built. */
suspend fun shareUri(): Uri? {
val detail = _editTarget.value?.detail ?: return null
return withContext(io) { icsExporter.stageEventShare(detail) }
}
/** Delete the event being edited, as far as [scope] reaches; result lands in [saveState]. */
fun delete(scope: RecurringWriteScope) {
val target = _editTarget.value ?: return
if (_saveState.value == SaveUiState.Saving) return
val opened = session
_saveState.value = SaveUiState.Saving
viewModelScope.launch {
val outcome = repository.tryDeleteEvent(target.eventId, target.beginMillis, scope)
if (opened != session) return@launch
_saveState.value = when (outcome) {
// Already gone is what a delete wants anyway.
DeleteOutcome.Deleted, DeleteOutcome.Gone -> SaveUiState.Deleted
DeleteOutcome.NeedsPermission -> SaveUiState.DeleteDenied
DeleteOutcome.Failed -> SaveUiState.DeleteFailed
}
} }
} }
@@ -809,15 +909,34 @@ class EventEditViewModel @Inject constructor(
_saveState.value = SaveUiState.Idle _saveState.value = SaveUiState.Idle
} }
private fun moveStart(transform: (LocalDateTime) -> LocalDateTime) = update { form -> private fun moveStart(transform: (LocalDateTime) -> LocalDateTime) = edit { form ->
val zone = TimeZone.currentSystemDefault() form.withStart(transform(form.start.dateTime), form.resolvedZone(zoneSource.current()), opened(form)?.start)
val newStart = transform(form.start)
val duration = form.end.toInstant(zone) - form.start.toInstant(zone)
val newEnd = (newStart.toInstant(zone) + duration).toLocalDateTime(zone)
form.copy(start = newStart, end = newEnd)
} }
private inline fun update(block: (EventForm) -> EventForm) { private fun moveEnd(transform: (LocalDateTime) -> LocalDateTime) = edit { form ->
form.withEnd(transform(form.end.dateTime), form.resolvedZone(zoneSource.current()), opened(form)?.end)
}
/**
* The event as it was opened, while its times still mean the same instants:
* picking one of them again keeps its pass of a repeated hour (#387).
*/
private fun opened(form: EventForm): EventForm? =
_editTarget.value?.original?.takeIf { it.timezone == form.timezone && !it.isAllDay }
private fun open(form: EventForm) {
_form.value = form
_baseline.value = form
}
/** A default the form applied itself; it moves the baseline too, so it's no unsaved change. */
private inline fun applyDefault(block: (EventForm) -> EventForm) {
_form.value = _form.value?.let(block)
_baseline.value = _baseline.value?.let(block)
}
/** A change the user made. */
private inline fun edit(block: (EventForm) -> EventForm) {
_form.value = _form.value?.let(block) _form.value = _form.value?.let(block)
} }
} }
@@ -4,20 +4,19 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.lifecycle.HiltViewModel
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
import de.jeanlucmakiola.calendula.data.di.IoDispatcher
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.FailureReason import de.jeanlucmakiola.calendula.domain.FailureReason
import de.jeanlucmakiola.calendula.domain.calendarListFailure import de.jeanlucmakiola.calendula.domain.calendarListFailure
import de.jeanlucmakiola.calendula.ui.common.groupByAccount import de.jeanlucmakiola.calendula.ui.common.groupByAccount
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
import de.jeanlucmakiola.floret.di.IoDispatcher
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import javax.inject.Inject import javax.inject.Inject
@@ -45,9 +44,8 @@ class FilterViewModel @Inject constructor(
} }
.catch { emit(FilterUiState.Failure(FailureReason.ProviderUnavailable)) } .catch { emit(FilterUiState.Failure(FailureReason.ProviderUnavailable)) }
.flowOn(io) .flowOn(io)
.stateIn( .stateWhileSubscribed(
scope = viewModelScope, scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = FilterUiState.Loading, initialValue = FilterUiState.Loading,
) )
@@ -5,7 +5,6 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.lifecycle.HiltViewModel
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
import de.jeanlucmakiola.calendula.data.di.IoDispatcher
import de.jeanlucmakiola.calendula.data.ics.IcsImporter import de.jeanlucmakiola.calendula.data.ics.IcsImporter
import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.EventForm
@@ -15,6 +14,7 @@ import de.jeanlucmakiola.calendula.domain.ics.IcsParser
import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent
import de.jeanlucmakiola.calendula.domain.ics.toEventForm import de.jeanlucmakiola.calendula.domain.ics.toEventForm
import de.jeanlucmakiola.calendula.domain.isEventTarget import de.jeanlucmakiola.calendula.domain.isEventTarget
import de.jeanlucmakiola.floret.di.IoDispatcher
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
@@ -4,6 +4,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable import androidx.compose.runtime.Stable
import androidx.compose.runtime.compositionLocalOf import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
@@ -133,6 +134,10 @@ class MonthDragController {
var settling: MonthChipDrag? by mutableStateOf(null) var settling: MonthChipDrag? by mutableStateOf(null)
private set private set
/** How many real drops this controller has handed back. */
var drops by mutableIntStateOf(0)
private set
/** /**
* Which chip is lifted, and whether anything is. Separate snapshot state from * Which chip is lifted, and whether anything is. Separate snapshot state from
* [drag], which changes every frame, so the chips and rows that only need * [drag], which changes every frame, so the chips and rows that only need
@@ -291,6 +296,7 @@ class MonthDragController {
settledGhost = true settledGhost = true
undoable = settling undoable = settling
settledAbandonedMark = abandonedTicks?.value ?: 0 settledAbandonedMark = abandonedTicks?.value ?: 0
drops++
return MonthChipDrop(landed.event, landed.grabDate, target) return MonthChipDrop(landed.event, landed.grabDate, target)
} }
@@ -21,9 +21,9 @@ import de.jeanlucmakiola.calendula.ui.common.LocalViewFocus
import de.jeanlucmakiola.calendula.ui.common.ViewMorphKey import de.jeanlucmakiola.calendula.ui.common.ViewMorphKey
import de.jeanlucmakiola.calendula.ui.common.morphDay import de.jeanlucmakiola.calendula.ui.common.morphDay
import de.jeanlucmakiola.calendula.ui.common.morphEvent import de.jeanlucmakiola.calendula.ui.common.morphEvent
import de.jeanlucmakiola.calendula.ui.common.morphPageActive
import de.jeanlucmakiola.calendula.ui.common.jumpToPage import de.jeanlucmakiola.calendula.ui.common.jumpToPage
import de.jeanlucmakiola.calendula.ui.common.rememberCalendarPageSpec import de.jeanlucmakiola.calendula.ui.common.rememberCalendarPageSpec
import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.drop
import androidx.compose.animation.ExperimentalSharedTransitionApi import androidx.compose.animation.ExperimentalSharedTransitionApi
@@ -46,7 +46,6 @@ import androidx.compose.foundation.background
import androidx.compose.foundation.clickable import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.awaitEachGesture import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.BoxWithConstraints
@@ -75,11 +74,7 @@ import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.HorizontalDivider
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.InputChip import androidx.compose.material3.InputChip
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text import androidx.compose.material3.Text
@@ -87,6 +82,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
@@ -166,10 +162,9 @@ import de.jeanlucmakiola.calendula.ui.agenda.agendaDayLabel
import de.jeanlucmakiola.calendula.ui.common.formatCalendarTitle import de.jeanlucmakiola.calendula.ui.common.formatCalendarTitle
import de.jeanlucmakiola.calendula.ui.common.AppBarSpacing import de.jeanlucmakiola.calendula.ui.common.AppBarSpacing
import de.jeanlucmakiola.calendula.ui.common.CalendarFailure 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.calendula.ui.common.EventDimAlpha import de.jeanlucmakiola.calendula.ui.common.EventDimAlpha
import de.jeanlucmakiola.calendula.ui.common.LocalDimCutoff import de.jeanlucmakiola.calendula.ui.common.LocalDimCutoff
import de.jeanlucmakiola.calendula.ui.common.isPastOn
import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors
import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat import de.jeanlucmakiola.calendula.ui.common.LocalUse24HourFormat
import de.jeanlucmakiola.calendula.ui.common.inlineTimeLabel import de.jeanlucmakiola.calendula.ui.common.inlineTimeLabel
@@ -197,13 +192,17 @@ import kotlinx.datetime.TimeZone
import kotlinx.datetime.plus import kotlinx.datetime.plus
import kotlinx.datetime.YearMonth import kotlinx.datetime.YearMonth
import kotlinx.datetime.toJavaLocalDate import kotlinx.datetime.toJavaLocalDate
import kotlinx.datetime.toLocalDateTime
import kotlin.time.Clock
import kotlin.time.Instant import kotlin.time.Instant
import java.time.format.TextStyle as JavaTextStyle import java.time.format.TextStyle as JavaTextStyle
import java.util.Locale import java.util.Locale
private val LocalTodayPulse = staticCompositionLocalOf { 0 } private val LocalTodayPulse = staticCompositionLocalOf { 0 }
/** Live today for the pages, whose cached states may have been built before midnight (#373). */
private val LocalMonthToday = compositionLocalOf<LocalDate?> { null }
private fun MonthUiState.Success.withToday(today: LocalDate?): MonthUiState.Success =
if (today == null || today == this.today) this else copy(today = today)
private val LocalOpenWeek = staticCompositionLocalOf<((LocalDate) -> Unit)?> { null } private val LocalOpenWeek = staticCompositionLocalOf<((LocalDate) -> Unit)?> { null }
/** A brief push from today's full cell into its immediate neighbours. */ /** A brief push from today's full cell into its immediate neighbours. */
@@ -319,12 +318,7 @@ fun MonthScreen(
} }
val dense = viewStyle == MonthViewStyle.Dense val dense = viewStyle == MonthViewStyle.Dense
// Today, from whichever state is driving; the clock only covers the first val today by viewModel.today.collectAsStateWithLifecycle()
// frame, before either has loaded.
val today = when {
scrolling -> (continuousState as? ContinuousMonthUiState.Success)?.today
else -> (state as? MonthUiState.Success)?.today
} ?: Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).date
// The two scrolling styles index their items differently — Continuous by // The two scrolling styles index their items differently — Continuous by
// month (which the week start can't move), Dense by week (which it can) — so // month (which the week start can't move), Dense by week (which it can) — so
@@ -520,6 +514,7 @@ fun MonthScreen(
LocalDimCutoff provides dimCutoff, LocalDimCutoff provides dimCutoff,
LocalMonthDrag provides chipDrag, LocalMonthDrag provides chipDrag,
LocalTodayPulse provides todayPulse, LocalTodayPulse provides todayPulse,
LocalMonthToday provides today,
LocalOpenWeek provides onOpenWeek, LocalOpenWeek provides onOpenWeek,
) { ) {
if (scrolling) { if (scrolling) {
@@ -532,7 +527,7 @@ fun MonthScreen(
onOpenDay = onOpenDay, onOpenDay = onOpenDay,
onEventClick = onEventClick, onEventClick = onEventClick,
) )
} else if (viewStyle == MonthViewStyle.Split || viewStyle == MonthViewStyle.Paged) { } else {
SplitMonthContent( SplitMonthContent(
state = state, state = state,
selected = selectedDate, selected = selectedDate,
@@ -558,17 +553,6 @@ fun MonthScreen(
onEventClick = onEventClick, onEventClick = onEventClick,
onCreateEvent = { onCreateEvent(it, null) }, onCreateEvent = { onCreateEvent(it, null) },
) )
} else {
MonthContent(
state = state,
pagerState = pagerState,
weekStart = weekStart,
monthState = viewModel::month,
showWeekNumbers = showWeekNumbers,
onRetry = jumpToToday,
onOpenDay = onOpenDay,
onEventClick = onEventClick,
)
} }
} }
} }
@@ -587,14 +571,14 @@ private const val MONTH_SETTLE_TIMEOUT_MILLIS = 450L
@Composable @Composable
private fun MonthDragOverlay(controller: MonthDragController) { private fun MonthDragOverlay(controller: MonthDragController) {
var origin by remember { mutableStateOf(Offset.Zero) } var origin by remember { mutableStateOf(Offset.Zero) }
val dark = isSystemInDarkTheme() val dark = LocalFloretDarkTheme.current
val density = LocalDensity.current val density = LocalDensity.current
val timeChipWidth = rememberMonthTimeChipWidth() val timeChipWidth = rememberMonthTimeChipWidth()
val reduceMotion = rememberReduceMotion() val reduceMotion = rememberReduceMotion()
val moveInFlight = moveInFlight() val moveInFlight = moveInFlight()
// Here rather than beside the controller: this reads [drag], which changes // Here rather than beside the controller: this reads [drag], which changes
// every frame, and this composable is the one that is meant to. // every frame, and this composable is the one that is meant to.
DragSnapHaptics(controller.drag?.targetDate) DragSnapHaptics(controller.drag?.targetDate, controller.drops)
// Hold the landed chip until the write is done — including the time a // Hold the landed chip until the write is done — including the time a
// recurring drop's scope dialog is up — and then, unlike the timeline, carry // recurring drop's scope dialog is up — and then, unlike the timeline, carry
// it to its seat: it was dropped at whatever height the finger was at, while // it to its seat: it was dropped at whatever height the finger was at, while
@@ -677,117 +661,6 @@ private fun MonthDragOverlay(controller: MonthDragController) {
} }
} }
@Composable
private fun MonthContent(
state: MonthUiState,
pagerState: PagerState,
weekStart: DayOfWeek,
monthState: (YearMonth, DayOfWeek) -> StateFlow<MonthUiState>,
showWeekNumbers: Boolean,
onRetry: () -> Unit,
onOpenDay: (LocalDate) -> Unit,
onEventClick: (EventInstance) -> Unit,
) {
val fadeSpec = rememberCalendarFadeSpec()
// Loading and failure concern the provider as a whole, so they stand in for
// the pager; a page still loading its own month handles that itself.
AnimatedContent(
targetState = state,
modifier = Modifier.fillMaxSize(),
contentKey = { it::class },
transitionSpec = { fadeIn(fadeSpec) togetherWith fadeOut(fadeSpec) },
label = "month-state",
) { s ->
when (s) {
MonthUiState.Loading -> MonthGridLoading()
is MonthUiState.Failure -> CalendarFailure(reason = s.reason, onRetry = onRetry)
is MonthUiState.Success -> MonthPager(
pagerState = pagerState,
weekStart = weekStart,
monthState = monthState,
modifier = Modifier.fillMaxSize(),
) { _, page ->
MonthGrid(
state = page,
showWeekNumbers = showWeekNumbers,
onOpenDay = onOpenDay,
onEventClick = onEventClick,
)
}
}
}
}
/**
* The paged and split styles' months as pages that follow the finger and snap
* once a swipe passes half a page or is flung (#336). Only the page on screen
* carries the chip drag and the morph tags: its neighbours show some of its
* dates among their leading and trailing days, and would otherwise claim its
* drops and its shared elements.
*/
@Composable
private fun MonthPager(
pagerState: PagerState,
weekStart: DayOfWeek,
monthState: (YearMonth, DayOfWeek) -> StateFlow<MonthUiState>,
modifier: Modifier = Modifier,
loading: @Composable () -> Unit = { MonthGridLoading() },
page: @Composable (index: Int, state: MonthUiState.Success) -> Unit,
) {
val chipDrag = LocalMonthDrag.current
HorizontalPager(
state = pagerState,
modifier = modifier,
// The months either side are composed ahead, so a swipe lands on a loaded
// month rather than watching it fill in.
beyondViewportPageCount = 1,
verticalAlignment = Alignment.Top,
// A held chip moves within its month; the page stays put under it.
userScrollEnabled = chipDrag?.isDragging != true,
flingBehavior = PagerDefaults.flingBehavior(
state = pagerState,
snapAnimationSpec = rememberCalendarPageSpec(),
),
) { index ->
MonthPage(
index = index,
active = index == pagerState.currentPage,
morphActive = morphPageActive(index, pagerState.settledPage),
weekStart = weekStart,
monthState = monthState,
loading = loading,
page = page,
)
}
}
@Composable
private fun MonthPage(
index: Int,
active: Boolean,
morphActive: Boolean,
weekStart: DayOfWeek,
monthState: (YearMonth, DayOfWeek) -> StateFlow<MonthUiState>,
loading: @Composable () -> Unit,
page: @Composable (index: Int, state: MonthUiState.Success) -> Unit,
) {
val ym = yearMonthForIndex(index)
val state by remember(ym, weekStart) { monthState(ym, weekStart) }.collectAsStateWithLifecycle()
val chipDrag = LocalMonthDrag.current
val morph = LocalMonthMorph.current
val viewMorph = LocalViewMorph.current
CompositionLocalProvider(
LocalMonthDrag provides chipDrag.takeIf { active },
LocalMonthMorph provides morph.takeIf { active },
LocalViewMorph provides viewMorph.takeIf { morphActive },
) {
when (val s = state) {
is MonthUiState.Success -> page(index, s)
else -> loading()
}
}
}
/** /**
* Content for both scrolling styles. No swipe detector and no [AnimatedContent]: * Content for both scrolling styles. No swipe detector and no [AnimatedContent]:
* vertical scrolling owns the gesture, and the list never swaps wholesale — it * vertical scrolling owns the gesture, and the list never swaps wholesale — it
@@ -1388,7 +1261,8 @@ private fun SplitMonthContent(
val ym = yearMonthForIndex(index) val ym = yearMonthForIndex(index)
val pageState by remember(ym, weekStart) { monthState(ym, weekStart) } val pageState by remember(ym, weekStart) { monthState(ym, weekStart) }
.collectAsStateWithLifecycle() .collectAsStateWithLifecycle()
val page = pageState as? MonthUiState.Success ?: return@HorizontalPager val page = (pageState as? MonthUiState.Success)?.withToday(LocalMonthToday.current)
?: return@HorizontalPager
// Only the settled page carries the drag and the morph tags: its // Only the settled page carries the drag and the morph tags: its
// neighbours repeat some of its dates and would claim them. // neighbours repeat some of its dates and would claim them.
val active = index == pagerState.settledPage val active = index == pagerState.settledPage
@@ -1459,8 +1333,14 @@ private fun SplitMonthContent(
showWeekNumbers = showWeekNumbers, showWeekNumbers = showWeekNumbers,
expandDrag = expandDrag, expandDrag = expandDrag,
onSelectDay = onSelectDay, onSelectDay = onSelectDay,
onPaneSwipeNext = onPaneSwipeNext, onPaneSwipeNext = {
onPaneSwipePrev = onPaneSwipePrev, onPaneSwipeNext()
haptics.performHapticFeedback(HapticFeedbackType.SegmentTick)
},
onPaneSwipePrev = {
onPaneSwipePrev()
haptics.performHapticFeedback(HapticFeedbackType.SegmentTick)
},
onClearSelection = onClearSelection, onClearSelection = onClearSelection,
onOpenDay = onOpenDay, onOpenDay = onOpenDay,
onEventClick = onEventClick, onEventClick = onEventClick,
@@ -1718,7 +1598,7 @@ internal fun SplitMonthGrid(
onSelectDay: (LocalDate) -> Unit, onSelectDay: (LocalDate) -> Unit,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
) { ) {
val dark = isSystemInDarkTheme() val dark = LocalFloretDarkTheme.current
val month = state.month val month = state.month
val hasToday = state.today.year == month.year && state.today.month == month.month val hasToday = state.today.year == month.year && state.today.month == month.month
val ripple = rememberTodayRipple(active = hasToday) val ripple = rememberTodayRipple(active = hasToday)
@@ -1937,7 +1817,7 @@ private fun SplitDots(
modifier = Modifier modifier = Modifier
.morphBounds(MonthMorphKey.Event(date, event.instanceId)) .morphBounds(MonthMorphKey.Event(date, event.instanceId))
.size(SPLIT_DOT_SIZE) .size(SPLIT_DOT_SIZE)
.alpha(if (dimCutoff != null && event.hasEnded(dimCutoff)) EventDimAlpha else 1f) .alpha(if (dimCutoff != null && event.isPastOn(date, dimCutoff)) EventDimAlpha else 1f)
.background(eventAccent(event.color, dark, soften), CircleShape), .background(eventAccent(event.color, dark, soften), CircleShape),
) )
} }
@@ -1951,7 +1831,7 @@ private fun SplitDots(
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier modifier = Modifier
.morphBounds(MonthMorphKey.Overflow(date)) .morphBounds(MonthMorphKey.Overflow(date))
.alpha(if (allEnded(hidden, dimCutoff)) EventDimAlpha else 1f), .alpha(if (allEnded(hidden, date, dimCutoff)) EventDimAlpha else 1f),
) )
} }
} }
@@ -1994,7 +1874,7 @@ private fun SplitMonthAgendaPane(
day = day, day = day,
zone = state.zone, zone = state.zone,
position = positionOf(index, events.size), position = positionOf(index, events.size),
dimmed = dimCutoff != null && event.hasEnded(dimCutoff), dimmed = dimCutoff != null && event.isPastOn(day, dimCutoff),
modifier = animateItemMotion().morphEvent(ViewMorphKey.event(event, day)), modifier = animateItemMotion().morphEvent(ViewMorphKey.event(event, day)),
onClick = { onEventClick(event) }, onClick = { onEventClick(event) },
) )
@@ -2063,7 +1943,7 @@ internal fun SplitDayPane(
day = day, day = day,
zone = zone, zone = zone,
position = positionOf(index, dayEvents.size), position = positionOf(index, dayEvents.size),
dimmed = dimCutoff != null && event.hasEnded(dimCutoff), dimmed = dimCutoff != null && event.isPastOn(day, dimCutoff),
onClick = { onEventClick(event) }, onClick = { onEventClick(event) },
// An event added to or removed from the day you are // An event added to or removed from the day you are
// already looking at moves its neighbours rather // already looking at moves its neighbours rather
@@ -2227,7 +2107,7 @@ private fun MonthWeekRow(
*/ */
selected: LocalDate? = null, selected: LocalDate? = null,
) { ) {
val dark = isSystemInDarkTheme() val dark = LocalFloretDarkTheme.current
val todayCol = week.days.indexOf(today).takeIf { it >= 0 && inMonth(today) } val todayCol = week.days.indexOf(today).takeIf { it >= 0 && inMonth(today) }
val ripple = rememberTodayRipple(active = todayCol != null) val ripple = rememberTodayRipple(active = todayCol != null)
val overflowRow = rememberOverflowRowHeight() val overflowRow = rememberOverflowRowHeight()
@@ -2539,6 +2419,7 @@ private fun MonthWeekRow(
} }
OverflowDots( OverflowDots(
events = hiddenEvents, events = hiddenEvents,
day = d,
total = hidden, total = hidden,
dark = dark, dark = dark,
rowHeight = overflowRow, rowHeight = overflowRow,
@@ -2863,7 +2744,9 @@ private fun MonthBar(
) { ) {
val title = event.title.ifBlank { stringResource(R.string.event_untitled) } val title = event.title.ifBlank { stringResource(R.string.event_untitled) }
val dimCutoff = LocalDimCutoff.current val dimCutoff = LocalDimCutoff.current
val dimmed = dimCutoff != null && event.hasEnded(dimCutoff) // A bar is one piece, so it dims once the last day it covers has passed.
val dimmed = dimCutoff != null &&
(event.hasEnded(dimCutoff) || days?.let { event.isPastOn(it.last(), dimCutoff) } == true)
val paint = eventPaint(event, dark) val paint = eventPaint(event, dark)
// The same title/secondary ink pairing the week and day blocks use, with // The same title/secondary ink pairing the week and day blocks use, with
// the time on the quieter half. // the time on the quieter half.
@@ -2916,6 +2799,7 @@ private fun MonthBar(
@Composable @Composable
private fun OverflowDots( private fun OverflowDots(
events: List<EventInstance>, events: List<EventInstance>,
day: LocalDate,
total: Int, total: Int,
dark: Boolean, dark: Boolean,
rowHeight: Dp, rowHeight: Dp,
@@ -2934,7 +2818,7 @@ private fun OverflowDots(
Box( Box(
modifier = Modifier modifier = Modifier
.size(OVERFLOW_DOT_SIZE) .size(OVERFLOW_DOT_SIZE)
.alpha(if (allEnded(byColor.getValue(argb), dimCutoff)) EventDimAlpha else 1f) .alpha(if (allEnded(byColor.getValue(argb), day, dimCutoff)) EventDimAlpha else 1f)
.background(eventAccent(argb, dark, soften), CircleShape), .background(eventAccent(argb, dark, soften), CircleShape),
) )
} }
@@ -2944,15 +2828,15 @@ private fun OverflowDots(
text = "+$extra", text = "+$extra",
style = MaterialTheme.typography.labelSmall, style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.alpha(if (allEnded(events, dimCutoff)) EventDimAlpha else 1f), modifier = Modifier.alpha(if (allEnded(events, day, dimCutoff)) EventDimAlpha else 1f),
) )
} }
} }
} }
/** True when dimming is on and every one of [events] is already over. */ /** True when dimming is on and every one of [events] is already over on [day]. */
private fun allEnded(events: List<EventInstance>, dimCutoff: Instant?): Boolean = private fun allEnded(events: List<EventInstance>, day: LocalDate, dimCutoff: Instant?): Boolean =
dimCutoff != null && events.isNotEmpty() && events.all { it.hasEnded(dimCutoff) } dimCutoff != null && events.isNotEmpty() && events.all { it.isPastOn(day, dimCutoff) }
@Composable @Composable
private fun MonthGridLoading() { private fun MonthGridLoading() {
@@ -8,8 +8,8 @@ import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import de.jeanlucmakiola.calendula.ui.common.ScaledViewPreview
import de.jeanlucmakiola.calendula.ui.common.sampleMonthEvents import de.jeanlucmakiola.calendula.ui.common.sampleMonthEvents
import de.jeanlucmakiola.floret.components.ScaledViewPreview
import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.DayOfWeek import kotlinx.datetime.DayOfWeek
import kotlinx.datetime.LocalDate import kotlinx.datetime.LocalDate
@@ -4,9 +4,10 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.lifecycle.HiltViewModel
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
import de.jeanlucmakiola.calendula.data.di.IoDispatcher
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.data.prefs.firstDayOfWeek 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.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.CalendarSource
import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.domain.FailureReason import de.jeanlucmakiola.calendula.domain.FailureReason
@@ -17,10 +18,11 @@ import de.jeanlucmakiola.calendula.domain.eventDisplayComparator
import de.jeanlucmakiola.calendula.ui.week.coversDay import de.jeanlucmakiola.calendula.ui.week.coversDay
import de.jeanlucmakiola.calendula.ui.week.layoutAllDay import de.jeanlucmakiola.calendula.ui.week.layoutAllDay
import de.jeanlucmakiola.calendula.ui.week.spansMultipleDays import de.jeanlucmakiola.calendula.ui.week.spansMultipleDays
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
import de.jeanlucmakiola.floret.di.IoDispatcher
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.combine
@@ -31,7 +33,6 @@ import kotlinx.coroutines.flow.filterNot
import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.map
import kotlin.math.abs import kotlin.math.abs
import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.stateIn
import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.DayOfWeek import kotlinx.datetime.DayOfWeek
import kotlinx.datetime.LocalDate import kotlinx.datetime.LocalDate
@@ -45,7 +46,6 @@ import kotlinx.datetime.minus
import kotlinx.datetime.plus import kotlinx.datetime.plus
import kotlinx.datetime.toInstant import kotlinx.datetime.toInstant
import kotlinx.datetime.toLocalDateTime import kotlinx.datetime.toLocalDateTime
import kotlin.time.Clock
import kotlin.time.Instant import kotlin.time.Instant
import javax.inject.Inject import javax.inject.Inject
@@ -57,6 +57,7 @@ private const val MONTH_CACHE_SPAN = 2
class MonthViewModel @Inject constructor( class MonthViewModel @Inject constructor(
private val repository: CalendarRepository, private val repository: CalendarRepository,
settingsPrefs: SettingsPrefs, settingsPrefs: SettingsPrefs,
todaySource: TodaySource,
@IoDispatcher private val io: CoroutineDispatcher, @IoDispatcher private val io: CoroutineDispatcher,
) : ViewModel() { ) : ViewModel() {
@@ -67,43 +68,42 @@ class MonthViewModel @Inject constructor(
/** Whether to fade events that have already finished (display concern only). */ /** Whether to fade events that have already finished (display concern only). */
val dimCompletedEvents: StateFlow<Boolean> = settingsPrefs.dimCompletedEvents val dimCompletedEvents: StateFlow<Boolean> = settingsPrefs.dimCompletedEvents
.stateIn( .stateWhileSubscribed(
scope = viewModelScope, scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = false, initialValue = false,
) )
/** Whether to show the calendar-week number gutter (#25; display only). */ /** Whether to show the calendar-week number gutter (#25; display only). */
val showWeekNumbers: StateFlow<Boolean> = settingsPrefs.showWeekNumbers val showWeekNumbers: StateFlow<Boolean> = settingsPrefs.showWeekNumbers
.stateIn( .stateWhileSubscribed(
scope = viewModelScope, scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = false, initialValue = false,
) )
/** How the grid is laid out and navigated (#38, #53). */ /** How the grid is laid out and navigated (#38, #53). */
val viewStyle: StateFlow<MonthViewStyle> = settingsPrefs.monthViewStyle val viewStyle: StateFlow<MonthViewStyle> = settingsPrefs.monthViewStyle
.stateIn( .stateWhileSubscribed(
scope = viewModelScope, scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = MonthViewStyle.Paged, initialValue = MonthViewStyle.Paged,
) )
private val todayDate: LocalDate private val todayDate: LocalDate
get() = Clock.System.now().toLocalDateTime(zone).date get() = currentDate()
private var lastToday = todayDate
/** Today, kept current across midnight so a grid left open doesn't mark yesterday (#373). */
val today: StateFlow<LocalDate> = todaySource.today
.onEach { date ->
val old = lastToday
lastToday = date
if (old != date) followToday(old, date)
}
.stateWhileSubscribed(viewModelScope, todayDate)
private val _month = MutableStateFlow(YearMonth(todayDate.year, todayDate.month)) private val _month = MutableStateFlow(YearMonth(todayDate.year, todayDate.month))
val month: StateFlow<YearMonth> = _month val month: StateFlow<YearMonth> = _month
/** The pager page the anchor month sits on, for the paged and split styles. */
val anchorPage: StateFlow<Int> = _month
.map { monthIndexOf(it) }
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = monthIndexOf(_month.value),
)
/** /**
* The anchor month's state. Once loaded it never falls back to * The anchor month's state. Once loaded it never falls back to
* [MonthUiState.Loading]: moving the anchor keeps the last result until the * [MonthUiState.Loading]: moving the anchor keeps the last result until the
@@ -120,9 +120,8 @@ class MonthViewModel @Inject constructor(
month(ym, ws).filterNot { it is MonthUiState.Loading } month(ym, ws).filterNot { it is MonthUiState.Loading }
} }
.catch { emit(MonthUiState.Failure(FailureReason.ProviderUnavailable)) } .catch { emit(MonthUiState.Failure(FailureReason.ProviderUnavailable)) }
.stateIn( .stateWhileSubscribed(
scope = viewModelScope, scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = MonthUiState.Loading, initialValue = MonthUiState.Loading,
) )
@@ -139,8 +138,9 @@ class MonthViewModel @Inject constructor(
combine( combine(
repository.calendars(), repository.calendars(),
repository.instances(monthGridRange(ym, ws, zone)), repository.instances(monthGridRange(ym, ws, zone)),
) { calendars, instances -> today,
buildState(ym, ws, calendars, instances) ) { calendars, instances, today ->
buildState(ym, ws, calendars, instances, today)
} }
.catch { emit(MonthUiState.Failure(FailureReason.ProviderUnavailable)) } .catch { emit(MonthUiState.Failure(FailureReason.ProviderUnavailable)) }
.flowOn(io) .flowOn(io)
@@ -156,7 +156,8 @@ class MonthViewModel @Inject constructor(
fun onPageSettled(page: Int) { fun onPageSettled(page: Int) {
if (monthIndexOf(_month.value) == page) return if (monthIndexOf(_month.value) == page) return
_month.value = yearMonthForIndex(page) _month.value = yearMonthForIndex(page)
realignSelection() // Moving the grid to another month restores its full agenda.
_selectedDate.value = null
} }
// --- Continuous + Dense styles (#38) ---------------------------------- // --- Continuous + Dense styles (#38) ----------------------------------
@@ -211,8 +212,9 @@ class MonthViewModel @Inject constructor(
combine( combine(
repository.calendars(), repository.calendars(),
repository.instances(range), repository.instances(range),
) { calendars, instances -> today,
buildContinuousState(window, ws, style, calendars, instances) ) { calendars, instances, today ->
buildContinuousState(window, ws, style, calendars, instances, today)
} }
} }
// A load landing is the cue to reach further out. Widening from here // A load landing is the cue to reach further out. Widening from here
@@ -221,9 +223,8 @@ class MonthViewModel @Inject constructor(
.onEach { if (it is ContinuousMonthUiState.Success) widenLoadedWindow() } .onEach { if (it is ContinuousMonthUiState.Success) widenLoadedWindow() }
.catch { emit(ContinuousMonthUiState.Failure(FailureReason.ProviderUnavailable)) } .catch { emit(ContinuousMonthUiState.Failure(FailureReason.ProviderUnavailable)) }
.flowOn(io) .flowOn(io)
.stateIn( .stateWhileSubscribed(
scope = viewModelScope, scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = ContinuousMonthUiState.Loading, initialValue = ContinuousMonthUiState.Loading,
) )
@@ -257,6 +258,7 @@ class MonthViewModel @Inject constructor(
style: MonthViewStyle, style: MonthViewStyle,
calendars: List<CalendarSource>, calendars: List<CalendarSource>,
instances: List<EventInstance>, instances: List<EventInstance>,
today: LocalDate,
): ContinuousMonthUiState { ): ContinuousMonthUiState {
calendarListFailure(calendars)?.let { return ContinuousMonthUiState.Failure(it) } calendarListFailure(calendars)?.let { return ContinuousMonthUiState.Failure(it) }
// Bucketed once for the whole window: a row then takes the handful of // Bucketed once for the whole window: a row then takes the handful of
@@ -283,7 +285,7 @@ class MonthViewModel @Inject constructor(
emptyMap() emptyMap()
} }
return ContinuousMonthUiState.Success( return ContinuousMonthUiState.Success(
today = todayDate, today = today,
monthsByIndex = months, monthsByIndex = months,
weeksByIndex = weeks, weeksByIndex = weeks,
weekStart = weekStart, weekStart = weekStart,
@@ -323,13 +325,20 @@ class MonthViewModel @Inject constructor(
} }
} }
/** Moving the grid to another month restores its full agenda. */ fun goToToday() {
private fun realignSelection() { _month.value = YearMonth(todayDate.year, todayDate.month)
_selectedDate.value = null _selectedDate.value = null
} }
fun goToToday() { /**
_month.value = YearMonth(todayDate.year, todayDate.month) * The date rolled over from [old] to [new]. A paged grid still on [old]'s
* month moves on to [new]'s and drops the day picked yesterday; one browsed
* elsewhere stays put. The scrolling styles only repaint the today marker.
*/
private fun followToday(old: LocalDate, new: LocalDate) {
if (viewStyle.value.isScrolling) return
if (_month.value != YearMonth(old.year, old.month)) return
_month.value = YearMonth(new.year, new.month)
_selectedDate.value = null _selectedDate.value = null
} }
@@ -358,12 +367,13 @@ class MonthViewModel @Inject constructor(
weekStart: DayOfWeek, weekStart: DayOfWeek,
calendars: List<CalendarSource>, calendars: List<CalendarSource>,
instances: List<EventInstance>, instances: List<EventInstance>,
today: LocalDate,
): MonthUiState { ): MonthUiState {
calendarListFailure(calendars)?.let { return MonthUiState.Failure(it) } calendarListFailure(calendars)?.let { return MonthUiState.Failure(it) }
val weeks = layoutMonthWeeks(ym, weekStart, instances, zone) val weeks = layoutMonthWeeks(ym, weekStart, instances, zone)
return MonthUiState.Success( return MonthUiState.Success(
month = ym, month = ym,
today = todayDate, today = today,
weeks = weeks, weeks = weeks,
instancesByDay = instancesByDay(weeks.flatMap { it.days }, instances, zone), instancesByDay = instancesByDay(weeks.flatMap { it.days }, instances, zone),
zone = zone, zone = zone,
@@ -10,17 +10,14 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CloudOff import androidx.compose.material.icons.filled.CloudOff
import androidx.compose.material.icons.filled.FolderOpen import androidx.compose.material.icons.filled.FolderOpen
import androidx.compose.material.icons.filled.Schedule import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.floret.components.BenefitRow import de.jeanlucmakiola.floret.components.BenefitRow
import de.jeanlucmakiola.floret.components.OnboardingPrimaryButton
import de.jeanlucmakiola.floret.components.OnboardingScaffold import de.jeanlucmakiola.floret.components.OnboardingScaffold
import de.jeanlucmakiola.floret.components.OnboardingSpace import de.jeanlucmakiola.floret.components.OnboardingSpace
@@ -53,15 +50,10 @@ internal fun BackupStep(
topSpacing = OnboardingSpace.lg, topSpacing = OnboardingSpace.lg,
hero = { IconHero(Icons.Filled.CloudOff) }, hero = { IconHero(Icons.Filled.CloudOff) },
actions = { actions = {
Button( OnboardingPrimaryButton(
text = stringResource(R.string.onboarding_backup_enable_button),
onClick = { runCatching { pickFolder.launch(null) } }, onClick = { runCatching { pickFolder.launch(null) } },
modifier = Modifier.fillMaxWidth().height(56.dp), )
) {
Text(
text = stringResource(R.string.onboarding_backup_enable_button),
style = MaterialTheme.typography.titleMedium,
)
}
TextButton( TextButton(
onClick = onSkip, onClick = onSkip,
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
@@ -69,20 +61,9 @@ internal fun BackupStep(
Text(stringResource(R.string.onboarding_backup_skip_button)) Text(stringResource(R.string.onboarding_backup_skip_button))
} }
}, },
headline = stringResource(R.string.onboarding_backup_title),
supporting = stringResource(R.string.onboarding_backup_body),
) { ) {
Text(
text = stringResource(R.string.onboarding_backup_title),
style = MaterialTheme.typography.headlineMedium,
textAlign = TextAlign.Center,
)
Spacer(Modifier.height(12.dp))
Text(
text = stringResource(R.string.onboarding_backup_body),
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
)
Spacer(Modifier.height(OnboardingSpace.lg)) Spacer(Modifier.height(OnboardingSpace.lg))
BenefitRow( BenefitRow(
@@ -9,7 +9,6 @@ import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.CloudSync import androidx.compose.material.icons.filled.CloudSync
import androidx.compose.material.icons.filled.PhoneAndroid import androidx.compose.material.icons.filled.PhoneAndroid
import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text import androidx.compose.material3.Text
@@ -30,6 +29,7 @@ import de.jeanlucmakiola.calendula.data.calendar.CalendarColorPalette
import de.jeanlucmakiola.calendula.ui.calendars.CalendarEditor import de.jeanlucmakiola.calendula.ui.calendars.CalendarEditor
import de.jeanlucmakiola.calendula.ui.settings.openUrl import de.jeanlucmakiola.calendula.ui.settings.openUrl
import de.jeanlucmakiola.floret.components.BenefitRow import de.jeanlucmakiola.floret.components.BenefitRow
import de.jeanlucmakiola.floret.components.OnboardingPrimaryButton
import de.jeanlucmakiola.floret.components.OnboardingScaffold import de.jeanlucmakiola.floret.components.OnboardingScaffold
import de.jeanlucmakiola.floret.components.OnboardingSpace import de.jeanlucmakiola.floret.components.OnboardingSpace
@@ -108,18 +108,13 @@ internal fun CalendarsStep(
topSpacing = OnboardingSpace.lg, topSpacing = OnboardingSpace.lg,
hero = { IconHero(Icons.Filled.CalendarMonth) }, hero = { IconHero(Icons.Filled.CalendarMonth) },
actions = { actions = {
Button( OnboardingPrimaryButton(
text = stringResource(R.string.onboarding_calendars_local_button),
onClick = { onClick = {
onClearCreation() onClearCreation()
creating = true creating = true
}, },
modifier = Modifier.fillMaxWidth().height(56.dp), )
) {
Text(
text = stringResource(R.string.onboarding_calendars_local_button),
style = MaterialTheme.typography.titleMedium,
)
}
OutlinedButton( OutlinedButton(
onClick = { openUrl(context, DAVX5_URL) }, onClick = { openUrl(context, DAVX5_URL) },
modifier = Modifier.fillMaxWidth().height(56.dp), modifier = Modifier.fillMaxWidth().height(56.dp),
@@ -133,20 +128,9 @@ internal fun CalendarsStep(
Text(stringResource(R.string.onboarding_calendars_skip_button)) Text(stringResource(R.string.onboarding_calendars_skip_button))
} }
}, },
headline = stringResource(R.string.onboarding_calendars_title),
supporting = stringResource(R.string.onboarding_calendars_body),
) { ) {
Text(
text = stringResource(R.string.onboarding_calendars_title),
style = MaterialTheme.typography.headlineMedium,
textAlign = TextAlign.Center,
)
Spacer(Modifier.height(12.dp))
Text(
text = stringResource(R.string.onboarding_calendars_body),
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
)
if (creation is CalendarCreation.Failed) { if (creation is CalendarCreation.Failed) {
Spacer(Modifier.height(12.dp)) Spacer(Modifier.height(12.dp))
Text( Text(
@@ -189,30 +173,14 @@ private fun CalendarCreated(
topSpacing = OnboardingSpace.lg, topSpacing = OnboardingSpace.lg,
hero = { IconHero(Icons.Filled.CheckCircle) }, hero = { IconHero(Icons.Filled.CheckCircle) },
actions = { actions = {
Button( OnboardingPrimaryButton(
text = stringResource(R.string.onboarding_calendars_created_continue),
onClick = onContinue, onClick = onContinue,
modifier = Modifier.fillMaxWidth().height(56.dp), )
) {
Text(
text = stringResource(R.string.onboarding_calendars_created_continue),
style = MaterialTheme.typography.titleMedium,
)
}
}, },
headline = stringResource(R.string.onboarding_calendars_created_title, name),
supporting = stringResource(R.string.onboarding_calendars_created_body),
) { ) {
Text(
text = stringResource(R.string.onboarding_calendars_created_title, name),
style = MaterialTheme.typography.headlineMedium,
textAlign = TextAlign.Center,
)
Spacer(Modifier.height(12.dp))
Text(
text = stringResource(R.string.onboarding_calendars_created_body),
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
)
Spacer(Modifier.height(OnboardingSpace.lg)) Spacer(Modifier.height(OnboardingSpace.lg))
BenefitRow( BenefitRow(
@@ -1,17 +1,10 @@
package de.jeanlucmakiola.calendula.ui.onboarding package de.jeanlucmakiola.calendula.ui.onboarding
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.floret.components.OnboardingPrimaryButton
import de.jeanlucmakiola.floret.components.OnboardingScaffold import de.jeanlucmakiola.floret.components.OnboardingScaffold
import de.jeanlucmakiola.floret.components.OnboardingSpace import de.jeanlucmakiola.floret.components.OnboardingSpace
@@ -34,28 +27,12 @@ internal fun DoneStep(
topSpacing = OnboardingSpace.lg, topSpacing = OnboardingSpace.lg,
hero = { BrandHero(HeroBadge.Done) }, hero = { BrandHero(HeroBadge.Done) },
actions = { actions = {
Button( OnboardingPrimaryButton(
text = stringResource(R.string.onboarding_done_button),
onClick = onFinished, onClick = onFinished,
modifier = Modifier.fillMaxWidth().height(56.dp), )
) {
Text(
text = stringResource(R.string.onboarding_done_button),
style = MaterialTheme.typography.titleMedium,
)
}
}, },
) { headline = stringResource(R.string.onboarding_done_title),
Text( supporting = stringResource(R.string.onboarding_done_body),
text = stringResource(R.string.onboarding_done_title), )
style = MaterialTheme.typography.headlineMedium,
textAlign = TextAlign.Center,
)
Spacer(Modifier.height(12.dp))
Text(
text = stringResource(R.string.onboarding_done_body),
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
)
}
} }
@@ -7,7 +7,6 @@ import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.VisibilityOff import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch import androidx.compose.material3.Switch
import androidx.compose.material3.Text import androidx.compose.material3.Text
@@ -25,6 +24,7 @@ import de.jeanlucmakiola.calendula.domain.hasVisibilitySwitch
import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip
import de.jeanlucmakiola.floret.components.GroupedListInset import de.jeanlucmakiola.floret.components.GroupedListInset
import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.GroupedRow
import de.jeanlucmakiola.floret.components.OnboardingPrimaryButton
import de.jeanlucmakiola.floret.components.OnboardingScaffold import de.jeanlucmakiola.floret.components.OnboardingScaffold
import de.jeanlucmakiola.floret.components.OnboardingSpace import de.jeanlucmakiola.floret.components.OnboardingSpace
import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.Position
@@ -65,24 +65,17 @@ internal fun HiddenCalendarsStep(
scrollingActions = true, scrollingActions = true,
hero = { IconHero(Icons.Filled.VisibilityOff) }, hero = { IconHero(Icons.Filled.VisibilityOff) },
actions = { actions = {
Button( OnboardingPrimaryButton(
text = stringResource(
if (anyVisible) {
R.string.onboarding_view_continue_button
} else {
R.string.onboarding_hidden_switch_all_button
},
),
onClick = if (anyVisible) onFinished else onSwitchAllOn, onClick = if (anyVisible) onFinished else onSwitchAllOn,
modifier = Modifier modifier = Modifier.padding(horizontal = GroupedListInset),
.padding(horizontal = GroupedListInset) )
.fillMaxWidth()
.height(56.dp),
) {
Text(
text = stringResource(
if (anyVisible) {
R.string.onboarding_view_continue_button
} else {
R.string.onboarding_hidden_switch_all_button
},
),
style = MaterialTheme.typography.titleMedium,
)
}
// Only while nothing is on: once something is, the step has been // Only while nothing is on: once something is, the step has been
// answered and the one button left to press says so. // answered and the one button left to press says so.
if (!anyVisible) { if (!anyVisible) {
@@ -10,7 +10,6 @@ import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.calendula.data.backup.BackupScheduler import de.jeanlucmakiola.calendula.data.backup.BackupScheduler
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
import de.jeanlucmakiola.calendula.data.calendar.CalendarVisibilityReconciler import de.jeanlucmakiola.calendula.data.calendar.CalendarVisibilityReconciler
import de.jeanlucmakiola.calendula.data.di.IoDispatcher
import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.data.prefs.WeekStartPref import de.jeanlucmakiola.calendula.data.prefs.WeekStartPref
@@ -20,6 +19,8 @@ import de.jeanlucmakiola.calendula.domain.hasVisibilitySwitch
import de.jeanlucmakiola.calendula.domain.orderedForManager import de.jeanlucmakiola.calendula.domain.orderedForManager
import de.jeanlucmakiola.calendula.ui.common.CalendarView import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.month.MonthViewStyle import de.jeanlucmakiola.calendula.ui.month.MonthViewStyle
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
import de.jeanlucmakiola.floret.di.IoDispatcher
import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
@@ -92,9 +93,8 @@ class OnboardingViewModel @Inject constructor(
list.catch { emit(null) }.flowOn(io) list.catch { emit(null) }.flowOn(io)
} }
} }
.stateIn( .stateWhileSubscribed(
scope = viewModelScope, scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = null, initialValue = null,
) )
@@ -183,9 +183,8 @@ class OnboardingViewModel @Inject constructor(
*/ */
val hiddenCalendars: StateFlow<List<CalendarSource>> = calendars val hiddenCalendars: StateFlow<List<CalendarSource>> = calendars
.map { it.orEmpty().orderedForManager() } .map { it.orEmpty().orderedForManager() }
.stateIn( .stateWhileSubscribed(
scope = viewModelScope, scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = emptyList(), initialValue = emptyList(),
) )
@@ -232,9 +231,8 @@ class OnboardingViewModel @Inject constructor(
doneShown = closing.doneShown, doneShown = closing.doneShown,
) )
} }
}.stateIn( }.stateWhileSubscribed(
scope = viewModelScope, scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = null, initialValue = null,
) )
@@ -244,9 +242,8 @@ class OnboardingViewModel @Inject constructor(
prefs.monthViewStyle, prefs.monthViewStyle,
prefs.weekStart, prefs.weekStart,
::ViewChoice, ::ViewChoice,
).stateIn( ).stateWhileSubscribed(
scope = viewModelScope, scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000L),
initialValue = null, initialValue = null,
) )
@@ -1,6 +1,7 @@
package de.jeanlucmakiola.calendula.ui.onboarding package de.jeanlucmakiola.calendula.ui.onboarding
import de.jeanlucmakiola.floret.components.BenefitRow import de.jeanlucmakiola.floret.components.BenefitRow
import de.jeanlucmakiola.floret.components.OnboardingPrimaryButton
import de.jeanlucmakiola.floret.components.OnboardingScaffold import de.jeanlucmakiola.floret.components.OnboardingScaffold
import de.jeanlucmakiola.floret.components.OnboardingSpace import de.jeanlucmakiola.floret.components.OnboardingSpace
@@ -13,28 +14,20 @@ import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowForward import androidx.compose.material.icons.automirrored.filled.ArrowForward
import androidx.compose.material.icons.filled.CalendarMonth import androidx.compose.material.icons.filled.CalendarMonth
import androidx.compose.material.icons.filled.Lock import androidx.compose.material.icons.filled.Lock
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.R
private val CALENDAR_PERMISSIONS = arrayOf( private val CALENDAR_PERMISSIONS = arrayOf(
@@ -47,9 +40,8 @@ fun PermissionScreen(
onGranted: () -> Unit, onGranted: () -> Unit,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
progress: (@Composable () -> Unit)? = null, progress: (@Composable () -> Unit)? = null,
viewModel: PermissionViewModel = hiltViewModel(),
) { ) {
val state by viewModel.state.collectAsStateWithLifecycle() var denied by rememberSaveable { mutableStateOf(false) }
// READ and WRITE are requested together (one system dialog — same // READ and WRITE are requested together (one system dialog — same
// permission group), but only READ gates the app: declining write keeps // permission group), but only READ gates the app: declining write keeps
@@ -58,33 +50,27 @@ fun PermissionScreen(
contract = ActivityResultContracts.RequestMultiplePermissions(), contract = ActivityResultContracts.RequestMultiplePermissions(),
) { results -> ) { results ->
if (results[Manifest.permission.READ_CALENDAR] == true) { if (results[Manifest.permission.READ_CALENDAR] == true) {
viewModel.onGranted() onGranted()
} else { } else {
viewModel.onDenied() denied = true
} }
} }
LaunchedEffect(state) { if (denied) {
if (state == PermissionUiState.Granted) onGranted() DeniedContent(
}
when (state) {
is PermissionUiState.Rationale -> RationaleContent(
onRequest = { launcher.launch(CALENDAR_PERMISSIONS) },
progress = progress,
modifier = modifier,
)
is PermissionUiState.Denied -> DeniedContent(
onRetry = { onRetry = {
viewModel.onRetry() denied = false
launcher.launch(CALENDAR_PERMISSIONS) launcher.launch(CALENDAR_PERMISSIONS)
}, },
progress = progress, progress = progress,
modifier = modifier, modifier = modifier,
) )
is PermissionUiState.Granted -> { } else {
// Transient — LaunchedEffect above fires and parent replaces us. RationaleContent(
} onRequest = { launcher.launch(CALENDAR_PERMISSIONS) },
progress = progress,
modifier = modifier,
)
} }
} }
@@ -100,37 +86,15 @@ private fun RationaleContent(
topSpacing = OnboardingSpace.lg, topSpacing = OnboardingSpace.lg,
hero = { BrandHero() }, hero = { BrandHero() },
actions = { actions = {
Button( OnboardingPrimaryButton(
text = stringResource(R.string.permission_request_button),
onClick = onRequest, onClick = onRequest,
modifier = Modifier.fillMaxWidth().height(56.dp), trailingIcon = Icons.AutoMirrored.Filled.ArrowForward,
contentPadding = ButtonDefaults.ButtonWithIconContentPadding, )
) {
Text(
text = stringResource(R.string.permission_request_button),
style = MaterialTheme.typography.titleMedium,
)
Spacer(Modifier.width(OnboardingSpace.xs))
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowForward,
contentDescription = null,
modifier = Modifier.size(20.dp),
)
}
}, },
headline = stringResource(R.string.permission_rationale_title),
supporting = stringResource(R.string.permission_rationale_body),
) { ) {
Text(
text = stringResource(R.string.permission_rationale_title),
style = MaterialTheme.typography.headlineMedium,
textAlign = TextAlign.Center,
)
Spacer(Modifier.height(12.dp))
Text(
text = stringResource(R.string.permission_rationale_body),
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
)
Spacer(Modifier.height(OnboardingSpace.lg)) Spacer(Modifier.height(OnboardingSpace.lg))
BenefitRow( BenefitRow(
@@ -159,7 +123,8 @@ private fun DeniedContent(
progress = progress, progress = progress,
hero = { BrandHero(HeroBadge.Denied) }, hero = { BrandHero(HeroBadge.Denied) },
actions = { actions = {
Button( OnboardingPrimaryButton(
text = stringResource(R.string.permission_open_settings_button),
onClick = { onClick = {
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply { val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
data = Uri.fromParts("package", context.packageName, null) data = Uri.fromParts("package", context.packageName, null)
@@ -167,13 +132,7 @@ private fun DeniedContent(
} }
context.startActivity(intent) context.startActivity(intent)
}, },
modifier = Modifier.fillMaxWidth().height(56.dp), )
) {
Text(
text = stringResource(R.string.permission_open_settings_button),
style = MaterialTheme.typography.titleMedium,
)
}
TextButton( TextButton(
onClick = onRetry, onClick = onRetry,
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
@@ -181,18 +140,7 @@ private fun DeniedContent(
Text(stringResource(R.string.permission_retry_button)) Text(stringResource(R.string.permission_retry_button))
} }
}, },
) { headline = stringResource(R.string.permission_denied_title),
Text( supporting = stringResource(R.string.permission_denied_body),
text = stringResource(R.string.permission_denied_title), )
style = MaterialTheme.typography.headlineMedium,
textAlign = TextAlign.Center,
)
Spacer(Modifier.height(12.dp))
Text(
text = stringResource(R.string.permission_denied_body),
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
)
}
} }
@@ -1,7 +0,0 @@
package de.jeanlucmakiola.calendula.ui.onboarding
sealed interface PermissionUiState {
data object Rationale : PermissionUiState
data object Denied : PermissionUiState
data object Granted : PermissionUiState
}
@@ -1,29 +0,0 @@
package de.jeanlucmakiola.calendula.ui.onboarding
import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import javax.inject.Inject
@HiltViewModel
class PermissionViewModel @Inject constructor() : ViewModel() {
private val _state = MutableStateFlow<PermissionUiState>(PermissionUiState.Rationale)
val state: StateFlow<PermissionUiState> = _state.asStateFlow()
// The visibility reconcile a grant owes (#75) hangs off RootScreen, which
// also catches grants made outside the app.
fun onGranted() {
_state.value = PermissionUiState.Granted
}
fun onDenied() {
_state.value = PermissionUiState.Denied
}
fun onRetry() {
_state.value = PermissionUiState.Rationale
}
}
@@ -1,6 +1,7 @@
package de.jeanlucmakiola.calendula.ui.onboarding package de.jeanlucmakiola.calendula.ui.onboarding
import de.jeanlucmakiola.floret.components.BenefitRow import de.jeanlucmakiola.floret.components.BenefitRow
import de.jeanlucmakiola.floret.components.OnboardingPrimaryButton
import de.jeanlucmakiola.floret.components.OnboardingScaffold import de.jeanlucmakiola.floret.components.OnboardingScaffold
import de.jeanlucmakiola.floret.components.OnboardingSpace import de.jeanlucmakiola.floret.components.OnboardingSpace
@@ -14,15 +15,11 @@ import androidx.compose.foundation.layout.height
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.NotificationsActive import androidx.compose.material.icons.filled.NotificationsActive
import androidx.compose.material.icons.filled.ContentCopy import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.R
/** /**
@@ -53,7 +50,8 @@ fun ReminderStep(
topSpacing = OnboardingSpace.lg, topSpacing = OnboardingSpace.lg,
hero = { IconHero(Icons.Filled.NotificationsActive) }, hero = { IconHero(Icons.Filled.NotificationsActive) },
actions = { actions = {
Button( OnboardingPrimaryButton(
text = stringResource(R.string.reminder_onboarding_enable_button),
onClick = { onClick = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
launcher.launch(Manifest.permission.POST_NOTIFICATIONS) launcher.launch(Manifest.permission.POST_NOTIFICATIONS)
@@ -61,13 +59,7 @@ fun ReminderStep(
onFinished(true) onFinished(true)
} }
}, },
modifier = Modifier.fillMaxWidth().height(56.dp), )
) {
Text(
text = stringResource(R.string.reminder_onboarding_enable_button),
style = MaterialTheme.typography.titleMedium,
)
}
TextButton( TextButton(
onClick = { onFinished(false) }, onClick = { onFinished(false) },
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
@@ -75,20 +67,9 @@ fun ReminderStep(
Text(stringResource(R.string.reminder_onboarding_skip_button)) Text(stringResource(R.string.reminder_onboarding_skip_button))
} }
}, },
headline = stringResource(R.string.reminder_onboarding_title),
supporting = stringResource(R.string.reminder_onboarding_body),
) { ) {
Text(
text = stringResource(R.string.reminder_onboarding_title),
style = MaterialTheme.typography.headlineMedium,
textAlign = TextAlign.Center,
)
Spacer(Modifier.height(12.dp))
Text(
text = stringResource(R.string.reminder_onboarding_body),
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
)
Spacer(Modifier.height(OnboardingSpace.lg)) Spacer(Modifier.height(OnboardingSpace.lg))
BenefitRow( BenefitRow(

Some files were not shown because too many files have changed in this diff Show More