Compare commits
109
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
754745586d | ||
|
|
1a1df07dc3 | ||
|
|
75315d92a7 | ||
|
|
e9cf7d66ba | ||
|
|
e01d6efb84 | ||
|
|
b7c801c8db | ||
|
|
b15e90cc64 | ||
|
|
8d3be6aba3 | ||
|
|
464ae8952e | ||
|
|
2007541adf | ||
|
|
d6167617a9 | ||
|
|
38d7c1494d | ||
|
|
c0c0d56e86 | ||
|
|
745301d14b | ||
|
|
8d640b595e | ||
|
|
1925e1c2f4 | ||
|
|
0595124ecd | ||
|
|
8e3202d1ad | ||
|
|
5f8eb39206 | ||
|
|
95ad3a30cf | ||
|
|
8ce4831efa | ||
|
|
e7bf700f36 | ||
|
|
c10342818a | ||
|
|
0f29dc4db6 | ||
|
|
80fae240da | ||
|
|
ab2e11a2e4 | ||
|
|
fb4fd17603 | ||
|
|
86f7637213 | ||
|
|
c5084b86af | ||
|
|
919b95c378 | ||
|
|
ec7db10601 | ||
|
|
73403ee799 | ||
|
|
a294542eda | ||
|
|
786bde2965 | ||
|
|
e2ac8bbdc7 | ||
|
|
673cfc2f99 | ||
|
|
c533cc0439 | ||
|
|
7a49dffe0d | ||
|
|
e6ab85d382 | ||
|
|
011356e103 | ||
|
|
c8595ccedd | ||
|
|
9e1fd2956d | ||
|
|
6a1697dc5a | ||
|
|
2641145b60 | ||
|
|
70a7bf1033 | ||
|
|
a92dd013bc | ||
|
|
6d6baf3f35 | ||
|
|
72f2b33754 | ||
|
|
89a456f88c | ||
|
|
d98d995326 | ||
|
|
20a76f1921 | ||
|
|
0c4a7992a7 | ||
|
|
5e6b88fa31 | ||
|
|
d8735cc738 | ||
|
|
185671adb5 | ||
|
|
ee268444b7 | ||
|
|
9387bdc1ee | ||
|
|
7cfdb43f37 | ||
|
|
06f658917f | ||
|
|
88d5614158 | ||
|
|
f896153fb7 | ||
|
|
1004356e75 | ||
|
|
77b0c6db09 | ||
|
|
dec2d1cb05 | ||
|
|
76314aebbd | ||
|
|
7d149d2ab1 | ||
|
|
ff4082d5df | ||
|
|
51f58e76b2 | ||
|
|
347ce74808 | ||
|
|
726dbbbaf3 | ||
|
|
fb434f3f15 | ||
|
|
aacd86cebe | ||
|
|
bd3b4605cb | ||
|
|
f267744c1c | ||
|
|
fffb033e39 | ||
|
|
f574f039f5 | ||
|
|
506ebdb092 | ||
|
+3 |
9ccc303a2a | ||
|
|
a5c4a73de1 | ||
|
|
dbd5ce6700 | ||
|
|
068a96b228 | ||
|
|
7c522c5903 | ||
|
|
6ef516fe4d | ||
|
|
9a7d65be6b | ||
|
|
c2aae1629f | ||
|
|
a697803e29 | ||
|
|
f4b6cb3acb | ||
|
|
c3f3eb83f2 | ||
|
|
5d10f773ca | ||
|
|
b2fcc55018 | ||
|
|
10414fcf05 | ||
|
|
49f604bdc2 | ||
|
|
56763f58da | ||
|
|
af34f014a7 | ||
|
|
3280191309 | ||
|
|
76cdc1c535 | ||
|
|
68c0a262fa | ||
|
|
39e13e86d2 | ||
|
|
1cc7f40f7e | ||
|
|
8a15325fdc | ||
|
|
7f977971ed | ||
|
|
632155c016 | ||
|
|
8834884d4e | ||
|
|
236372d740 | ||
|
|
678a526cb9 | ||
|
|
84fd51baf6 | ||
|
|
450b8b0107 | ||
|
|
8078fb4f10 | ||
|
|
46b88cc03e |
No files matched your search
@@ -318,13 +318,16 @@ jobs:
|
|||||||
# not provide node inside custom job containers, so JavaScript actions
|
# not provide node inside custom job containers, so JavaScript actions
|
||||||
# (checkout, download-artifact) can't run there. The Renovate job gets away
|
# (checkout, download-artifact) can't run there. The Renovate job gets away
|
||||||
# with a container because its only step is a shell command. Ruby is installed
|
# with a container because its only step is a shell command. Ruby is installed
|
||||||
# the same way sshpass, jq and fdroidserver are in the job above.
|
# the same way sshpass, jq and fdroidserver are in the job above, from trixie:
|
||||||
|
# fastlane >= 2.241 needs Ruby 3.2+, and bookworm's apt only has 3.1.
|
||||||
play:
|
play:
|
||||||
needs: [detect, release]
|
needs: [detect, release]
|
||||||
# workflow_dispatch is the F-Droid re-sign recovery path — it must never
|
# workflow_dispatch is the F-Droid re-sign recovery path — it must never
|
||||||
# touch Play, so gate on a real release only.
|
# touch Play, so gate on a real release only.
|
||||||
if: needs.detect.outputs.is_release == 'true'
|
if: needs.detect.outputs.is_release == 'true'
|
||||||
runs-on: docker
|
runs-on: docker
|
||||||
|
container:
|
||||||
|
image: node:22-trixie
|
||||||
env:
|
env:
|
||||||
VERSION: ${{ needs.detect.outputs.version }}
|
VERSION: ${{ needs.detect.outputs.version }}
|
||||||
VERSION_CODE: ${{ needs.detect.outputs.version_code }}
|
VERSION_CODE: ${{ needs.detect.outputs.version_code }}
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ jobs:
|
|||||||
# directly drops the docker-in-docker requirement entirely.
|
# directly drops the docker-in-docker requirement entirely.
|
||||||
# Full tag pinned; Renovate's github-actions manager keeps it bumped.
|
# Full tag pinned; Renovate's github-actions manager keeps it bumped.
|
||||||
container:
|
container:
|
||||||
image: ghcr.io/renovatebot/renovate:43.232.0
|
image: ghcr.io/renovatebot/renovate:44.237.3
|
||||||
steps:
|
steps:
|
||||||
- name: Run Renovate
|
- name: Run Renovate
|
||||||
run: renovate
|
run: renovate
|
||||||
|
|||||||
+112
-1
@@ -7,8 +7,76 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [2.24.2] — 2026-11-13
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **Quick moves no longer get lost.** Dropping an event while an earlier move was still saving used to snap it back without a word. Drops now wait in line and are saved in order, and a moved event stays where you dropped it until the calendar shows it there. If an event changed before a drop could be saved, or the line is full, a message says so instead ([#494]).
|
||||||
|
- **Undo after a run of moves** keeps the first move's Undo, and each failed move gets its own message rather than replacing the last one ([#494]).
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **The day view's title names the month**, like the week and 3-day views. Weekday and date already sit in the column header below it ([#501]).
|
||||||
|
- Library updates (kotlinx-datetime, AppCompat).
|
||||||
|
|
||||||
|
## [2.24.1] — 2026-11-12
|
||||||
|
|
||||||
### Added
|
### 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]).
|
- **A classic style for the agenda widget.** Its settings now have a Style option: Cards keeps the new look, Classic brings back the 2.23 layout with a line per day and a colour stripe beside each event, under the current header. Dates in another year show the year. Classic has an Invert text colour switch, so its text stays readable on light and dark wallpapers ([#489]).
|
||||||
|
- **Widget opacity.** Every widget with a Solid or Tinted background has an Opacity slider from 20 to 100%. Below 50%, the card-style widgets back their content like a Transparent widget so it stays readable ([#489]).
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **Week numbers match your region.** With weeks starting on Sunday, the month and week views showed every week number one too low. Rows are now numbered by your region's rules, so ISO regions such as Germany are unchanged ([#493]).
|
||||||
|
- **The month widget shows events at every height.** At some sizes a week row had room for a little more than the date but not a full line of events, and drew none. It now fits a slimmer line there, and a row with a single line shows "+N" on days with more events than fit ([#491]).
|
||||||
|
- **Dimmed past events in dark widgets are readable again.** They used to turn pastel with white text on top ([#475]).
|
||||||
|
- **A widget set to Light or Dark matches the system colours.** With Material You, the + button and today's date could look different from a widget that follows the app ([#475]).
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **Fewer permissions.** Calendula no longer asks for network state, wake lock or foreground service access, which a library added without the app needing them ([#448]).
|
||||||
|
- Translation updates from [Calendula's Weblate](https://weblate.dev.jeanlucmakiola.de/projects/calendula/).
|
||||||
|
|
||||||
|
## [2.24.0] — 2026-11-06
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **Six new home-screen widgets.** Quick add (1×1) opens a new event on today with the same defaults as the app's + button ([#435]). Date (1×1) shows today's weekday and day number on a rounded shape and opens today ([#376]). Week strip (4×1) shows this week's days with a dot in each event's colour and today filled ([#436]). Upcoming (2×2) shows today's date over your next events, as many as fit ([#437]). Today lists today's events; once they're over it says "Nothing left today" and shows tomorrow's first one or two ([#438]). Countdown counts down to your next timed event, or to an event or series you pick, like a holiday in 12 days ([#439]).
|
||||||
|
- **A month and day widget.** A compact month grid sits beside the events of one day. Tap a day in the grid to see its events, and tap the list to open that day in the app ([#441]).
|
||||||
|
- **Each widget has its own settings.** Placing a widget, or long-pressing it and choosing Edit, opens a settings screen with a live preview. Pick a solid, tinted or transparent background, a light or dark theme or the app's, and which calendars it shows. Widgets that list events also have their time range, text size and how past events look. Settings → Widgets lists the widgets on your home screen so you can change them from there. These options used to be shared by all widgets; widgets you already placed keep what you had set ([#292]).
|
||||||
|
- **Turn off start times in the month view.** Settings → Views → Month → Start times hides the time in front of event titles, so narrow fonts keep more of the title. With it on, the time now only shows when the whole title, or at least its first 12 characters, still fits beside it ([#476]).
|
||||||
|
- **Drag all-day events.** In the day, 3-day and week views, long-press an event in the all-day strip and move it sideways to another day, or down into the grid to turn it into a timed event ([#296]).
|
||||||
|
- **Traditional Chinese**, started as a community translation through [Calendula's Weblate](https://weblate.dev.jeanlucmakiola.de/projects/calendula/). It covers only a few screens so far, so the rest still shows in English until it fills out. Pick it under Settings → Language. Thanks to AventineC.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **The agenda and month widgets have a new look.** The agenda puts each day in its own card, with a round date pill beside the first event and today's pill filled. The month widget has rounded day cells, weekday pills, shaded days outside the month and a + for a new event. The agenda's refresh button is gone, since widgets now update on their own ([#71], [#90]).
|
||||||
|
- **Tapping a day in the month widget opens that day,** wherever in its cell you tap ([#386]).
|
||||||
|
- **The widget picker shows what each widget looks like.** On Android 15 and later the previews are the real widgets with sample events, in your language and colours; on older versions they are redrawn to match.
|
||||||
|
- **Widgets are listed by their name alone,** without "Calendula" in front, and each has a short description in the picker ([#71]).
|
||||||
|
- **Past events in widgets stay readable when dimmed.** Their background fades further and their text less ([#90]).
|
||||||
|
- **Events from midnight to midnight show as all-day events.** A timed event that starts and ends at midnight now sits in the all-day strip, shows as "All day" in the agenda and widgets, and its reminder names the day instead of 00:00 – 00:00. The event itself stays as it was saved ([#296]).
|
||||||
|
- **Cancelled and tentative events are marked.** Cancelled events are struck through and listed last, like declined invites, and tentative ones get the outline used for unanswered invites. Cancelled one-off events and series no longer disappear ([#388]).
|
||||||
|
- **One notification per event.** An event with several reminders now keeps a single notification, which each later reminder updates in place ([#463]).
|
||||||
|
- **Go further back and forward in time.** Every view and the date picker now reach from 1600 to 2399 ([#457]).
|
||||||
|
- **The split month agenda only lists days with events.** In other months it no longer starts with an empty 1st, and a month with nothing in it says so in one row ([#142]).
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **Widgets show your changes straight away.** After you added, edited or deleted an event, a widget could keep showing the old events until something else redrew it ([#420], [#229]).
|
||||||
|
- **Widgets follow the app's language.** After you picked a language in Settings, widgets kept the old one until something redrew them ([#90]).
|
||||||
|
- **The month widget handles busy months.** It could show "Can't show content", or only one or two events per day. Each day now shows as many events as its height fits, and the rest fold into +N ([#372]).
|
||||||
|
- **Short events late in the day are fully visible.** An event like 23:58–23:59 used to be cut down to a sliver at the bottom of the day, week and 3-day views. It now keeps its usual minimum height and sits flush against midnight ([#483]).
|
||||||
|
- **The month view no longer crashes after going before 1900** in the day or week view ([#457]).
|
||||||
|
- **Month pages keep updating.** After a small swipe that snapped back, a month page could stop showing new or edited events, and opening an event from the split view could show its old times ([#440], [#454]).
|
||||||
|
- **Smoother expand and collapse in the split month view.** The day cells morph cleanly between the two layouts, and week numbers now animate along with them ([#473]).
|
||||||
|
- **Back clears the selected day in the split month view.** With a day picked, the back gesture used to close the app; it now goes back to the whole month's agenda first ([#142]).
|
||||||
|
|
||||||
|
## [2.23.1] — 2026-10-28
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **The split month view fits more events.** With a day selected, its date is no longer shown twice: the filter chip now stands in for the day's header. Tapping the chip opens the day, and its ✕ clears the filter. The day headers in the month agenda below the grid take less room too ([#142]).
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **Event dots in the split month grid stay in place on busy days.** A day with a "+N" next to its dots used to push them further down the cell ([#142]).
|
||||||
|
|
||||||
|
## [2.23.0] — 2026-10-21
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **Long press an event to select it.** In the day, 3-day and week views, a long press lifts the event and selects it. Keep your finger down and move to drag it straight away. A selected event has handles at its top and bottom: drag them to change when it starts or ends, in 15-minute steps and across midnight if you want. The bar at the top edits, duplicates, shares or deletes it, and tapping elsewhere or going back deselects it. The bar shows the new times while you move or resize. Read-only events can be selected but not moved or resized ([#141]).
|
||||||
- **Long press an empty slot to draft an event.** In the day, 3-day and week views, a long press on free time drops a block of your default event length there. Move it while still holding, or let go and drag it or its handles into place, then tap the tick to open a new event at that time. The ✕, a tap elsewhere or going back throws the draft away ([#153]).
|
- **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]).
|
- **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]).
|
- **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]).
|
||||||
@@ -16,12 +84,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
- **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]).
|
- **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]).
|
- **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]).
|
- **A black theme for AMOLED screens.** Settings → Appearance → Theme now has Black next to System, Light and Dark. It's the dark theme with pure black backgrounds, which saves battery on AMOLED screens and makes event colours stand out more. Day cells and the hour grid stay a shade above black so the grid lines still show, and sheets and menus still stand out from the page. It works with Material You colours too. The home-screen widgets aren't affected ([#181]).
|
||||||
|
- **Donate through Liberapay.** Settings → Support development now offers Liberapay for recurring donations next to Ko-fi for one-off tips.
|
||||||
|
- **More haptic feedback.** Swiping between days in the split month pane ticks, and dropping a moved or resized event gives a short buzz ([#116]).
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **The editor says Create for a new event.** New events, duplicates, shared text, imported .ics files and long-press drafts show Create instead of Save, so a duplicate no longer looks like you're editing the original ([#141]).
|
||||||
|
|
||||||
### Fixed
|
### 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]).
|
- **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]).
|
- **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]).
|
- **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]).
|
- **Multi-day events dim on the days already behind you.** With past events dimmed, an event running over several days stayed at full strength on its earlier days until it ended. Those days now dim in the agenda, month, week and day views ([#367]).
|
||||||
|
- **Moving a recurring event to another calendar keeps the occurrences you changed.** Deleted occurrences used to come back after the move, and edited ones showed up twice. They now stay deleted or edited, and keep their colour.
|
||||||
|
- **Sharing an .ics file to Calendula opens the import,** even when the email app adds a subject line as text.
|
||||||
|
- **Rotating the phone no longer throws away an open import, duplicate or picker.**
|
||||||
|
- **The repeat-until date picker opens on today.** Near midnight it used to open on yesterday or tomorrow.
|
||||||
|
- **Tap ripples on week numbers, split-view day cells and the split-view handle stay inside their rounded shape** ([#413]).
|
||||||
|
- **The export calendar picker previews the back gesture** like the other full-screen pickers.
|
||||||
|
|
||||||
## [2.22.5] — 2026-10-07
|
## [2.22.5] — 2026-10-07
|
||||||
|
|
||||||
@@ -1826,6 +1905,7 @@ automatically, with zero telemetry and no internet permission.
|
|||||||
[#146]: https://codeberg.org/jlmakiola/calendula/issues/146
|
[#146]: https://codeberg.org/jlmakiola/calendula/issues/146
|
||||||
[#267]: https://codeberg.org/jlmakiola/calendula/issues/267
|
[#267]: https://codeberg.org/jlmakiola/calendula/issues/267
|
||||||
[#239]: https://codeberg.org/jlmakiola/calendula/issues/239
|
[#239]: https://codeberg.org/jlmakiola/calendula/issues/239
|
||||||
|
[#296]: https://codeberg.org/jlmakiola/calendula/issues/296
|
||||||
[#297]: https://codeberg.org/jlmakiola/calendula/issues/297
|
[#297]: https://codeberg.org/jlmakiola/calendula/issues/297
|
||||||
[#298]: https://codeberg.org/jlmakiola/calendula/issues/298
|
[#298]: https://codeberg.org/jlmakiola/calendula/issues/298
|
||||||
[#309]: https://codeberg.org/jlmakiola/calendula/issues/309
|
[#309]: https://codeberg.org/jlmakiola/calendula/issues/309
|
||||||
@@ -1874,3 +1954,34 @@ automatically, with zero telemetry and no internet permission.
|
|||||||
[#181]: https://codeberg.org/jlmakiola/calendula/issues/181
|
[#181]: https://codeberg.org/jlmakiola/calendula/issues/181
|
||||||
[#306]: https://codeberg.org/jlmakiola/calendula/issues/306
|
[#306]: https://codeberg.org/jlmakiola/calendula/issues/306
|
||||||
[#178]: https://codeberg.org/jlmakiola/calendula/issues/178
|
[#178]: https://codeberg.org/jlmakiola/calendula/issues/178
|
||||||
|
[#116]: https://codeberg.org/jlmakiola/calendula/issues/116
|
||||||
|
[#388]: https://codeberg.org/jlmakiola/calendula/issues/388
|
||||||
|
[#413]: https://codeberg.org/jlmakiola/calendula/issues/413
|
||||||
|
[#71]: https://codeberg.org/jlmakiola/calendula/issues/71
|
||||||
|
[#90]: https://codeberg.org/jlmakiola/calendula/issues/90
|
||||||
|
[#229]: https://codeberg.org/jlmakiola/calendula/issues/229
|
||||||
|
[#292]: https://codeberg.org/jlmakiola/calendula/issues/292
|
||||||
|
[#372]: https://codeberg.org/jlmakiola/calendula/issues/372
|
||||||
|
[#376]: https://codeberg.org/jlmakiola/calendula/issues/376
|
||||||
|
[#386]: https://codeberg.org/jlmakiola/calendula/issues/386
|
||||||
|
[#420]: https://codeberg.org/jlmakiola/calendula/issues/420
|
||||||
|
[#435]: https://codeberg.org/jlmakiola/calendula/issues/435
|
||||||
|
[#436]: https://codeberg.org/jlmakiola/calendula/issues/436
|
||||||
|
[#437]: https://codeberg.org/jlmakiola/calendula/issues/437
|
||||||
|
[#438]: https://codeberg.org/jlmakiola/calendula/issues/438
|
||||||
|
[#439]: https://codeberg.org/jlmakiola/calendula/issues/439
|
||||||
|
[#440]: https://codeberg.org/jlmakiola/calendula/issues/440
|
||||||
|
[#441]: https://codeberg.org/jlmakiola/calendula/issues/441
|
||||||
|
[#454]: https://codeberg.org/jlmakiola/calendula/issues/454
|
||||||
|
[#457]: https://codeberg.org/jlmakiola/calendula/issues/457
|
||||||
|
[#463]: https://codeberg.org/jlmakiola/calendula/issues/463
|
||||||
|
[#473]: https://codeberg.org/jlmakiola/calendula/issues/473
|
||||||
|
[#476]: https://codeberg.org/jlmakiola/calendula/issues/476
|
||||||
|
[#483]: https://codeberg.org/jlmakiola/calendula/issues/483
|
||||||
|
[#448]: https://codeberg.org/jlmakiola/calendula/issues/448
|
||||||
|
[#475]: https://codeberg.org/jlmakiola/calendula/issues/475
|
||||||
|
[#489]: https://codeberg.org/jlmakiola/calendula/issues/489
|
||||||
|
[#491]: https://codeberg.org/jlmakiola/calendula/issues/491
|
||||||
|
[#493]: https://codeberg.org/jlmakiola/calendula/issues/493
|
||||||
|
[#494]: https://codeberg.org/jlmakiola/calendula/issues/494
|
||||||
|
[#501]: https://codeberg.org/jlmakiola/calendula/issues/501
|
||||||
@@ -7,4 +7,4 @@ source "https://rubygems.org"
|
|||||||
# Pinned exactly; Renovate's bundler manager keeps it bumped. No Gemfile.lock is
|
# Pinned exactly; Renovate's bundler manager keeps it bumped. No Gemfile.lock is
|
||||||
# committed on purpose: this resolves an uploader's transitive deps, not the
|
# committed on purpose: this resolves an uploader's transitive deps, not the
|
||||||
# app's, and none of it affects the reproducible release build.
|
# app's, and none of it affects the reproducible release build.
|
||||||
gem "fastlane", "2.237.0"
|
gem "fastlane", "2.241.1"
|
||||||
@@ -23,6 +23,8 @@ It works on top of the system calendar and has no network access.</p>
|
|||||||
<a href="https://apps.obtainium.imranr.dev/redirect?r=obtainium://add/https://codeberg.org/jlmakiola/calendula"><img src="https://github.com/ImranR98/Obtainium/blob/main/assets/graphics/badge_obtainium.png?raw=true" alt="Get it on Obtainium" height="56"></a>
|
<a href="https://apps.obtainium.imranr.dev/redirect?r=obtainium://add/https://codeberg.org/jlmakiola/calendula"><img src="https://github.com/ImranR98/Obtainium/blob/main/assets/graphics/badge_obtainium.png?raw=true" alt="Get it on Obtainium" height="56"></a>
|
||||||
|
|
||||||
<a href="https://ko-fi.com/jeanlucmakiola"><img src="https://storage.ko-fi.com/cdn/brandasset/v2/support_me_on_kofi_badge_beige.png" alt="Support me on Ko-fi" height="56"></a>
|
<a href="https://ko-fi.com/jeanlucmakiola"><img src="https://storage.ko-fi.com/cdn/brandasset/v2/support_me_on_kofi_badge_beige.png" alt="Support me on Ko-fi" height="56"></a>
|
||||||
|
|
||||||
|
<a href="https://liberapay.com/Jean-Luc_Makiola/donate"><img src="https://liberapay.com/assets/widgets/donate.svg" alt="Donate using Liberapay" height="56"></a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p>
|
<p>
|
||||||
@@ -203,6 +205,13 @@ anywhere. Your events stay in Android's own calendar store.
|
|||||||
[Privacy policy](https://jeanlucmakiola.de/calendula/privacy), written in
|
[Privacy policy](https://jeanlucmakiola.de/calendula/privacy), written in
|
||||||
[`docs/PRIVACY.md`](docs/PRIVACY.md), which is what that page renders.
|
[`docs/PRIVACY.md`](docs/PRIVACY.md), which is what that page renders.
|
||||||
|
|
||||||
|
## Support
|
||||||
|
|
||||||
|
Calendula is free and has no ads. If you'd like to support its development,
|
||||||
|
you can tip once on [Ko-fi](https://ko-fi.com/jeanlucmakiola) or donate
|
||||||
|
regularly on [Liberapay](https://liberapay.com/Jean-Luc_Makiola/donate). Both
|
||||||
|
are linked in the app under *Settings → Support development*.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
[MIT](LICENSE), Jean-Luc Makiola, 2026
|
[MIT](LICENSE), Jean-Luc Makiola, 2026
|
||||||
@@ -32,8 +32,8 @@ android {
|
|||||||
// (up to 2.22.3: 2.22.3 -> 22203; from 2.22.4: 2.23.0-beta.1 -> 2230001,
|
// (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.
|
// 2.22.4 -> 2220499), and CI fails if the committed one doesn't match.
|
||||||
// See docs/RELEASING.md.
|
// See docs/RELEASING.md.
|
||||||
versionCode = 2230004
|
versionCode = 2240299
|
||||||
versionName = "2.23.0-beta.4"
|
versionName = "2.24.2"
|
||||||
|
|
||||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||||
}
|
}
|
||||||
@@ -175,9 +175,13 @@ 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-prefs")
|
||||||
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("de.jeanlucmakiola.floret:glance")
|
||||||
implementation(libs.kotlinx.coroutines.core)
|
implementation(libs.kotlinx.coroutines.core)
|
||||||
|
|
||||||
debugImplementation(libs.androidx.ui.tooling)
|
debugImplementation(libs.androidx.ui.tooling)
|
||||||
|
|||||||
+91
@@ -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)!!)
|
||||||
|
}
|
||||||
|
}
|
||||||
+140
@@ -0,0 +1,140 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.widget.month
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.content.ContentUris
|
||||||
|
import android.content.ContentValues
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.Parcel
|
||||||
|
import android.provider.CalendarContract
|
||||||
|
import android.util.Log
|
||||||
|
import android.view.View
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import android.widget.FrameLayout
|
||||||
|
import android.widget.TextView
|
||||||
|
import androidx.compose.ui.unit.DpSize
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.glance.ExperimentalGlanceApi
|
||||||
|
import androidx.glance.appwidget.compose
|
||||||
|
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||||
|
import androidx.test.platform.app.InstrumentationRegistry
|
||||||
|
import androidx.test.rule.GrantPermissionRule
|
||||||
|
import com.google.common.truth.Truth.assertThat
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Before
|
||||||
|
import org.junit.Rule
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import de.jeanlucmakiola.calendula.R
|
||||||
|
import java.time.LocalDate
|
||||||
|
import java.time.ZoneId
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renders the month widget for a packed month through Glance's own translator
|
||||||
|
* (#372) and checks what one size costs on the wire: the host's binder buffer is
|
||||||
|
* 1 MB for every widget update at once, and Exact sends one copy per size (#214).
|
||||||
|
*/
|
||||||
|
@OptIn(ExperimentalGlanceApi::class)
|
||||||
|
@RunWith(AndroidJUnit4::class)
|
||||||
|
class MonthWidgetPayloadTest {
|
||||||
|
|
||||||
|
@get:Rule
|
||||||
|
val permissionRule: GrantPermissionRule =
|
||||||
|
GrantPermissionRule.grant(Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR)
|
||||||
|
|
||||||
|
private val instrumentation = InstrumentationRegistry.getInstrumentation()
|
||||||
|
private val context = instrumentation.targetContext
|
||||||
|
private var calendarId = -1L
|
||||||
|
|
||||||
|
private fun Uri.asSyncAdapter(): Uri = buildUpon()
|
||||||
|
.appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
|
||||||
|
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, ACCOUNT)
|
||||||
|
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, CalendarContract.ACCOUNT_TYPE_LOCAL)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
@Before
|
||||||
|
fun packTheMonth() {
|
||||||
|
val calendar = ContentValues().apply {
|
||||||
|
put(CalendarContract.Calendars.ACCOUNT_NAME, ACCOUNT)
|
||||||
|
put(CalendarContract.Calendars.ACCOUNT_TYPE, CalendarContract.ACCOUNT_TYPE_LOCAL)
|
||||||
|
put(CalendarContract.Calendars.NAME, ACCOUNT)
|
||||||
|
put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, ACCOUNT)
|
||||||
|
put(CalendarContract.Calendars.CALENDAR_COLOR, 0xFF3F51B5.toInt())
|
||||||
|
put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_OWNER)
|
||||||
|
put(CalendarContract.Calendars.OWNER_ACCOUNT, ACCOUNT)
|
||||||
|
put(CalendarContract.Calendars.VISIBLE, 1)
|
||||||
|
put(CalendarContract.Calendars.SYNC_EVENTS, 1)
|
||||||
|
}
|
||||||
|
val uri = context.contentResolver.insert(CalendarContract.Calendars.CONTENT_URI.asSyncAdapter(), calendar)
|
||||||
|
calendarId = ContentUris.parseId(requireNotNull(uri))
|
||||||
|
|
||||||
|
val zone = ZoneId.systemDefault()
|
||||||
|
val first = LocalDate.now(zone).withDayOfMonth(1).minusDays(7)
|
||||||
|
val events = (0 until 49).flatMap { offset ->
|
||||||
|
val day = first.plusDays(offset.toLong())
|
||||||
|
(0 until EVENTS_PER_DAY).map { i ->
|
||||||
|
val start = day.atTime(8 + i, 0).atZone(zone).toInstant().toEpochMilli()
|
||||||
|
ContentValues().apply {
|
||||||
|
put(CalendarContract.Events.CALENDAR_ID, calendarId)
|
||||||
|
put(CalendarContract.Events.TITLE, "Busy $i")
|
||||||
|
put(CalendarContract.Events.DTSTART, start)
|
||||||
|
put(CalendarContract.Events.DTEND, start + 30 * 60_000L)
|
||||||
|
put(CalendarContract.Events.EVENT_TIMEZONE, zone.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
context.contentResolver.bulkInsert(CalendarContract.Events.CONTENT_URI.asSyncAdapter(), events.toTypedArray())
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
fun removeCalendar() {
|
||||||
|
if (calendarId < 0) return
|
||||||
|
context.contentResolver.delete(
|
||||||
|
ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI, calendarId).asSyncAdapter(),
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun aPackedMonthRendersWithinItsPayload() = runBlocking {
|
||||||
|
for (size in listOf(DpSize(250.dp, 250.dp), DpSize(320.dp, 360.dp), DpSize(420.dp, 520.dp), DpSize(600.dp, 1000.dp))) {
|
||||||
|
val views = MonthWidget().compose(context, size = size)
|
||||||
|
val bytes = Parcel.obtain().let { parcel ->
|
||||||
|
try {
|
||||||
|
views.writeToParcel(parcel, 0)
|
||||||
|
parcel.dataSize()
|
||||||
|
} finally {
|
||||||
|
parcel.recycle()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var dayNumbers = 0
|
||||||
|
var bars = 0
|
||||||
|
instrumentation.runOnMainSync {
|
||||||
|
val root = views.apply(context, FrameLayout(context))
|
||||||
|
fun walk(view: View) {
|
||||||
|
if (view.id in DAY_IDS && view is TextView && view.text.isNotEmpty()) dayNumbers += 1
|
||||||
|
if (view.id == R.id.bar_title) bars += 1
|
||||||
|
if (view is ViewGroup) for (i in 0 until view.childCount) walk(view.getChildAt(i))
|
||||||
|
}
|
||||||
|
walk(root)
|
||||||
|
}
|
||||||
|
Log.i(TAG, "size=$size bytes=$bytes days=$dayNumbers bars=$bars")
|
||||||
|
// The grid itself rendered, not Glance's error layout: a number in every day of every week.
|
||||||
|
assertThat(dayNumbers % 7).isEqualTo(0)
|
||||||
|
assertThat(dayNumbers).isAtLeast(28)
|
||||||
|
assertThat(bytes).isAtMost(MAX_BYTES_PER_SIZE)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val TAG = "MonthWidgetPayload"
|
||||||
|
const val ACCOUNT = "calendula-widget-payload-test"
|
||||||
|
const val EVENTS_PER_DAY = 6
|
||||||
|
|
||||||
|
val DAY_IDS = setOf(R.id.day_0, R.id.day_1, R.id.day_2, R.id.day_3, R.id.day_4, R.id.day_5, R.id.day_6)
|
||||||
|
|
||||||
|
/** A quarter of the host's buffer, leaving room for a second size and every other widget. */
|
||||||
|
const val MAX_BYTES_PER_SIZE = 256 * 1024
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -41,6 +41,11 @@
|
|||||||
-->
|
-->
|
||||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||||
|
|
||||||
|
<!-- WorkManager declares these for network constraints and foreground workers, neither of which the app uses (#448). -->
|
||||||
|
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" tools:node="remove" />
|
||||||
|
<uses-permission android:name="android.permission.WAKE_LOCK" tools:node="remove" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" tools:node="remove" />
|
||||||
|
|
||||||
<!-- Package visibility (Android 11+): without this, getLaunchIntentForPackage
|
<!-- Package visibility (Android 11+): without this, getLaunchIntentForPackage
|
||||||
returns null and the calendar manager's per-account "manage" button can't
|
returns null and the calendar manager's per-account "manage" button can't
|
||||||
open the source sync app (DAVx5, ICSx5, Google Calendar, …). The LAUNCHER
|
open the source sync app (DAVx5, ICSx5, Google Calendar, …). The LAUNCHER
|
||||||
@@ -152,7 +157,7 @@
|
|||||||
</intent-filter>
|
</intent-filter>
|
||||||
|
|
||||||
<!-- Text shared or selected in another app opens a prefilled new
|
<!-- Text shared or selected in another app opens a prefilled new
|
||||||
event (MainActivity.sharedTextExtrasOrNull, issue #306). -->
|
event (MainActivity.sharedTextRequestOrNull, issue #306). -->
|
||||||
<intent-filter>
|
<intent-filter>
|
||||||
<action android:name="android.intent.action.SEND" />
|
<action android:name="android.intent.action.SEND" />
|
||||||
<category android:name="android.intent.category.DEFAULT" />
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
@@ -318,6 +323,16 @@
|
|||||||
android:exported="false" />
|
android:exported="false" />
|
||||||
|
|
||||||
<!-- Home-screen widgets (Glance). Exported: the launcher/host binds them. -->
|
<!-- Home-screen widgets (Glance). Exported: the launcher/host binds them. -->
|
||||||
|
<activity
|
||||||
|
android:name=".widget.config.WidgetConfigActivity"
|
||||||
|
android:exported="true"
|
||||||
|
android:excludeFromRecents="true"
|
||||||
|
android:taskAffinity=""
|
||||||
|
android:theme="@style/Theme.Calendula.WidgetConfig">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
|
||||||
|
</intent-filter>
|
||||||
|
</activity>
|
||||||
<receiver
|
<receiver
|
||||||
android:name=".widget.agenda.AgendaWidgetReceiver"
|
android:name=".widget.agenda.AgendaWidgetReceiver"
|
||||||
android:label="@string/widget_agenda_label"
|
android:label="@string/widget_agenda_label"
|
||||||
@@ -342,14 +357,110 @@
|
|||||||
android:resource="@xml/appwidget_info_month" />
|
android:resource="@xml/appwidget_info_month" />
|
||||||
</receiver>
|
</receiver>
|
||||||
|
|
||||||
|
<receiver
|
||||||
|
android:name=".widget.quickadd.QuickAddWidgetReceiver"
|
||||||
|
android:label="@string/widget_quick_add_label"
|
||||||
|
android:exported="true">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||||
|
</intent-filter>
|
||||||
|
<meta-data
|
||||||
|
android:name="android.appwidget.provider"
|
||||||
|
android:resource="@xml/appwidget_info_quick_add" />
|
||||||
|
</receiver>
|
||||||
|
|
||||||
|
<receiver
|
||||||
|
android:name=".widget.date.DateWidgetReceiver"
|
||||||
|
android:label="@string/widget_date_label"
|
||||||
|
android:exported="true">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||||
|
</intent-filter>
|
||||||
|
<meta-data
|
||||||
|
android:name="android.appwidget.provider"
|
||||||
|
android:resource="@xml/appwidget_info_date" />
|
||||||
|
</receiver>
|
||||||
|
|
||||||
|
<receiver
|
||||||
|
android:name=".widget.week.WeekStripWidgetReceiver"
|
||||||
|
android:label="@string/widget_week_strip_label"
|
||||||
|
android:exported="true">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||||
|
</intent-filter>
|
||||||
|
<meta-data
|
||||||
|
android:name="android.appwidget.provider"
|
||||||
|
android:resource="@xml/appwidget_info_week_strip" />
|
||||||
|
</receiver>
|
||||||
|
|
||||||
|
<receiver
|
||||||
|
android:name=".widget.upcoming.UpcomingWidgetReceiver"
|
||||||
|
android:label="@string/widget_upcoming_label"
|
||||||
|
android:exported="true">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||||
|
</intent-filter>
|
||||||
|
<meta-data
|
||||||
|
android:name="android.appwidget.provider"
|
||||||
|
android:resource="@xml/appwidget_info_upcoming" />
|
||||||
|
</receiver>
|
||||||
|
|
||||||
|
<receiver
|
||||||
|
android:name=".widget.today.TodayWidgetReceiver"
|
||||||
|
android:label="@string/widget_today_label"
|
||||||
|
android:exported="true">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||||
|
</intent-filter>
|
||||||
|
<meta-data
|
||||||
|
android:name="android.appwidget.provider"
|
||||||
|
android:resource="@xml/appwidget_info_today" />
|
||||||
|
</receiver>
|
||||||
|
|
||||||
|
<receiver
|
||||||
|
android:name=".widget.countdown.CountdownWidgetReceiver"
|
||||||
|
android:label="@string/widget_countdown_label"
|
||||||
|
android:exported="true">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||||
|
</intent-filter>
|
||||||
|
<meta-data
|
||||||
|
android:name="android.appwidget.provider"
|
||||||
|
android:resource="@xml/appwidget_info_countdown" />
|
||||||
|
</receiver>
|
||||||
|
|
||||||
|
<!-- A countdown widget's redraw for when its label changes (#439). -->
|
||||||
|
<receiver
|
||||||
|
android:name=".widget.WidgetTickReceiver"
|
||||||
|
android:exported="false" />
|
||||||
|
|
||||||
|
<receiver
|
||||||
|
android:name=".widget.split.MonthDayWidgetReceiver"
|
||||||
|
android:label="@string/widget_month_day_label"
|
||||||
|
android:exported="true">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||||
|
</intent-filter>
|
||||||
|
<meta-data
|
||||||
|
android:name="android.appwidget.provider"
|
||||||
|
android:resource="@xml/appwidget_info_month_day" />
|
||||||
|
</receiver>
|
||||||
|
|
||||||
<!-- Keeps both widgets fresh: the calendar provider broadcasts
|
<!-- Keeps both widgets fresh: the calendar provider broadcasts
|
||||||
PROVIDER_CHANGED on any data change (our writes and external sync).
|
PROVIDER_CHANGED on any data change (external sync; the app's own
|
||||||
The day boundary arrives as the app's own ROLLOVER alarm (#228), by
|
writes redraw directly). The day boundary arrives as the app's own
|
||||||
explicit PendingIntent, so it needs no filter here; DATE_CHANGED is
|
ROLLOVER alarm (#228), by explicit PendingIntent, so it needs no
|
||||||
a free extra only, since Android 8+ withholds it from manifest
|
filter here; DATE_CHANGED is a free extra only, since Android 8+
|
||||||
receivers. The four below re-arm that alarm: TIME_SET /
|
withholds it from manifest receivers. TIME_SET / TIMEZONE_CHANGED
|
||||||
TIMEZONE_CHANGED move the boundary, boot / package-replace wipe it.
|
move the boundary, boot / package-replace wipe the alarm, and
|
||||||
|
LOCALE_CHANGED redraws the labels in the new language.
|
||||||
Exported: the system broadcasts arrive from outside the app. -->
|
Exported: the system broadcasts arrive from outside the app. -->
|
||||||
|
<!-- The app's own redraw request (language change); not exported so
|
||||||
|
other apps can't trigger it. -->
|
||||||
|
<receiver
|
||||||
|
android:name=".widget.WidgetRedrawReceiver"
|
||||||
|
android:exported="false" />
|
||||||
|
|
||||||
<receiver
|
<receiver
|
||||||
android:name=".widget.WidgetUpdateReceiver"
|
android:name=".widget.WidgetUpdateReceiver"
|
||||||
android:exported="true">
|
android:exported="true">
|
||||||
@@ -365,6 +476,7 @@
|
|||||||
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
|
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
|
||||||
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||||
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
|
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
|
||||||
|
<action android:name="android.intent.action.LOCALE_CHANGED" />
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
</receiver>
|
</receiver>
|
||||||
|
|
||||||
|
|||||||
@@ -10,9 +10,12 @@ import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesScheduler
|
|||||||
import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesSyncWorker
|
import de.jeanlucmakiola.calendula.data.contacts.SpecialDatesSyncWorker
|
||||||
import de.jeanlucmakiola.calendula.data.reminders.ReminderMaintenanceScheduler
|
import de.jeanlucmakiola.calendula.data.reminders.ReminderMaintenanceScheduler
|
||||||
import de.jeanlucmakiola.calendula.data.reminders.ReminderMaintenanceWorker
|
import de.jeanlucmakiola.calendula.data.reminders.ReminderMaintenanceWorker
|
||||||
import de.jeanlucmakiola.calendula.widget.WidgetRolloverScheduler
|
import de.jeanlucmakiola.calendula.widget.publishCalendulaWidgetPreviews
|
||||||
|
import de.jeanlucmakiola.calendula.widget.syncWidgetRollover
|
||||||
|
import de.jeanlucmakiola.calendula.widget.widgetEntryPoint
|
||||||
import de.jeanlucmakiola.floret.crash.CrashConfig
|
import de.jeanlucmakiola.floret.crash.CrashConfig
|
||||||
import de.jeanlucmakiola.floret.crash.CrashReporter
|
import de.jeanlucmakiola.floret.crash.CrashReporter
|
||||||
|
import de.jeanlucmakiola.floret.locale.AppLanguage
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.SupervisorJob
|
import kotlinx.coroutines.SupervisorJob
|
||||||
@@ -43,6 +46,11 @@ class CalendulaApp : Application() {
|
|||||||
chooseIssueUrl = getString(R.string.report_issue_choose_url),
|
chooseIssueUrl = getString(R.string.report_issue_choose_url),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
// Below API 33 only AppCompat activities get the app language; a process
|
||||||
|
// woken for a widget formats in it too (#90).
|
||||||
|
AppLanguage.applyDefault(this)
|
||||||
|
// Before anything that writes, so the widgets see every change (#420).
|
||||||
|
widgetEntryPoint().widgetRefreshCoordinator().start()
|
||||||
reconcileAutoBackup()
|
reconcileAutoBackup()
|
||||||
reconcileSpecialDates()
|
reconcileSpecialDates()
|
||||||
reconcileCalendarVisibility()
|
reconcileCalendarVisibility()
|
||||||
@@ -55,10 +63,12 @@ class CalendulaApp : Application() {
|
|||||||
* (#228). Idempotent, and it covers what no broadcast reaches — an alarm
|
* (#228). Idempotent, and it covers what no broadcast reaches — an alarm
|
||||||
* dropped by a force-stop is armed again the next time the app is opened.
|
* dropped by a force-stop is armed again the next time the app is opened.
|
||||||
* Off the main thread: a handful of binder calls on every process start.
|
* Off the main thread: a handful of binder calls on every process start.
|
||||||
|
* The picker previews are republished here too, once per update.
|
||||||
*/
|
*/
|
||||||
private fun reconcileWidgetRollover() {
|
private fun reconcileWidgetRollover() {
|
||||||
CoroutineScope(SupervisorJob() + Dispatchers.Default).launch {
|
CoroutineScope(SupervisorJob() + Dispatchers.Default).launch {
|
||||||
WidgetRolloverScheduler.sync(this@CalendulaApp)
|
syncWidgetRollover(this@CalendulaApp)
|
||||||
|
publishCalendulaWidgetPreviews(this@CalendulaApp)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import android.content.res.Configuration
|
|||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.provider.CalendarContract
|
import android.provider.CalendarContract
|
||||||
|
import android.provider.OpenableColumns
|
||||||
import androidx.activity.SystemBarStyle
|
import androidx.activity.SystemBarStyle
|
||||||
import androidx.activity.compose.setContent
|
import androidx.activity.compose.setContent
|
||||||
import androidx.activity.enableEdgeToEdge
|
import androidx.activity.enableEdgeToEdge
|
||||||
@@ -29,11 +30,16 @@ 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.calendar.CalendarRepository
|
||||||
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
|
||||||
import de.jeanlucmakiola.calendula.data.prefs.ThemeMode
|
import de.jeanlucmakiola.floret.locale.AppLanguage
|
||||||
|
import de.jeanlucmakiola.floret.prefs.ThemeMode
|
||||||
|
import de.jeanlucmakiola.floret.prefs.isDark
|
||||||
|
import de.jeanlucmakiola.floret.prefs.isPureBlack
|
||||||
import de.jeanlucmakiola.calendula.data.prefs.is24Hour
|
import de.jeanlucmakiola.calendula.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.domain.sharedTextOrNull
|
||||||
|
import de.jeanlucmakiola.calendula.ui.ExternalRequests
|
||||||
|
import de.jeanlucmakiola.calendula.ui.InsertRequest
|
||||||
import de.jeanlucmakiola.calendula.ui.RootScreen
|
import de.jeanlucmakiola.calendula.ui.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
|
||||||
@@ -57,6 +63,8 @@ import de.jeanlucmakiola.calendula.ui.theme.WindowThemeCache
|
|||||||
import de.jeanlucmakiola.calendula.ui.theme.windowBackgroundRes
|
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.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.combine
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.datetime.LocalDate
|
import kotlinx.datetime.LocalDate
|
||||||
import kotlinx.datetime.TimeZone
|
import kotlinx.datetime.TimeZone
|
||||||
@@ -65,9 +73,6 @@ import kotlin.time.Clock
|
|||||||
import kotlin.time.Instant
|
import kotlin.time.Instant
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
/** A prefilled create form from an external launch, with the source it came from. */
|
|
||||||
private data class InsertRequest(val form: EventForm, val source: ImportSource)
|
|
||||||
|
|
||||||
@AndroidEntryPoint
|
@AndroidEntryPoint
|
||||||
class MainActivity : AppCompatActivity() {
|
class MainActivity : AppCompatActivity() {
|
||||||
|
|
||||||
@@ -79,23 +84,12 @@ class MainActivity : AppCompatActivity() {
|
|||||||
// picks up the in-app override instead of the night resource qualifier.
|
// picks up the in-app override instead of the night resource qualifier.
|
||||||
private var systemBarsDark = false
|
private var systemBarsDark = false
|
||||||
|
|
||||||
// The occurrence a reminder notification was tapped for (eventId, begin,
|
private val requests = ExternalRequests(
|
||||||
// end — the detail screen's key shape). singleTop + onNewIntent route a
|
onExternalFormClosed = {
|
||||||
// tap into the running activity; CalendarHost consumes and clears it.
|
insertFormOpen = false
|
||||||
private var requestedDetailKey by mutableStateOf<LongArray?>(null)
|
if (launchedForInsert) finish()
|
||||||
|
},
|
||||||
// A navigation a home-screen widget asked for (open a date / start a
|
)
|
||||||
// create). Consumed once by CalendarHost, same pattern as the detail key.
|
|
||||||
private var requestedNav by mutableStateOf<WidgetNavRequest?>(null)
|
|
||||||
|
|
||||||
// An .ics file opened/shared into the app (ACTION_VIEW/SEND). Consumed once
|
|
||||||
// by CalendarHost's import flow.
|
|
||||||
private var requestedImportUri by mutableStateOf<Uri?>(null)
|
|
||||||
|
|
||||||
// A prefilled new-event form from an external ACTION_INSERT launch (another
|
|
||||||
// app/widget asking us to create an event, issue #30) or shared text (#306).
|
|
||||||
// Consumed once by CalendarHost, which opens it in the create form for review.
|
|
||||||
private var requestedInsert by mutableStateOf<InsertRequest?>(null)
|
|
||||||
|
|
||||||
// Whether such a form is still open. Only then does a recreation re-read the
|
// 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.
|
// intent to bring it back; a saved or dismissed one stays closed.
|
||||||
@@ -105,11 +99,6 @@ class MainActivity : AppCompatActivity() {
|
|||||||
// app that asked instead of leaving the calendar on top of it.
|
// app that asked instead of leaving the calendar on top of it.
|
||||||
private var launchedForInsert = false
|
private var launchedForInsert = false
|
||||||
|
|
||||||
// An external "edit this event" (ACTION_EDIT on content://.../events/<id>):
|
|
||||||
// opens the occurrence in the edit form. Same occurrence-key shape as the
|
|
||||||
// detail channel; consumed once by CalendarHost.
|
|
||||||
private var requestedEditKey by mutableStateOf<LongArray?>(null)
|
|
||||||
|
|
||||||
// A captured crash report awaiting the user's decision, surfaced as a dialog
|
// A captured crash report awaiting the user's decision, surfaced as a dialog
|
||||||
// over the calendar on the next launch (the single-crash path). A startup
|
// over the calendar on the next launch (the single-crash path). A startup
|
||||||
// crash-loop is handled out of band, before setContent — see below.
|
// crash-loop is handled out of band, before setContent — see below.
|
||||||
@@ -137,16 +126,19 @@ class MainActivity : AppCompatActivity() {
|
|||||||
// backdrop and bar icons instead of the night qualifier's (#181).
|
// backdrop and bar icons instead of the night qualifier's (#181).
|
||||||
val cachedTheme = WindowThemeCache.read(this)
|
val cachedTheme = WindowThemeCache.read(this)
|
||||||
cachedTheme?.windowBackgroundRes()?.let { window.setBackgroundDrawableResource(it) }
|
cachedTheme?.windowBackgroundRes()?.let { window.setBackgroundDrawableResource(it) }
|
||||||
systemBarsDark = when (cachedTheme) {
|
systemBarsDark = (cachedTheme ?: ThemeMode.SYSTEM).isDark(systemDark)
|
||||||
null, ThemeMode.SYSTEM -> systemDark
|
|
||||||
ThemeMode.LIGHT -> false
|
|
||||||
ThemeMode.DARK, ThemeMode.BLACK -> true
|
|
||||||
}
|
|
||||||
applyEdgeToEdge()
|
applyEdgeToEdge()
|
||||||
|
val appearance = MutableStateFlow(
|
||||||
|
Appearance(
|
||||||
|
themeMode = cachedTheme ?: ThemeMode.SYSTEM,
|
||||||
|
dynamicColor = WindowThemeCache.readDynamicColor(this),
|
||||||
|
),
|
||||||
|
)
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
settingsPrefs.themeMode.collect { mode ->
|
combine(settingsPrefs.themeMode, settingsPrefs.dynamicColor, ::Appearance).collect { stored ->
|
||||||
WindowThemeCache.write(this@MainActivity, mode)
|
WindowThemeCache.write(this@MainActivity, stored.themeMode, stored.dynamicColor ?: true)
|
||||||
window.setBackgroundDrawableResource(mode.windowBackgroundRes() ?: R.color.window_background)
|
window.setBackgroundDrawableResource(stored.themeMode.windowBackgroundRes() ?: R.color.window_background)
|
||||||
|
appearance.value = stored
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Android hands the intent that started the task back to onCreate every
|
// Android hands the intent that started the task back to onCreate every
|
||||||
@@ -162,29 +154,30 @@ class MainActivity : AppCompatActivity() {
|
|||||||
// is what carries one through a recreation — the create form only while
|
// is what carries one through a recreation — the create form only while
|
||||||
// it's still open.
|
// it's still open.
|
||||||
val replaying = savedInstanceState != null || intent.isRelaunch()
|
val replaying = savedInstanceState != null || intent.isRelaunch()
|
||||||
|
requests.replayed = savedInstanceState != null
|
||||||
if (!replaying) {
|
if (!replaying) {
|
||||||
requestedDetailKey = intent.detailKeyOrNull() ?: intent.viewEventKeyOrNull()
|
requests.detailKey = intent.detailKeyOrNull() ?: intent.viewEventKeyOrNull()
|
||||||
requestedEditKey = intent.editEventKeyOrNull()
|
requests.editKey = intent.editEventKeyOrNull()
|
||||||
}
|
}
|
||||||
requestedNav = intent.navRequestOrNull()
|
requests.nav = intent.navRequestOrNull()
|
||||||
?.takeUnless { replaying && it is WidgetNavRequest.OpenEvent }
|
?.takeUnless { replaying && it is WidgetNavRequest.OpenEvent }
|
||||||
requestedImportUri = intent.importUriOrNull()
|
requests.importUri = intent.importUriOrNull()
|
||||||
val insertOpenBefore = savedInstanceState?.getBoolean(KEY_INSERT_FORM_OPEN) == true
|
val insertOpenBefore = savedInstanceState?.getBoolean(KEY_INSERT_FORM_OPEN) == true
|
||||||
requestedInsert = intent.createRequestOrNull()?.takeIf { !replaying || insertOpenBefore }
|
requests.insert = intent.createRequestOrNull()?.takeIf { !replaying || insertOpenBefore }
|
||||||
insertFormOpen = requestedInsert != null
|
insertFormOpen = requests.insert != null
|
||||||
launchedForInsert = savedInstanceState?.getBoolean(KEY_LAUNCHED_FOR_INSERT)
|
launchedForInsert = savedInstanceState?.getBoolean(KEY_LAUNCHED_FOR_INSERT)
|
||||||
?: (requestedInsert != null)
|
?: (requests.insert != 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
|
||||||
// and the Settings screen, so a theme change applies app-wide at once.
|
// and the Settings screen, so a theme change applies app-wide at once.
|
||||||
val settingsViewModel: SettingsViewModel = hiltViewModel()
|
val settingsViewModel: SettingsViewModel = hiltViewModel()
|
||||||
val settings by settingsViewModel.state.collectAsStateWithLifecycle()
|
val settings by settingsViewModel.state.collectAsStateWithLifecycle()
|
||||||
val darkTheme = when (settings.themeMode) {
|
// Seeded from the cache, so the first frame doesn't draw the default
|
||||||
ThemeMode.SYSTEM -> isSystemInDarkTheme()
|
// theme and palette before the stored choices arrive.
|
||||||
ThemeMode.LIGHT -> false
|
val shownAppearance by appearance.collectAsStateWithLifecycle()
|
||||||
ThemeMode.DARK, ThemeMode.BLACK -> true
|
val themeMode = shownAppearance.themeMode
|
||||||
}
|
val darkTheme = themeMode.isDark(isSystemInDarkTheme())
|
||||||
// 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
|
||||||
// the app's light/dark choice.
|
// the app's light/dark choice.
|
||||||
@@ -222,8 +215,8 @@ class MainActivity : AppCompatActivity() {
|
|||||||
}
|
}
|
||||||
CalendulaTheme(
|
CalendulaTheme(
|
||||||
darkTheme = darkTheme,
|
darkTheme = darkTheme,
|
||||||
dynamicColor = settings.dynamicColor,
|
dynamicColor = shownAppearance.dynamicColor ?: settings.dynamicColor,
|
||||||
pureBlack = settings.themeMode == ThemeMode.BLACK,
|
pureBlack = themeMode.isPureBlack,
|
||||||
typography = typography,
|
typography = typography,
|
||||||
) {
|
) {
|
||||||
Box(modifier = Modifier.fillMaxSize()) {
|
Box(modifier = Modifier.fillMaxSize()) {
|
||||||
@@ -236,21 +229,7 @@ class MainActivity : AppCompatActivity() {
|
|||||||
) {
|
) {
|
||||||
RootScreen(
|
RootScreen(
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
requestedDetailKey = requestedDetailKey,
|
requests = requests,
|
||||||
onDetailKeyConsumed = { requestedDetailKey = null },
|
|
||||||
widgetNavRequest = requestedNav,
|
|
||||||
onWidgetNavConsumed = { requestedNav = null },
|
|
||||||
requestedImportUri = requestedImportUri,
|
|
||||||
onImportConsumed = { requestedImportUri = null },
|
|
||||||
requestedInsertForm = requestedInsert?.form,
|
|
||||||
requestedInsertSource = requestedInsert?.source ?: ImportSource.Insert,
|
|
||||||
onInsertConsumed = { requestedInsert = null },
|
|
||||||
onExternalFormClosed = {
|
|
||||||
insertFormOpen = false
|
|
||||||
if (launchedForInsert) finish()
|
|
||||||
},
|
|
||||||
requestedEditKey = requestedEditKey,
|
|
||||||
onEditKeyConsumed = { requestedEditKey = null },
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
// A persistent corner marker so a debug build is never
|
// A persistent corner marker so a debug build is never
|
||||||
@@ -300,6 +279,7 @@ class MainActivity : AppCompatActivity() {
|
|||||||
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)
|
||||||
|
AppLanguage.syncMirror(this)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onSaveInstanceState(outState: Bundle) {
|
override fun onSaveInstanceState(outState: Bundle) {
|
||||||
@@ -310,14 +290,22 @@ class MainActivity : AppCompatActivity() {
|
|||||||
|
|
||||||
override fun onNewIntent(intent: Intent) {
|
override fun onNewIntent(intent: Intent) {
|
||||||
super.onNewIntent(intent)
|
super.onNewIntent(intent)
|
||||||
(intent.detailKeyOrNull() ?: intent.viewEventKeyOrNull())?.let { requestedDetailKey = it }
|
requests.replayed = false
|
||||||
intent.navRequestOrNull()?.let { requestedNav = it }
|
(intent.detailKeyOrNull() ?: intent.viewEventKeyOrNull())?.let { requests.detailKey = it }
|
||||||
intent.importUriOrNull()?.let { requestedImportUri = it }
|
intent.navRequestOrNull()?.let { requests.nav = it }
|
||||||
|
intent.importUriOrNull()?.let { requests.importUri = it }
|
||||||
intent.createRequestOrNull()?.let {
|
intent.createRequestOrNull()?.let {
|
||||||
requestedInsert = it
|
requests.insert = it
|
||||||
insertFormOpen = true
|
insertFormOpen = true
|
||||||
}
|
}
|
||||||
intent.editEventKeyOrNull()?.let { requestedEditKey = it }
|
intent.editEventKeyOrNull()?.let { requests.editKey = it }
|
||||||
|
// The user moved on into the app, so closing the create form no longer
|
||||||
|
// hands control back to the app that started it.
|
||||||
|
if (requests.detailKey != null || requests.nav != null || requests.importUri != null ||
|
||||||
|
requests.editKey != null
|
||||||
|
) {
|
||||||
|
launchedForInsert = false
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -338,9 +326,10 @@ 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.
|
// Shared text is a create (#306); a text/plain file is imported only
|
||||||
Intent.ACTION_SEND -> IntentCompat.getParcelableExtra(this, Intent.EXTRA_STREAM, Uri::class.java)
|
// when it is calendar data, e.g. an .ics attachment labelled text/plain.
|
||||||
.takeUnless { type == SHARED_TEXT_TYPE }
|
Intent.ACTION_SEND -> sharedStreamOrNull()
|
||||||
|
?.takeUnless { type == SHARED_TEXT_TYPE && !it.isCalendarFile() }
|
||||||
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;
|
||||||
@@ -394,7 +383,7 @@ class MainActivity : AppCompatActivity() {
|
|||||||
*/
|
*/
|
||||||
private fun Intent.sharedTextRequestOrNull(): InsertRequest? {
|
private fun Intent.sharedTextRequestOrNull(): InsertRequest? {
|
||||||
val shared = when (action) {
|
val shared = when (action) {
|
||||||
Intent.ACTION_SEND -> if (type == SHARED_TEXT_TYPE) {
|
Intent.ACTION_SEND -> if (type == SHARED_TEXT_TYPE && sharedStreamOrNull()?.isCalendarFile() != true) {
|
||||||
sharedTextOrNull(
|
sharedTextOrNull(
|
||||||
subject = getCharSequenceExtra(Intent.EXTRA_SUBJECT)?.toString(),
|
subject = getCharSequenceExtra(Intent.EXTRA_SUBJECT)?.toString(),
|
||||||
text = getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString(),
|
text = getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString(),
|
||||||
@@ -415,6 +404,23 @@ class MainActivity : AppCompatActivity() {
|
|||||||
return InsertRequest(form, ImportSource.InsertOpenEnded)
|
return InsertRequest(form, ImportSource.InsertOpenEnded)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun Intent.sharedStreamOrNull(): Uri? =
|
||||||
|
IntentCompat.getParcelableExtra(this, Intent.EXTRA_STREAM, Uri::class.java)
|
||||||
|
|
||||||
|
/** Whether a shared file is iCalendar/vCalendar data, by its resolved type or its name. */
|
||||||
|
private fun Uri.isCalendarFile(): Boolean {
|
||||||
|
val resolvedType = runCatching { contentResolver.getType(this) }.getOrNull()
|
||||||
|
if (resolvedType in CALENDAR_TYPES) return true
|
||||||
|
val name = when (scheme) {
|
||||||
|
"content" -> runCatching {
|
||||||
|
contentResolver.query(this, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)
|
||||||
|
?.use { c -> if (c.moveToFirst()) c.getString(0) else null }
|
||||||
|
}.getOrNull()
|
||||||
|
else -> lastPathSegment
|
||||||
|
} ?: return false
|
||||||
|
return CALENDAR_EXTENSIONS.any { name.endsWith(it, ignoreCase = true) }
|
||||||
|
}
|
||||||
|
|
||||||
/** A Long extra's value, or null when the extra is absent. */
|
/** 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
|
||||||
@@ -541,6 +547,8 @@ class MainActivity : AppCompatActivity() {
|
|||||||
// 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 SHARED_TEXT_TYPE = "text/plain"
|
||||||
|
private val CALENDAR_TYPES = setOf("text/calendar", "text/x-vcalendar", "application/ics")
|
||||||
|
private val CALENDAR_EXTENSIONS = listOf(".ics", ".vcs")
|
||||||
private const val KEY_INSERT_FORM_OPEN = "insert_form_open"
|
private const val KEY_INSERT_FORM_OPEN = "insert_form_open"
|
||||||
private const val KEY_LAUNCHED_FOR_INSERT = "launched_for_insert"
|
private const val KEY_LAUNCHED_FOR_INSERT = "launched_for_insert"
|
||||||
|
|
||||||
@@ -587,7 +595,9 @@ class MainActivity : AppCompatActivity() {
|
|||||||
*/
|
*/
|
||||||
fun openDateIntent(context: Context, date: LocalDate, source: CalendarView): Intent =
|
fun openDateIntent(context: Context, date: LocalDate, source: CalendarView): Intent =
|
||||||
Intent(context, MainActivity::class.java).apply {
|
Intent(context, MainActivity::class.java).apply {
|
||||||
data = "calendula://date/$date".toUri()
|
// The source is part of the URI so widgets of different kinds
|
||||||
|
// tapping the same date don't share one PendingIntent.
|
||||||
|
data = "calendula://date/$date/${source.name}".toUri()
|
||||||
putExtra(EXTRA_DATE_ISO, date.toString())
|
putExtra(EXTRA_DATE_ISO, date.toString())
|
||||||
putExtra(EXTRA_SOURCE_VIEW, source.name)
|
putExtra(EXTRA_SOURCE_VIEW, source.name)
|
||||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
@@ -606,6 +616,7 @@ class MainActivity : AppCompatActivity() {
|
|||||||
endMillis: Long,
|
endMillis: Long,
|
||||||
source: CalendarView,
|
source: CalendarView,
|
||||||
): Intent = eventDetailIntent(context, eventId, beginMillis, endMillis).apply {
|
): Intent = eventDetailIntent(context, eventId, beginMillis, endMillis).apply {
|
||||||
|
data = "calendula://event/$eventId/$beginMillis/${source.name}".toUri()
|
||||||
putExtra(EXTRA_SOURCE_VIEW, source.name)
|
putExtra(EXTRA_SOURCE_VIEW, source.name)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -633,3 +644,6 @@ class MainActivity : AppCompatActivity() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The theme choices the window needs before the settings screen's state loads. */
|
||||||
|
private data class Appearance(val themeMode: ThemeMode, val dynamicColor: Boolean?)
|
||||||
@@ -5,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(
|
||||||
|
|||||||
+247
-331
@@ -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,9 +33,11 @@ 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.LocalDate
|
import java.time.LocalDate
|
||||||
import java.time.ZoneId
|
import java.time.ZoneId
|
||||||
import java.time.ZoneOffset
|
import java.time.ZoneOffset
|
||||||
@@ -57,6 +56,10 @@ import javax.inject.Singleton
|
|||||||
interface CalendarDataSource {
|
interface CalendarDataSource {
|
||||||
fun calendars(): List<CalendarSource>
|
fun calendars(): List<CalendarSource>
|
||||||
fun instances(beginMillis: Long, endMillis: Long): List<EventInstance>
|
fun instances(beginMillis: Long, endMillis: Long): List<EventInstance>
|
||||||
|
|
||||||
|
/** [instances] of event [eventId] alone, soonest first. */
|
||||||
|
fun eventInstances(eventId: Long, beginMillis: Long, endMillis: Long): List<EventInstance> =
|
||||||
|
instances(beginMillis, endMillis).filter { it.eventId == eventId }
|
||||||
/**
|
/**
|
||||||
* [allDayReminderTimeMinutes]: the hour all-day reminders fire at, needed to
|
* [allDayReminderTimeMinutes]: the hour all-day reminders fire at, needed to
|
||||||
* decode their stored offsets back to whole-day lead times (see
|
* decode their stored offsets back to whole-day lead times (see
|
||||||
@@ -76,21 +79,13 @@ interface CalendarDataSource {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* The event-colour palette the calendar's account publishes
|
* The event-colour palette the calendar's account publishes
|
||||||
* (`CalendarContract.Colors`, `TYPE_EVENT`), curated for display — deduped,
|
* (`CalendarContract.Colors`, `TYPE_EVENT`), every key in provider order.
|
||||||
* thinned to visually distinct swatches when oversized (CalDAV adapters
|
|
||||||
* publish all ~147 CSS3 names, #22) and hue-sorted; see [curatedForPicker].
|
|
||||||
* Empty when the account exposes no palette (most local calendars, some
|
* Empty when the account exposes no palette (most local calendars, some
|
||||||
* CalDAV) — the signal that a custom colour can only be written as a raw
|
* CalDAV) — the signal that a custom colour can only be written as a raw
|
||||||
* `EVENT_COLOR`, which a synced calendar may drop on its next sync.
|
* `EVENT_COLOR`, which a synced calendar may drop on its next sync. The
|
||||||
*/
|
* picker shows it curated ([curatedForPicker]); matching a colour that came
|
||||||
fun eventColorPalette(calendarId: Long): List<EventColorOption>
|
* from outside the account runs against this full set, since those keys are
|
||||||
|
* all the calendar accepts.
|
||||||
/**
|
|
||||||
* The same palette **uncurated** — every key the account publishes, in
|
|
||||||
* provider order. Curation is a display concession (it folds look-alikes and
|
|
||||||
* drops the neutrals outright from an oversized palette), so matching a
|
|
||||||
* colour that came from outside the account has to run against the full set:
|
|
||||||
* those keys are all the calendar accepts. See [eventColorPalette].
|
|
||||||
*/
|
*/
|
||||||
fun publishedEventColors(calendarId: Long): List<EventColorOption>
|
fun publishedEventColors(calendarId: Long): List<EventColorOption>
|
||||||
|
|
||||||
@@ -238,8 +233,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 +320,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
|
||||||
@@ -358,7 +354,7 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
CalendarProjection.COLUMNS,
|
CalendarProjection.COLUMNS,
|
||||||
null, null,
|
null, null,
|
||||||
CalendarContract.Calendars.CALENDAR_DISPLAY_NAME + " ASC",
|
CalendarContract.Calendars.CALENDAR_DISPLAY_NAME + " ASC",
|
||||||
)?.use { it.mapAll(::toCalendarSource) } ?: emptyList()
|
)?.use { c -> c.mapRows { toCalendarSource() } } ?: emptyList()
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -375,7 +371,20 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
)
|
)
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
override fun createLocalCalendar(displayName: String, color: Int, description: String?): Long {
|
override fun createLocalCalendar(displayName: String, color: Int, description: String?): Long =
|
||||||
|
insertLocalCalendar(displayName, color, "create local calendar") { putDescription(description) }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Insert an owned, visible, syncing calendar on the Calendula local account;
|
||||||
|
* [extra] adds the columns that tell the kinds apart. [what] names the write
|
||||||
|
* in the failure — never the calendar name, which can reach a crash report.
|
||||||
|
*/
|
||||||
|
private fun insertLocalCalendar(
|
||||||
|
displayName: String,
|
||||||
|
color: Int,
|
||||||
|
what: String,
|
||||||
|
extra: ContentValues.() -> Unit,
|
||||||
|
): Long {
|
||||||
val name = displayName.trim()
|
val name = displayName.trim()
|
||||||
val values = ContentValues().apply {
|
val values = ContentValues().apply {
|
||||||
put(CalendarContract.Calendars.ACCOUNT_NAME, LOCAL_ACCOUNT_NAME)
|
put(CalendarContract.Calendars.ACCOUNT_NAME, LOCAL_ACCOUNT_NAME)
|
||||||
@@ -391,11 +400,9 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
)
|
)
|
||||||
put(CalendarContract.Calendars.VISIBLE, 1)
|
put(CalendarContract.Calendars.VISIBLE, 1)
|
||||||
put(CalendarContract.Calendars.SYNC_EVENTS, 1)
|
put(CalendarContract.Calendars.SYNC_EVENTS, 1)
|
||||||
putDescription(description)
|
extra()
|
||||||
}
|
}
|
||||||
val uri = resolver.insert(localCalendarsUri(), values)
|
val uri = resolver.insert(localCalendarsUri(), values) ?: throw WriteFailedException(what)
|
||||||
// No calendar name in the message — it can reach a crash report.
|
|
||||||
?: throw WriteFailedException("create local calendar")
|
|
||||||
return ContentUris.parseId(uri)
|
return ContentUris.parseId(uri)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -460,33 +467,15 @@ 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()
|
insertLocalCalendar(displayName, color, "create managed calendar") {
|
||||||
val values = ContentValues().apply {
|
|
||||||
put(CalendarContract.Calendars.ACCOUNT_NAME, LOCAL_ACCOUNT_NAME)
|
|
||||||
put(CalendarContract.Calendars.ACCOUNT_TYPE, CalendarContract.ACCOUNT_TYPE_LOCAL)
|
|
||||||
put(CalendarContract.Calendars.OWNER_ACCOUNT, LOCAL_ACCOUNT_NAME)
|
|
||||||
put(CalendarContract.Calendars.NAME, name)
|
|
||||||
put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, name)
|
|
||||||
put(CalendarContract.Calendars.CALENDAR_COLOR, color)
|
|
||||||
put(
|
|
||||||
CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL,
|
|
||||||
CalendarContract.Calendars.CAL_ACCESS_OWNER,
|
|
||||||
)
|
|
||||||
put(CalendarContract.Calendars.VISIBLE, 1)
|
|
||||||
put(CalendarContract.Calendars.SYNC_EVENTS, 1)
|
|
||||||
// The marker that identifies this as our special-dates calendar,
|
// The marker that identifies this as our special-dates calendar,
|
||||||
// independent of the (user-editable) display name. CAL_SYNC1 already
|
// independent of the (user-editable) display name. CAL_SYNC1 already
|
||||||
// holds the description, so the marker lives in CAL_SYNC2.
|
// holds the description, so the marker lives in CAL_SYNC2.
|
||||||
put(MANAGED_MARKER_COLUMN, markerFor(type))
|
put(MANAGED_MARKER_COLUMN, markerFor(type))
|
||||||
}
|
}
|
||||||
val uri = resolver.insert(localCalendarsUri(), values)
|
|
||||||
?: throw WriteFailedException("create managed calendar")
|
|
||||||
return ContentUris.parseId(uri)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun findManagedCalendars(): List<ManagedCalendarRow> = resolver.query(
|
override fun findManagedCalendars(): List<ManagedCalendarRow> = resolver.query(
|
||||||
CalendarContract.Calendars.CONTENT_URI,
|
CalendarContract.Calendars.CONTENT_URI,
|
||||||
@@ -550,22 +539,16 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
// Seeded once, then never re-touched by sync — so a user who moves a
|
// Seeded once, then never re-touched by sync — so a user who moves a
|
||||||
// birthday reminder keeps their change. Encoded against the upcoming
|
// birthday reminder keeps their change. Encoded against the upcoming
|
||||||
// occurrence, not the ancient DTSTART anchor (wrong timezone offset).
|
// occurrence, not the ancient DTSTART anchor (wrong timezone offset).
|
||||||
val anchor = Instant.ofEpochMilli(times.dtStartMillis).atZone(ZoneOffset.UTC).toLocalDate()
|
|
||||||
insertReminderRows(
|
insertReminderRows(
|
||||||
eventId,
|
eventId,
|
||||||
managedAllDayReminderMinutes(anchor, form.reminders, allDayReminderTimeMinutes),
|
managedAllDayReminderMinutes(utcDate(times.dtStartMillis), form.reminders, allDayReminderTimeMinutes),
|
||||||
)
|
)
|
||||||
return eventId
|
return eventId
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun updateManagedFields(eventId: Long, values: Map<String, Any?>) {
|
override fun updateManagedFields(eventId: Long, values: Map<String, Any?>) {
|
||||||
if (values.isEmpty()) return
|
if (values.isEmpty()) return
|
||||||
val rows = resolver.update(
|
updateEventRow(eventId, values.toContentValues(), "update managed event id=$eventId")
|
||||||
ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventId),
|
|
||||||
values.toContentValues(),
|
|
||||||
null, null,
|
|
||||||
)
|
|
||||||
if (rows == 0) throw WriteFailedException("update managed event id=$eventId")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun applyManagedCalendarReminders(
|
override fun applyManagedCalendarReminders(
|
||||||
@@ -573,51 +556,74 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
allDayReminderTimeMinutes: Int,
|
allDayReminderTimeMinutes: Int,
|
||||||
minutes: List<Int>,
|
minutes: List<Int>,
|
||||||
) {
|
) {
|
||||||
resolver.query(
|
// Only our own mirror events, so a stray user event in this calendar
|
||||||
CalendarContract.Events.CONTENT_URI,
|
// isn't all-day-re-encoded or stripped of its own reminders.
|
||||||
arrayOf(CalendarContract.Events._ID, CalendarContract.Events.DTSTART),
|
queryManagedEvents(calendarId).forEach { event ->
|
||||||
// Only our own mirror events, so a stray user event in this calendar
|
// Managed events are all-day: DTSTART is a UTC midnight anchor.
|
||||||
// isn't all-day-re-encoded or stripped of its own reminders.
|
reconcileReminders(
|
||||||
"${CalendarContract.Events.CALENDAR_ID} = ? AND " +
|
event.eventId,
|
||||||
"${CalendarContract.Events.DELETED} = 0 AND " +
|
managedAllDayReminderMinutes(utcDate(event.dtStartMillis), minutes, allDayReminderTimeMinutes),
|
||||||
"${CalendarContract.Events.UID_2445} LIKE ?",
|
)
|
||||||
arrayOf(calendarId.toString(), "$MANAGED_UID_PREFIX%"),
|
|
||||||
null,
|
|
||||||
)?.use { c ->
|
|
||||||
while (c.moveToNext()) {
|
|
||||||
val eventId = c.getLong(0)
|
|
||||||
// Managed events are all-day: DTSTART is a UTC midnight anchor.
|
|
||||||
val anchor = Instant.ofEpochMilli(c.getLong(1))
|
|
||||||
.atZone(ZoneOffset.UTC).toLocalDate()
|
|
||||||
reconcileReminders(
|
|
||||||
eventId,
|
|
||||||
managedAllDayReminderMinutes(anchor, minutes, allDayReminderTimeMinutes),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun instances(beginMillis: Long, endMillis: Long): List<EventInstance> {
|
override fun instances(beginMillis: Long, endMillis: Long): List<EventInstance> {
|
||||||
ensureObserversRegistered()
|
val listed = queryInstances(beginMillis, endMillis, null, null)
|
||||||
val uri = CalendarContract.Instances.CONTENT_URI.buildUpon().apply {
|
// A provider that does expand cancelled events already listed them.
|
||||||
ContentUris.appendId(this, beginMillis)
|
val shown = listed.mapTo(HashSet()) { it.eventId }
|
||||||
ContentUris.appendId(this, endMillis)
|
val cancelled = queryCancelledOneOffs(beginMillis, endMillis).filter { it.eventId !in shown }
|
||||||
}.build()
|
return if (cancelled.isEmpty()) listed else (listed + cancelled).sortedBy { it.start }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Cancelled one-off events overlapping the window, which AOSP leaves out of Instances (#388). */
|
||||||
|
private fun queryCancelledOneOffs(beginMillis: Long, endMillis: Long): List<EventInstance> {
|
||||||
|
val selection = "${CalendarContract.Events.STATUS} = ${CalendarContract.Events.STATUS_CANCELED} AND " +
|
||||||
|
"${CalendarContract.Events.DELETED} = 0 AND " +
|
||||||
|
"${CalendarContract.Events.RRULE} IS NULL AND ${CalendarContract.Events.RDATE} IS NULL AND " +
|
||||||
|
"${CalendarContract.Events.ORIGINAL_ID} IS NULL AND " +
|
||||||
|
"${CalendarContract.Events.ORIGINAL_SYNC_ID} IS NULL AND " +
|
||||||
|
"${CalendarContract.Events.DTSTART} < ? AND " +
|
||||||
|
"COALESCE(${CalendarContract.Events.DTEND}, ${CalendarContract.Events.DTSTART}) >= ?"
|
||||||
return resolver.query(
|
return resolver.query(
|
||||||
uri,
|
CalendarContract.Events.CONTENT_URI,
|
||||||
InstanceProjection.COLUMNS,
|
CancelledEventProjection.COLUMNS,
|
||||||
// Hide cancelled occurrences: "delete only this event" writes a
|
selection,
|
||||||
// cancelled exception for the one instance (#47). A NULL status is a
|
arrayOf(endMillis.toString(), beginMillis.toString()),
|
||||||
// normal, un-cancelled event, so it must survive the filter — a bare
|
|
||||||
// `!= CANCELED` would drop it (NULL != 2 is NULL, not true).
|
|
||||||
// DELETED = 0: a provider that soft-deletes may keep the row's
|
|
||||||
// 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,
|
||||||
|
)?.use { c -> c.mapRowsNotNull { toCancelledOneOff() } } ?: emptyList()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun eventInstances(eventId: Long, beginMillis: Long, endMillis: Long): List<EventInstance> =
|
||||||
|
// The series' own rows plus its exceptions, so an occurrence edited on
|
||||||
|
// its own is still one of the series' occurrences.
|
||||||
|
queryInstances(
|
||||||
|
beginMillis,
|
||||||
|
endMillis,
|
||||||
|
"(${CalendarContract.Instances.EVENT_ID} = ? OR ${CalendarContract.Instances.ORIGINAL_ID} = ?)",
|
||||||
|
arrayOf(eventId.toString(), eventId.toString()),
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun queryInstances(
|
||||||
|
beginMillis: Long,
|
||||||
|
endMillis: Long,
|
||||||
|
extraSelection: String?,
|
||||||
|
args: Array<String>?,
|
||||||
|
): List<EventInstance> {
|
||||||
|
ensureObserversRegistered()
|
||||||
|
// Hide deleted occurrences (cancelled exceptions, #47) but keep a cancelled
|
||||||
|
// event of its own (#388); NULL status is a normal event. DELETED: #364.
|
||||||
|
val visible = "(${CalendarContract.Instances.STATUS} IS NULL OR " +
|
||||||
|
"${CalendarContract.Instances.STATUS} != ${CalendarContract.Events.STATUS_CANCELED} OR " +
|
||||||
|
"(${CalendarContract.Instances.ORIGINAL_ID} IS NULL AND " +
|
||||||
|
"${CalendarContract.Instances.ORIGINAL_SYNC_ID} IS NULL)) AND " +
|
||||||
|
"${CalendarContract.Events.DELETED} = 0"
|
||||||
|
return resolver.query(
|
||||||
|
instancesUri(beginMillis, endMillis),
|
||||||
|
InstanceProjection.COLUMNS,
|
||||||
|
if (extraSelection == null) visible else "$visible AND $extraSelection",
|
||||||
|
args,
|
||||||
CalendarContract.Instances.BEGIN + " ASC",
|
CalendarContract.Instances.BEGIN + " ASC",
|
||||||
)?.use { c -> c.mapAllNotNull { CursorColumnReader(c).toEventInstance() } } ?: emptyList()
|
)?.use { c -> c.mapRowsNotNull { toEventInstance() } } ?: emptyList()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun searchEvents(query: String): List<SearchCandidate> {
|
override fun searchEvents(query: String): List<SearchCandidate> {
|
||||||
@@ -639,7 +645,8 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
.toTypedArray()
|
.toTypedArray()
|
||||||
val selection = "($match) AND " +
|
val selection = "($match) AND " +
|
||||||
"${CalendarContract.Events.DELETED} = 0 AND " +
|
"${CalendarContract.Events.DELETED} = 0 AND " +
|
||||||
"${CalendarContract.Events.ORIGINAL_ID} IS NULL"
|
"${CalendarContract.Events.ORIGINAL_ID} IS NULL AND " +
|
||||||
|
"${CalendarContract.Events.ORIGINAL_SYNC_ID} IS NULL"
|
||||||
return resolver.query(
|
return resolver.query(
|
||||||
CalendarContract.Events.CONTENT_URI,
|
CalendarContract.Events.CONTENT_URI,
|
||||||
SearchProjection.COLUMNS,
|
SearchProjection.COLUMNS,
|
||||||
@@ -721,13 +728,9 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
endMillis: Long,
|
endMillis: Long,
|
||||||
soonestFirst: Boolean,
|
soonestFirst: Boolean,
|
||||||
): Pair<Long, Long>? {
|
): Pair<Long, Long>? {
|
||||||
val uri = CalendarContract.Instances.CONTENT_URI.buildUpon().apply {
|
|
||||||
ContentUris.appendId(this, beginMillis)
|
|
||||||
ContentUris.appendId(this, endMillis)
|
|
||||||
}.build()
|
|
||||||
val order = CalendarContract.Instances.BEGIN + if (soonestFirst) " ASC" else " DESC"
|
val order = CalendarContract.Instances.BEGIN + if (soonestFirst) " ASC" else " DESC"
|
||||||
return resolver.query(
|
return resolver.query(
|
||||||
uri,
|
instancesUri(beginMillis, endMillis),
|
||||||
arrayOf(CalendarContract.Instances.BEGIN, CalendarContract.Instances.END),
|
arrayOf(CalendarContract.Instances.BEGIN, CalendarContract.Instances.END),
|
||||||
"${CalendarContract.Instances.EVENT_ID} = ?",
|
"${CalendarContract.Instances.EVENT_ID} = ?",
|
||||||
arrayOf(eventId.toString()),
|
arrayOf(eventId.toString()),
|
||||||
@@ -741,7 +744,7 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
val attendees = queryAttendees(eventId)
|
val attendees = queryAttendees(eventId)
|
||||||
val reminders = queryReminders(eventId)
|
val reminders = queryReminders(eventId)
|
||||||
return resolver.query(
|
return resolver.query(
|
||||||
ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventId),
|
eventUri(eventId),
|
||||||
EventDetailProjection.COLUMNS,
|
EventDetailProjection.COLUMNS,
|
||||||
null, null, null,
|
null, null, null,
|
||||||
)?.use { c ->
|
)?.use { c ->
|
||||||
@@ -752,9 +755,6 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun eventColorPalette(calendarId: Long): List<EventColorOption> =
|
|
||||||
publishedEventColors(calendarId).curatedForPicker()
|
|
||||||
|
|
||||||
override fun publishedEventColors(calendarId: Long): List<EventColorOption> {
|
override fun publishedEventColors(calendarId: Long): List<EventColorOption> {
|
||||||
val account = calendarAccount(calendarId) ?: return emptyList()
|
val account = calendarAccount(calendarId) ?: return emptyList()
|
||||||
return resolver.query(
|
return resolver.query(
|
||||||
@@ -770,7 +770,7 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
),
|
),
|
||||||
null,
|
null,
|
||||||
)?.use { c ->
|
)?.use { c ->
|
||||||
c.mapAll { EventColorOption(key = it.getString(0).orEmpty(), argb = it.getInt(1)) }
|
c.mapRows { EventColorOption(key = getString(0).orEmpty(), argb = getInt(1)) }
|
||||||
}
|
}
|
||||||
?.filter { it.key.isNotEmpty() }
|
?.filter { it.key.isNotEmpty() }
|
||||||
?: emptyList()
|
?: emptyList()
|
||||||
@@ -807,11 +807,10 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
null,
|
null,
|
||||||
CalendarContract.Events.DTSTART + " ASC",
|
CalendarContract.Events.DTSTART + " ASC",
|
||||||
)?.use { c ->
|
)?.use { c ->
|
||||||
c.mapAll {
|
c.mapRows {
|
||||||
val reader = CursorColumnReader(c)
|
val eventId = getLong(EventExportProjection.IDX_ID)
|
||||||
val eventId = reader.getLong(EventExportProjection.IDX_ID)
|
val calendarId = getLong(EventExportProjection.IDX_CALENDAR_ID)
|
||||||
val calendarId = reader.getLong(EventExportProjection.IDX_CALENDAR_ID)
|
toIcsEvent(
|
||||||
reader.toIcsEvent(
|
|
||||||
reminderMinutes = queryReminders(eventId).map { it.minutes },
|
reminderMinutes = queryReminders(eventId).map { it.minutes },
|
||||||
calendarName = names[calendarId],
|
calendarName = names[calendarId],
|
||||||
allDayReminderTimeMinutes = allDayReminderTimeMinutes,
|
allDayReminderTimeMinutes = allDayReminderTimeMinutes,
|
||||||
@@ -846,7 +845,7 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
calendarId = calendarId,
|
calendarId = calendarId,
|
||||||
// Preserve the file's UID so a re-import dedups against it; mint one
|
// Preserve the file's UID so a re-import dedups against it; mint one
|
||||||
// only when the source event carried none.
|
// only when the source event carried none.
|
||||||
uid = event.uid?.takeIf { it.isNotBlank() } ?: "${UUID.randomUUID()}@calendula",
|
uid = event.uid?.takeIf { it.isNotBlank() } ?: mintUid(),
|
||||||
palette = colorPalette,
|
palette = colorPalette,
|
||||||
)
|
)
|
||||||
val uri = resolver.insert(CalendarContract.Events.CONTENT_URI, values.toContentValues())
|
val uri = resolver.insert(CalendarContract.Events.CONTENT_URI, values.toContentValues())
|
||||||
@@ -859,8 +858,7 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
// (see [importedAllDayReminderDate]).
|
// (see [importedAllDayReminderDate]).
|
||||||
val reminderDate = if (event.isAllDay) {
|
val reminderDate = if (event.isAllDay) {
|
||||||
importedAllDayReminderDate(
|
importedAllDayReminderDate(
|
||||||
startDate = Instant.ofEpochMilli(event.start.toEpochMilliseconds())
|
startDate = utcDate(event.start.toEpochMilliseconds()),
|
||||||
.atZone(ZoneOffset.UTC).toLocalDate(),
|
|
||||||
recurrenceRule = event.recurrenceRule,
|
recurrenceRule = event.recurrenceRule,
|
||||||
today = LocalDate.now(zone),
|
today = LocalDate.now(zone),
|
||||||
)
|
)
|
||||||
@@ -878,24 +876,7 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
} else {
|
} else {
|
||||||
minutes
|
minutes
|
||||||
}
|
}
|
||||||
val reminder = ContentValues().apply {
|
insertReminderRow(eventId, providerMinutes)
|
||||||
put(CalendarContract.Reminders.EVENT_ID, eventId)
|
|
||||||
put(CalendarContract.Reminders.MINUTES, providerMinutes)
|
|
||||||
put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT)
|
|
||||||
}
|
|
||||||
// The event row is already in. A reminder that won't attach costs
|
|
||||||
// that one alarm, not the event: throwing here would have the import
|
|
||||||
// count an event it did create as failed, and the retry would then
|
|
||||||
// skip it as a duplicate.
|
|
||||||
val attached = try {
|
|
||||||
resolver.insert(CalendarContract.Reminders.CONTENT_URI, reminder)
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.w(TAG, "Reminder insert threw for imported event $eventId", e)
|
|
||||||
null
|
|
||||||
}
|
|
||||||
if (attached == null) {
|
|
||||||
Log.w(TAG, "Failed to attach reminder ($minutes min) to imported event $eventId")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return eventId
|
return eventId
|
||||||
}
|
}
|
||||||
@@ -951,18 +932,13 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
// back to a stable synthesised UID at export time (deriveIcsUid).
|
// back to a stable synthesised UID at export time (deriveIcsUid).
|
||||||
val values = buildEventInsertValues(
|
val values = buildEventInsertValues(
|
||||||
form,
|
form,
|
||||||
uid = "${UUID.randomUUID()}@calendula",
|
uid = mintUid(),
|
||||||
times = form.toWriteTimes(ZoneId.systemDefault()),
|
times = form.toWriteTimes(ZoneId.systemDefault()),
|
||||||
).toContentValues().apply {
|
) + eventColorColumns(form.colorKey, form.color)
|
||||||
// A null colour just leaves both columns unset (the event inherits
|
// A new row has nothing to clear: unset columns inherit the
|
||||||
// its calendar's colour), so only the key/raw cases are written.
|
// calendar's colour, so only the key/raw values are written.
|
||||||
when {
|
.filterValues { it != null }
|
||||||
form.colorKey != null ->
|
val uri = resolver.insert(CalendarContract.Events.CONTENT_URI, values.toContentValues())
|
||||||
put(CalendarContract.Events.EVENT_COLOR_KEY, form.colorKey)
|
|
||||||
form.color != null -> put(CalendarContract.Events.EVENT_COLOR, form.color)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
val uri = resolver.insert(CalendarContract.Events.CONTENT_URI, values)
|
|
||||||
?: throw WriteFailedException("insert event into calendar id=${form.calendarId}")
|
?: throw WriteFailedException("insert event into calendar id=${form.calendarId}")
|
||||||
val eventId = ContentUris.parseId(uri)
|
val eventId = ContentUris.parseId(uri)
|
||||||
seedReminders(eventId, form, allDayReminderTimeMinutes)
|
seedReminders(eventId, form, allDayReminderTimeMinutes)
|
||||||
@@ -983,16 +959,32 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
|
|
||||||
/** Insert one `METHOD_ALERT` reminder row per raw provider offset. */
|
/** Insert one `METHOD_ALERT` reminder row per raw provider offset. */
|
||||||
private fun insertReminderRows(eventId: Long, encodedMinutes: List<Int>) {
|
private fun insertReminderRows(eventId: Long, encodedMinutes: List<Int>) {
|
||||||
encodedMinutes.forEach { minutes ->
|
encodedMinutes.forEach { insertReminderRow(eventId, it) }
|
||||||
val reminder = ContentValues().apply {
|
}
|
||||||
put(CalendarContract.Reminders.EVENT_ID, eventId)
|
|
||||||
put(CalendarContract.Reminders.MINUTES, minutes)
|
/**
|
||||||
put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT)
|
* Best effort: the event row is already in, so a reminder that won't attach
|
||||||
}
|
* costs that one alarm, not the event. Throwing would report an event that
|
||||||
if (resolver.insert(CalendarContract.Reminders.CONTENT_URI, reminder) == null) {
|
* was created as failed — and an import retry would then skip it as a
|
||||||
Log.w(TAG, "Failed to attach reminder ($minutes min) to event $eventId")
|
* duplicate.
|
||||||
}
|
*/
|
||||||
|
private fun insertReminderRow(
|
||||||
|
eventId: Long,
|
||||||
|
minutes: Int,
|
||||||
|
method: Int = CalendarContract.Reminders.METHOD_ALERT,
|
||||||
|
) {
|
||||||
|
val reminder = ContentValues().apply {
|
||||||
|
put(CalendarContract.Reminders.EVENT_ID, eventId)
|
||||||
|
put(CalendarContract.Reminders.MINUTES, minutes)
|
||||||
|
put(CalendarContract.Reminders.METHOD, method)
|
||||||
}
|
}
|
||||||
|
val attached = try {
|
||||||
|
resolver.insert(CalendarContract.Reminders.CONTENT_URI, reminder)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Reminder insert threw for event $eventId", e)
|
||||||
|
null
|
||||||
|
}
|
||||||
|
if (attached == null) Log.w(TAG, "Failed to attach reminder ($minutes min) to event $eventId")
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1029,12 +1021,7 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
zone = ZoneId.systemDefault(),
|
zone = ZoneId.systemDefault(),
|
||||||
)
|
)
|
||||||
if (values.isNotEmpty()) {
|
if (values.isNotEmpty()) {
|
||||||
val rows = resolver.update(
|
updateEventRow(eventId, values.toContentValues(), "update event id=$eventId")
|
||||||
ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventId),
|
|
||||||
values.toContentValues(),
|
|
||||||
null, null,
|
|
||||||
)
|
|
||||||
if (rows == 0) throw WriteFailedException("update event id=$eventId")
|
|
||||||
}
|
}
|
||||||
// Untouched reminder sets are left alone so unrelated edits can't
|
// Untouched reminder sets are left alone so unrelated edits can't
|
||||||
// disturb provider rows the form never knew about. The diff is on the
|
// disturb provider rows the form never knew about. The diff is on the
|
||||||
@@ -1067,16 +1054,17 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
?: throw WriteFailedException("read event to move id=$eventId")
|
?: throw WriteFailedException("read event to move id=$eventId")
|
||||||
// Keep the source UID so an .ics backup dedups and a sync adapter can
|
// Keep the source UID so an .ics backup dedups and a sync adapter can
|
||||||
// recognise the moved event; mint one only if the source carried none.
|
// recognise the moved event; mint one only if the source carried none.
|
||||||
val uid = master.uid?.takeIf { it.isNotEmpty() } ?: "${UUID.randomUUID()}@calendula"
|
val uid = master.uid?.takeIf { it.isNotEmpty() } ?: mintUid()
|
||||||
val newEventId = resolver.insert(
|
val newEventId = resolver.insert(
|
||||||
CalendarContract.Events.CONTENT_URI,
|
CalendarContract.Events.CONTENT_URI,
|
||||||
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
|
||||||
@@ -1086,6 +1074,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)
|
||||||
@@ -1094,7 +1083,7 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
|
|
||||||
/** The master row of the event to move, as a verbatim-insert snapshot. */
|
/** The master row of the event to move, as a verbatim-insert snapshot. */
|
||||||
private fun queryMoveMaster(eventId: Long): MoveMaster? = resolver.query(
|
private fun queryMoveMaster(eventId: Long): MoveMaster? = resolver.query(
|
||||||
ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventId),
|
eventUri(eventId),
|
||||||
MoveMasterProjection.COLUMNS,
|
MoveMasterProjection.COLUMNS,
|
||||||
null, null, null,
|
null, null, null,
|
||||||
)?.use { c ->
|
)?.use { c ->
|
||||||
@@ -1106,8 +1095,7 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
title = r.getString(MoveMasterProjection.IDX_TITLE).orEmpty(),
|
title = r.getString(MoveMasterProjection.IDX_TITLE).orEmpty(),
|
||||||
isAllDay = r.getInt(MoveMasterProjection.IDX_ALL_DAY) != 0,
|
isAllDay = r.getInt(MoveMasterProjection.IDX_ALL_DAY) != 0,
|
||||||
dtStartMillis = r.getLong(MoveMasterProjection.IDX_DTSTART),
|
dtStartMillis = r.getLong(MoveMasterProjection.IDX_DTSTART),
|
||||||
dtEndMillis = r.getLong(MoveMasterProjection.IDX_DTEND)
|
dtEndMillis = r.getLongOrNull(MoveMasterProjection.IDX_DTEND),
|
||||||
.takeUnless { r.isNull(MoveMasterProjection.IDX_DTEND) },
|
|
||||||
duration = r.getString(MoveMasterProjection.IDX_DURATION),
|
duration = r.getString(MoveMasterProjection.IDX_DURATION),
|
||||||
rrule = r.getString(MoveMasterProjection.IDX_RRULE)?.takeIf { it.isNotBlank() },
|
rrule = r.getString(MoveMasterProjection.IDX_RRULE)?.takeIf { it.isNotBlank() },
|
||||||
rdate = r.getString(MoveMasterProjection.IDX_RDATE),
|
rdate = r.getString(MoveMasterProjection.IDX_RDATE),
|
||||||
@@ -1115,8 +1103,7 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
timezone = r.getString(MoveMasterProjection.IDX_EVENT_TIMEZONE),
|
timezone = r.getString(MoveMasterProjection.IDX_EVENT_TIMEZONE),
|
||||||
availability = r.getInt(MoveMasterProjection.IDX_AVAILABILITY),
|
availability = r.getInt(MoveMasterProjection.IDX_AVAILABILITY),
|
||||||
accessLevel = r.getInt(MoveMasterProjection.IDX_ACCESS_LEVEL),
|
accessLevel = r.getInt(MoveMasterProjection.IDX_ACCESS_LEVEL),
|
||||||
status = r.getInt(MoveMasterProjection.IDX_STATUS)
|
status = r.getIntOrNull(MoveMasterProjection.IDX_STATUS),
|
||||||
.takeUnless { r.isNull(MoveMasterProjection.IDX_STATUS) },
|
|
||||||
location = r.getString(MoveMasterProjection.IDX_LOCATION),
|
location = r.getString(MoveMasterProjection.IDX_LOCATION),
|
||||||
description = r.getString(MoveMasterProjection.IDX_DESCRIPTION),
|
description = r.getString(MoveMasterProjection.IDX_DESCRIPTION),
|
||||||
),
|
),
|
||||||
@@ -1133,16 +1120,7 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
arrayOf(fromEventId.toString()),
|
arrayOf(fromEventId.toString()),
|
||||||
null,
|
null,
|
||||||
)?.use { c ->
|
)?.use { c ->
|
||||||
while (c.moveToNext()) {
|
while (c.moveToNext()) insertReminderRow(toEventId, minutes = c.getInt(0), method = c.getInt(1))
|
||||||
val values = ContentValues().apply {
|
|
||||||
put(CalendarContract.Reminders.EVENT_ID, toEventId)
|
|
||||||
put(CalendarContract.Reminders.MINUTES, c.getInt(0))
|
|
||||||
put(CalendarContract.Reminders.METHOD, c.getInt(1))
|
|
||||||
}
|
|
||||||
if (resolver.insert(CalendarContract.Reminders.CONTENT_URI, values) == null) {
|
|
||||||
Log.w(TAG, "Failed to copy a reminder to moved event $toEventId")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} ?: Unit
|
} ?: Unit
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1162,44 +1140,33 @@ 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, colorKey = null)
|
||||||
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 values = querySeriesRow(toEventId).exdateValues(exceptions.map { it.originalInstanceMillis })
|
||||||
|
updateEventRow(toEventId, values, "exdate moved exceptions event id=$toEventId")
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The series' exception rows (modified + cancelled), oldest occurrence first. */
|
/** The series' exception rows (modified + cancelled), oldest occurrence first. */
|
||||||
@@ -1210,26 +1177,14 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
arrayOf(seriesEventId.toString()),
|
arrayOf(seriesEventId.toString()),
|
||||||
CalendarContract.Events.ORIGINAL_INSTANCE_TIME + " ASC",
|
CalendarContract.Events.ORIGINAL_INSTANCE_TIME + " ASC",
|
||||||
)?.use { c ->
|
)?.use { c ->
|
||||||
c.mapAll {
|
c.mapRows {
|
||||||
val r = CursorColumnReader(c)
|
|
||||||
val status = r.getInt(ExceptionProjection.IDX_STATUS)
|
|
||||||
.takeUnless { r.isNull(ExceptionProjection.IDX_STATUS) }
|
|
||||||
ExceptionRowSnapshot(
|
ExceptionRowSnapshot(
|
||||||
exceptionEventId = r.getLong(ExceptionProjection.IDX_ID),
|
exceptionEventId = getLong(ExceptionProjection.IDX_ID),
|
||||||
originalInstanceMillis = r.getLong(ExceptionProjection.IDX_ORIGINAL_INSTANCE_TIME),
|
originalInstanceMillis = getLong(ExceptionProjection.IDX_ORIGINAL_INSTANCE_TIME),
|
||||||
isCancelled = status == CalendarContract.Events.STATUS_CANCELED,
|
isCancelled = getIntOrNull(ExceptionProjection.IDX_STATUS) == CalendarContract.Events.STATUS_CANCELED,
|
||||||
status = status,
|
dtStartMillis = getLong(ExceptionProjection.IDX_DTSTART),
|
||||||
title = r.getString(ExceptionProjection.IDX_TITLE).orEmpty(),
|
dtEndMillis = getLongOrNull(ExceptionProjection.IDX_DTEND),
|
||||||
isAllDay = r.getInt(ExceptionProjection.IDX_ALL_DAY) != 0,
|
duration = getString(ExceptionProjection.IDX_DURATION),
|
||||||
dtStartMillis = r.getLong(ExceptionProjection.IDX_DTSTART),
|
|
||||||
dtEndMillis = r.getLong(ExceptionProjection.IDX_DTEND)
|
|
||||||
.takeUnless { r.isNull(ExceptionProjection.IDX_DTEND) },
|
|
||||||
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()
|
||||||
@@ -1266,7 +1221,7 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
val exceptionId = ContentUris.parseId(uri)
|
val exceptionId = ContentUris.parseId(uri)
|
||||||
form.colorKey?.let { key ->
|
form.colorKey?.let { key ->
|
||||||
resolver.update(
|
resolver.update(
|
||||||
ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, exceptionId),
|
eventUri(exceptionId),
|
||||||
ContentValues().apply { put(CalendarContract.Events.EVENT_COLOR_KEY, key) },
|
ContentValues().apply { put(CalendarContract.Events.EVENT_COLOR_KEY, key) },
|
||||||
null, null,
|
null, null,
|
||||||
)
|
)
|
||||||
@@ -1320,34 +1275,19 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
// a fresh UID — the detached row is a separate event now, and sharing the
|
// a fresh UID — the detached row is a separate event now, and sharing the
|
||||||
// parent's would collide with it in .ics restore dedup.
|
// parent's would collide with it in .ics restore dedup.
|
||||||
val detachedId = insertEvent(form.toDetachedOccurrence(), allDayReminderTimeMinutes)
|
val detachedId = insertEvent(form.toDetachedOccurrence(), allDayReminderTimeMinutes)
|
||||||
val values = buildOccurrenceExdateValues(
|
|
||||||
existingExdate = row.exdate,
|
|
||||||
occurrenceMillis = beginMillis,
|
|
||||||
dtStartMillis = row.dtStartMillis,
|
|
||||||
rrule = row.rrule,
|
|
||||||
rdate = row.rdate,
|
|
||||||
duration = row.duration,
|
|
||||||
timezone = row.timezone,
|
|
||||||
allDay = row.allDay,
|
|
||||||
)
|
|
||||||
// Rows touched, not occurrences excluded — 1 whenever the series row still
|
// Rows touched, not occurrences excluded — 1 whenever the series row still
|
||||||
// exists. It catches the row disappearing under us, not an EXDATE the
|
// exists. It catches the row disappearing under us, not an EXDATE the
|
||||||
// provider's expansion fails to match.
|
// provider's expansion fails to match.
|
||||||
val updatedRows = try {
|
try {
|
||||||
resolver.update(
|
updateEventRow(
|
||||||
ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventId),
|
eventId,
|
||||||
values.toContentValues(), null, null,
|
row.exdateValues(listOf(beginMillis)),
|
||||||
|
"exdate occurrence for edit, event id=$eventId begin=$beginMillis",
|
||||||
)
|
)
|
||||||
} catch (t: Throwable) {
|
} catch (t: Throwable) {
|
||||||
rollBackDetached(detachedId)
|
rollBackDetached(detachedId)
|
||||||
throw t
|
throw t
|
||||||
}
|
}
|
||||||
if (updatedRows == 0) {
|
|
||||||
rollBackDetached(detachedId)
|
|
||||||
throw WriteFailedException(
|
|
||||||
"exdate occurrence for edit, event id=$eventId begin=$beginMillis",
|
|
||||||
)
|
|
||||||
}
|
|
||||||
return detachedId
|
return detachedId
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1420,23 +1360,11 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
updated = updated,
|
updated = updated,
|
||||||
zone = ZoneId.systemDefault(),
|
zone = ZoneId.systemDefault(),
|
||||||
) ?: return
|
) ?: return
|
||||||
val row = querySeriesRow(newEventId)
|
val values = querySeriesRow(newEventId).timeColumns().apply {
|
||||||
val values = ContentValues().apply {
|
|
||||||
put(CalendarContract.Events.EXDATE, carried)
|
put(CalendarContract.Events.EXDATE, carried)
|
||||||
put(CalendarContract.Events.DTSTART, row.dtStartMillis)
|
|
||||||
put(CalendarContract.Events.RRULE, row.rrule)
|
|
||||||
put(CalendarContract.Events.DURATION, row.duration)
|
|
||||||
put(CalendarContract.Events.EVENT_TIMEZONE, row.timezone)
|
|
||||||
put(CalendarContract.Events.ALL_DAY, row.allDay)
|
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
val rows = resolver.update(
|
updateEventRow(newEventId, values, "carry exdate onto split series id=$newEventId")
|
||||||
ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, newEventId),
|
|
||||||
values, null, null,
|
|
||||||
)
|
|
||||||
if (rows == 0) {
|
|
||||||
throw WriteFailedException("carry exdate onto split series id=$newEventId")
|
|
||||||
}
|
|
||||||
} catch (t: Throwable) {
|
} catch (t: Throwable) {
|
||||||
runCatching { deleteEvent(newEventId) }
|
runCatching { deleteEvent(newEventId) }
|
||||||
throw t
|
throw t
|
||||||
@@ -1464,29 +1392,18 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
*/
|
*/
|
||||||
private fun truncateSeries(eventId: Long, row: SeriesRow, beginMillis: Long) {
|
private fun truncateSeries(eventId: Long, row: SeriesRow, beginMillis: Long) {
|
||||||
requireNotNull(row.rrule) { "truncateSeries needs a recurring row" }
|
requireNotNull(row.rrule) { "truncateSeries needs a recurring row" }
|
||||||
val values = ContentValues().apply {
|
val values = row.timeColumns().apply {
|
||||||
put(CalendarContract.Events.DTSTART, row.dtStartMillis)
|
|
||||||
put(CalendarContract.Events.DURATION, row.duration)
|
|
||||||
put(CalendarContract.Events.EVENT_TIMEZONE, row.timezone)
|
|
||||||
put(CalendarContract.Events.ALL_DAY, row.allDay)
|
|
||||||
put(
|
put(
|
||||||
CalendarContract.Events.RRULE,
|
CalendarContract.Events.RRULE,
|
||||||
rruleTruncatedAt(row.rrule, untilUtcMillis = row.truncationCutoff(beginMillis)),
|
rruleTruncatedAt(row.rrule, untilUtcMillis = row.truncationCutoff(beginMillis)),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
val rows = resolver.update(
|
updateEventRow(eventId, values, "truncate series event id=$eventId begin=$beginMillis")
|
||||||
ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventId),
|
|
||||||
values,
|
|
||||||
null, null,
|
|
||||||
)
|
|
||||||
if (rows == 0) {
|
|
||||||
throw WriteFailedException("truncate series event id=$eventId begin=$beginMillis")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The series anchor: every time-related column of the Events row. */
|
/** The series anchor: every time-related column of the Events row. */
|
||||||
private fun querySeriesRow(eventId: Long): SeriesRow = resolver.query(
|
private fun querySeriesRow(eventId: Long): SeriesRow = resolver.query(
|
||||||
ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventId),
|
eventUri(eventId),
|
||||||
arrayOf(
|
arrayOf(
|
||||||
CalendarContract.Events.DTSTART,
|
CalendarContract.Events.DTSTART,
|
||||||
CalendarContract.Events.RRULE,
|
CalendarContract.Events.RRULE,
|
||||||
@@ -1534,6 +1451,30 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
*/
|
*/
|
||||||
val recurs: Boolean get() = !rrule.isNullOrBlank() || !rdate.isNullOrBlank()
|
val recurs: Boolean get() = !rrule.isNullOrBlank() || !rdate.isNullOrBlank()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The time/recurrence set a series write carries together: the provider
|
||||||
|
* re-expands instances only from what the update itself holds.
|
||||||
|
*/
|
||||||
|
fun timeColumns(): ContentValues = ContentValues().apply {
|
||||||
|
put(CalendarContract.Events.DTSTART, dtStartMillis)
|
||||||
|
put(CalendarContract.Events.RRULE, rrule)
|
||||||
|
put(CalendarContract.Events.DURATION, duration)
|
||||||
|
put(CalendarContract.Events.EVENT_TIMEZONE, timezone)
|
||||||
|
put(CalendarContract.Events.ALL_DAY, allDay)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** This row's columns with [occurrences] added to EXDATE ([buildOccurrencesExdateValues]). */
|
||||||
|
fun exdateValues(occurrences: List<Long>): Map<String, Any?> = buildOccurrencesExdateValues(
|
||||||
|
existingExdate = exdate,
|
||||||
|
occurrences = occurrences,
|
||||||
|
dtStartMillis = dtStartMillis,
|
||||||
|
rrule = rrule,
|
||||||
|
rdate = rdate,
|
||||||
|
duration = duration,
|
||||||
|
timezone = timezone,
|
||||||
|
allDay = allDay,
|
||||||
|
)
|
||||||
|
|
||||||
/** UNTIL cutoff for ending the series before the occurrence at [beginMillis]. */
|
/** UNTIL cutoff for ending the series before the occurrence at [beginMillis]. */
|
||||||
fun truncationCutoff(beginMillis: Long): Long = previousLocalDayEndUtcMillis(
|
fun truncationCutoff(beginMillis: Long): Long = previousLocalDayEndUtcMillis(
|
||||||
beginMillis = beginMillis,
|
beginMillis = beginMillis,
|
||||||
@@ -1559,20 +1500,10 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
arrayOf(eventId.toString(), minutes.toString()),
|
arrayOf(eventId.toString(), minutes.toString()),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
(target - existing).forEach { minutes ->
|
insertReminderRows(eventId, (target - existing).toList())
|
||||||
val reminder = ContentValues().apply {
|
|
||||||
put(CalendarContract.Reminders.EVENT_ID, eventId)
|
|
||||||
put(CalendarContract.Reminders.MINUTES, minutes)
|
|
||||||
put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT)
|
|
||||||
}
|
|
||||||
if (resolver.insert(CalendarContract.Reminders.CONTENT_URI, reminder) == null) {
|
|
||||||
Log.w(TAG, "Failed to attach reminder ($minutes min) to event $eventId")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Normalised key an attendee is matched/deduped on (case-insensitive email). */
|
private fun EventAttendee.key(): String = emailKey(email)
|
||||||
private fun EventAttendee.key(): String = email.trim().lowercase()
|
|
||||||
|
|
||||||
/** Distinct guests by email; blanks dropped (we key and write on the address). */
|
/** Distinct guests by email; blanks dropped (we key and write on the address). */
|
||||||
private fun List<EventAttendee>.distinctByEmail(): List<EventAttendee> {
|
private fun List<EventAttendee>.distinctByEmail(): List<EventAttendee> {
|
||||||
@@ -1624,7 +1555,7 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
val relationship: Int,
|
val relationship: Int,
|
||||||
val type: Int,
|
val type: Int,
|
||||||
) {
|
) {
|
||||||
val key: String get() = email.trim().lowercase()
|
val key: String get() = emailKey(email)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun queryAttendeeRows(eventId: Long): List<AttendeeRow> = resolver.query(
|
private fun queryAttendeeRows(eventId: Long): List<AttendeeRow> = resolver.query(
|
||||||
@@ -1689,17 +1620,20 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
target.filterNot { it.key() in editableKeys }.forEach { attendee ->
|
insertAttendees(eventId, target.filterNot { it.key() in editableKeys })
|
||||||
if (resolver.insert(
|
|
||||||
CalendarContract.Attendees.CONTENT_URI,
|
|
||||||
attendeeValues(eventId, attendee),
|
|
||||||
) == null
|
|
||||||
) {
|
|
||||||
Log.w(TAG, "Failed to attach a guest to event $eventId")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun eventUri(eventId: Long): Uri =
|
||||||
|
ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventId)
|
||||||
|
|
||||||
|
/** Update the Events row [eventId]; [what] names the write when no row was touched. */
|
||||||
|
private fun updateEventRow(eventId: Long, values: ContentValues, what: String) {
|
||||||
|
if (resolver.update(eventUri(eventId), values, null, null) == 0) throw WriteFailedException(what)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateEventRow(eventId: Long, values: Map<String, Any?>, what: String) =
|
||||||
|
updateEventRow(eventId, values.toContentValues(), what)
|
||||||
|
|
||||||
private fun Map<String, Any?>.toContentValues(): ContentValues =
|
private fun Map<String, Any?>.toContentValues(): ContentValues =
|
||||||
ContentValues().also { cv ->
|
ContentValues().also { cv ->
|
||||||
forEach { (column, value) ->
|
forEach { (column, value) ->
|
||||||
@@ -1716,7 +1650,7 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
|
|
||||||
override fun deleteEvent(eventId: Long) {
|
override fun deleteEvent(eventId: Long) {
|
||||||
val deleted = resolver.delete(
|
val deleted = resolver.delete(
|
||||||
ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventId),
|
eventUri(eventId),
|
||||||
null, null,
|
null, null,
|
||||||
)
|
)
|
||||||
if (deleted == 0) throw WriteFailedException("delete event id=$eventId")
|
if (deleted == 0) throw WriteFailedException("delete event id=$eventId")
|
||||||
@@ -1738,23 +1672,11 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
// occurrence with it (#47 on a local calendar). EXDATE needs no link.
|
// occurrence with it (#47 on a local calendar). EXDATE needs no link.
|
||||||
// Calendula's own contact special-date calendars are local and hold
|
// Calendula's own contact special-date calendars are local and hold
|
||||||
// yearly series, so this path is reached in normal use.
|
// yearly series, so this path is reached in normal use.
|
||||||
val values = buildOccurrenceExdateValues(
|
updateEventRow(
|
||||||
existingExdate = row.exdate,
|
eventId,
|
||||||
occurrenceMillis = beginMillis,
|
row.exdateValues(listOf(beginMillis)),
|
||||||
dtStartMillis = row.dtStartMillis,
|
"exdate occurrence event id=$eventId begin=$beginMillis",
|
||||||
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, eventId),
|
|
||||||
values.toContentValues(), null, null,
|
|
||||||
)
|
|
||||||
if (updated == 0) {
|
|
||||||
throw WriteFailedException("exdate occurrence event id=$eventId begin=$beginMillis")
|
|
||||||
}
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// A cancelled exception row hides exactly this occurrence; the sync
|
// A cancelled exception row hides exactly this occurrence; the sync
|
||||||
@@ -1804,7 +1726,7 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
CalendarContract.Attendees.EVENT_ID + " = ?",
|
CalendarContract.Attendees.EVENT_ID + " = ?",
|
||||||
arrayOf(eventId.toString()),
|
arrayOf(eventId.toString()),
|
||||||
null,
|
null,
|
||||||
)?.use { c -> c.mapAll { CursorColumnReader(c).toAttendee() } } ?: emptyList()
|
)?.use { c -> c.mapRows { toAttendee() } } ?: emptyList()
|
||||||
|
|
||||||
private fun queryReminders(eventId: Long): List<Reminder> = resolver.query(
|
private fun queryReminders(eventId: Long): List<Reminder> = resolver.query(
|
||||||
CalendarContract.Reminders.CONTENT_URI,
|
CalendarContract.Reminders.CONTENT_URI,
|
||||||
@@ -1812,19 +1734,10 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
CalendarContract.Reminders.EVENT_ID + " = ?",
|
CalendarContract.Reminders.EVENT_ID + " = ?",
|
||||||
arrayOf(eventId.toString()),
|
arrayOf(eventId.toString()),
|
||||||
null,
|
null,
|
||||||
)?.use { c -> c.mapAll { CursorColumnReader(c).toReminder() } } ?: emptyList()
|
)?.use { c -> c.mapRows { toReminder() } } ?: emptyList()
|
||||||
|
|
||||||
private fun toCalendarSource(c: Cursor): CalendarSource = CursorColumnReader(c).toCalendarSource()
|
/** A fresh globally-unique `UID_2445`, for an event that carries none of its own. */
|
||||||
|
private fun mintUid(): String = "${UUID.randomUUID()}@calendula"
|
||||||
/** Iterate every row and map; skips nothing. */
|
|
||||||
private inline fun <T> Cursor.mapAll(mapper: (Cursor) -> T): List<T> = buildList {
|
|
||||||
while (moveToNext()) add(mapper(this@mapAll))
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Iterate every row and map; drops nulls. */
|
|
||||||
private inline fun <T : Any> Cursor.mapAllNotNull(mapper: (Cursor) -> T?): List<T> = buildList {
|
|
||||||
while (moveToNext()) mapper(this@mapAllNotNull)?.let(::add)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The `CAL_SYNC2` marker value identifying a managed calendar's [type]. */
|
/** The `CAL_SYNC2` marker value identifying a managed calendar's [type]. */
|
||||||
private fun markerFor(type: SpecialDateType): String = when (type) {
|
private fun markerFor(type: SpecialDateType): String = when (type) {
|
||||||
@@ -1840,6 +1753,9 @@ class AndroidCalendarDataSource @Inject constructor(
|
|||||||
private companion object {
|
private companion object {
|
||||||
const val TAG = "CalendarDataSource"
|
const val TAG = "CalendarDataSource"
|
||||||
|
|
||||||
|
/** Normalised key an attendee is matched/deduped on (case-insensitive email). */
|
||||||
|
fun emailKey(email: String): String = email.trim().lowercase()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Shared account for every app-created local calendar, so they group
|
* Shared account for every app-created local calendar, so they group
|
||||||
* together (by account) in the filter sheet and calendar manager.
|
* together (by account) in the filter sheet and calendar manager.
|
||||||
|
|||||||
@@ -10,14 +10,22 @@ import de.jeanlucmakiola.calendula.domain.ics.IcsEvent
|
|||||||
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.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.flow.emptyFlow
|
||||||
import kotlin.time.Instant
|
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>>
|
||||||
|
|
||||||
|
/** One read of event [eventId]'s occurrences overlapping [range], soonest first, whatever calendar it is in. */
|
||||||
|
suspend fun eventOccurrences(eventId: Long, range: ClosedRange<Instant>): List<EventInstance>
|
||||||
|
|
||||||
/** Re-query every open [calendars] / [instances] flow. */
|
/** Re-query every open [calendars] / [instances] flow. */
|
||||||
fun refresh()
|
fun refresh()
|
||||||
|
|
||||||
|
/** Emits on the app's own writes and visibility changes; not on provider notifications or [refresh]. */
|
||||||
|
val localChanges: Flow<Unit>
|
||||||
|
|
||||||
suspend fun eventDetail(eventId: Long): EventDetail
|
suspend fun eventDetail(eventId: Long): EventDetail
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -29,7 +37,7 @@ interface CalendarRepository {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* The event-colour palette a calendar's account publishes; empty when it
|
* The event-colour palette a calendar's account publishes; empty when it
|
||||||
* exposes none (see [CalendarDataSource.eventColorPalette]).
|
* exposes none (see [CalendarDataSource.publishedEventColors]).
|
||||||
*/
|
*/
|
||||||
suspend fun eventColorPalette(calendarId: Long): List<EventColorOption>
|
suspend fun eventColorPalette(calendarId: Long): List<EventColorOption>
|
||||||
|
|
||||||
@@ -101,6 +109,12 @@ interface CalendarRepository {
|
|||||||
form: EventForm,
|
form: EventForm,
|
||||||
): Long
|
): Long
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Every series split the app makes ([updateEventFromOccurrence]), so what
|
||||||
|
* follows a series by id can move on to the part that continues it.
|
||||||
|
*/
|
||||||
|
val seriesSplits: Flow<SeriesSplit> get() = emptyFlow()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Change a recurring event from [beginMillis] onwards (series split);
|
* Change a recurring event from [beginMillis] onwards (series split);
|
||||||
* returns the new event's `Events._ID`.
|
* returns the new event's `Events._ID`.
|
||||||
@@ -128,3 +142,6 @@ class NoSuchEventException(eventId: Long) :
|
|||||||
/** A ContentResolver write affected no rows or returned no URI. */
|
/** A ContentResolver write affected no rows or returned no URI. */
|
||||||
class WriteFailedException(operation: String) :
|
class WriteFailedException(operation: String) :
|
||||||
RuntimeException("Calendar write failed: $operation")
|
RuntimeException("Calendar write failed: $operation")
|
||||||
|
|
||||||
|
/** A "this and following" edit: [oldEventId] now ends where [newEventId] picks up. */
|
||||||
|
data class SeriesSplit(val oldEventId: Long, val newEventId: Long)
|
||||||
+39
-16
@@ -1,10 +1,11 @@
|
|||||||
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.curatedForPicker
|
||||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||||
import de.jeanlucmakiola.calendula.domain.EventColorOption
|
import de.jeanlucmakiola.calendula.domain.EventColorOption
|
||||||
import de.jeanlucmakiola.calendula.domain.EventDetail
|
import de.jeanlucmakiola.calendula.domain.EventDetail
|
||||||
@@ -77,15 +78,28 @@ class CalendarRepositoryImpl @Inject constructor(
|
|||||||
ticks.tryEmit(Unit)
|
ticks.tryEmit(Unit)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private val writes = MutableSharedFlow<Unit>(
|
||||||
|
replay = 0,
|
||||||
|
extraBufferCapacity = 1,
|
||||||
|
onBufferOverflow = BufferOverflow.DROP_OLDEST,
|
||||||
|
)
|
||||||
|
|
||||||
/** Run a provider write on [io], then re-query whether or not it threw. */
|
/** Run a provider write on [io], then re-query whether or not it threw. */
|
||||||
private suspend fun <T> write(block: suspend () -> T): T = withContext(io) {
|
private suspend fun <T> write(block: suspend () -> T): T = withContext(io) {
|
||||||
try {
|
try {
|
||||||
block()
|
block()
|
||||||
} finally {
|
} finally {
|
||||||
refresh()
|
refresh()
|
||||||
|
writes.tryEmit(Unit)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override val localChanges: Flow<Unit> = merge(
|
||||||
|
writes,
|
||||||
|
prefs.pendingDisabledCalendarIds.distinctUntilChanged().drop(1).map {},
|
||||||
|
prefs.hiddenCalendarIds.distinctUntilChanged().drop(1).map {},
|
||||||
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Re-query signal for everything filtered by visibility: the provider's own
|
* Re-query signal for everything filtered by visibility: the provider's own
|
||||||
* notifications, plus every change to the pending switch-off set.
|
* notifications, plus every change to the pending switch-off set.
|
||||||
@@ -125,8 +139,7 @@ class CalendarRepositoryImpl @Inject constructor(
|
|||||||
beginMillis = range.start.toEpochMillis(),
|
beginMillis = range.start.toEpochMillis(),
|
||||||
endMillis = range.endInclusive.toEpochMillis(),
|
endMillis = range.endInclusive.toEpochMillis(),
|
||||||
),
|
),
|
||||||
switchedOffCalendarIds = invisibleCalendarIds() +
|
switchedOffCalendarIds = switchedOffCalendarIds(),
|
||||||
prefs.pendingDisabledCalendarIds.first(),
|
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
prefs.hiddenCalendarIds,
|
prefs.hiddenCalendarIds,
|
||||||
@@ -151,6 +164,10 @@ class CalendarRepositoryImpl @Inject constructor(
|
|||||||
.filterNot { it.isVisibleInSystem }
|
.filterNot { it.isVisibleInSystem }
|
||||||
.mapTo(mutableSetOf()) { it.id }
|
.mapTo(mutableSetOf()) { it.id }
|
||||||
|
|
||||||
|
/** [invisibleCalendarIds] plus the switch-offs still waiting to be written. */
|
||||||
|
private suspend fun switchedOffCalendarIds(): Set<Long> =
|
||||||
|
invisibleCalendarIds() + prefs.pendingDisabledCalendarIds.first()
|
||||||
|
|
||||||
private val calendarsLock = Mutex()
|
private val calendarsLock = Mutex()
|
||||||
private var cachedGeneration = -1L
|
private var cachedGeneration = -1L
|
||||||
private var cachedPending: Set<Long>? = null
|
private var cachedPending: Set<Long>? = null
|
||||||
@@ -177,6 +194,11 @@ class CalendarRepositoryImpl @Inject constructor(
|
|||||||
cachedCalendars
|
cachedCalendars
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override suspend fun eventOccurrences(eventId: Long, range: ClosedRange<Instant>): List<EventInstance> =
|
||||||
|
withContext(io) {
|
||||||
|
dataSource.eventInstances(eventId, range.start.toEpochMillis(), range.endInclusive.toEpochMillis())
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun eventDetail(eventId: Long): EventDetail = withContext(io) {
|
override suspend fun eventDetail(eventId: Long): EventDetail = withContext(io) {
|
||||||
dataSource.eventDetail(eventId, allDayReminderTimeMinutes())
|
dataSource.eventDetail(eventId, allDayReminderTimeMinutes())
|
||||||
?: throw NoSuchEventException(eventId)
|
?: throw NoSuchEventException(eventId)
|
||||||
@@ -184,15 +206,13 @@ class CalendarRepositoryImpl @Inject constructor(
|
|||||||
|
|
||||||
override suspend fun searchEvents(query: String): List<SearchCandidate> = withContext(io) {
|
override suspend fun searchEvents(query: String): List<SearchCandidate> = withContext(io) {
|
||||||
if (query.isBlank()) return@withContext emptyList()
|
if (query.isBlank()) return@withContext emptyList()
|
||||||
val excluded = prefs.hiddenCalendarIds.first() +
|
val excluded = prefs.hiddenCalendarIds.first() + switchedOffCalendarIds()
|
||||||
prefs.pendingDisabledCalendarIds.first() +
|
|
||||||
invisibleCalendarIds()
|
|
||||||
dataSource.searchEvents(query)
|
dataSource.searchEvents(query)
|
||||||
.let { if (excluded.isEmpty()) it else it.filterNot { c -> c.event.calendarId in excluded } }
|
.let { if (excluded.isEmpty()) it else it.filterNot { c -> c.event.calendarId in excluded } }
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun eventColorPalette(calendarId: Long): List<EventColorOption> =
|
override suspend fun eventColorPalette(calendarId: Long): List<EventColorOption> =
|
||||||
withContext(io) { dataSource.eventColorPalette(calendarId) }
|
withContext(io) { dataSource.publishedEventColors(calendarId).curatedForPicker() }
|
||||||
|
|
||||||
override suspend fun createLocalCalendar(
|
override suspend fun createLocalCalendar(
|
||||||
displayName: String,
|
displayName: String,
|
||||||
@@ -214,16 +234,15 @@ class CalendarRepositoryImpl @Inject constructor(
|
|||||||
|
|
||||||
override suspend fun setCalendarsVisible(ids: Collection<Long>, visible: Boolean) =
|
override suspend fun setCalendarsVisible(ids: Collection<Long>, visible: Boolean) =
|
||||||
write {
|
write {
|
||||||
if (dataSource.canWriteCalendars()) {
|
val canWrite = dataSource.canWriteCalendars()
|
||||||
ids.forEach { dataSource.setCalendarVisible(it, visible) }
|
if (canWrite) 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 write
|
||||||
// write lands (and switching one back on retires its entry).
|
// lands, and switching one back on retires its entry. With read-only
|
||||||
prefs.removePendingDisabledCalendarIds(ids)
|
// permission a switch-off still works, app-side, and the reconciler
|
||||||
} else if (visible) {
|
// flushes it if WRITE_CALENDAR ever arrives.
|
||||||
|
if (canWrite || visible) {
|
||||||
prefs.removePendingDisabledCalendarIds(ids)
|
prefs.removePendingDisabledCalendarIds(ids)
|
||||||
} else {
|
} else {
|
||||||
// Read-only permission: the switch still works, app-side, and
|
|
||||||
// the reconciler flushes it if WRITE_CALENDAR ever arrives.
|
|
||||||
prefs.addPendingDisabledCalendarIds(ids)
|
prefs.addPendingDisabledCalendarIds(ids)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -332,7 +351,11 @@ class CalendarRepositoryImpl @Inject constructor(
|
|||||||
dataSource.updateEventFromOccurrence(
|
dataSource.updateEventFromOccurrence(
|
||||||
eventId, beginMillis, original, updated, allDayReminderTimeMinutes(),
|
eventId, beginMillis, original, updated, allDayReminderTimeMinutes(),
|
||||||
)
|
)
|
||||||
}
|
}.also { newId -> if (newId != eventId) splits.tryEmit(SeriesSplit(eventId, newId)) }
|
||||||
|
|
||||||
|
private val splits = MutableSharedFlow<SeriesSplit>(extraBufferCapacity = 8)
|
||||||
|
|
||||||
|
override val seriesSplits: Flow<SeriesSplit> = splits
|
||||||
|
|
||||||
override suspend fun deleteOccurrence(eventId: Long, beginMillis: Long) = write {
|
override suspend fun deleteOccurrence(eventId: Long, beginMillis: Long) = write {
|
||||||
dataSource.deleteOccurrence(eventId, beginMillis)
|
dataSource.deleteOccurrence(eventId, beginMillis)
|
||||||
|
|||||||
+4
-7
@@ -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,6 +1,11 @@
|
|||||||
package de.jeanlucmakiola.calendula.data.calendar
|
package de.jeanlucmakiola.calendula.data.calendar
|
||||||
|
|
||||||
import android.database.Cursor
|
import android.database.Cursor
|
||||||
|
import de.jeanlucmakiola.calendula.domain.EventStatus
|
||||||
|
import de.jeanlucmakiola.calendula.domain.ics.parseRfc2445DurationMillis
|
||||||
|
import java.time.Instant
|
||||||
|
import java.time.LocalDate
|
||||||
|
import java.time.ZoneOffset
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Read-only view over a single row's columns by index. Lets the mappers work
|
* Read-only view over a single row's columns by index. Lets the mappers work
|
||||||
@@ -20,3 +25,33 @@ internal class CursorColumnReader(private val cursor: Cursor) : ColumnReader {
|
|||||||
override fun getInt(index: Int): Int = cursor.getInt(index)
|
override fun getInt(index: Int): Int = cursor.getInt(index)
|
||||||
override fun isNull(index: Int): Boolean = cursor.isNull(index)
|
override fun isNull(index: Int): Boolean = cursor.isNull(index)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal fun ColumnReader.getIntOrNull(index: Int): Int? = if (isNull(index)) null else getInt(index)
|
||||||
|
|
||||||
|
internal fun ColumnReader.getLongOrNull(index: Int): Long? = if (isNull(index)) null else getLong(index)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The row's end: DTEND, or DTSTART + DURATION for a recurring row, which stores
|
||||||
|
* no DTEND. Unclamped; a missing/blank both means a zero-length event.
|
||||||
|
*/
|
||||||
|
internal fun ColumnReader.endMillis(dtStartMillis: Long, dtEndIndex: Int, durationIndex: Int): Long =
|
||||||
|
getLongOrNull(dtEndIndex) ?: (dtStartMillis + parseRfc2445DurationMillis(getString(durationIndex)))
|
||||||
|
|
||||||
|
/** STATUS shares value 0 with TENTATIVE, so an absent column must read as Confirmed. */
|
||||||
|
internal fun ColumnReader.eventStatus(index: Int): EventStatus =
|
||||||
|
getIntOrNull(index)?.let(::mapEventStatus) ?: EventStatus.Confirmed
|
||||||
|
|
||||||
|
/** Map every row, reading each through one [CursorColumnReader]. */
|
||||||
|
internal inline fun <T> Cursor.mapRows(map: ColumnReader.() -> T): List<T> {
|
||||||
|
val reader = CursorColumnReader(this)
|
||||||
|
return buildList { while (moveToNext()) add(reader.map()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** [mapRows], dropping the rows [map] returns null for. */
|
||||||
|
internal inline fun <T : Any> Cursor.mapRowsNotNull(map: ColumnReader.() -> T?): List<T> {
|
||||||
|
val reader = CursorColumnReader(this)
|
||||||
|
return buildList { while (moveToNext()) reader.map()?.let(::add) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The UTC calendar day of [millis] — an all-day row's date, since it sits at UTC midnight. */
|
||||||
|
internal fun utcDate(millis: Long): LocalDate = Instant.ofEpochMilli(millis).atZone(ZoneOffset.UTC).toLocalDate()
|
||||||
@@ -15,9 +15,7 @@ import de.jeanlucmakiola.calendula.domain.EventStatus
|
|||||||
import de.jeanlucmakiola.calendula.domain.Reminder
|
import de.jeanlucmakiola.calendula.domain.Reminder
|
||||||
import de.jeanlucmakiola.calendula.domain.ReminderMethod
|
import de.jeanlucmakiola.calendula.domain.ReminderMethod
|
||||||
import de.jeanlucmakiola.calendula.domain.ics.parseRfc2445DurationMillis
|
import de.jeanlucmakiola.calendula.domain.ics.parseRfc2445DurationMillis
|
||||||
import java.time.Instant
|
|
||||||
import java.time.ZoneId
|
import java.time.ZoneId
|
||||||
import java.time.ZoneOffset
|
|
||||||
|
|
||||||
private const val TAG = "EventDetailMapper"
|
private const val TAG = "EventDetailMapper"
|
||||||
|
|
||||||
@@ -48,11 +46,8 @@ internal fun ColumnReader.toEventDetailCore(
|
|||||||
// — the same trap as the pre-1970 DTSTART bug above (issue #34): it would
|
// — the same trap as the pre-1970 DTSTART bug above (issue #34): it would
|
||||||
// surface as the generic error screen with no way to open the event and fix
|
// surface as the generic error screen with no way to open the event and fix
|
||||||
// it. Clamp to a zero-length event instead (matching SearchMapper).
|
// it. Clamp to a zero-length event instead (matching SearchMapper).
|
||||||
val end = if (isNull(EventDetailProjection.IDX_DTEND)) {
|
val end = getLongOrNull(EventDetailProjection.IDX_DTEND)?.coerceAtLeast(begin)
|
||||||
begin + parseRfc2445DurationMillis(getString(EventDetailProjection.IDX_DURATION))
|
?: (begin + parseRfc2445DurationMillis(getString(EventDetailProjection.IDX_DURATION)))
|
||||||
} else {
|
|
||||||
getLong(EventDetailProjection.IDX_DTEND).coerceAtLeast(begin)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Kept raw (no untitled fallback): the detail screen substitutes its own
|
// Kept raw (no untitled fallback): the detail screen substitutes its own
|
||||||
// localized placeholder, and the edit form must prefill the true value.
|
// localized placeholder, and the edit form must prefill the true value.
|
||||||
@@ -61,11 +56,7 @@ internal fun ColumnReader.toEventDetailCore(
|
|||||||
// The event's own colour (null = inherits the calendar's) is kept apart
|
// The event's own colour (null = inherits the calendar's) is kept apart
|
||||||
// from the resolved display colour: the edit form needs to tell the two
|
// from the resolved display colour: the edit form needs to tell the two
|
||||||
// cases apart, while the instance carries the calendar fallback for display.
|
// cases apart, while the instance carries the calendar fallback for display.
|
||||||
val eventColor = if (isNull(EventDetailProjection.IDX_EVENT_COLOR)) {
|
val eventColor = getIntOrNull(EventDetailProjection.IDX_EVENT_COLOR)
|
||||||
null
|
|
||||||
} else {
|
|
||||||
getInt(EventDetailProjection.IDX_EVENT_COLOR)
|
|
||||||
}
|
|
||||||
val eventColorKey = getString(EventDetailProjection.IDX_EVENT_COLOR_KEY)
|
val eventColorKey = getString(EventDetailProjection.IDX_EVENT_COLOR_KEY)
|
||||||
val color = eventColor ?: getInt(EventDetailProjection.IDX_CALENDAR_COLOR)
|
val color = eventColor ?: getInt(EventDetailProjection.IDX_CALENDAR_COLOR)
|
||||||
|
|
||||||
@@ -88,7 +79,7 @@ internal fun ColumnReader.toEventDetailCore(
|
|||||||
// and detail screen speak. DTSTART is UTC midnight for all-day events, so the
|
// and detail screen speak. DTSTART is UTC midnight for all-day events, so the
|
||||||
// event's date is its UTC date.
|
// event's date is its UTC date.
|
||||||
val displayReminders = if (isAllDay) {
|
val displayReminders = if (isAllDay) {
|
||||||
val startDate = Instant.ofEpochMilli(begin).atZone(ZoneOffset.UTC).toLocalDate()
|
val startDate = utcDate(begin)
|
||||||
val zone = ZoneId.systemDefault()
|
val zone = ZoneId.systemDefault()
|
||||||
reminders.map {
|
reminders.map {
|
||||||
it.copy(
|
it.copy(
|
||||||
@@ -101,14 +92,6 @@ internal fun ColumnReader.toEventDetailCore(
|
|||||||
reminders
|
reminders
|
||||||
}
|
}
|
||||||
|
|
||||||
// STATUS shares its 0 value with STATUS_TENTATIVE, so a missing column must
|
|
||||||
// be distinguished from a present 0 — an absent status means "just confirmed".
|
|
||||||
val status = if (isNull(EventDetailProjection.IDX_STATUS)) {
|
|
||||||
EventStatus.Confirmed
|
|
||||||
} else {
|
|
||||||
mapEventStatus(getInt(EventDetailProjection.IDX_STATUS))
|
|
||||||
}
|
|
||||||
|
|
||||||
return EventDetail(
|
return EventDetail(
|
||||||
instance = instance,
|
instance = instance,
|
||||||
description = getString(EventDetailProjection.IDX_DESCRIPTION),
|
description = getString(EventDetailProjection.IDX_DESCRIPTION),
|
||||||
@@ -116,7 +99,7 @@ internal fun ColumnReader.toEventDetailCore(
|
|||||||
attendees = attendees,
|
attendees = attendees,
|
||||||
rrule = getString(EventDetailProjection.IDX_RRULE),
|
rrule = getString(EventDetailProjection.IDX_RRULE),
|
||||||
reminders = displayReminders,
|
reminders = displayReminders,
|
||||||
status = status,
|
status = eventStatus(EventDetailProjection.IDX_STATUS),
|
||||||
// BUSY and DEFAULT are both 0, so a null column folds into the same
|
// BUSY and DEFAULT are both 0, so a null column folds into the same
|
||||||
// default these mappers already return — no isNull guard needed.
|
// default these mappers already return — no isNull guard needed.
|
||||||
availability = mapAvailability(getInt(EventDetailProjection.IDX_AVAILABILITY)),
|
availability = mapAvailability(getInt(EventDetailProjection.IDX_AVAILABILITY)),
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ 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.FormTime
|
||||||
import de.jeanlucmakiola.calendula.domain.EventStatus
|
import de.jeanlucmakiola.calendula.domain.EventStatus
|
||||||
|
import de.jeanlucmakiola.calendula.domain.forNewEvent
|
||||||
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
|
||||||
@@ -132,6 +133,8 @@ internal fun buildEventInsertValues(
|
|||||||
put(CalendarContract.Events.EVENT_TIMEZONE, times.timezone)
|
put(CalendarContract.Events.EVENT_TIMEZONE, times.timezone)
|
||||||
put(CalendarContract.Events.AVAILABILITY, form.availability.toProviderValue())
|
put(CalendarContract.Events.AVAILABILITY, form.availability.toProviderValue())
|
||||||
put(CalendarContract.Events.ACCESS_LEVEL, form.accessLevel.toProviderValue())
|
put(CalendarContract.Events.ACCESS_LEVEL, form.accessLevel.toProviderValue())
|
||||||
|
form.status.forNewEvent().takeIf { it != EventStatus.Confirmed }
|
||||||
|
?.let { put(CalendarContract.Events.STATUS, it.toProviderStatus()) }
|
||||||
form.location.trim().takeIf { it.isNotEmpty() }
|
form.location.trim().takeIf { it.isNotEmpty() }
|
||||||
?.let { put(CalendarContract.Events.EVENT_LOCATION, it) }
|
?.let { put(CalendarContract.Events.EVENT_LOCATION, it) }
|
||||||
form.description.trim().takeIf { it.isNotEmpty() }
|
form.description.trim().takeIf { it.isNotEmpty() }
|
||||||
@@ -179,6 +182,9 @@ internal fun buildEventUpdateValues(
|
|||||||
if (updated.accessLevel != original.accessLevel) {
|
if (updated.accessLevel != original.accessLevel) {
|
||||||
put(CalendarContract.Events.ACCESS_LEVEL, updated.accessLevel.toProviderValue())
|
put(CalendarContract.Events.ACCESS_LEVEL, updated.accessLevel.toProviderValue())
|
||||||
}
|
}
|
||||||
|
if (updated.status != original.status) {
|
||||||
|
put(CalendarContract.Events.STATUS, updated.status.toProviderStatus())
|
||||||
|
}
|
||||||
if (updated.colorKey != original.colorKey || updated.color != original.color) {
|
if (updated.colorKey != original.colorKey || updated.color != original.color) {
|
||||||
putAll(eventColorColumns(updated.colorKey, updated.color))
|
putAll(eventColorColumns(updated.colorKey, updated.color))
|
||||||
}
|
}
|
||||||
@@ -279,6 +285,7 @@ internal fun buildOccurrenceExceptionValues(
|
|||||||
put(CalendarContract.Events.EVENT_TIMEZONE, times.timezone)
|
put(CalendarContract.Events.EVENT_TIMEZONE, times.timezone)
|
||||||
put(CalendarContract.Events.AVAILABILITY, form.availability.toProviderValue())
|
put(CalendarContract.Events.AVAILABILITY, form.availability.toProviderValue())
|
||||||
put(CalendarContract.Events.ACCESS_LEVEL, form.accessLevel.toProviderValue())
|
put(CalendarContract.Events.ACCESS_LEVEL, form.accessLevel.toProviderValue())
|
||||||
|
put(CalendarContract.Events.STATUS, form.status.forNewEvent().toProviderStatus())
|
||||||
put(CalendarContract.Events.EVENT_LOCATION, form.location.trim().ifEmpty { null })
|
put(CalendarContract.Events.EVENT_LOCATION, form.location.trim().ifEmpty { null })
|
||||||
put(CalendarContract.Events.DESCRIPTION, form.description.trim().ifEmpty { null })
|
put(CalendarContract.Events.DESCRIPTION, form.description.trim().ifEmpty { null })
|
||||||
if (form.colorKey == null) putAll(eventColorColumns(null, form.color))
|
if (form.colorKey == null) putAll(eventColorColumns(null, form.color))
|
||||||
@@ -354,7 +361,8 @@ internal fun buildMovedMasterValues(
|
|||||||
}
|
}
|
||||||
put(CalendarContract.Events.AVAILABILITY, snapshot.availability)
|
put(CalendarContract.Events.AVAILABILITY, snapshot.availability)
|
||||||
put(CalendarContract.Events.ACCESS_LEVEL, snapshot.accessLevel)
|
put(CalendarContract.Events.ACCESS_LEVEL, snapshot.accessLevel)
|
||||||
snapshot.status?.let { put(CalendarContract.Events.STATUS, it) }
|
snapshot.status?.takeIf { it != CalendarContract.Events.STATUS_CANCELED }
|
||||||
|
?.let { put(CalendarContract.Events.STATUS, it) }
|
||||||
put(CalendarContract.Events.EVENT_LOCATION, snapshot.location?.ifEmpty { null })
|
put(CalendarContract.Events.EVENT_LOCATION, snapshot.location?.ifEmpty { null })
|
||||||
put(CalendarContract.Events.DESCRIPTION, snapshot.description?.ifEmpty { null })
|
put(CalendarContract.Events.DESCRIPTION, snapshot.description?.ifEmpty { null })
|
||||||
}
|
}
|
||||||
@@ -372,48 +380,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
|
||||||
@@ -479,9 +450,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,
|
||||||
@@ -631,7 +617,7 @@ internal fun exdateAfter(
|
|||||||
* optionally behind the parameter prefix AOSP's `RecurrenceSet` puts in front of
|
* optionally behind the parameter prefix AOSP's `RecurrenceSet` puts in front of
|
||||||
* a zoned one ([exdateListZone] reads that half).
|
* a zoned one ([exdateListZone] reads that half).
|
||||||
*/
|
*/
|
||||||
private fun exdateStamps(exdate: String?): List<String> = exdate
|
internal fun exdateStamps(exdate: String?): List<String> = exdate
|
||||||
?.withoutExdateParameters()
|
?.withoutExdateParameters()
|
||||||
?.split(',')
|
?.split(',')
|
||||||
?.map { it.trim() }
|
?.map { it.trim() }
|
||||||
@@ -880,7 +866,7 @@ internal fun buildImportedEventValues(
|
|||||||
// timed rows keep the event's own zone.
|
// timed rows keep the event's own zone.
|
||||||
put(CalendarContract.Events.EVENT_TIMEZONE, if (event.isAllDay) "UTC" else event.zoneId)
|
put(CalendarContract.Events.EVENT_TIMEZONE, if (event.isAllDay) "UTC" else event.zoneId)
|
||||||
put(CalendarContract.Events.AVAILABILITY, event.availability.toProviderValue())
|
put(CalendarContract.Events.AVAILABILITY, event.availability.toProviderValue())
|
||||||
put(CalendarContract.Events.STATUS, event.status.toProviderStatus())
|
put(CalendarContract.Events.STATUS, event.status.forNewEvent().toProviderStatus())
|
||||||
event.location?.trim()?.takeIf { it.isNotEmpty() }
|
event.location?.trim()?.takeIf { it.isNotEmpty() }
|
||||||
?.let { put(CalendarContract.Events.EVENT_LOCATION, it) }
|
?.let { put(CalendarContract.Events.EVENT_LOCATION, it) }
|
||||||
event.description?.trim()?.takeIf { it.isNotEmpty() }
|
event.description?.trim()?.takeIf { it.isNotEmpty() }
|
||||||
@@ -901,7 +887,7 @@ internal fun buildImportedEventValues(
|
|||||||
*/
|
*/
|
||||||
private fun importDuration(startMillis: Long, endMillis: Long, isAllDay: Boolean): String {
|
private fun importDuration(startMillis: Long, endMillis: Long, isAllDay: Boolean): String {
|
||||||
val span = (endMillis - startMillis).coerceAtLeast(0)
|
val span = (endMillis - startMillis).coerceAtLeast(0)
|
||||||
return if (isAllDay) "P${(span / 86_400_000L).coerceAtLeast(1)}D" else "P${span / 1_000L}S"
|
return rfc2445Duration(if (isAllDay) span.coerceAtLeast(MILLIS_PER_DAY) else span, isAllDay)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun EventStatus.toProviderStatus(): Int = when (this) {
|
private fun EventStatus.toProviderStatus(): Int = when (this) {
|
||||||
|
|||||||
@@ -1,13 +1,9 @@
|
|||||||
package de.jeanlucmakiola.calendula.data.calendar
|
package de.jeanlucmakiola.calendula.data.calendar
|
||||||
|
|
||||||
import de.jeanlucmakiola.floret.time.toKotlinInstantFromEpochMillis
|
import de.jeanlucmakiola.floret.time.toKotlinInstantFromEpochMillis
|
||||||
import de.jeanlucmakiola.calendula.domain.EventStatus
|
|
||||||
import de.jeanlucmakiola.calendula.domain.ics.IcsEvent
|
import de.jeanlucmakiola.calendula.domain.ics.IcsEvent
|
||||||
import de.jeanlucmakiola.calendula.domain.ics.deriveIcsUid
|
import de.jeanlucmakiola.calendula.domain.ics.deriveIcsUid
|
||||||
import de.jeanlucmakiola.calendula.domain.ics.parseRfc2445DurationMillis
|
|
||||||
import java.time.Instant
|
|
||||||
import java.time.ZoneId
|
import java.time.ZoneId
|
||||||
import java.time.ZoneOffset
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Map one Events row (read through [EventExportProjection]) into an [IcsEvent]
|
* Map one Events row (read through [EventExportProjection]) into an [IcsEvent]
|
||||||
@@ -33,19 +29,8 @@ internal fun ColumnReader.toIcsEvent(
|
|||||||
val rrule = getString(EventExportProjection.IDX_RRULE)?.takeIf { it.isNotBlank() }
|
val rrule = getString(EventExportProjection.IDX_RRULE)?.takeIf { it.isNotBlank() }
|
||||||
val isAllDay = getInt(EventExportProjection.IDX_ALL_DAY) != 0
|
val isAllDay = getInt(EventExportProjection.IDX_ALL_DAY) != 0
|
||||||
|
|
||||||
// Recurring rows store DURATION instead of DTEND; reconstruct the end from it
|
// Unclamped: the writer renders DTEND as stored.
|
||||||
// so the writer can render DTEND. A missing/blank both means a zero-length event.
|
val end = endMillis(dtStart, EventExportProjection.IDX_DTEND, EventExportProjection.IDX_DURATION)
|
||||||
val end = when {
|
|
||||||
!isNull(EventExportProjection.IDX_DTEND) -> getLong(EventExportProjection.IDX_DTEND)
|
|
||||||
else -> dtStart + parseRfc2445DurationMillis(getString(EventExportProjection.IDX_DURATION))
|
|
||||||
}
|
|
||||||
|
|
||||||
// STATUS shares value 0 with TENTATIVE, so an absent column must read as Confirmed.
|
|
||||||
val status = if (isNull(EventExportProjection.IDX_STATUS)) {
|
|
||||||
EventStatus.Confirmed
|
|
||||||
} else {
|
|
||||||
mapEventStatus(getInt(EventExportProjection.IDX_STATUS))
|
|
||||||
}
|
|
||||||
|
|
||||||
return IcsEvent(
|
return IcsEvent(
|
||||||
uid = deriveIcsUid(getString(EventExportProjection.IDX_UID), eventId, dtStart),
|
uid = deriveIcsUid(getString(EventExportProjection.IDX_UID), eventId, dtStart),
|
||||||
@@ -68,14 +53,14 @@ internal fun ColumnReader.toIcsEvent(
|
|||||||
location = getString(EventExportProjection.IDX_LOCATION),
|
location = getString(EventExportProjection.IDX_LOCATION),
|
||||||
description = getString(EventExportProjection.IDX_DESCRIPTION),
|
description = getString(EventExportProjection.IDX_DESCRIPTION),
|
||||||
reminderMinutes = if (isAllDay) {
|
reminderMinutes = if (isAllDay) {
|
||||||
val startDate = Instant.ofEpochMilli(dtStart).atZone(ZoneOffset.UTC).toLocalDate()
|
val startDate = utcDate(dtStart)
|
||||||
reminderMinutes.map {
|
reminderMinutes.map {
|
||||||
fromProviderAllDayMinutes(it, startDate, zone, allDayReminderTimeMinutes)
|
fromProviderAllDayMinutes(it, startDate, zone, allDayReminderTimeMinutes)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
reminderMinutes
|
reminderMinutes
|
||||||
},
|
},
|
||||||
status = status,
|
status = eventStatus(EventExportProjection.IDX_STATUS),
|
||||||
availability = mapAvailability(getInt(EventExportProjection.IDX_AVAILABILITY)),
|
availability = mapAvailability(getInt(EventExportProjection.IDX_AVAILABILITY)),
|
||||||
calendarName = calendarName,
|
calendarName = calendarName,
|
||||||
)
|
)
|
||||||
@@ -112,11 +97,7 @@ internal fun exportExDates(
|
|||||||
): List<String> {
|
): List<String> {
|
||||||
if (exdate.isNullOrBlank()) return emptyList()
|
if (exdate.isNullOrBlank()) return emptyList()
|
||||||
val zone = exdateListZone(exdate, eventTimezone)
|
val zone = exdateListZone(exdate, eventTimezone)
|
||||||
return exdate
|
return exdateStamps(exdate)
|
||||||
.withoutExdateParameters()
|
|
||||||
.split(',')
|
|
||||||
.map { it.trim() }
|
|
||||||
.filter { it.isNotEmpty() }
|
|
||||||
.map { stamp ->
|
.map { stamp ->
|
||||||
if (isAllDay) {
|
if (isAllDay) {
|
||||||
stamp.substringBefore('T')
|
stamp.substringBefore('T')
|
||||||
|
|||||||
@@ -25,11 +25,7 @@ internal fun ColumnReader.toEventInstance(): EventInstance? {
|
|||||||
// string, so it belongs to the UI layer where it can be localised (#321).
|
// string, so it belongs to the UI layer where it can be localised (#321).
|
||||||
val title = getString(InstanceProjection.IDX_TITLE).orEmpty()
|
val title = getString(InstanceProjection.IDX_TITLE).orEmpty()
|
||||||
|
|
||||||
val color = if (isNull(InstanceProjection.IDX_EVENT_COLOR)) {
|
val color = getIntOrNull(InstanceProjection.IDX_EVENT_COLOR) ?: getInt(InstanceProjection.IDX_CALENDAR_COLOR)
|
||||||
getInt(InstanceProjection.IDX_CALENDAR_COLOR)
|
|
||||||
} else {
|
|
||||||
getInt(InstanceProjection.IDX_EVENT_COLOR)
|
|
||||||
}
|
|
||||||
|
|
||||||
return EventInstance(
|
return EventInstance(
|
||||||
instanceId = getLong(InstanceProjection.IDX_INSTANCE_ID),
|
instanceId = getLong(InstanceProjection.IDX_INSTANCE_ID),
|
||||||
@@ -42,9 +38,17 @@ internal fun ColumnReader.toEventInstance(): EventInstance? {
|
|||||||
color = color,
|
color = color,
|
||||||
location = getString(InstanceProjection.IDX_LOCATION),
|
location = getString(InstanceProjection.IDX_LOCATION),
|
||||||
response = mapEventResponse(getInt(InstanceProjection.IDX_SELF_ATTENDEE_STATUS)),
|
response = mapEventResponse(getInt(InstanceProjection.IDX_SELF_ATTENDEE_STATUS)),
|
||||||
|
status = eventStatus(InstanceProjection.IDX_STATUS),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A [CancelledEventProjection] row as an instance. Its id is the negated event
|
||||||
|
* id, so it can't collide with a provider instance id.
|
||||||
|
*/
|
||||||
|
internal fun ColumnReader.toCancelledOneOff(): EventInstance? =
|
||||||
|
toEventInstance()?.let { it.copy(instanceId = -it.eventId) }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* `SELF_ATTENDEE_STATUS` as the calendar surfaces read it: a tentative "maybe"
|
* `SELF_ATTENDEE_STATUS` as the calendar surfaces read it: a tentative "maybe"
|
||||||
* counts as going, and everything that is not an open or refused invitation —
|
* counts as going, and everything that is not an open or refused invitation —
|
||||||
|
|||||||
@@ -1,7 +1,16 @@
|
|||||||
package de.jeanlucmakiola.calendula.data.calendar
|
package de.jeanlucmakiola.calendula.data.calendar
|
||||||
|
|
||||||
|
import android.content.ContentUris
|
||||||
|
import android.net.Uri
|
||||||
import android.provider.CalendarContract
|
import android.provider.CalendarContract
|
||||||
|
|
||||||
|
/** The `Instances` table over the window [beginMillis]..[endMillis]. */
|
||||||
|
internal fun instancesUri(beginMillis: Long, endMillis: Long): Uri =
|
||||||
|
CalendarContract.Instances.CONTENT_URI.buildUpon().apply {
|
||||||
|
ContentUris.appendId(this, beginMillis)
|
||||||
|
ContentUris.appendId(this, endMillis)
|
||||||
|
}.build()
|
||||||
|
|
||||||
internal object CalendarProjection {
|
internal object CalendarProjection {
|
||||||
val COLUMNS: Array<String> = arrayOf(
|
val COLUMNS: Array<String> = arrayOf(
|
||||||
CalendarContract.Calendars._ID,
|
CalendarContract.Calendars._ID,
|
||||||
@@ -53,6 +62,7 @@ internal object InstanceProjection {
|
|||||||
CalendarContract.Instances.CALENDAR_COLOR,
|
CalendarContract.Instances.CALENDAR_COLOR,
|
||||||
CalendarContract.Instances.EVENT_LOCATION,
|
CalendarContract.Instances.EVENT_LOCATION,
|
||||||
CalendarContract.Instances.SELF_ATTENDEE_STATUS,
|
CalendarContract.Instances.SELF_ATTENDEE_STATUS,
|
||||||
|
CalendarContract.Instances.STATUS,
|
||||||
)
|
)
|
||||||
|
|
||||||
const val IDX_INSTANCE_ID = 0
|
const val IDX_INSTANCE_ID = 0
|
||||||
@@ -66,6 +76,29 @@ internal object InstanceProjection {
|
|||||||
const val IDX_CALENDAR_COLOR = 8
|
const val IDX_CALENDAR_COLOR = 8
|
||||||
const val IDX_LOCATION = 9
|
const val IDX_LOCATION = 9
|
||||||
const val IDX_SELF_ATTENDEE_STATUS = 10
|
const val IDX_SELF_ATTENDEE_STATUS = 10
|
||||||
|
const val IDX_STATUS = 11
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A cancelled one-off straight from the Events table, laid out on
|
||||||
|
* [InstanceProjection]'s indices so [toCancelledOneOff] reuses its mapper. AOSP
|
||||||
|
* writes no Instances rows for a cancelled event (#388).
|
||||||
|
*/
|
||||||
|
internal object CancelledEventProjection {
|
||||||
|
val COLUMNS: Array<String> = arrayOf(
|
||||||
|
CalendarContract.Events._ID,
|
||||||
|
CalendarContract.Events._ID,
|
||||||
|
CalendarContract.Events.CALENDAR_ID,
|
||||||
|
CalendarContract.Events.TITLE,
|
||||||
|
CalendarContract.Events.DTSTART,
|
||||||
|
CalendarContract.Events.DTEND,
|
||||||
|
CalendarContract.Events.ALL_DAY,
|
||||||
|
CalendarContract.Events.EVENT_COLOR,
|
||||||
|
CalendarContract.Events.CALENDAR_COLOR,
|
||||||
|
CalendarContract.Events.EVENT_LOCATION,
|
||||||
|
CalendarContract.Events.SELF_ATTENDEE_STATUS,
|
||||||
|
CalendarContract.Events.STATUS,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
internal object EventDetailProjection {
|
internal object EventDetailProjection {
|
||||||
@@ -189,6 +222,7 @@ internal object SearchProjection {
|
|||||||
// Excerpted, not just filtered on: a hit has to show what it matched.
|
// Excerpted, not just filtered on: a hit has to show what it matched.
|
||||||
CalendarContract.Events.DESCRIPTION,
|
CalendarContract.Events.DESCRIPTION,
|
||||||
CalendarContract.Events.SELF_ATTENDEE_STATUS,
|
CalendarContract.Events.SELF_ATTENDEE_STATUS,
|
||||||
|
CalendarContract.Events.STATUS,
|
||||||
)
|
)
|
||||||
|
|
||||||
const val IDX_ID = 0
|
const val IDX_ID = 0
|
||||||
@@ -205,6 +239,7 @@ internal object SearchProjection {
|
|||||||
const val IDX_RDATE = 11
|
const val IDX_RDATE = 11
|
||||||
const val IDX_DESCRIPTION = 12
|
const val IDX_DESCRIPTION = 12
|
||||||
const val IDX_SELF_ATTENDEE_STATUS = 13
|
const val IDX_SELF_ATTENDEE_STATUS = 13
|
||||||
|
const val IDX_STATUS = 14
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -251,40 +286,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,7 +2,6 @@ package de.jeanlucmakiola.calendula.data.calendar
|
|||||||
|
|
||||||
import de.jeanlucmakiola.floret.time.toKotlinInstantFromEpochMillis
|
import de.jeanlucmakiola.floret.time.toKotlinInstantFromEpochMillis
|
||||||
import de.jeanlucmakiola.calendula.domain.EventInstance
|
import de.jeanlucmakiola.calendula.domain.EventInstance
|
||||||
import de.jeanlucmakiola.calendula.domain.ics.parseRfc2445DurationMillis
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Map an Events-table row (a search hit) to an [EventInstance]. Unlike the
|
* Map an Events-table row (a search hit) to an [EventInstance]. Unlike the
|
||||||
@@ -16,17 +15,11 @@ internal fun ColumnReader.toSearchResult(): EventInstance? {
|
|||||||
// long-running birthdays/anniversaries still surface in search.
|
// long-running birthdays/anniversaries still surface in search.
|
||||||
if (isNull(SearchProjection.IDX_DTSTART)) return null
|
if (isNull(SearchProjection.IDX_DTSTART)) return null
|
||||||
val dtStart = getLong(SearchProjection.IDX_DTSTART)
|
val dtStart = getLong(SearchProjection.IDX_DTSTART)
|
||||||
val end = when {
|
val end = endMillis(dtStart, SearchProjection.IDX_DTEND, SearchProjection.IDX_DURATION)
|
||||||
!isNull(SearchProjection.IDX_DTEND) -> getLong(SearchProjection.IDX_DTEND)
|
.coerceAtLeast(dtStart)
|
||||||
else -> dtStart + parseRfc2445DurationMillis(getString(SearchProjection.IDX_DURATION))
|
|
||||||
}.coerceAtLeast(dtStart)
|
|
||||||
|
|
||||||
val title = getString(SearchProjection.IDX_TITLE).orEmpty()
|
val title = getString(SearchProjection.IDX_TITLE).orEmpty()
|
||||||
val color = if (isNull(SearchProjection.IDX_EVENT_COLOR)) {
|
val color = getIntOrNull(SearchProjection.IDX_EVENT_COLOR) ?: getInt(SearchProjection.IDX_CALENDAR_COLOR)
|
||||||
getInt(SearchProjection.IDX_CALENDAR_COLOR)
|
|
||||||
} else {
|
|
||||||
getInt(SearchProjection.IDX_EVENT_COLOR)
|
|
||||||
}
|
|
||||||
val eventId = getLong(SearchProjection.IDX_ID)
|
val eventId = getLong(SearchProjection.IDX_ID)
|
||||||
|
|
||||||
return EventInstance(
|
return EventInstance(
|
||||||
@@ -42,5 +35,6 @@ internal fun ColumnReader.toSearchResult(): EventInstance? {
|
|||||||
isRecurring = !getString(SearchProjection.IDX_RRULE).isNullOrEmpty() ||
|
isRecurring = !getString(SearchProjection.IDX_RRULE).isNullOrEmpty() ||
|
||||||
!getString(SearchProjection.IDX_RDATE).isNullOrEmpty(),
|
!getString(SearchProjection.IDX_RDATE).isNullOrEmpty(),
|
||||||
response = mapEventResponse(getInt(SearchProjection.IDX_SELF_ATTENDEE_STATUS)),
|
response = mapEventResponse(getInt(SearchProjection.IDX_SELF_ATTENDEE_STATUS)),
|
||||||
|
status = eventStatus(SearchProjection.IDX_STATUS),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
+2
-4
@@ -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) {
|
||||||
|
|||||||
+2
-1
@@ -2,6 +2,7 @@ package de.jeanlucmakiola.calendula.data.di
|
|||||||
|
|
||||||
import javax.inject.Qualifier
|
import javax.inject.Qualifier
|
||||||
|
|
||||||
|
/** The process-wide `CoroutineScope` that app-lifetime singletons share their flows in. */
|
||||||
@Qualifier
|
@Qualifier
|
||||||
@Retention(AnnotationRetention.BINARY)
|
@Retention(AnnotationRetention.BINARY)
|
||||||
annotation class IoDispatcher
|
annotation class ApplicationScope
|
||||||
@@ -24,8 +24,9 @@ import de.jeanlucmakiola.calendula.data.time.AndroidTodaySource
|
|||||||
import de.jeanlucmakiola.calendula.data.time.AndroidZoneSource
|
import de.jeanlucmakiola.calendula.data.time.AndroidZoneSource
|
||||||
import de.jeanlucmakiola.calendula.data.time.TodaySource
|
import de.jeanlucmakiola.calendula.data.time.TodaySource
|
||||||
import de.jeanlucmakiola.calendula.data.time.ZoneSource
|
import de.jeanlucmakiola.calendula.data.time.ZoneSource
|
||||||
import kotlinx.coroutines.CoroutineDispatcher
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
private val Context.calendulaDataStore: DataStore<Preferences> by preferencesDataStore(
|
private val Context.calendulaDataStore: DataStore<Preferences> by preferencesDataStore(
|
||||||
@@ -89,6 +90,7 @@ object DataProvideModule {
|
|||||||
context.calendulaDataStore
|
context.calendulaDataStore
|
||||||
|
|
||||||
@Provides
|
@Provides
|
||||||
@IoDispatcher
|
@Singleton
|
||||||
fun provideIoDispatcher(): CoroutineDispatcher = Dispatchers.IO
|
@ApplicationScope
|
||||||
|
fun provideApplicationScope(): CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||||
}
|
}
|
||||||
@@ -1,15 +1,13 @@
|
|||||||
package de.jeanlucmakiola.calendula.data.prefs
|
package de.jeanlucmakiola.calendula.data.prefs
|
||||||
|
|
||||||
import androidx.datastore.core.DataStore
|
import androidx.datastore.core.DataStore
|
||||||
import androidx.datastore.preferences.core.MutablePreferences
|
|
||||||
import androidx.datastore.preferences.core.Preferences
|
import androidx.datastore.preferences.core.Preferences
|
||||||
import androidx.datastore.preferences.core.booleanPreferencesKey
|
import de.jeanlucmakiola.floret.prefs.Pref
|
||||||
import androidx.datastore.preferences.core.edit
|
import de.jeanlucmakiola.floret.prefs.PrefStore
|
||||||
import androidx.datastore.preferences.core.longPreferencesKey
|
import de.jeanlucmakiola.floret.prefs.nullableBooleanPref
|
||||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
import de.jeanlucmakiola.floret.prefs.nullableLongPref
|
||||||
|
import de.jeanlucmakiola.floret.prefs.nullableStringPref
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
|
||||||
import kotlinx.coroutines.flow.map
|
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
@@ -26,18 +24,13 @@ import javax.inject.Singleton
|
|||||||
*/
|
*/
|
||||||
@Singleton
|
@Singleton
|
||||||
class CalendarPrefs @Inject constructor(
|
class CalendarPrefs @Inject constructor(
|
||||||
private val store: DataStore<Preferences>,
|
store: DataStore<Preferences>,
|
||||||
) {
|
) {
|
||||||
|
private val prefs = PrefStore(store)
|
||||||
|
|
||||||
// Both id sets are deduped: the store is shared with SettingsPrefs, so any
|
val hiddenCalendarIds: Flow<Set<Long>> = prefs.flow(HIDDEN_IDS)
|
||||||
// unrelated write would otherwise re-emit an identical set.
|
|
||||||
val hiddenCalendarIds: Flow<Set<Long>> = store.data
|
|
||||||
.map { prefs -> prefs[HIDDEN_IDS_KEY].parseIds() }
|
|
||||||
.distinctUntilChanged()
|
|
||||||
|
|
||||||
suspend fun setHiddenCalendarIds(ids: Set<Long>) {
|
suspend fun setHiddenCalendarIds(ids: Set<Long>) = prefs.set(HIDDEN_IDS, ids)
|
||||||
store.edit { prefs -> prefs.writeIds(HIDDEN_IDS_KEY, ids) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Switch-offs the provider does not know about yet, because writing
|
* Switch-offs the provider does not know about yet, because writing
|
||||||
@@ -48,24 +41,18 @@ class CalendarPrefs @Inject constructor(
|
|||||||
* second visibility model: `CalendarVisibilityReconciler` drains it entry by
|
* second visibility model: `CalendarVisibilityReconciler` drains it entry by
|
||||||
* entry as soon as the app may write, and nothing adds to it while it may.
|
* entry as soon as the app may write, and nothing adds to it while it may.
|
||||||
*/
|
*/
|
||||||
val pendingDisabledCalendarIds: Flow<Set<Long>> = store.data
|
val pendingDisabledCalendarIds: Flow<Set<Long>> = prefs.flow(DISABLED_IDS)
|
||||||
.map { prefs -> prefs[DISABLED_IDS_KEY].parseIds() }
|
|
||||||
.distinctUntilChanged()
|
|
||||||
|
|
||||||
suspend fun addPendingDisabledCalendarIds(ids: Collection<Long>) =
|
suspend fun addPendingDisabledCalendarIds(ids: Collection<Long>) {
|
||||||
editPendingDisabled { it + ids }
|
prefs.update(DISABLED_IDS) { it + ids }
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Drop [ids] from the pending set, one at a time as the reconciler flushes
|
* Drop [ids] from the pending set, one at a time as the reconciler flushes
|
||||||
* them, so a run that fails part-way never re-applies what already landed.
|
* them, so a run that fails part-way never re-applies what already landed.
|
||||||
*/
|
*/
|
||||||
suspend fun removePendingDisabledCalendarIds(ids: Collection<Long>) =
|
suspend fun removePendingDisabledCalendarIds(ids: Collection<Long>) {
|
||||||
editPendingDisabled { it - ids.toSet() }
|
prefs.update(DISABLED_IDS) { it - ids.toSet() }
|
||||||
|
|
||||||
private suspend fun editPendingDisabled(transform: (Set<Long>) -> Set<Long>) {
|
|
||||||
store.edit { prefs ->
|
|
||||||
prefs.writeIds(DISABLED_IDS_KEY, transform(prefs[DISABLED_IDS_KEY].parseIds()))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -73,39 +60,28 @@ class CalendarPrefs @Inject constructor(
|
|||||||
* owed. Null until the reconciler has evaluated it (which needs the calendar
|
* owed. Null until the reconciler has evaluated it (which needs the calendar
|
||||||
* permission), false once it has been shown or was never needed.
|
* permission), false once it has been shown or was never needed.
|
||||||
*/
|
*/
|
||||||
val visibilityNoticePending: Flow<Boolean?> = store.data.map { prefs ->
|
val visibilityNoticePending: Flow<Boolean?> = prefs.flow(VISIBILITY_NOTICE)
|
||||||
prefs[VISIBILITY_NOTICE_KEY]
|
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun setVisibilityNoticePending(pending: Boolean) {
|
suspend fun setVisibilityNoticePending(pending: Boolean) = prefs.set(VISIBILITY_NOTICE, pending)
|
||||||
store.edit { prefs -> prefs[VISIBILITY_NOTICE_KEY] = pending }
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The calendar the user last created an event in; preselected in the
|
* The calendar the user last created an event in; preselected in the
|
||||||
* event form. Null until the first event is created.
|
* event form. Null until the first event is created.
|
||||||
*/
|
*/
|
||||||
val lastUsedCalendarId: Flow<Long?> = store.data.map { prefs ->
|
val lastUsedCalendarId: Flow<Long?> = prefs.flow(LAST_USED_CALENDAR)
|
||||||
prefs[LAST_USED_CALENDAR_KEY]
|
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun setLastUsedCalendarId(id: Long) {
|
suspend fun setLastUsedCalendarId(id: Long) = prefs.set(LAST_USED_CALENDAR, id)
|
||||||
store.edit { prefs -> prefs[LAST_USED_CALENDAR_KEY] = id }
|
|
||||||
}
|
|
||||||
|
|
||||||
companion object {
|
private companion object {
|
||||||
internal val HIDDEN_IDS_KEY = stringPreferencesKey("hidden_calendar_ids")
|
val HIDDEN_IDS = idSetPref("hidden_calendar_ids")
|
||||||
internal val DISABLED_IDS_KEY = stringPreferencesKey("disabled_calendar_ids")
|
val DISABLED_IDS = idSetPref("disabled_calendar_ids")
|
||||||
internal val VISIBILITY_NOTICE_KEY = booleanPreferencesKey("visibility_notice_pending")
|
val VISIBILITY_NOTICE = nullableBooleanPref("visibility_notice_pending")
|
||||||
internal val LAST_USED_CALENDAR_KEY = longPreferencesKey("last_used_calendar_id")
|
val LAST_USED_CALENDAR = nullableLongPref("last_used_calendar_id")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun String?.parseIds(): Set<Long> = orEmpty()
|
/** A comma-joined id set; non-numeric tokens are dropped, and an empty set removes the key. */
|
||||||
.split(',')
|
private fun idSetPref(name: String): Pref<Set<Long>> = nullableStringPref(name).map(
|
||||||
.mapNotNull { it.trim().toLongOrNull() }
|
{ stored -> stored.orEmpty().split(',').mapNotNull { it.trim().toLongOrNull() }.toSet() },
|
||||||
.toSet()
|
{ ids -> if (ids.isEmpty()) null else ids.sorted().joinToString(",") },
|
||||||
|
)
|
||||||
private fun MutablePreferences.writeIds(key: Preferences.Key<String>, ids: Set<Long>) {
|
|
||||||
if (ids.isEmpty()) remove(key) else set(key, ids.sorted().joinToString(","))
|
|
||||||
}
|
|
||||||
@@ -2,10 +2,8 @@ package de.jeanlucmakiola.calendula.data.prefs
|
|||||||
|
|
||||||
import androidx.datastore.core.DataStore
|
import androidx.datastore.core.DataStore
|
||||||
import androidx.datastore.preferences.core.Preferences
|
import androidx.datastore.preferences.core.Preferences
|
||||||
import androidx.datastore.preferences.core.edit
|
import de.jeanlucmakiola.floret.prefs.PrefStore
|
||||||
import androidx.datastore.preferences.core.longPreferencesKey
|
import de.jeanlucmakiola.floret.prefs.nullableLongPref
|
||||||
import kotlinx.coroutines.flow.first
|
|
||||||
import kotlinx.coroutines.flow.map
|
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
@@ -20,17 +18,16 @@ import javax.inject.Singleton
|
|||||||
*/
|
*/
|
||||||
@Singleton
|
@Singleton
|
||||||
class ReminderStatePrefs @Inject constructor(
|
class ReminderStatePrefs @Inject constructor(
|
||||||
private val store: DataStore<Preferences>,
|
store: DataStore<Preferences>,
|
||||||
) {
|
) {
|
||||||
|
private val prefs = PrefStore(store)
|
||||||
|
|
||||||
/** The watermark, or `null` before the first scan has ever run. */
|
/** The watermark, or `null` before the first scan has ever run. */
|
||||||
suspend fun lastScanMillis(): Long? = store.data.map { it[LAST_SCAN_KEY] }.first()
|
suspend fun lastScanMillis(): Long? = prefs.get(LAST_SCAN)
|
||||||
|
|
||||||
suspend fun setLastScanMillis(millis: Long) {
|
suspend fun setLastScanMillis(millis: Long) = prefs.set(LAST_SCAN, millis)
|
||||||
store.edit { prefs -> prefs[LAST_SCAN_KEY] = millis }
|
|
||||||
}
|
|
||||||
|
|
||||||
private companion object {
|
private companion object {
|
||||||
val LAST_SCAN_KEY = longPreferencesKey("reminder_last_scan_millis")
|
val LAST_SCAN = nullableLongPref("reminder_last_scan_millis")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
+21
-25
@@ -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
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -41,30 +38,24 @@ class ReminderActionReceiver : BroadcastReceiver() {
|
|||||||
ACTION_DISMISS -> notifier.cancel(alert)
|
ACTION_DISMISS -> notifier.cancel(alert)
|
||||||
|
|
||||||
ACTION_SNOOZE -> {
|
ACTION_SNOOZE -> {
|
||||||
|
// Tapped on a stale view: the reminder that replaced it stays put.
|
||||||
|
if (notifier.isSuperseded(alert)) return
|
||||||
// Cancel now so the notification doesn't linger until the alarm;
|
// 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 {
|
// A later reminder posted while this one was snoozed has taken its place.
|
||||||
try {
|
if (notifier.isSuperseded(alert)) return@goAsync
|
||||||
if (settingsPrefs.remindersEnabled.first() && notifier.canPost()) {
|
if (settingsPrefs.remindersEnabled.first() && notifier.canPost()) {
|
||||||
notifier.post(alert)
|
notifier.post(alert)
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
pendingResult.finish()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -95,12 +86,14 @@ class ReminderActionReceiver : BroadcastReceiver() {
|
|||||||
/**
|
/**
|
||||||
* An explicit intent to this receiver carrying [alert] as extras. The
|
* An explicit intent to this receiver carrying [alert] as extras. The
|
||||||
* data URI duplicates no information but is what keeps two reminders'
|
* data URI duplicates no information but is what keeps two reminders'
|
||||||
* `PendingIntent`s apart — `filterEquals` never compares extras.
|
* `PendingIntent`s apart — `filterEquals` never compares extras. The
|
||||||
|
* snooze alarm is the exception: one per occurrence, so a later snooze
|
||||||
|
* replaces an earlier one and a newer reminder can cancel it.
|
||||||
*/
|
*/
|
||||||
fun intent(context: Context, action: String, alert: ReminderAlert): Intent =
|
fun intent(context: Context, action: String, alert: ReminderAlert): Intent =
|
||||||
Intent(context, ReminderActionReceiver::class.java).apply {
|
Intent(context, ReminderActionReceiver::class.java).apply {
|
||||||
this.action = action
|
this.action = action
|
||||||
data = "calendula://reminder/${alert.key}".toUri()
|
data = "calendula://reminder/${identity(alert, action)}".toUri()
|
||||||
putExtra(EXTRA_ALERT_KEY, alert.key)
|
putExtra(EXTRA_ALERT_KEY, alert.key)
|
||||||
putExtra(EXTRA_EVENT_ID, alert.eventId)
|
putExtra(EXTRA_EVENT_ID, alert.eventId)
|
||||||
putExtra(EXTRA_CALENDAR_ID, alert.calendarId)
|
putExtra(EXTRA_CALENDAR_ID, alert.calendarId)
|
||||||
@@ -114,7 +107,7 @@ class ReminderActionReceiver : BroadcastReceiver() {
|
|||||||
/**
|
/**
|
||||||
* A stable request code per (alert, action), so one notification's
|
* A stable request code per (alert, action), so one notification's
|
||||||
* PendingIntents stay distinct. The shift keeps the action slot intact;
|
* PendingIntents stay distinct. The shift keeps the action slot intact;
|
||||||
* the top bits it drops are separated by [intent]'s per-reminder URI.
|
* the top bits it drops are separated by [intent]'s URI.
|
||||||
*/
|
*/
|
||||||
fun requestCode(alert: ReminderAlert, action: String): Int {
|
fun requestCode(alert: ReminderAlert, action: String): Int {
|
||||||
val actionOffset = when (action) {
|
val actionOffset = when (action) {
|
||||||
@@ -124,9 +117,12 @@ class ReminderActionReceiver : BroadcastReceiver() {
|
|||||||
ACTION_OPEN -> 4
|
ACTION_OPEN -> 4
|
||||||
else -> 0
|
else -> 0
|
||||||
}
|
}
|
||||||
return (alert.key.toInt() shl 3) + actionOffset
|
return (identity(alert, action).toInt() shl 3) + actionOffset
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun identity(alert: ReminderAlert, action: String): Long =
|
||||||
|
if (action == ACTION_SHOW) alert.occurrenceKey else alert.key
|
||||||
|
|
||||||
private fun alertFrom(intent: Intent): ReminderAlert? {
|
private fun alertFrom(intent: Intent): ReminderAlert? {
|
||||||
if (!intent.hasExtra(EXTRA_ALERT_KEY)) return null
|
if (!intent.hasExtra(EXTRA_ALERT_KEY)) return null
|
||||||
return ReminderAlert(
|
return ReminderAlert(
|
||||||
|
|||||||
@@ -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. */
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package de.jeanlucmakiola.calendula.data.reminders
|
package de.jeanlucmakiola.calendula.data.reminders
|
||||||
|
|
||||||
import de.jeanlucmakiola.calendula.domain.reminders.PlannedReminder
|
import de.jeanlucmakiola.calendula.domain.reminders.PlannedReminder
|
||||||
|
import de.jeanlucmakiola.calendula.domain.reminders.occurrenceKey
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* One reminder as the notification layer needs it: what to show, and the stable
|
* One reminder as the notification layer needs it: what to show, and the stable
|
||||||
@@ -20,6 +21,13 @@ data class ReminderAlert(
|
|||||||
val isAllDay: Boolean,
|
val isAllDay: Boolean,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The occurrence [ReminderAlert] belongs to. Keys the notification and the
|
||||||
|
* snooze alarm, so a later reminder for the same occurrence replaces the earlier
|
||||||
|
* one instead of stacking beside it (#463).
|
||||||
|
*/
|
||||||
|
val ReminderAlert.occurrenceKey: Long get() = occurrenceKey(eventId, beginMillis)
|
||||||
|
|
||||||
fun PlannedReminder.toAlert(): ReminderAlert = ReminderAlert(
|
fun PlannedReminder.toAlert(): ReminderAlert = ReminderAlert(
|
||||||
key = key,
|
key = key,
|
||||||
eventId = instance.eventId,
|
eventId = instance.eventId,
|
||||||
|
|||||||
+2
-5
@@ -1,9 +1,9 @@
|
|||||||
package de.jeanlucmakiola.calendula.data.reminders
|
package de.jeanlucmakiola.calendula.data.reminders
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.ContentUris
|
|
||||||
import android.provider.CalendarContract
|
import android.provider.CalendarContract
|
||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import de.jeanlucmakiola.calendula.data.calendar.instancesUri
|
||||||
import de.jeanlucmakiola.calendula.domain.reminders.ReminderEventInstance
|
import de.jeanlucmakiola.calendula.domain.reminders.ReminderEventInstance
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
@@ -37,10 +37,7 @@ class ProviderReminderInstanceSource @Inject constructor(
|
|||||||
) : ReminderInstanceSource {
|
) : ReminderInstanceSource {
|
||||||
|
|
||||||
override fun occurrences(fromMillis: Long, toMillis: Long): List<ReminderEventInstance> {
|
override fun occurrences(fromMillis: Long, toMillis: Long): List<ReminderEventInstance> {
|
||||||
val uri = CalendarContract.Instances.CONTENT_URI.buildUpon().apply {
|
val uri = instancesUri(fromMillis, toMillis)
|
||||||
ContentUris.appendId(this, fromMillis)
|
|
||||||
ContentUris.appendId(this, toMillis)
|
|
||||||
}.build()
|
|
||||||
// `visible` is the flag the app's one visibility model writes (#75).
|
// `visible` is the flag the app's one visibility model writes (#75).
|
||||||
// The status clause mirrors CalendarDataSource.instances: NULL means
|
// The status clause mirrors CalendarDataSource.instances: NULL means
|
||||||
// "normal", so a bare `!= CANCELED` would drop every ordinary event.
|
// "normal", so a bare `!= CANCELED` would drop every ordinary event.
|
||||||
|
|||||||
@@ -5,12 +5,11 @@ 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.os.Bundle
|
||||||
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 +18,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
|
||||||
@@ -29,13 +29,13 @@ import javax.inject.Inject
|
|||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Posts one notification per due reminder on a dedicated channel. Tapping opens
|
* Posts one notification per occurrence on a dedicated channel. Tapping opens
|
||||||
* the event's detail screen.
|
* the event's detail screen.
|
||||||
*
|
*
|
||||||
* The tag is the reminder's stable key, so a scan that posts the same reminder
|
* The tag is the [occurrenceKey], so each reminder for an occurrence replaces
|
||||||
* again — a catch-up pass overlapping the alarm that already fired — replaces
|
* the one before it in place (#463). A different reminder alerts afresh; the
|
||||||
* its notification silently ([NotificationCompat.Builder.setOnlyAlertOnce])
|
* same one posted again — a catch-up pass overlapping the alarm that already
|
||||||
* instead of stacking a second one.
|
* fired — replaces its notification silently.
|
||||||
*/
|
*/
|
||||||
@Singleton
|
@Singleton
|
||||||
class ReminderNotifier @Inject constructor(
|
class ReminderNotifier @Inject constructor(
|
||||||
@@ -48,8 +48,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,15 +62,11 @@ 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 = displayTitle(alert)
|
||||||
val is24Hour = settingsPrefs.timeFormat.first()
|
val is24Hour = settingsPrefs.timeFormat.first()
|
||||||
.is24Hour(android.text.format.DateFormat.is24HourFormat(context))
|
.is24Hour(android.text.format.DateFormat.is24HourFormat(context))
|
||||||
val zone = ZoneId.systemDefault()
|
val zone = ZoneId.systemDefault()
|
||||||
@@ -102,7 +97,8 @@ class ReminderNotifier @Inject constructor(
|
|||||||
.setCategory(NotificationCompat.CATEGORY_EVENT)
|
.setCategory(NotificationCompat.CATEGORY_EVENT)
|
||||||
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
||||||
.setAutoCancel(true)
|
.setAutoCancel(true)
|
||||||
.setOnlyAlertOnce(true)
|
.setOnlyAlertOnce(shownKey(alert) == alert.key)
|
||||||
|
.addExtras(Bundle().apply { putLong(EXTRA_REMINDER_KEY, alert.key) })
|
||||||
.setContentIntent(detailIntent(alert))
|
.setContentIntent(detailIntent(alert))
|
||||||
.addAction(
|
.addAction(
|
||||||
R.drawable.ic_notification_snooze,
|
R.drawable.ic_notification_snooze,
|
||||||
@@ -115,22 +111,58 @@ class ReminderNotifier @Inject constructor(
|
|||||||
actionIntent(alert, ReminderActionReceiver.ACTION_DISMISS),
|
actionIntent(alert, ReminderActionReceiver.ACTION_DISMISS),
|
||||||
)
|
)
|
||||||
.build()
|
.build()
|
||||||
|
val manager = NotificationManagerCompat.from(context)
|
||||||
|
cancelLegacy(alert)
|
||||||
try {
|
try {
|
||||||
NotificationManagerCompat.from(context)
|
manager.notify(alert.occurrenceKey.toString(), NOTIFICATION_ID, notification)
|
||||||
.notify(alert.key.toString(), NOTIFICATION_ID, notification)
|
|
||||||
} catch (e: SecurityException) {
|
} catch (e: SecurityException) {
|
||||||
// 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 [alert]'s notification (snooze re-shows it later; dismiss is final),
|
||||||
|
* unless a later reminder has replaced it — an action tapped on a stale view
|
||||||
|
* mustn't take the newer one with it.
|
||||||
|
*/
|
||||||
fun cancel(alert: ReminderAlert) {
|
fun cancel(alert: ReminderAlert) {
|
||||||
NotificationManagerCompat.from(context).cancel(alert.key.toString(), NOTIFICATION_ID)
|
val manager = NotificationManagerCompat.from(context)
|
||||||
|
if (shownKey(alert) == alert.key) manager.cancel(alert.occurrenceKey.toString(), NOTIFICATION_ID)
|
||||||
|
// Posted before reminders shared a notification, under the reminder's own key.
|
||||||
|
manager.cancel(alert.key.toString(), NOTIFICATION_ID)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Whether a different reminder for [alert]'s occurrence is on screen now. */
|
||||||
|
fun isSuperseded(alert: ReminderAlert): Boolean = shownKey(alert).let { it != null && it != alert.key }
|
||||||
|
|
||||||
|
/** The key of the reminder showing for [alert]'s occurrence, if any. */
|
||||||
|
private fun shownKey(alert: ReminderAlert): Long? {
|
||||||
|
val tag = alert.occurrenceKey.toString()
|
||||||
|
return NotificationManagerCompat.from(context).activeNotifications
|
||||||
|
.firstOrNull { it.tag == tag && it.id == NOTIFICATION_ID }
|
||||||
|
?.notification?.extras
|
||||||
|
?.takeIf { it.containsKey(EXTRA_REMINDER_KEY) }
|
||||||
|
?.getLong(EXTRA_REMINDER_KEY)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove a reminder for the same occurrence posted before reminders shared a
|
||||||
|
* notification. It carries no reminder key; its time and title identify it.
|
||||||
|
*/
|
||||||
|
private fun cancelLegacy(alert: ReminderAlert) {
|
||||||
|
val manager = NotificationManagerCompat.from(context)
|
||||||
|
manager.activeNotifications
|
||||||
|
.filter { it.id == NOTIFICATION_ID && it.notification.channelId == CHANNEL_ID }
|
||||||
|
.filter { !it.notification.extras.containsKey(EXTRA_REMINDER_KEY) }
|
||||||
|
.filter { it.notification.`when` == alert.beginMillis }
|
||||||
|
.filter { it.notification.extras.getCharSequence(NotificationCompat.EXTRA_TITLE)?.toString() == displayTitle(alert) }
|
||||||
|
.forEach { manager.cancel(it.tag, it.id) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun displayTitle(alert: ReminderAlert): String =
|
||||||
|
alert.title.ifBlank { context.getString(R.string.event_untitled) }
|
||||||
|
|
||||||
private fun actionIntent(alert: ReminderAlert, action: String): PendingIntent =
|
private fun actionIntent(alert: ReminderAlert, action: String): PendingIntent =
|
||||||
PendingIntent.getBroadcast(
|
PendingIntent.getBroadcast(
|
||||||
context,
|
context,
|
||||||
@@ -165,8 +197,10 @@ class ReminderNotifier @Inject constructor(
|
|||||||
const val TAG = "ReminderNotifier"
|
const val TAG = "ReminderNotifier"
|
||||||
const val CHANNEL_ID = "reminders"
|
const val CHANNEL_ID = "reminders"
|
||||||
|
|
||||||
// One id, distinct tags: the tag (alert id) already keys the
|
// One id, distinct tags: the tag (occurrence) already keys the
|
||||||
// notification, so a fixed id keeps cancellation/replacement simple.
|
// notification, so a fixed id keeps cancellation/replacement simple.
|
||||||
const val NOTIFICATION_ID = 1
|
const val NOTIFICATION_ID = 1
|
||||||
|
|
||||||
|
const val EXTRA_REMINDER_KEY = "de.jeanlucmakiola.calendula.reminder_key"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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
|
||||||
@@ -44,6 +43,7 @@ class ReminderScanner @Inject constructor(
|
|||||||
private val source: ReminderInstanceSource,
|
private val source: ReminderInstanceSource,
|
||||||
private val calendarDataSource: CalendarDataSource,
|
private val calendarDataSource: CalendarDataSource,
|
||||||
private val notifier: ReminderNotifier,
|
private val notifier: ReminderNotifier,
|
||||||
|
private val snoozes: ReminderSnoozeScheduler,
|
||||||
private val alarms: ReminderAlarmScheduler,
|
private val alarms: ReminderAlarmScheduler,
|
||||||
private val state: ReminderStatePrefs,
|
private val state: ReminderStatePrefs,
|
||||||
private val settingsPrefs: SettingsPrefs,
|
private val settingsPrefs: SettingsPrefs,
|
||||||
@@ -105,7 +105,11 @@ class ReminderScanner @Inject constructor(
|
|||||||
)
|
)
|
||||||
|
|
||||||
if (notifier.canPost()) {
|
if (notifier.canPost()) {
|
||||||
schedule.due.forEach { notifier.post(it.toAlert()) }
|
schedule.due.forEach {
|
||||||
|
val alert = it.toAlert()
|
||||||
|
snoozes.cancel(alert)
|
||||||
|
notifier.post(alert)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// Advance even when nothing could be posted, so muting notifications
|
// Advance even when nothing could be posted, so muting notifications
|
||||||
// doesn't build a backlog.
|
// doesn't build a backlog.
|
||||||
@@ -113,9 +117,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
|
||||||
|
|||||||
+2
-12
@@ -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 {
|
||||||
|
|||||||
+13
-19
@@ -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,18 @@ 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,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Drop a snooze still pending for [alert]'s occurrence, so it can't re-show over a newer reminder. */
|
||||||
* True on API < 31 (no restriction), and on 31+ when the exact-alarm
|
fun cancel(alert: ReminderAlert) {
|
||||||
* capability is held — auto-granted via `USE_EXACT_ALARM` on API 33+
|
val pendingIntent = PendingIntent.getBroadcast(
|
||||||
* (Calendula is a calendar app), user-revocable on 31–32.
|
context,
|
||||||
*/
|
ReminderActionReceiver.requestCode(alert, ReminderActionReceiver.ACTION_SHOW),
|
||||||
private fun canScheduleExact(alarmManager: AlarmManager): Boolean =
|
ReminderActionReceiver.intent(context, ReminderActionReceiver.ACTION_SHOW, alert),
|
||||||
Build.VERSION.SDK_INT < Build.VERSION_CODES.S || alarmManager.canScheduleExactAlarms()
|
PendingIntent.FLAG_NO_CREATE or PendingIntent.FLAG_IMMUTABLE,
|
||||||
|
) ?: return
|
||||||
|
context.getSystemService<AlarmManager>()?.cancel(pendingIntent)
|
||||||
|
pendingIntent.cancel()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package de.jeanlucmakiola.calendula.data.reminders
|
package de.jeanlucmakiola.calendula.data.reminders
|
||||||
|
|
||||||
|
import de.jeanlucmakiola.calendula.domain.runsMidnightToMidnight
|
||||||
import de.jeanlucmakiola.calendula.ui.common.timeOfDayFormatter
|
import de.jeanlucmakiola.calendula.ui.common.timeOfDayFormatter
|
||||||
import java.time.DayOfWeek
|
import java.time.DayOfWeek
|
||||||
import java.time.Instant
|
import java.time.Instant
|
||||||
@@ -11,6 +12,8 @@ import java.time.format.FormatStyle
|
|||||||
import java.time.format.TextStyle
|
import java.time.format.TextStyle
|
||||||
import java.time.temporal.ChronoUnit
|
import java.time.temporal.ChronoUnit
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
|
import kotlinx.datetime.toKotlinTimeZone
|
||||||
|
import kotlin.time.Instant as KInstant
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The one line of time context in a reminder notification. Pure so it can be
|
* The one line of time context in a reminder notification. Pure so it can be
|
||||||
@@ -32,7 +35,8 @@ import java.util.Locale
|
|||||||
* - all-day, multi-day: "Tomorrow – 12 Jun 2026" (relative start, explicit end)
|
* - all-day, multi-day: "Tomorrow – 12 Jun 2026" (relative start, explicit end)
|
||||||
*
|
*
|
||||||
* All-day instances store UTC midnights with an exclusive end, so they are read
|
* All-day instances store UTC midnights with an exclusive end, so they are read
|
||||||
* in UTC and the end day is the last *covered* day (issue #308).
|
* in UTC and the end day is the last *covered* day (issue #308). A timed event
|
||||||
|
* from local midnight to local midnight reads like one too, in [zone] (#296).
|
||||||
*/
|
*/
|
||||||
fun reminderTimeText(
|
fun reminderTimeText(
|
||||||
beginMillis: Long,
|
beginMillis: Long,
|
||||||
@@ -47,11 +51,17 @@ fun reminderTimeText(
|
|||||||
tomorrowLabel: String,
|
tomorrowLabel: String,
|
||||||
yesterdayLabel: String,
|
yesterdayLabel: String,
|
||||||
): String {
|
): String {
|
||||||
if (isAllDay) {
|
val wholeDays = !isAllDay && runsMidnightToMidnight(
|
||||||
|
KInstant.fromEpochMilliseconds(beginMillis),
|
||||||
|
KInstant.fromEpochMilliseconds(endMillis),
|
||||||
|
zone.toKotlinTimeZone(),
|
||||||
|
)
|
||||||
|
if (isAllDay || wholeDays) {
|
||||||
|
val dayZone = if (isAllDay) ZoneOffset.UTC else zone
|
||||||
val dateFormat = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(locale)
|
val dateFormat = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(locale)
|
||||||
// (atZone().toLocalDate() instead of LocalDate.ofInstant — API 34+)
|
// (atZone().toLocalDate() instead of LocalDate.ofInstant — API 34+)
|
||||||
val firstDay = Instant.ofEpochMilli(beginMillis).atZone(ZoneOffset.UTC).toLocalDate()
|
val firstDay = Instant.ofEpochMilli(beginMillis).atZone(dayZone).toLocalDate()
|
||||||
val lastDay = Instant.ofEpochMilli(endMillis).atZone(ZoneOffset.UTC).toLocalDate()
|
val lastDay = Instant.ofEpochMilli(endMillis).atZone(dayZone).toLocalDate()
|
||||||
.minusDays(1)
|
.minusDays(1)
|
||||||
.coerceAtLeast(firstDay)
|
.coerceAtLeast(firstDay)
|
||||||
val start = relativeDayPrefix(
|
val start = relativeDayPrefix(
|
||||||
|
|||||||
@@ -1,18 +1,20 @@
|
|||||||
package de.jeanlucmakiola.calendula.data.time
|
package de.jeanlucmakiola.calendula.data.time
|
||||||
|
|
||||||
import android.content.BroadcastReceiver
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.content.IntentFilter
|
|
||||||
import androidx.core.content.ContextCompat
|
|
||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import de.jeanlucmakiola.calendula.data.di.ApplicationScope
|
||||||
|
import de.jeanlucmakiola.floret.android.broadcastTicks
|
||||||
|
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||||
import kotlinx.coroutines.channels.awaitClose
|
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
import kotlinx.coroutines.flow.callbackFlow
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
|
import kotlinx.coroutines.flow.shareIn
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||||
import kotlinx.coroutines.flow.onStart
|
import kotlinx.coroutines.flow.onEach
|
||||||
import kotlinx.coroutines.flow.transformLatest
|
import kotlinx.coroutines.flow.transformLatest
|
||||||
import kotlinx.datetime.LocalDate
|
import kotlinx.datetime.LocalDate
|
||||||
import kotlinx.datetime.TimeZone
|
import kotlinx.datetime.TimeZone
|
||||||
@@ -28,27 +30,16 @@ interface TodaySource {
|
|||||||
/**
|
/**
|
||||||
* Re-reads the date on every minute boundary while collected, and at once on the
|
* 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.
|
* system's date, time and zone broadcasts, which can arrive late or not at all.
|
||||||
|
* One receiver and tick loop is shared by every collector.
|
||||||
*/
|
*/
|
||||||
@OptIn(ExperimentalCoroutinesApi::class)
|
@OptIn(ExperimentalCoroutinesApi::class)
|
||||||
class AndroidTodaySource @Inject constructor(
|
class AndroidTodaySource @Inject constructor(
|
||||||
@ApplicationContext private val context: Context,
|
@ApplicationContext private val context: Context,
|
||||||
|
@ApplicationScope scope: CoroutineScope,
|
||||||
) : TodaySource {
|
) : TodaySource {
|
||||||
|
|
||||||
override val today: Flow<LocalDate> = callbackFlow {
|
override val today: Flow<LocalDate> = context
|
||||||
val receiver = object : BroadcastReceiver() {
|
.broadcastTicks(Intent.ACTION_DATE_CHANGED, Intent.ACTION_TIME_CHANGED, Intent.ACTION_TIMEZONE_CHANGED)
|
||||||
override fun onReceive(context: Context, intent: Intent) {
|
|
||||||
trySend(Unit)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
val filter = IntentFilter().apply {
|
|
||||||
addAction(Intent.ACTION_DATE_CHANGED)
|
|
||||||
addAction(Intent.ACTION_TIME_CHANGED)
|
|
||||||
addAction(Intent.ACTION_TIMEZONE_CHANGED)
|
|
||||||
}
|
|
||||||
ContextCompat.registerReceiver(context, receiver, filter, ContextCompat.RECEIVER_NOT_EXPORTED)
|
|
||||||
awaitClose { context.unregisterReceiver(receiver) }
|
|
||||||
}
|
|
||||||
.onStart { emit(Unit) }
|
|
||||||
.transformLatest {
|
.transformLatest {
|
||||||
while (true) {
|
while (true) {
|
||||||
emit(currentDate())
|
emit(currentDate())
|
||||||
@@ -56,8 +47,27 @@ class AndroidTodaySource @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
.distinctUntilChanged()
|
.distinctUntilChanged()
|
||||||
|
.shareIn(scope, SharingStarted.WhileSubscribed(replayExpirationMillis = 0), replay = 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
private const val MINUTE_MILLIS = 60_000L
|
private const val MINUTE_MILLIS = 60_000L
|
||||||
|
|
||||||
fun currentDate(): LocalDate = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).date
|
fun currentDate(): LocalDate = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).date
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Today as a hot flow seeded with [initial]. [onRollover] runs with the previous
|
||||||
|
* and the new date each time the day changes while collected, so a screen left
|
||||||
|
* open over midnight can move off yesterday (#373).
|
||||||
|
*/
|
||||||
|
fun Flow<LocalDate>.stateFollowingDays(
|
||||||
|
scope: CoroutineScope,
|
||||||
|
initial: LocalDate,
|
||||||
|
onRollover: (old: LocalDate, new: LocalDate) -> Unit,
|
||||||
|
): StateFlow<LocalDate> {
|
||||||
|
var last = initial
|
||||||
|
return onEach { date ->
|
||||||
|
val old = last
|
||||||
|
last = date
|
||||||
|
if (old != date) onRollover(old, date)
|
||||||
|
}.stateWhileSubscribed(scope, initial)
|
||||||
|
}
|
||||||
@@ -1,17 +1,16 @@
|
|||||||
package de.jeanlucmakiola.calendula.data.time
|
package de.jeanlucmakiola.calendula.data.time
|
||||||
|
|
||||||
import android.content.BroadcastReceiver
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.content.IntentFilter
|
|
||||||
import androidx.core.content.ContextCompat
|
|
||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
import kotlinx.coroutines.channels.awaitClose
|
import de.jeanlucmakiola.calendula.data.di.ApplicationScope
|
||||||
|
import de.jeanlucmakiola.floret.android.broadcastTicks
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
import kotlinx.coroutines.flow.callbackFlow
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||||
import kotlinx.coroutines.flow.map
|
import kotlinx.coroutines.flow.map
|
||||||
import kotlinx.coroutines.flow.onStart
|
import kotlinx.coroutines.flow.shareIn
|
||||||
import kotlinx.datetime.TimeZone
|
import kotlinx.datetime.TimeZone
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
@@ -28,24 +27,16 @@ interface ZoneSource {
|
|||||||
fun current(): TimeZone
|
fun current(): TimeZone
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Follows the system's zone broadcast. */
|
/** Follows the system's zone broadcast, one receiver shared by every collector. */
|
||||||
class AndroidZoneSource @Inject constructor(
|
class AndroidZoneSource @Inject constructor(
|
||||||
@ApplicationContext private val context: Context,
|
@ApplicationContext private val context: Context,
|
||||||
|
@ApplicationScope scope: CoroutineScope,
|
||||||
) : ZoneSource {
|
) : ZoneSource {
|
||||||
|
|
||||||
override val zone: Flow<TimeZone> = callbackFlow {
|
override val zone: Flow<TimeZone> = context.broadcastTicks(Intent.ACTION_TIMEZONE_CHANGED)
|
||||||
val receiver = object : BroadcastReceiver() {
|
|
||||||
override fun onReceive(context: Context, intent: Intent) {
|
|
||||||
trySend(Unit)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
val filter = IntentFilter(Intent.ACTION_TIMEZONE_CHANGED)
|
|
||||||
ContextCompat.registerReceiver(context, receiver, filter, ContextCompat.RECEIVER_NOT_EXPORTED)
|
|
||||||
awaitClose { context.unregisterReceiver(receiver) }
|
|
||||||
}
|
|
||||||
.onStart { emit(Unit) }
|
|
||||||
.map { current() }
|
.map { current() }
|
||||||
.distinctUntilChanged()
|
.distinctUntilChanged()
|
||||||
|
.shareIn(scope, SharingStarted.WhileSubscribed(replayExpirationMillis = 0), replay = 1)
|
||||||
|
|
||||||
override fun current(): TimeZone = TimeZone.currentSystemDefault()
|
override fun current(): TimeZone = TimeZone.currentSystemDefault()
|
||||||
}
|
}
|
||||||
@@ -1,18 +1,35 @@
|
|||||||
package de.jeanlucmakiola.calendula.domain
|
package de.jeanlucmakiola.calendula.domain
|
||||||
|
|
||||||
import kotlinx.datetime.TimeZone
|
import kotlinx.datetime.TimeZone
|
||||||
|
import kotlinx.datetime.atStartOfDayIn
|
||||||
|
import kotlin.time.Instant
|
||||||
|
|
||||||
/** Lower values appear first in lists and get the upper visible lanes in grids. */
|
/** Lower values appear first in lists and get the upper visible lanes in grids. */
|
||||||
fun EventInstance.displayPriority(zone: TimeZone): Int = when {
|
fun EventInstance.displayPriority(zone: TimeZone): Int = when {
|
||||||
isDeclined -> 3
|
isCrossedOut -> 3
|
||||||
spansMultipleDays(zone) -> 0
|
spansMultipleDays(zone) -> 0
|
||||||
isAllDay -> 1
|
coversWholeDays(zone) -> 1
|
||||||
else -> 2
|
else -> 2
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Shared order for agenda and split day lists. Grid bars add their lane geometry. */
|
/**
|
||||||
fun eventDisplayComparator(zone: TimeZone): Comparator<EventInstance> =
|
* Shared order for agenda and split day lists. Grid bars add their lane geometry.
|
||||||
compareBy<EventInstance> { it.displayPriority(zone) }
|
* Each event's priority is worked out once, not on every comparison.
|
||||||
.thenBy { it.start }
|
*/
|
||||||
.thenBy { it.title }
|
fun List<EventInstance>.sortedForDisplay(zone: TimeZone): List<EventInstance> =
|
||||||
.thenBy { it.instanceId }
|
map { Triple(it, it.displayPriority(zone), it.displayStart(zone)) }
|
||||||
|
.sortedWith(
|
||||||
|
compareBy<Triple<EventInstance, Int, Instant>> { it.second }
|
||||||
|
.thenBy { it.third }
|
||||||
|
.thenBy { it.first.title }
|
||||||
|
.thenBy { it.first.instanceId },
|
||||||
|
)
|
||||||
|
.map { it.first }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where an event starts for ordering: a whole-day event at local midnight of its
|
||||||
|
* first day, since an all-day one is stored at UTC midnight and would otherwise
|
||||||
|
* sort around timed events by the device's offset (#296).
|
||||||
|
*/
|
||||||
|
internal fun EventInstance.displayStart(zone: TimeZone): Instant =
|
||||||
|
if (coversWholeDays(zone)) spanFirstDay(zone).atStartOfDayIn(zone) else start
|
||||||
@@ -42,6 +42,8 @@ data class EventForm(
|
|||||||
val reminders: List<Int> = emptyList(),
|
val reminders: List<Int> = emptyList(),
|
||||||
val availability: Availability = Availability.Busy,
|
val availability: Availability = Availability.Busy,
|
||||||
val accessLevel: AccessLevel = AccessLevel.Default,
|
val accessLevel: AccessLevel = AccessLevel.Default,
|
||||||
|
/** Confirmed / Tentative / Cancelled (#388). */
|
||||||
|
val status: EventStatus = EventStatus.Confirmed,
|
||||||
/**
|
/**
|
||||||
* Bare RRULE value (`Events.RRULE` convention, no "RRULE:" prefix); null
|
* Bare RRULE value (`Events.RRULE` convention, no "RRULE:" prefix); null
|
||||||
* means a one-off event. May hold rules the simple picker can't express —
|
* means a one-off event. May hold rules the simple picker can't express —
|
||||||
@@ -113,6 +115,7 @@ enum class EventFormField {
|
|||||||
Reminders,
|
Reminders,
|
||||||
Recurrence,
|
Recurrence,
|
||||||
Availability,
|
Availability,
|
||||||
|
Status,
|
||||||
Visibility,
|
Visibility,
|
||||||
Color,
|
Color,
|
||||||
Attendees,
|
Attendees,
|
||||||
@@ -148,23 +151,21 @@ enum class EventFormProblem {
|
|||||||
fun EventDetail.toEditForm(beginMillis: Long, endMillis: Long, zone: TimeZone): EventForm {
|
fun EventDetail.toEditForm(beginMillis: Long, endMillis: Long, zone: TimeZone): EventForm {
|
||||||
// All-day events are date-anchored and carry a nominal "UTC" that is an
|
// All-day events are date-anchored and carry a nominal "UTC" that is an
|
||||||
// anchor, not a location, so they never pin a zone.
|
// anchor, not a location, so they never pin a zone.
|
||||||
val pinnedZone = if (instance.isAllDay) {
|
val pinned = if (instance.isAllDay) {
|
||||||
null
|
null
|
||||||
} else {
|
} else {
|
||||||
eventTimezone
|
eventTimezone
|
||||||
?.takeIf { it != zone.id }
|
?.takeIf { it != zone.id }
|
||||||
// An unparseable id (a malformed sync row) can't be honoured or
|
// An unparseable id (a malformed sync row) can't be honoured or
|
||||||
// shown; fall back to the device zone rather than failing the open.
|
// shown; fall back to the device zone rather than failing the open.
|
||||||
?.takeIf { runCatching { TimeZone.of(it) }.isSuccess }
|
?.let { id -> zoneOrNull(id)?.let { id to it } }
|
||||||
}
|
}
|
||||||
val formZone = pinnedZone?.let { TimeZone.of(it) } ?: zone
|
val pinnedZone = pinned?.first
|
||||||
|
val formZone = pinned?.second ?: zone
|
||||||
val begin = Instant.fromEpochMilliseconds(beginMillis)
|
val begin = Instant.fromEpochMilliseconds(beginMillis)
|
||||||
val finish = Instant.fromEpochMilliseconds(endMillis)
|
val finish = Instant.fromEpochMilliseconds(endMillis)
|
||||||
val (start, end) = if (instance.isAllDay) {
|
val (start, end) = if (instance.isAllDay) {
|
||||||
val startDate = begin.toLocalDateTime(TimeZone.UTC).date
|
allDayFormTimes(begin.toLocalDateTime(TimeZone.UTC).date, finish.toLocalDateTime(TimeZone.UTC).date)
|
||||||
val endExclusive = finish.toLocalDateTime(TimeZone.UTC).date
|
|
||||||
val endDate = maxOf(startDate, LocalDate.fromEpochDays(endExclusive.toEpochDays() - 1))
|
|
||||||
FormTime(LocalDateTime(startDate, LocalTime(9, 0))) to FormTime(LocalDateTime(endDate, LocalTime(10, 0)))
|
|
||||||
} else {
|
} else {
|
||||||
begin.toFormTime(formZone) to finish.toFormTime(formZone)
|
begin.toFormTime(formZone) to finish.toFormTime(formZone)
|
||||||
}
|
}
|
||||||
@@ -180,7 +181,8 @@ fun EventDetail.toEditForm(beginMillis: Long, endMillis: Long, zone: TimeZone):
|
|||||||
reminders = reminders.map { it.minutes }.distinct().sorted(),
|
reminders = reminders.map { it.minutes }.distinct().sorted(),
|
||||||
availability = availability,
|
availability = availability,
|
||||||
accessLevel = accessLevel,
|
accessLevel = accessLevel,
|
||||||
rrule = rrule?.removePrefix("RRULE:")?.takeIf { it.isNotBlank() },
|
status = status,
|
||||||
|
rrule = rrule.normalizedRrule(),
|
||||||
// The provider fills EVENT_COLOR from the key, so [color] is the
|
// The provider fills EVENT_COLOR from the key, so [color] is the
|
||||||
// swatch either way; a null colour means the event inherits its
|
// swatch either way; a null colour means the event inherits its
|
||||||
// calendar's colour.
|
// calendar's colour.
|
||||||
@@ -215,7 +217,7 @@ fun EventDetail.toEditForm(beginMillis: Long, endMillis: Long, zone: TimeZone):
|
|||||||
* re-deriving with the same occurrence would mask an externally moved
|
* re-deriving with the same occurrence would mask an externally moved
|
||||||
* event. Guests are covered (the form writes editable attendees), so an
|
* event. Guests are covered (the form writes editable attendees), so an
|
||||||
* external attendee change now also trips the conflict check. Still not
|
* external attendee change now also trips the conflict check. Still not
|
||||||
* covered: status, the user's own response, reminder methods, the
|
* covered: the user's own response, reminder methods, the
|
||||||
* organizer/resource rows, and a recurring event's duration.
|
* organizer/resource rows, and a recurring event's duration.
|
||||||
*/
|
*/
|
||||||
data class EditSnapshot(
|
data class EditSnapshot(
|
||||||
@@ -232,6 +234,35 @@ fun EventDetail.toEditSnapshot(beginMillis: Long, endMillis: Long, zone: TimeZon
|
|||||||
rowEnd = instance.end,
|
rowEnd = instance.end,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Form times for an all-day span stored as UTC midnights with an exclusive
|
||||||
|
* end: the last covered day (never before [start]), with placeholder
|
||||||
|
* wall-clock times kept in case the user switches the event to timed.
|
||||||
|
*/
|
||||||
|
internal fun allDayFormTimes(start: LocalDate, endExclusive: LocalDate?): Pair<FormTime, FormTime> {
|
||||||
|
val end = endExclusive?.let { maxOf(start, LocalDate.fromEpochDays(it.toEpochDays() - 1)) } ?: start
|
||||||
|
return FormTime(LocalDateTime(start, LocalTime(9, 0))) to FormTime(LocalDateTime(end, LocalTime(10, 0)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The bare RRULE value the form edits; blank means none. */
|
||||||
|
internal fun String?.normalizedRrule(): String? = this?.removePrefix("RRULE:")?.takeIf { it.isNotBlank() }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether this form may be saved apart from its series, as one modified
|
||||||
|
* occurrence or as a split-off "this & following" tail. A cancelled exception
|
||||||
|
* row is how Android records a deleted occurrence, and Google reads an inserted
|
||||||
|
* cancelled event as deleted, so either would vanish rather than show struck
|
||||||
|
* through (#388).
|
||||||
|
*/
|
||||||
|
fun EventForm.canSaveApartFromSeries(): Boolean = status != EventStatus.Cancelled
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The status a newly inserted row may carry. Google reads an inserted cancelled
|
||||||
|
* event as deleted, so every new row (a copy, an import, a calendar move or an
|
||||||
|
* exception) starts confirmed instead (#388).
|
||||||
|
*/
|
||||||
|
fun EventStatus.forNewEvent(): EventStatus = if (this == EventStatus.Cancelled) EventStatus.Confirmed else this
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Whether this form's times mean something else in [target] — a timed event
|
* Whether this form's times mean something else in [target] — a timed event
|
||||||
* pinned to another zone. False when there's nothing to disambiguate: an
|
* pinned to another zone. False when there's nothing to disambiguate: an
|
||||||
@@ -243,8 +274,7 @@ fun EventDetail.toEditSnapshot(beginMillis: Long, endMillis: Long, zone: TimeZon
|
|||||||
*/
|
*/
|
||||||
fun EventForm.isPinnedAwayFrom(target: TimeZone): Boolean {
|
fun EventForm.isPinnedAwayFrom(target: TimeZone): Boolean {
|
||||||
if (isAllDay) return false
|
if (isAllDay) return false
|
||||||
val pinned = timezone?.let { runCatching { TimeZone.of(it) }.getOrNull() } ?: return false
|
return resolvedZone(target).id != target.id
|
||||||
return pinned.id != target.id
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -259,6 +289,7 @@ fun EventForm.populatedFields(): Set<EventFormField> = buildSet {
|
|||||||
if (reminders.isNotEmpty()) add(EventFormField.Reminders)
|
if (reminders.isNotEmpty()) add(EventFormField.Reminders)
|
||||||
if (rrule != null) add(EventFormField.Recurrence)
|
if (rrule != null) add(EventFormField.Recurrence)
|
||||||
if (availability != Availability.Busy) add(EventFormField.Availability)
|
if (availability != Availability.Busy) add(EventFormField.Availability)
|
||||||
|
if (status != EventStatus.Confirmed) add(EventFormField.Status)
|
||||||
if (accessLevel != AccessLevel.Default) add(EventFormField.Visibility)
|
if (accessLevel != AccessLevel.Default) add(EventFormField.Visibility)
|
||||||
if (colorKey != null || color != null) add(EventFormField.Color)
|
if (colorKey != null || color != null) add(EventFormField.Color)
|
||||||
if (attendees.isNotEmpty()) add(EventFormField.Attendees)
|
if (attendees.isNotEmpty()) add(EventFormField.Attendees)
|
||||||
@@ -301,4 +332,5 @@ fun EventDetail.toDuplicateForm(canModify: Boolean, zone: TimeZone): EventForm =
|
|||||||
).copy(
|
).copy(
|
||||||
rrule = null,
|
rrule = null,
|
||||||
calendarId = instance.calendarId.takeIf { canModify },
|
calendarId = instance.calendarId.takeIf { canModify },
|
||||||
|
status = status.forNewEvent(),
|
||||||
)
|
)
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
package de.jeanlucmakiola.calendula.domain
|
package de.jeanlucmakiola.calendula.domain
|
||||||
|
|
||||||
import kotlinx.datetime.DateTimeUnit
|
import kotlinx.datetime.DateTimeUnit
|
||||||
import kotlinx.datetime.LocalDate
|
|
||||||
import kotlinx.datetime.TimeZone
|
import kotlinx.datetime.TimeZone
|
||||||
|
import kotlinx.datetime.YearMonth
|
||||||
import kotlinx.datetime.atStartOfDayIn
|
import kotlinx.datetime.atStartOfDayIn
|
||||||
import kotlinx.datetime.number
|
import kotlinx.datetime.number
|
||||||
import kotlinx.datetime.plus
|
import kotlinx.datetime.plus
|
||||||
@@ -101,19 +101,13 @@ object EventSearch {
|
|||||||
|
|
||||||
val today = todayStart.toLocalDateTime(zone).date
|
val today = todayStart.toLocalDateTime(zone).date
|
||||||
val matched = candidates.mapNotNull { candidate -> match(candidate, tokens, now, zone) }
|
val matched = candidates.mapNotNull { candidate -> match(candidate, tokens, now, zone) }
|
||||||
val upcoming = { m: Matched -> m.event.spanLastDay(zone) >= today }
|
val (upcoming, past) = matched.partition { it.event.spanLastDay(zone) >= today }
|
||||||
val order = compareBy<Matched> { if (upcoming(it)) 0 else 1 }
|
// What is left reads forwards; what is behind us reads backwards from
|
||||||
.thenComparator { a, b ->
|
// today, nearest first.
|
||||||
// What is left reads forwards; what is behind us reads backwards
|
val ordered = upcoming.sortedBy { it.event.dayStart(zone) } +
|
||||||
// from today, nearest first.
|
past.sortedByDescending { it.event.dayStart(zone) }
|
||||||
if (upcoming(a)) {
|
|
||||||
a.event.dayStart(zone).compareTo(b.event.dayStart(zone))
|
|
||||||
} else {
|
|
||||||
b.event.dayStart(zone).compareTo(a.event.dayStart(zone))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
val (inDescriptions, dated) = matched.sortedWith(order).partition { it.descriptionOnly }
|
val (inDescriptions, dated) = ordered.partition { it.descriptionOnly }
|
||||||
return SearchResults(
|
return SearchResults(
|
||||||
months = groupByMonth(dated, zone, todayStart),
|
months = groupByMonth(dated, zone, todayStart),
|
||||||
inDescriptions = inDescriptions.map { it.hit },
|
inDescriptions = inDescriptions.map { it.hit },
|
||||||
@@ -126,33 +120,18 @@ object EventSearch {
|
|||||||
zone: TimeZone,
|
zone: TimeZone,
|
||||||
todayStart: Instant,
|
todayStart: Instant,
|
||||||
): List<SearchMonth> {
|
): List<SearchMonth> {
|
||||||
val currentKey = monthKey(todayStart.toLocalDateTime(zone).date)
|
val current = todayStart.toLocalDateTime(zone).date.let { YearMonth(it.year, it.month) }
|
||||||
return dated
|
val groups = dated.groupBy { m -> m.event.spanFirstDay(zone).let { YearMonth(it.year, it.month) } }
|
||||||
.groupBy { monthKey(it.event.spanFirstDay(zone)) }
|
val (behind, ahead) = groups.keys.partition { it < current }
|
||||||
.entries
|
return (ahead.sorted() + behind.sortedDescending()).map { month ->
|
||||||
.sortedWith(
|
SearchMonth(
|
||||||
compareBy<Map.Entry<Int, List<Matched>>> {
|
year = month.year,
|
||||||
when {
|
monthNumber = month.month.number,
|
||||||
it.key == currentKey -> 0
|
hits = groups.getValue(month).map { it.hit },
|
||||||
it.key > currentKey -> 1
|
|
||||||
else -> 2
|
|
||||||
}
|
|
||||||
}.thenComparator { a, b ->
|
|
||||||
if (a.key > currentKey) a.key.compareTo(b.key) else b.key.compareTo(a.key)
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
.map { (key, entries) ->
|
}
|
||||||
SearchMonth(
|
|
||||||
year = key / 12,
|
|
||||||
monthNumber = key % 12 + 1,
|
|
||||||
hits = entries.map { it.hit },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Year and month as one comparable number. */
|
|
||||||
private fun monthKey(date: LocalDate): Int = date.year * 12 + (date.month.number - 1)
|
|
||||||
|
|
||||||
private fun match(
|
private fun match(
|
||||||
candidate: SearchCandidate,
|
candidate: SearchCandidate,
|
||||||
tokens: List<String>,
|
tokens: List<String>,
|
||||||
|
|||||||
@@ -17,12 +17,15 @@ import kotlin.time.Instant
|
|||||||
import kotlin.time.toJavaInstant
|
import kotlin.time.toJavaInstant
|
||||||
import kotlin.time.toKotlinInstant
|
import kotlin.time.toKotlinInstant
|
||||||
|
|
||||||
|
/** [id] as a zone, or null when the tz database doesn't know it. */
|
||||||
|
internal fun zoneOrNull(id: String): TimeZone? = runCatching { TimeZone.of(id) }.getOrNull()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The zone this form's wall-clock times mean, matching what the data layer
|
* The zone this form's wall-clock times mean, matching what the data layer
|
||||||
* resolves them in at write time: the form's own pinned zone, else [deviceZone].
|
* resolves them in at write time: the form's own pinned zone, else [deviceZone].
|
||||||
*/
|
*/
|
||||||
fun EventForm.resolvedZone(deviceZone: TimeZone): TimeZone =
|
fun EventForm.resolvedZone(deviceZone: TimeZone): TimeZone =
|
||||||
timezone?.let { runCatching { TimeZone.of(it) }.getOrNull() } ?: deviceZone
|
timezone?.let(::zoneOrNull) ?: deviceZone
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This wall-clock time in [zone], at [preferred] when the fall-back hour repeats
|
* This wall-clock time in [zone], at [preferred] when the fall-back hour repeats
|
||||||
@@ -170,8 +173,11 @@ fun EventForm.shiftedByDays(days: Int, deviceZone: TimeZone): EventForm {
|
|||||||
return copy(start = movedStart, end = (startAt + span).toFormTime(zone))
|
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. */
|
/**
|
||||||
|
* The form with new start and end, each in the form's own zone — a resize. An
|
||||||
|
* all-day event becomes timed: one dragged out of the all-day strip.
|
||||||
|
*/
|
||||||
fun EventForm.resizedTo(newStart: Instant, newEnd: Instant, deviceZone: TimeZone): EventForm {
|
fun EventForm.resizedTo(newStart: Instant, newEnd: Instant, deviceZone: TimeZone): EventForm {
|
||||||
if (isAllDay) return this
|
val timed = copy(isAllDay = false)
|
||||||
return withTimes(newStart, newEnd, resolvedZone(deviceZone))
|
return timed.withTimes(newStart, newEnd, timed.resolvedZone(deviceZone))
|
||||||
}
|
}
|
||||||
@@ -131,6 +131,10 @@ private class HtmlRenderer(private val html: String) {
|
|||||||
text("<")
|
text("<")
|
||||||
return lt + 1
|
return lt + 1
|
||||||
}
|
}
|
||||||
|
if (!closing && isAutolink(html.substring(nameStart, end))) {
|
||||||
|
text(html.substring(lt, end + 1))
|
||||||
|
return end + 1
|
||||||
|
}
|
||||||
var nameEnd = nameStart
|
var nameEnd = nameStart
|
||||||
while (nameEnd < end && (html[nameEnd].isLetterOrDigit() || html[nameEnd] == ':')) nameEnd++
|
while (nameEnd < end && (html[nameEnd].isLetterOrDigit() || html[nameEnd] == ':')) nameEnd++
|
||||||
val name = html.substring(nameStart, nameEnd).lowercase()
|
val name = html.substring(nameStart, nameEnd).lowercase()
|
||||||
@@ -149,6 +153,11 @@ private class HtmlRenderer(private val html: String) {
|
|||||||
return end + 1
|
return end + 1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** An angle-bracketed URL or address (`<https://…>`, `<a@b.c>`), kept as text. */
|
||||||
|
private fun isAutolink(inner: String): Boolean =
|
||||||
|
LINK_SCHEMES.any { inner.startsWith(it, ignoreCase = true) } ||
|
||||||
|
('@' in inner && inner.none { it.isWhitespace() || it == '=' })
|
||||||
|
|
||||||
/** The `>` closing the tag at [lt], skipping any inside quoted attributes. */
|
/** The `>` closing the tag at [lt], skipping any inside quoted attributes. */
|
||||||
private fun tagEnd(lt: Int): Int {
|
private fun tagEnd(lt: Int): Int {
|
||||||
var quote: Char? = null
|
var quote: Char? = null
|
||||||
|
|||||||
@@ -1,8 +1,5 @@
|
|||||||
package de.jeanlucmakiola.calendula.domain
|
package de.jeanlucmakiola.calendula.domain
|
||||||
|
|
||||||
import kotlinx.datetime.LocalDate
|
|
||||||
import kotlinx.datetime.LocalDateTime
|
|
||||||
import kotlinx.datetime.LocalTime
|
|
||||||
import kotlinx.datetime.TimeZone
|
import kotlinx.datetime.TimeZone
|
||||||
import kotlinx.datetime.toLocalDateTime
|
import kotlinx.datetime.toLocalDateTime
|
||||||
import kotlin.time.Duration.Companion.hours
|
import kotlin.time.Duration.Companion.hours
|
||||||
@@ -35,17 +32,11 @@ fun buildInsertEventForm(
|
|||||||
now: Instant,
|
now: Instant,
|
||||||
): EventForm {
|
): EventForm {
|
||||||
val (start, end) = if (isAllDay) {
|
val (start, end) = if (isAllDay) {
|
||||||
// All-day provider times are UTC midnights with an exclusive end; show
|
|
||||||
// the last covered day and keep placeholder wall-clock times in case the
|
|
||||||
// user switches the event to timed (mirrors EventDetail.toEditForm).
|
|
||||||
val startDate = beginMillis
|
val startDate = beginMillis
|
||||||
?.let { Instant.fromEpochMilliseconds(it).toLocalDateTime(TimeZone.UTC).date }
|
?.let { Instant.fromEpochMilliseconds(it).toLocalDateTime(TimeZone.UTC).date }
|
||||||
?: now.toLocalDateTime(zone).date
|
?: now.toLocalDateTime(zone).date
|
||||||
val endDate = endMillis
|
val endExclusive = endMillis?.let { Instant.fromEpochMilliseconds(it).toLocalDateTime(TimeZone.UTC).date }
|
||||||
?.let { Instant.fromEpochMilliseconds(it).toLocalDateTime(TimeZone.UTC).date }
|
allDayFormTimes(startDate, endExclusive)
|
||||||
?.let { exclusive -> maxOf(startDate, LocalDate.fromEpochDays(exclusive.toEpochDays() - 1)) }
|
|
||||||
?: startDate
|
|
||||||
FormTime(LocalDateTime(startDate, LocalTime(9, 0))) to FormTime(LocalDateTime(endDate, LocalTime(10, 0)))
|
|
||||||
} else {
|
} else {
|
||||||
val startAt = beginMillis?.let(Instant::fromEpochMilliseconds) ?: nextFullHour(now)
|
val startAt = beginMillis?.let(Instant::fromEpochMilliseconds) ?: nextFullHour(now)
|
||||||
val endAt = endMillis?.let(Instant::fromEpochMilliseconds)?.takeIf { it >= startAt }
|
val endAt = endMillis?.let(Instant::fromEpochMilliseconds)?.takeIf { it >= startAt }
|
||||||
@@ -62,7 +53,7 @@ fun buildInsertEventForm(
|
|||||||
description = description.orEmpty(),
|
description = description.orEmpty(),
|
||||||
// Bare RRULE value (Events.RRULE convention); tolerate a leading "RRULE:"
|
// Bare RRULE value (Events.RRULE convention); tolerate a leading "RRULE:"
|
||||||
// some callers include.
|
// some callers include.
|
||||||
rrule = rrule?.removePrefix("RRULE:")?.takeIf { it.isNotBlank() },
|
rrule = rrule.normalizedRrule(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package de.jeanlucmakiola.calendula.domain
|
|||||||
|
|
||||||
import kotlinx.datetime.LocalDate
|
import kotlinx.datetime.LocalDate
|
||||||
import kotlinx.datetime.TimeZone
|
import kotlinx.datetime.TimeZone
|
||||||
|
import kotlinx.datetime.atStartOfDayIn
|
||||||
import kotlinx.datetime.toLocalDateTime
|
import kotlinx.datetime.toLocalDateTime
|
||||||
import kotlin.time.Duration.Companion.milliseconds
|
import kotlin.time.Duration.Companion.milliseconds
|
||||||
import kotlin.time.Instant
|
import kotlin.time.Instant
|
||||||
@@ -72,6 +73,8 @@ data class EventInstance(
|
|||||||
* (#180, #230).
|
* (#180, #230).
|
||||||
*/
|
*/
|
||||||
val response: EventResponse = EventResponse.Going,
|
val response: EventResponse = EventResponse.Going,
|
||||||
|
/** The event's own Confirmed / Tentative / Cancelled (`Events.STATUS`, #388). */
|
||||||
|
val status: EventStatus = EventStatus.Confirmed,
|
||||||
)
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -94,16 +97,33 @@ enum class EventResponse {
|
|||||||
Declined,
|
Declined,
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Shorthand for the declined case, which most surfaces test on its own (#180). */
|
/**
|
||||||
val EventInstance.isDeclined: Boolean get() = response == EventResponse.Declined
|
* Struck through on every surface and sorted last: an invitation you declined
|
||||||
|
* (#180), or an event its organizer cancelled (#388). Neither plans reminders.
|
||||||
|
*/
|
||||||
|
val EventInstance.isCrossedOut: Boolean
|
||||||
|
get() = response == EventResponse.Declined || status == EventStatus.Cancelled
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Drawn as an outline, still undecided: an invitation you have not answered
|
||||||
|
* (#230), or a tentative event (#388).
|
||||||
|
*/
|
||||||
|
val EventInstance.isOutlined: Boolean
|
||||||
|
get() = !isCrossedOut && (response == EventResponse.Invited || status == EventStatus.Tentative)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Whether this event has finished relative to [now] — its end is at or before
|
* Whether this event has finished relative to [now] — its end is at or before
|
||||||
* the current instant. An in-progress event (already started but not yet ended)
|
* the current instant. An in-progress event (already started but not yet ended)
|
||||||
* is *not* considered ended. All-day events end at the exclusive next-midnight,
|
* is *not* considered ended. All-day events end at the exclusive next-midnight
|
||||||
* so they only count as ended once their day is fully over.
|
* in [zone] rather than the UTC midnight they are stored on, so they only count
|
||||||
|
* as ended once their local day is fully over.
|
||||||
*/
|
*/
|
||||||
fun EventInstance.hasEnded(now: Instant): Boolean = end <= now
|
fun EventInstance.hasEnded(now: Instant, zone: TimeZone = TimeZone.currentSystemDefault()): Boolean =
|
||||||
|
localEnd(zone) <= now
|
||||||
|
|
||||||
|
/** [EventInstance.end], with an all-day event's UTC midnight moved to local midnight in [zone]. */
|
||||||
|
fun EventInstance.localEnd(zone: TimeZone): Instant =
|
||||||
|
if (isAllDay) end.toLocalDateTime(TimeZone.UTC).date.atStartOfDayIn(zone) else end
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The zone this event's calendar dates live in: the device [zone] for timed
|
* The zone this event's calendar dates live in: the device [zone] for timed
|
||||||
@@ -130,6 +150,20 @@ fun EventInstance.spanLastDay(zone: TimeZone): LocalDate {
|
|||||||
fun EventInstance.spansMultipleDays(zone: TimeZone): Boolean =
|
fun EventInstance.spansMultipleDays(zone: TimeZone): Boolean =
|
||||||
spanFirstDay(zone) != spanLastDay(zone)
|
spanFirstDay(zone) != spanLastDay(zone)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether this event fills whole days in [zone], so the grids and lists lay it
|
||||||
|
* out with the all-day events: an all-day event, or a timed one running from
|
||||||
|
* local midnight to local midnight (#296). The event itself stays timed.
|
||||||
|
*/
|
||||||
|
fun EventInstance.coversWholeDays(zone: TimeZone): Boolean = isAllDay || runsMidnightToMidnight(start, end, zone)
|
||||||
|
|
||||||
|
/** Whether a timed span from [start] to [end] runs from local midnight to local midnight in [zone] (#296). */
|
||||||
|
fun runsMidnightToMidnight(start: Instant, end: Instant, zone: TimeZone): Boolean =
|
||||||
|
end > start && start.isStartOfDay(zone) && end.isStartOfDay(zone)
|
||||||
|
|
||||||
|
private fun Instant.isStartOfDay(zone: TimeZone): Boolean =
|
||||||
|
this == toLocalDateTime(zone).date.atStartOfDayIn(zone)
|
||||||
|
|
||||||
data class EventDetail(
|
data class EventDetail(
|
||||||
val instance: EventInstance,
|
val instance: EventInstance,
|
||||||
val description: String?,
|
val description: String?,
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
package de.jeanlucmakiola.calendula.domain
|
package de.jeanlucmakiola.calendula.domain
|
||||||
|
|
||||||
|
import de.jeanlucmakiola.calendula.domain.ics.parseBasicDate
|
||||||
|
import de.jeanlucmakiola.calendula.domain.ics.parseBasicDateTime
|
||||||
|
import de.jeanlucmakiola.calendula.domain.ics.toUtcBasic
|
||||||
import kotlinx.datetime.DayOfWeek
|
import kotlinx.datetime.DayOfWeek
|
||||||
import kotlinx.datetime.LocalDate
|
import kotlinx.datetime.LocalDate
|
||||||
import kotlinx.datetime.LocalDateTime
|
import kotlinx.datetime.LocalDateTime
|
||||||
@@ -57,24 +60,13 @@ fun parseSimpleRecurrence(
|
|||||||
rrule: String,
|
rrule: String,
|
||||||
zone: TimeZone = TimeZone.currentSystemDefault(),
|
zone: TimeZone = TimeZone.currentSystemDefault(),
|
||||||
): SimpleRecurrence? {
|
): SimpleRecurrence? {
|
||||||
val parts = rrule.removePrefix("RRULE:").split(';')
|
val parts = rruleParts(rrule).associate { part -> (part.key ?: return null) to part.value }
|
||||||
.filter { it.isNotBlank() }
|
|
||||||
.associate { token ->
|
|
||||||
val eq = token.indexOf('=')
|
|
||||||
if (eq <= 0) return null
|
|
||||||
token.substring(0, eq).uppercase() to token.substring(eq + 1)
|
|
||||||
}
|
|
||||||
if (parts.keys.any { it !in setOf("FREQ", "INTERVAL", "UNTIL", "COUNT", "WKST", "BYDAY") }) {
|
if (parts.keys.any { it !in setOf("FREQ", "INTERVAL", "UNTIL", "COUNT", "WKST", "BYDAY") }) {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
val freq = when (parts["FREQ"]?.uppercase()) {
|
val freq = RecurrenceFreq.entries.firstOrNull { it.name.equals(parts["FREQ"], ignoreCase = true) }
|
||||||
"DAILY" -> RecurrenceFreq.Daily
|
?: return null
|
||||||
"WEEKLY" -> RecurrenceFreq.Weekly
|
|
||||||
"MONTHLY" -> RecurrenceFreq.Monthly
|
|
||||||
"YEARLY" -> RecurrenceFreq.Yearly
|
|
||||||
else -> return null
|
|
||||||
}
|
|
||||||
val interval = parts["INTERVAL"]?.let { it.toIntOrNull()?.takeIf { n -> n >= 1 } ?: return null } ?: 1
|
val interval = parts["INTERVAL"]?.let { it.toIntOrNull()?.takeIf { n -> n >= 1 } ?: return null } ?: 1
|
||||||
|
|
||||||
// BYDAY is simple only as plain weekday picks on a weekly rule; ordinal
|
// BYDAY is simple only as plain weekday picks on a weekly rule; ordinal
|
||||||
@@ -124,20 +116,27 @@ fun SimpleRecurrence.toRRule(zone: TimeZone = TimeZone.currentSystemDefault()):
|
|||||||
when (val e = end) {
|
when (val e = end) {
|
||||||
RecurrenceEnd.Never -> Unit
|
RecurrenceEnd.Never -> Unit
|
||||||
is RecurrenceEnd.Until -> {
|
is RecurrenceEnd.Until -> {
|
||||||
val utc = LocalDateTime(e.date, LocalTime(23, 59, 59))
|
append(";UNTIL=")
|
||||||
.toInstant(zone)
|
append(LocalDateTime(e.date, LocalTime(23, 59, 59)).toInstant(zone).toUtcBasic())
|
||||||
.toLocalDateTime(TimeZone.UTC)
|
|
||||||
append(
|
|
||||||
";UNTIL=%04d%02d%02dT%02d%02d%02dZ".format(
|
|
||||||
utc.year, utc.month.number, utc.day,
|
|
||||||
utc.hour, utc.minute, utc.second,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
is RecurrenceEnd.Count -> append(";COUNT=${e.times}")
|
is RecurrenceEnd.Count -> append(";COUNT=${e.times}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** One `;`-separated part of an RRULE as written; [key] is null when it has no `KEY=`. */
|
||||||
|
internal class RrulePart(val raw: String) {
|
||||||
|
private val eq = raw.indexOf('=')
|
||||||
|
val key: String? = if (eq > 0) raw.substring(0, eq).uppercase() else null
|
||||||
|
val value: String = if (eq > 0) raw.substring(eq + 1) else ""
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [rule]'s non-blank parts, after an optional leading "RRULE:". What to do
|
||||||
|
* with a malformed one (reject, repair or skip) is the caller's call.
|
||||||
|
*/
|
||||||
|
internal fun rruleParts(rule: String): List<RrulePart> =
|
||||||
|
rule.removePrefix("RRULE:").split(';').filter { it.isNotBlank() }.map(::RrulePart)
|
||||||
|
|
||||||
internal val RRULE_DAY_CODES: Map<DayOfWeek, String> = mapOf(
|
internal val RRULE_DAY_CODES: Map<DayOfWeek, String> = mapOf(
|
||||||
DayOfWeek.MONDAY to "MO",
|
DayOfWeek.MONDAY to "MO",
|
||||||
DayOfWeek.TUESDAY to "TU",
|
DayOfWeek.TUESDAY to "TU",
|
||||||
@@ -165,11 +164,7 @@ fun rruleTruncatedAt(rrule: String, untilUtcMillis: Long): String {
|
|||||||
val key = part.substringBefore('=').trim().uppercase()
|
val key = part.substringBefore('=').trim().uppercase()
|
||||||
key == "UNTIL" || key == "COUNT"
|
key == "UNTIL" || key == "COUNT"
|
||||||
}
|
}
|
||||||
val until = Instant.fromEpochMilliseconds(untilUtcMillis).toLocalDateTime(TimeZone.UTC)
|
val untilPart = "UNTIL=" + Instant.fromEpochMilliseconds(untilUtcMillis).toUtcBasic()
|
||||||
val untilPart = "UNTIL=%04d%02d%02dT%02d%02d%02dZ".format(
|
|
||||||
until.year, until.month.number, until.day,
|
|
||||||
until.hour, until.minute, until.second,
|
|
||||||
)
|
|
||||||
return (kept + untilPart).joinToString(";")
|
return (kept + untilPart).joinToString(";")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -178,20 +173,8 @@ fun rruleTruncatedAt(rrule: String, untilUtcMillis: Long): String {
|
|||||||
* forms are UTC (RFC 5545); the date is taken after converting into [zone] so
|
* forms are UTC (RFC 5545); the date is taken after converting into [zone] so
|
||||||
* a [toRRule]-rendered value round-trips to the day the user picked.
|
* a [toRRule]-rendered value round-trips to the day the user picked.
|
||||||
*/
|
*/
|
||||||
private fun parseUntilDate(raw: String, zone: TimeZone): LocalDate? = runCatching {
|
private fun parseUntilDate(raw: String, zone: TimeZone): LocalDate? {
|
||||||
val date = LocalDate(
|
val date = parseBasicDate(raw) ?: return null
|
||||||
raw.substring(0, 4).toInt(),
|
if (raw.length < 15 || raw[8] != 'T') return date
|
||||||
raw.substring(4, 6).toInt(),
|
return parseBasicDateTime(raw)?.toInstant(TimeZone.UTC)?.toLocalDateTime(zone)?.date
|
||||||
raw.substring(6, 8).toInt(),
|
}
|
||||||
)
|
|
||||||
if (raw.length >= 15 && raw[8] == 'T') {
|
|
||||||
val time = LocalTime(
|
|
||||||
raw.substring(9, 11).toInt(),
|
|
||||||
raw.substring(11, 13).toInt(),
|
|
||||||
raw.substring(13, 15).toInt(),
|
|
||||||
)
|
|
||||||
LocalDateTime(date, time).toInstant(TimeZone.UTC).toLocalDateTime(zone).date
|
|
||||||
} else {
|
|
||||||
date
|
|
||||||
}
|
|
||||||
}.getOrNull()
|
|
||||||
@@ -19,30 +19,30 @@ import kotlinx.datetime.LocalDate
|
|||||||
fun realignRecurrence(rrule: String, oldStart: LocalDate, newStart: LocalDate): String? {
|
fun realignRecurrence(rrule: String, oldStart: LocalDate, newStart: LocalDate): String? {
|
||||||
if (oldStart == newStart) return rrule
|
if (oldStart == newStart) return rrule
|
||||||
val prefix = if (rrule.startsWith("RRULE:")) "RRULE:" else ""
|
val prefix = if (rrule.startsWith("RRULE:")) "RRULE:" else ""
|
||||||
val parts = rrule.removePrefix("RRULE:").split(';').filter { it.isNotBlank() }
|
val parts = rruleParts(rrule)
|
||||||
if (parts.isEmpty()) return null
|
if (parts.isEmpty()) return null
|
||||||
|
var freq = false
|
||||||
var weekly = false
|
var weekly = false
|
||||||
|
var byDay = false
|
||||||
val rebuilt = parts.map { part ->
|
val rebuilt = parts.map { part ->
|
||||||
val eq = part.indexOf('=')
|
val value = part.value.trim()
|
||||||
if (eq <= 0) return null
|
when (part.key) {
|
||||||
val key = part.substring(0, eq).uppercase()
|
|
||||||
val value = part.substring(eq + 1).trim()
|
|
||||||
when (key) {
|
|
||||||
"FREQ" -> {
|
"FREQ" -> {
|
||||||
|
freq = true
|
||||||
weekly = value.equals("WEEKLY", ignoreCase = true)
|
weekly = value.equals("WEEKLY", ignoreCase = true)
|
||||||
part
|
part.raw
|
||||||
}
|
}
|
||||||
"BYDAY" -> {
|
"BYDAY" -> {
|
||||||
|
byDay = true
|
||||||
val old = RRULE_DAY_CODES[oldStart.dayOfWeek] ?: return null
|
val old = RRULE_DAY_CODES[oldStart.dayOfWeek] ?: return null
|
||||||
if (!value.equals(old, ignoreCase = true)) return null
|
if (!value.equals(old, ignoreCase = true)) return null
|
||||||
"BYDAY=${RRULE_DAY_CODES.getValue(newStart.dayOfWeek)}"
|
"BYDAY=${RRULE_DAY_CODES.getValue(newStart.dayOfWeek)}"
|
||||||
}
|
}
|
||||||
"INTERVAL", "COUNT", "UNTIL", "WKST" -> part
|
"INTERVAL", "COUNT", "UNTIL", "WKST" -> part.raw
|
||||||
else -> return null
|
else -> return null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// BYDAY is only simple on a weekly rule, matching parseSimpleRecurrence.
|
// BYDAY is only simple on a weekly rule, matching parseSimpleRecurrence.
|
||||||
if (!weekly && parts.any { it.substringBefore('=').trim().uppercase() == "BYDAY" }) return null
|
if (!freq || (byDay && !weekly)) return null
|
||||||
if (parts.none { it.substringBefore('=').trim().uppercase() == "FREQ" }) return null
|
|
||||||
return prefix + rebuilt.joinToString(";")
|
return prefix + rebuilt.joinToString(";")
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.domain.ics
|
||||||
|
|
||||||
|
import kotlinx.datetime.LocalDate
|
||||||
|
import kotlinx.datetime.LocalDateTime
|
||||||
|
import kotlinx.datetime.LocalTime
|
||||||
|
import kotlinx.datetime.TimeZone
|
||||||
|
import kotlinx.datetime.format
|
||||||
|
import kotlinx.datetime.format.char
|
||||||
|
import kotlinx.datetime.toLocalDateTime
|
||||||
|
import kotlin.time.Instant
|
||||||
|
|
||||||
|
/** RFC 5545 basic format, `yyyyMMddTHHmmss`. */
|
||||||
|
private val BASIC_DATE_TIME = LocalDateTime.Format {
|
||||||
|
date(LocalDate.Formats.ISO_BASIC)
|
||||||
|
char('T')
|
||||||
|
hour()
|
||||||
|
minute()
|
||||||
|
second()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `yyyyMMdd`. */
|
||||||
|
internal fun LocalDate.toBasic(): String = format(LocalDate.Formats.ISO_BASIC)
|
||||||
|
|
||||||
|
/** `yyyyMMddTHHmmss`, floating. */
|
||||||
|
internal fun LocalDateTime.toBasic(): String = format(BASIC_DATE_TIME)
|
||||||
|
|
||||||
|
/** `yyyyMMddTHHmmssZ`, the instant in UTC. */
|
||||||
|
internal fun Instant.toUtcBasic(): String = toLocalDateTime(TimeZone.UTC).toBasic() + "Z"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The date in the first eight characters of a basic-format value; whatever
|
||||||
|
* follows (a time, a `Z`) is ignored. Null when those aren't a valid date.
|
||||||
|
*/
|
||||||
|
internal fun parseBasicDate(s: String): LocalDate? = runCatching {
|
||||||
|
LocalDate(s.substring(0, 4).toInt(), s.substring(4, 6).toInt(), s.substring(6, 8).toInt())
|
||||||
|
}.getOrNull()
|
||||||
|
|
||||||
|
/** `yyyyMMddTHHmm[ss]`; the separator isn't checked and missing seconds read as zero. */
|
||||||
|
internal fun parseBasicDateTime(s: String): LocalDateTime? = runCatching {
|
||||||
|
val date = parseBasicDate(s) ?: return null
|
||||||
|
val time = LocalTime(
|
||||||
|
s.substring(9, 11).toInt(),
|
||||||
|
s.substring(11, 13).toInt(),
|
||||||
|
if (s.length >= 15) s.substring(13, 15).toInt() else 0,
|
||||||
|
)
|
||||||
|
LocalDateTime(date, time)
|
||||||
|
}.getOrNull()
|
||||||
@@ -2,19 +2,17 @@ package de.jeanlucmakiola.calendula.domain.ics
|
|||||||
|
|
||||||
import de.jeanlucmakiola.calendula.domain.Availability
|
import de.jeanlucmakiola.calendula.domain.Availability
|
||||||
import de.jeanlucmakiola.calendula.domain.EventStatus
|
import de.jeanlucmakiola.calendula.domain.EventStatus
|
||||||
import kotlinx.datetime.LocalDate
|
import de.jeanlucmakiola.calendula.domain.zoneOrNull
|
||||||
import kotlinx.datetime.LocalDateTime
|
import kotlinx.datetime.LocalDateTime
|
||||||
import kotlinx.datetime.LocalTime
|
|
||||||
import kotlinx.datetime.TimeZone
|
import kotlinx.datetime.TimeZone
|
||||||
import kotlinx.datetime.atStartOfDayIn
|
import kotlinx.datetime.atStartOfDayIn
|
||||||
import kotlinx.datetime.number
|
|
||||||
import kotlinx.datetime.toInstant
|
import kotlinx.datetime.toInstant
|
||||||
import kotlinx.datetime.toLocalDateTime
|
import kotlinx.datetime.toLocalDateTime
|
||||||
import kotlin.math.ceil
|
import kotlin.math.ceil
|
||||||
|
import kotlin.time.Duration.Companion.days
|
||||||
|
import kotlin.time.Duration.Companion.milliseconds
|
||||||
import kotlin.time.Instant
|
import kotlin.time.Instant
|
||||||
|
|
||||||
/** Milliseconds in a calendar day; all-day times are UTC midnights, so this is exact. */
|
|
||||||
private const val DAY_MILLIS = 86_400_000L
|
|
||||||
private const val MINUTES_PER_DAY = 1_440
|
private const val MINUTES_PER_DAY = 1_440
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -318,13 +316,9 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault
|
|||||||
dtEnd: IcsDateTime?,
|
dtEnd: IcsDateTime?,
|
||||||
duration: String?,
|
duration: String?,
|
||||||
): Instant {
|
): Instant {
|
||||||
val explicit = dtEnd?.instant ?: duration?.let {
|
val explicit = dtEnd?.instant ?: duration?.let { start.instant + parseRfc2445DurationMillis(it).milliseconds }
|
||||||
Instant.fromEpochMilliseconds(
|
|
||||||
start.instant.toEpochMilliseconds() + parseRfc2445DurationMillis(it),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
if (!start.isAllDay) return explicit ?: start.instant
|
if (!start.isAllDay) return explicit ?: start.instant
|
||||||
return explicit?.takeIf { it > start.instant } ?: start.instant.plusDays(1)
|
return explicit?.takeIf { it > start.instant } ?: (start.instant + 1.days)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -343,17 +337,17 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault
|
|||||||
*/
|
*/
|
||||||
private fun normalizeExDates(lines: List<IcsContentLine>, start: IcsDateTime): List<String> {
|
private fun normalizeExDates(lines: List<IcsContentLine>, start: IcsDateTime): List<String> {
|
||||||
if (lines.isEmpty()) return emptyList()
|
if (lines.isEmpty()) return emptyList()
|
||||||
val startZone = runCatching { TimeZone.of(start.zoneId) }.getOrNull() ?: deviceZone
|
val startZone = zoneOrNull(start.zoneId) ?: deviceZone
|
||||||
val startTime = start.instant.toLocalDateTime(startZone).time
|
val startTime = start.instant.toLocalDateTime(startZone).time
|
||||||
return lines
|
return lines
|
||||||
.flatMap { line -> line.value.split(',').map { line to it.trim() } }
|
.flatMap { line -> line.value.split(',').map { line to it.trim() } }
|
||||||
.mapNotNull { (line, token) ->
|
.mapNotNull { (line, token) ->
|
||||||
when {
|
when {
|
||||||
token.isEmpty() -> null
|
token.isEmpty() -> null
|
||||||
start.isAllDay -> parseBasicDate(token.substringBefore('T'))?.let(::dayCode)
|
start.isAllDay -> parseBasicDate(token.substringBefore('T'))?.toBasic()
|
||||||
token.contains('T') -> parseExDateTime(token, line, startZone)?.let(::utcStamp)
|
token.contains('T') -> parseExDateTime(token, line, startZone)?.toUtcBasic()
|
||||||
else -> parseBasicDate(token)
|
else -> parseBasicDate(token)
|
||||||
?.let { utcStamp(LocalDateTime(it, startTime).toInstant(startZone)) }
|
?.let { LocalDateTime(it, startTime).toInstant(startZone).toUtcBasic() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.distinct()
|
.distinct()
|
||||||
@@ -373,7 +367,7 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault
|
|||||||
val ldt = parseBasicDateTime(token.removeSuffix("Z")) ?: return null
|
val ldt = parseBasicDateTime(token.removeSuffix("Z")) ?: return null
|
||||||
val zone = when {
|
val zone = when {
|
||||||
token.endsWith("Z") -> TimeZone.UTC
|
token.endsWith("Z") -> TimeZone.UTC
|
||||||
else -> line.params["TZID"]?.let { runCatching { TimeZone.of(it) }.getOrNull() }
|
else -> line.params["TZID"]?.let(::zoneOrNull)
|
||||||
?: startZone
|
?: startZone
|
||||||
}
|
}
|
||||||
return ldt.toInstant(zone)
|
return ldt.toInstant(zone)
|
||||||
@@ -409,7 +403,7 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault
|
|||||||
if (isUtc) return IcsDateTime(ldt.toInstant(TimeZone.UTC), isAllDay = false, zoneId = "UTC")
|
if (isUtc) return IcsDateTime(ldt.toInstant(TimeZone.UTC), isAllDay = false, zoneId = "UTC")
|
||||||
|
|
||||||
val tzid = line.params["TZID"]
|
val tzid = line.params["TZID"]
|
||||||
val resolved = tzid?.let { id -> runCatching { TimeZone.of(id) }.getOrNull()?.let { id to it } }
|
val resolved = tzid?.let { id -> zoneOrNull(id)?.let { id to it } }
|
||||||
if (tzid != null && resolved == null) warnings.add(IcsParseWarning.UnknownTimezone)
|
if (tzid != null && resolved == null) warnings.add(IcsParseWarning.UnknownTimezone)
|
||||||
val (zoneId, zone) = resolved ?: (deviceZone.id to deviceZone)
|
val (zoneId, zone) = resolved ?: (deviceZone.id to deviceZone)
|
||||||
return IcsDateTime(ldt.toInstant(zone), isAllDay = false, zoneId = zoneId)
|
return IcsDateTime(ldt.toInstant(zone), isAllDay = false, zoneId = zoneId)
|
||||||
@@ -421,16 +415,6 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault
|
|||||||
fun IcsContentLine.isBegin(component: String) =
|
fun IcsContentLine.isBegin(component: String) =
|
||||||
name == "BEGIN" && value.trim().equals(component, true)
|
name == "BEGIN" && value.trim().equals(component, true)
|
||||||
|
|
||||||
fun Instant.plusDays(days: Int): Instant =
|
|
||||||
Instant.fromEpochMilliseconds(toEpochMilliseconds() + days * DAY_MILLIS)
|
|
||||||
|
|
||||||
fun dayCode(date: LocalDate): String =
|
|
||||||
"%04d%02d%02d".format(date.year, date.month.number, date.day)
|
|
||||||
|
|
||||||
fun utcStamp(instant: Instant): String = with(instant.toLocalDateTime(TimeZone.UTC)) {
|
|
||||||
"%04d%02d%02dT%02d%02d%02dZ".format(year, month.number, day, hour, minute, second)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A single-valued `CATEGORIES`, which is what the Fossify family writes
|
* A single-valued `CATEGORIES`, which is what the Fossify family writes
|
||||||
* for the source calendar's name. A multi-item list is a tag list and
|
* for the source calendar's name. A multi-item list is a tag list and
|
||||||
@@ -449,59 +433,26 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault
|
|||||||
.takeIf { it.isNotEmpty() && !it.equals("null", true) }
|
.takeIf { it.isNotEmpty() && !it.equals("null", true) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Index of the matching `END:<component>` at/after [from], or list end. */
|
|
||||||
/**
|
/**
|
||||||
* Where an unterminated component's body has to stop: the next top-level
|
* Where an unterminated component's body has to stop: the next top-level
|
||||||
* `VEVENT` / `VTODO` in `[from, end)`, or [end] when there is none. A
|
* `VEVENT` / `VTODO` in `[from, end)`, or [end] when there is none. A
|
||||||
* nested `VALARM` is part of the body and is not a boundary.
|
* nested `VALARM` is part of the body and is not a boundary.
|
||||||
*/
|
*/
|
||||||
fun indexOfNextComponent(lines: List<String>, from: Int, end: Int): Int {
|
fun indexOfNextComponent(lines: List<String>, from: Int, end: Int): Int =
|
||||||
var i = from
|
(from until end).firstOrNull { i ->
|
||||||
while (i < end) {
|
|
||||||
val line = parseContentLine(lines[i])
|
val line = parseContentLine(lines[i])
|
||||||
if (line != null && (line.isBegin("VEVENT") || line.isBegin("VTODO"))) {
|
line != null && (line.isBegin("VEVENT") || line.isBegin("VTODO"))
|
||||||
return i
|
} ?: end
|
||||||
}
|
|
||||||
i++
|
|
||||||
}
|
|
||||||
return end
|
|
||||||
}
|
|
||||||
|
|
||||||
fun indexOfEnd(lines: List<String>, from: Int, component: String): Int {
|
/** Index of the matching `END:<component>` at/after [from], or list end. */
|
||||||
var i = from
|
fun indexOfEnd(lines: List<String>, from: Int, component: String): Int =
|
||||||
while (i < lines.size) {
|
(from until lines.size).firstOrNull { i ->
|
||||||
val line = parseContentLine(lines[i])
|
val line = parseContentLine(lines[i])
|
||||||
if (line != null && line.name == "END" &&
|
line != null && line.name == "END" && line.value.trim().equals(component, true)
|
||||||
line.value.trim().equals(component, true)
|
} ?: lines.size
|
||||||
) {
|
|
||||||
return i
|
|
||||||
}
|
|
||||||
i++
|
|
||||||
}
|
|
||||||
return lines.size
|
|
||||||
}
|
|
||||||
|
|
||||||
fun mapIcsStatus(value: String): EventStatus = when (value.trim().uppercase()) {
|
fun mapIcsStatus(value: String): EventStatus =
|
||||||
"TENTATIVE" -> EventStatus.Tentative
|
EventStatus.entries.firstOrNull { it.name.equals(value.trim(), ignoreCase = true) }
|
||||||
"CANCELLED" -> EventStatus.Cancelled
|
?: EventStatus.Confirmed
|
||||||
else -> EventStatus.Confirmed
|
|
||||||
}
|
|
||||||
|
|
||||||
fun parseBasicDate(s: String): LocalDate? = runCatching {
|
|
||||||
LocalDate(s.substring(0, 4).toInt(), s.substring(4, 6).toInt(), s.substring(6, 8).toInt())
|
|
||||||
}.getOrNull()
|
|
||||||
|
|
||||||
fun parseBasicDateTime(s: String): LocalDateTime? = runCatching {
|
|
||||||
val date = LocalDate(
|
|
||||||
s.substring(0, 4).toInt(), s.substring(4, 6).toInt(), s.substring(6, 8).toInt(),
|
|
||||||
)
|
|
||||||
// Format is YYYYMMDD 'T' HHMMSS; seconds optional.
|
|
||||||
val time = LocalTime(
|
|
||||||
s.substring(9, 11).toInt(),
|
|
||||||
s.substring(11, 13).toInt(),
|
|
||||||
if (s.length >= 15) s.substring(13, 15).toInt() else 0,
|
|
||||||
)
|
|
||||||
LocalDateTime(date, time)
|
|
||||||
}.getOrNull()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
package de.jeanlucmakiola.calendula.domain.ics
|
package de.jeanlucmakiola.calendula.domain.ics
|
||||||
|
|
||||||
|
import de.jeanlucmakiola.calendula.domain.rruleParts
|
||||||
|
|
||||||
private val VALID_FREQ = setOf(
|
private val VALID_FREQ = setOf(
|
||||||
"SECONDLY", "MINUTELY", "HOURLY", "DAILY", "WEEKLY", "MONTHLY", "YEARLY",
|
"SECONDLY", "MINUTELY", "HOURLY", "DAILY", "WEEKLY", "MONTHLY", "YEARLY",
|
||||||
)
|
)
|
||||||
@@ -64,7 +66,9 @@ data class SanitizedRrule(val rule: String?, val repaired: Boolean)
|
|||||||
* rule at all — gives up entirely.
|
* rule at all — gives up entirely.
|
||||||
*/
|
*/
|
||||||
fun sanitizeRrule(raw: String?): SanitizedRrule {
|
fun sanitizeRrule(raw: String?): SanitizedRrule {
|
||||||
val rule = raw?.trim()?.removePrefix("RRULE:")?.trim().orEmpty()
|
val rule = raw?.trim()
|
||||||
|
?.let { if (it.startsWith("RRULE:", ignoreCase = true)) it.drop("RRULE:".length) else it }
|
||||||
|
?.trim().orEmpty()
|
||||||
if (rule.isEmpty()) return SanitizedRrule(rule = null, repaired = false)
|
if (rule.isEmpty()) return SanitizedRrule(rule = null, repaired = false)
|
||||||
|
|
||||||
var freqSeen = false
|
var freqSeen = false
|
||||||
@@ -79,13 +83,12 @@ fun sanitizeRrule(raw: String?): SanitizedRrule {
|
|||||||
return kept.takeIf { it.isNotEmpty() }?.joinToString(",")
|
return kept.takeIf { it.isNotEmpty() }?.joinToString(",")
|
||||||
}
|
}
|
||||||
|
|
||||||
for (part in rule.split(';')) {
|
// A stray separator ("FREQ=DAILY;") normalises away; nothing was lost.
|
||||||
// A stray separator ("FREQ=DAILY;") normalises away; nothing was lost.
|
// A part that carries text but no '=' ("FREQ=WEEKLY;BYDAY") is a part
|
||||||
// A part that carries text but no '=' ("FREQ=WEEKLY;BYDAY") is a part
|
// being dropped, so it falls through and marks the rule repaired.
|
||||||
// being dropped, so it falls through and marks the rule repaired.
|
for (part in rruleParts(rule)) {
|
||||||
if (part.isBlank()) continue
|
val key = part.key?.trim()?.uppercase().orEmpty()
|
||||||
val key = part.substringBefore('=', "").trim().uppercase()
|
val value = part.value.trim()
|
||||||
val value = if ('=' in part) part.substringAfter('=').trim() else ""
|
|
||||||
val kept = when {
|
val kept = when {
|
||||||
key.isEmpty() || value.isEmpty() -> null
|
key.isEmpty() || value.isEmpty() -> null
|
||||||
key == "FREQ" ->
|
key == "FREQ" ->
|
||||||
|
|||||||
@@ -2,9 +2,8 @@ package de.jeanlucmakiola.calendula.domain.ics
|
|||||||
|
|
||||||
import de.jeanlucmakiola.calendula.domain.Availability
|
import de.jeanlucmakiola.calendula.domain.Availability
|
||||||
import de.jeanlucmakiola.calendula.domain.EventStatus
|
import de.jeanlucmakiola.calendula.domain.EventStatus
|
||||||
import kotlinx.datetime.LocalDateTime
|
import de.jeanlucmakiola.calendula.domain.zoneOrNull
|
||||||
import kotlinx.datetime.TimeZone
|
import kotlinx.datetime.TimeZone
|
||||||
import kotlinx.datetime.number
|
|
||||||
import kotlinx.datetime.toLocalDateTime
|
import kotlinx.datetime.toLocalDateTime
|
||||||
import kotlin.time.Instant
|
import kotlin.time.Instant
|
||||||
|
|
||||||
@@ -41,7 +40,7 @@ class IcsWriter(private val prodId: String = ICS_PROD_ID) {
|
|||||||
private fun MutableList<String>.appendEvent(event: IcsEvent, dtStamp: Instant) {
|
private fun MutableList<String>.appendEvent(event: IcsEvent, dtStamp: Instant) {
|
||||||
add("BEGIN:VEVENT")
|
add("BEGIN:VEVENT")
|
||||||
add("UID:${event.uid}")
|
add("UID:${event.uid}")
|
||||||
add("DTSTAMP:${utcStamp(dtStamp)}")
|
add("DTSTAMP:${dtStamp.toUtcBasic()}")
|
||||||
add("SUMMARY:${escapeText(event.summary)}")
|
add("SUMMARY:${escapeText(event.summary)}")
|
||||||
appendTimes(event)
|
appendTimes(event)
|
||||||
event.recurrenceRule?.takeIf { it.isNotBlank() }
|
event.recurrenceRule?.takeIf { it.isNotBlank() }
|
||||||
@@ -63,24 +62,24 @@ class IcsWriter(private val prodId: String = ICS_PROD_ID) {
|
|||||||
|
|
||||||
private fun MutableList<String>.appendTimes(event: IcsEvent) = when {
|
private fun MutableList<String>.appendTimes(event: IcsEvent) = when {
|
||||||
event.isAllDay -> {
|
event.isAllDay -> {
|
||||||
add("DTSTART;VALUE=DATE:${utcDate(event.start)}")
|
add("DTSTART;VALUE=DATE:${event.start.toLocalDateTime(TimeZone.UTC).date.toBasic()}")
|
||||||
add("DTEND;VALUE=DATE:${utcDate(event.end)}")
|
add("DTEND;VALUE=DATE:${event.end.toLocalDateTime(TimeZone.UTC).date.toBasic()}")
|
||||||
}
|
}
|
||||||
// Recurring: anchor to wall-clock in the event's own zone.
|
// Recurring: anchor to wall-clock in the event's own zone.
|
||||||
event.recurrenceRule?.isNotBlank() == true -> {
|
event.recurrenceRule?.isNotBlank() == true -> {
|
||||||
val zone = runCatching { TimeZone.of(event.zoneId) }.getOrNull()
|
val zone = zoneOrNull(event.zoneId)
|
||||||
if (zone != null) {
|
if (zone != null) {
|
||||||
add("DTSTART;TZID=${event.zoneId}:${localStamp(event.start, zone)}")
|
add("DTSTART;TZID=${event.zoneId}:${event.start.toLocalDateTime(zone).toBasic()}")
|
||||||
add("DTEND;TZID=${event.zoneId}:${localStamp(event.end, zone)}")
|
add("DTEND;TZID=${event.zoneId}:${event.end.toLocalDateTime(zone).toBasic()}")
|
||||||
} else {
|
} else {
|
||||||
// Unknown zone id → fall back to plain UTC instants.
|
// Unknown zone id → fall back to plain UTC instants.
|
||||||
add("DTSTART:${utcStamp(event.start)}")
|
add("DTSTART:${event.start.toUtcBasic()}")
|
||||||
add("DTEND:${utcStamp(event.end)}")
|
add("DTEND:${event.end.toUtcBasic()}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else -> {
|
else -> {
|
||||||
add("DTSTART:${utcStamp(event.start)}")
|
add("DTSTART:${event.start.toUtcBasic()}")
|
||||||
add("DTEND:${utcStamp(event.end)}")
|
add("DTEND:${event.end.toUtcBasic()}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -120,20 +119,5 @@ class IcsWriter(private val prodId: String = ICS_PROD_ID) {
|
|||||||
// A lead time of 0 fires at start (PT0M); anything positive is "before".
|
// A lead time of 0 fires at start (PT0M); anything positive is "before".
|
||||||
fun triggerValue(minutes: Int): String =
|
fun triggerValue(minutes: Int): String =
|
||||||
if (minutes <= 0) "PT0M" else "-PT${minutes}M"
|
if (minutes <= 0) "PT0M" else "-PT${minutes}M"
|
||||||
|
|
||||||
fun utcStamp(instant: Instant): String =
|
|
||||||
basic(instant.toLocalDateTime(TimeZone.UTC)) + "Z"
|
|
||||||
|
|
||||||
fun localStamp(instant: Instant, zone: TimeZone): String =
|
|
||||||
basic(instant.toLocalDateTime(zone))
|
|
||||||
|
|
||||||
fun utcDate(instant: Instant): String {
|
|
||||||
val dt = instant.toLocalDateTime(TimeZone.UTC)
|
|
||||||
return "%04d%02d%02d".format(dt.year, dt.month.number, dt.day)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun basic(dt: LocalDateTime): String = "%04d%02d%02dT%02d%02d%02d".format(
|
|
||||||
dt.year, dt.month.number, dt.day, dt.hour, dt.minute, dt.second,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,11 +1,10 @@
|
|||||||
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.allDayFormTimes
|
||||||
|
import de.jeanlucmakiola.calendula.domain.forNewEvent
|
||||||
|
import de.jeanlucmakiola.calendula.domain.normalizedRrule
|
||||||
import de.jeanlucmakiola.calendula.domain.toFormTime
|
import de.jeanlucmakiola.calendula.domain.toFormTime
|
||||||
import kotlinx.datetime.LocalDate
|
|
||||||
import kotlinx.datetime.LocalDateTime
|
|
||||||
import kotlinx.datetime.LocalTime
|
|
||||||
import kotlinx.datetime.TimeZone
|
import kotlinx.datetime.TimeZone
|
||||||
import kotlinx.datetime.toLocalDateTime
|
import kotlinx.datetime.toLocalDateTime
|
||||||
|
|
||||||
@@ -23,10 +22,7 @@ import kotlinx.datetime.toLocalDateTime
|
|||||||
*/
|
*/
|
||||||
fun ParsedIcsEvent.toEventForm(zone: TimeZone): EventForm {
|
fun ParsedIcsEvent.toEventForm(zone: TimeZone): EventForm {
|
||||||
val (start, end) = if (isAllDay) {
|
val (start, end) = if (isAllDay) {
|
||||||
val startDate = this.start.toLocalDateTime(TimeZone.UTC).date
|
allDayFormTimes(this.start.toLocalDateTime(TimeZone.UTC).date, this.end.toLocalDateTime(TimeZone.UTC).date)
|
||||||
val endExclusive = this.end.toLocalDateTime(TimeZone.UTC).date
|
|
||||||
val endDate = maxOf(startDate, LocalDate.fromEpochDays(endExclusive.toEpochDays() - 1))
|
|
||||||
FormTime(LocalDateTime(startDate, LocalTime(9, 0))) to FormTime(LocalDateTime(endDate, LocalTime(10, 0)))
|
|
||||||
} else {
|
} else {
|
||||||
this.start.toFormTime(zone) to this.end.toFormTime(zone)
|
this.start.toFormTime(zone) to this.end.toFormTime(zone)
|
||||||
}
|
}
|
||||||
@@ -40,6 +36,7 @@ fun ParsedIcsEvent.toEventForm(zone: TimeZone): EventForm {
|
|||||||
description = description.orEmpty(),
|
description = description.orEmpty(),
|
||||||
reminders = semanticReminderMinutes(),
|
reminders = semanticReminderMinutes(),
|
||||||
availability = availability,
|
availability = availability,
|
||||||
rrule = recurrenceRule?.removePrefix("RRULE:")?.takeIf { it.isNotBlank() },
|
status = status.forNewEvent(),
|
||||||
|
rrule = recurrenceRule.normalizedRrule(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -32,19 +32,26 @@ data class PlannedReminder(
|
|||||||
val minutes: Int,
|
val minutes: Int,
|
||||||
val alarmMillis: Long,
|
val alarmMillis: Long,
|
||||||
) {
|
) {
|
||||||
|
/** The occurrence this reminder belongs to; it shares one notification with its siblings (#463). */
|
||||||
|
val occurrenceKey: Long = occurrenceKey(instance.eventId, instance.beginMillis)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stable identity, keying the notification tag and the snooze/dismiss
|
* Stable identity of this one reminder, keying the snooze/dismiss
|
||||||
* `PendingIntent`s. Survives reboot, re-scan and reinstall.
|
* `PendingIntent`s. Survives reboot, re-scan and reinstall.
|
||||||
*/
|
*/
|
||||||
val key: Long = key(instance.eventId, instance.beginMillis, minutes)
|
val key: Long = mix64(occurrenceKey + minutes)
|
||||||
|
}
|
||||||
|
|
||||||
private companion object {
|
/** Stable identity of one occurrence, shared by every reminder on it. */
|
||||||
fun key(eventId: Long, beginMillis: Long, minutes: Int): Long {
|
fun occurrenceKey(eventId: Long, beginMillis: Long): Long =
|
||||||
var h = eventId * 1_000_003L
|
mix64(mix64(eventId) + beginMillis)
|
||||||
h = (h xor beginMillis) * 31L
|
|
||||||
return h + minutes
|
/** SplitMix64's finaliser: spreads close inputs across all 64 bits. */
|
||||||
}
|
private fun mix64(value: Long): Long {
|
||||||
}
|
var z = value + -0x61c8864680b583ebL
|
||||||
|
z = (z xor (z ushr 30)) * -0x40a7b892e31b1a47L
|
||||||
|
z = (z xor (z ushr 27)) * -0x6b2fb644ecceee15L
|
||||||
|
return z xor (z ushr 31)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** What one scan concluded: post these now, and wake up again at [nextAlarmMillis]. */
|
/** What one scan concluded: post these now, and wake up again at [nextAlarmMillis]. */
|
||||||
@@ -146,7 +153,8 @@ private fun allDayAlarmMillis(
|
|||||||
*
|
*
|
||||||
* Due means the fire instant falls in `(lastFiredMillis, nowMillis]`, so a scan
|
* Due means the fire instant falls in `(lastFiredMillis, nowMillis]`, so a scan
|
||||||
* running twice cannot post twice while a late one still catches up. Reminders
|
* running twice cannot post twice while a late one still catches up. Reminders
|
||||||
* whose event has ended are dropped ([isStillRelevant]). [nextAlarmMillis] is
|
* whose event has ended are dropped ([isStillRelevant]), and of several due on
|
||||||
|
* one occurrence only the latest is kept — they'd replace each other anyway (#463). [nextAlarmMillis] is
|
||||||
* capped at [horizonMillis] so the lookahead window keeps rolling forward.
|
* capped at [horizonMillis] so the lookahead window keeps rolling forward.
|
||||||
*/
|
*/
|
||||||
fun scheduleReminders(
|
fun scheduleReminders(
|
||||||
@@ -158,7 +166,8 @@ fun scheduleReminders(
|
|||||||
val due = planned
|
val due = planned
|
||||||
.filter { it.alarmMillis in (lastFiredMillis + 1)..nowMillis }
|
.filter { it.alarmMillis in (lastFiredMillis + 1)..nowMillis }
|
||||||
.filter { it.instance.isStillRelevant(nowMillis) }
|
.filter { it.instance.isStillRelevant(nowMillis) }
|
||||||
.distinctBy { it.key }
|
.groupBy { it.occurrenceKey }
|
||||||
|
.values.map { siblings -> siblings.maxBy { it.alarmMillis } }
|
||||||
.sortedWith(compareBy({ it.instance.beginMillis }, { it.key }))
|
.sortedWith(compareBy({ it.instance.beginMillis }, { it.key }))
|
||||||
val nextPending = planned
|
val nextPending = planned
|
||||||
.filter { it.alarmMillis > nowMillis }
|
.filter { it.alarmMillis > nowMillis }
|
||||||
|
|||||||
@@ -4,8 +4,10 @@ import androidx.activity.compose.BackHandler
|
|||||||
import androidx.activity.compose.PredictiveBackHandler
|
import androidx.activity.compose.PredictiveBackHandler
|
||||||
import androidx.compose.animation.AnimatedContent
|
import androidx.compose.animation.AnimatedContent
|
||||||
import androidx.compose.animation.AnimatedVisibility
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
|
import androidx.compose.animation.AnimatedVisibilityScope
|
||||||
import androidx.compose.animation.ExperimentalSharedTransitionApi
|
import androidx.compose.animation.ExperimentalSharedTransitionApi
|
||||||
import androidx.compose.animation.SharedTransitionLayout
|
import androidx.compose.animation.SharedTransitionLayout
|
||||||
|
import androidx.compose.animation.core.MutableTransitionState
|
||||||
import androidx.compose.animation.core.SeekableTransitionState
|
import androidx.compose.animation.core.SeekableTransitionState
|
||||||
import androidx.compose.animation.core.rememberTransition
|
import androidx.compose.animation.core.rememberTransition
|
||||||
import androidx.compose.animation.fadeIn
|
import androidx.compose.animation.fadeIn
|
||||||
@@ -28,10 +30,12 @@ import androidx.compose.runtime.mutableStateOf
|
|||||||
import androidx.compose.runtime.mutableIntStateOf
|
import androidx.compose.runtime.mutableIntStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.rememberCoroutineScope
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.saveable.Saver
|
||||||
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.platform.LocalContext
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
|
import de.jeanlucmakiola.calendula.ui.common.rememberHeld
|
||||||
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
|
||||||
import androidx.compose.ui.layout.onGloballyPositioned
|
import androidx.compose.ui.layout.onGloballyPositioned
|
||||||
@@ -39,6 +43,7 @@ import androidx.compose.ui.layout.positionInWindow
|
|||||||
import androidx.compose.ui.platform.LocalDensity
|
import androidx.compose.ui.platform.LocalDensity
|
||||||
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.data.time.currentDate
|
||||||
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.ui.agenda.AgendaScreen
|
import de.jeanlucmakiola.calendula.ui.agenda.AgendaScreen
|
||||||
@@ -63,7 +68,7 @@ import de.jeanlucmakiola.calendula.ui.common.EventSelectionHost
|
|||||||
import de.jeanlucmakiola.calendula.ui.common.eventActionFailureMessage
|
import de.jeanlucmakiola.calendula.ui.common.eventActionFailureMessage
|
||||||
import de.jeanlucmakiola.calendula.ui.common.rememberFabSelection
|
import de.jeanlucmakiola.calendula.ui.common.rememberFabSelection
|
||||||
import de.jeanlucmakiola.calendula.ui.common.canWriteCalendar
|
import de.jeanlucmakiola.calendula.ui.common.canWriteCalendar
|
||||||
import de.jeanlucmakiola.calendula.ui.common.rememberWriteGateOr
|
import de.jeanlucmakiola.calendula.ui.common.rememberWriteAction
|
||||||
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
|
||||||
@@ -99,7 +104,6 @@ import kotlinx.datetime.LocalDate
|
|||||||
import kotlinx.datetime.TimeZone
|
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.Instant
|
import kotlin.time.Instant
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -116,29 +120,18 @@ import kotlin.time.Instant
|
|||||||
* view remains. So back from a widget-opened screen returns to that widget's
|
* view remains. So back from a widget-opened screen returns to that widget's
|
||||||
* view, then home; and back through pill switches walks the views in reverse.
|
* view, then home; and back through pill switches walks the views in reverse.
|
||||||
*
|
*
|
||||||
* [requestedDetailKey] is an externally requested occurrence (a tapped
|
* [requests] carries what notifications, widgets and other apps asked to
|
||||||
* reminder notification routed through MainActivity): it opens the detail
|
* open. A tapped reminder's occurrence opens the detail overlay exactly like an
|
||||||
* overlay exactly like an event tap and is cleared via [onDetailKeyConsumed]
|
* event tap; each request is cleared once acted on so a later recomposition
|
||||||
* so a later recomposition can't re-open it. (A widget event tap instead arrives
|
* can't re-open it. (A widget event tap instead arrives as
|
||||||
* as [WidgetNavRequest.OpenEvent], which also roots the back stack in the
|
* [WidgetNavRequest.OpenEvent], which also roots the back stack in the widget's
|
||||||
* widget's view.)
|
* view.)
|
||||||
*/
|
*/
|
||||||
@OptIn(ExperimentalSharedTransitionApi::class)
|
@OptIn(ExperimentalSharedTransitionApi::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun CalendarHost(
|
fun CalendarHost(
|
||||||
|
requests: ExternalRequests,
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
requestedDetailKey: LongArray? = null,
|
|
||||||
onDetailKeyConsumed: () -> Unit = {},
|
|
||||||
widgetNavRequest: WidgetNavRequest? = null,
|
|
||||||
onWidgetNavConsumed: () -> Unit = {},
|
|
||||||
requestedImportUri: android.net.Uri? = null,
|
|
||||||
onImportConsumed: () -> Unit = {},
|
|
||||||
requestedInsertForm: EventForm? = null,
|
|
||||||
requestedInsertSource: ImportSource = ImportSource.Insert,
|
|
||||||
onInsertConsumed: () -> Unit = {},
|
|
||||||
onExternalFormClosed: () -> Unit = {},
|
|
||||||
requestedEditKey: LongArray? = null,
|
|
||||||
onEditKeyConsumed: () -> Unit = {},
|
|
||||||
viewModel: CalendarHostViewModel = hiltViewModel(),
|
viewModel: CalendarHostViewModel = hiltViewModel(),
|
||||||
) {
|
) {
|
||||||
// Wait for the persisted default view before seeding the stack, so the app
|
// Wait for the persisted default view before seeding the stack, so the app
|
||||||
@@ -163,7 +156,7 @@ fun CalendarHost(
|
|||||||
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(currentDate()) }
|
||||||
// A focus still on yesterday follows the date over, so the next view opened
|
// 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.
|
// doesn't land on the old day (#373); one moved elsewhere stays put.
|
||||||
val today = viewModel.today.collectAsStateWithLifecycle().value
|
val today = viewModel.today.collectAsStateWithLifecycle().value
|
||||||
@@ -194,27 +187,17 @@ fun CalendarHost(
|
|||||||
// it overlays whichever calendar view is active. We forward the tapped
|
// it overlays whichever calendar view is active. We forward the tapped
|
||||||
// occurrence's own times (eventId + begin + end, packed as a saveable
|
// occurrence's own times (eventId + begin + end, packed as a saveable
|
||||||
// long[]) so recurring events show the correct date, not the series start.
|
// long[]) so recurring events show the correct date, not the series start.
|
||||||
// [heldKey] keeps the last shown key alive through the slide-out (when
|
// Like every overlay below, it draws its last key through the slide-out
|
||||||
// [detailKey] is cleared); it is set in the tap callback — never a [0,0,0]
|
// ([rememberHeld]) rather than a placeholder.
|
||||||
// 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) }
|
val onOpenDetail: (EventInstance) -> Unit = { event -> detailKey = event.occurrenceKey() }
|
||||||
val onOpenDetail: (EventInstance) -> Unit = { event ->
|
|
||||||
val key = longArrayOf(
|
|
||||||
event.eventId,
|
|
||||||
event.start.toEpochMilliseconds(),
|
|
||||||
event.end.toEpochMilliseconds(),
|
|
||||||
)
|
|
||||||
heldKey = key
|
|
||||||
detailKey = key
|
|
||||||
}
|
|
||||||
|
|
||||||
// A tapped reminder notification asks for a specific occurrence.
|
// A tapped reminder notification asks for a specific occurrence.
|
||||||
|
val requestedDetailKey = requests.detailKey
|
||||||
LaunchedEffect(requestedDetailKey) {
|
LaunchedEffect(requestedDetailKey) {
|
||||||
if (requestedDetailKey != null) {
|
if (requestedDetailKey != null) {
|
||||||
heldKey = requestedDetailKey
|
|
||||||
detailKey = requestedDetailKey
|
detailKey = requestedDetailKey
|
||||||
onDetailKeyConsumed()
|
requests.detailKey = null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -238,31 +221,17 @@ fun CalendarHost(
|
|||||||
// calendar list rather than by preferences. Reached from both.
|
// calendar list rather than by preferences. Reached from both.
|
||||||
var showBackup by rememberSaveable { mutableStateOf(false) }
|
var showBackup by rememberSaveable { mutableStateOf(false) }
|
||||||
|
|
||||||
// Event form (v1.2 create) — same held-key pattern as the detail screen:
|
// Event form (v1.2 create), opened on a date, a tapped slot or a drafted block.
|
||||||
// [heldCreateIso] keeps the prefill date alive through the slide-out.
|
var createRequest by rememberSaveable(stateSaver = createRequestSaver) {
|
||||||
// [createStartMinutes] is the tapped slot's start (minutes from midnight)
|
mutableStateOf<CreateRequest?>(null)
|
||||||
// when the form is opened from a day/week grid tap; null from the FAB.
|
|
||||||
var createDateIso by rememberSaveable { mutableStateOf<String?>(null) }
|
|
||||||
var heldCreateIso by remember { mutableStateOf<String?>(null) }
|
|
||||||
var createStartMinutes by rememberSaveable { mutableStateOf<Int?>(null) }
|
|
||||||
var heldCreateMinutes by remember { mutableStateOf<Int?>(null) }
|
|
||||||
// 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()
|
|
||||||
createDateIso = date.toString()
|
|
||||||
heldCreateMinutes = startMinutes
|
|
||||||
createStartMinutes = startMinutes
|
|
||||||
heldCreateDraftMillis = draftMillis
|
|
||||||
createDraftMillis = draftMillis
|
|
||||||
}
|
}
|
||||||
val onCreateEvent: (LocalDate, Int?) -> Unit = { date, startMinutes -> openCreate(date, startMinutes, null) }
|
fun openCreate(dateIso: String, startMinutes: Int? = null, draftMillis: LongArray? = null) {
|
||||||
|
createRequest = CreateRequest(dateIso, startMinutes, draftMillis)
|
||||||
|
}
|
||||||
|
val onCreateEvent: (LocalDate, Int?) -> Unit = { date, startMinutes -> openCreate(date.toString(), startMinutes) }
|
||||||
val onCreateDraft: (Instant, Instant) -> Unit = { start, end ->
|
val onCreateDraft: (Instant, Instant) -> Unit = { start, end ->
|
||||||
val date = start.toLocalDateTime(TimeZone.currentSystemDefault()).date
|
val date = start.toLocalDateTime(TimeZone.currentSystemDefault()).date
|
||||||
openCreate(date, null, longArrayOf(start.toEpochMilliseconds(), end.toEpochMilliseconds()))
|
openCreate(date.toString(), draftMillis = 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
|
||||||
@@ -272,25 +241,33 @@ fun CalendarHost(
|
|||||||
// falling back to the auto-refreshing calendar is the only honest
|
// falling back to the auto-refreshing calendar is the only honest
|
||||||
// destination.
|
// destination.
|
||||||
var editKey by rememberSaveable { mutableStateOf<LongArray?>(null) }
|
var editKey by rememberSaveable { mutableStateOf<LongArray?>(null) }
|
||||||
var heldEditKey by remember { mutableStateOf<LongArray?>(null) }
|
|
||||||
|
|
||||||
// An opened/received .ics file. [ImportScreen] parses it and either opens
|
// An opened/received .ics file. [ImportScreen] parses it and either opens
|
||||||
// the prefilled create form (one event → [importForm]) or its own bulk
|
// the prefilled create form (one event → [importForm]) or its own bulk
|
||||||
// picker (many). A plain conditional overlay (no slide) — it's transient.
|
// picker (many). A plain conditional overlay (no slide) — it's transient.
|
||||||
var importUri by remember { mutableStateOf<android.net.Uri?>(null) }
|
var importUri by rememberSaveable { mutableStateOf<android.net.Uri?>(null) }
|
||||||
var importForm by remember { mutableStateOf<EventForm?>(null) }
|
val importViewModel: EventEditViewModel = hiltViewModel(key = "import")
|
||||||
|
// Saved as "open"; a recreation takes the form back from the ViewModel, which
|
||||||
|
// still holds the user's edits.
|
||||||
|
var importForm by rememberSaveable(
|
||||||
|
stateSaver = Saver<EventForm?, Boolean>(
|
||||||
|
save = { it != null },
|
||||||
|
restore = { open -> if (open) importViewModel.currentForm() else null },
|
||||||
|
),
|
||||||
|
) { mutableStateOf<EventForm?>(null) }
|
||||||
// Which channel filled [importForm]: an .ics file (prompt to apply the default
|
// 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 rememberSaveable { mutableStateOf(ImportSource.File) }
|
||||||
// Bumped per open, so even an equal prefill starts a fresh form.
|
// Bumped per open, so even an equal prefill starts a fresh form.
|
||||||
var importFormId by remember { mutableIntStateOf(0) }
|
var importFormId by rememberSaveable { mutableIntStateOf(0) }
|
||||||
// Whether [importForm] came from an external create request (#30, #306);
|
// Whether [importForm] came from an external create request (#30, #306);
|
||||||
// closing it then hands control back to whoever asked.
|
// closing it then hands control back to whoever asked.
|
||||||
var importFromRequest by rememberSaveable { mutableStateOf(false) }
|
var importFromRequest by rememberSaveable { mutableStateOf(false) }
|
||||||
// A second external request that arrived while a prefilled form was open:
|
// A second external request that arrived while a prefilled form was open:
|
||||||
// it waits behind that form's unsaved-changes prompt, then opens.
|
// it waits behind that form's unsaved-changes prompt, then opens.
|
||||||
var pendingInsert by remember { mutableStateOf<Pair<EventForm, ImportSource>?>(null) }
|
var pendingInsert by remember { mutableStateOf<Pair<EventForm, ImportSource>?>(null) }
|
||||||
val importViewModel: EventEditViewModel = hiltViewModel(key = "import")
|
val createViewModel: EventEditViewModel = hiltViewModel(key = "create")
|
||||||
|
val editViewModel: EventEditViewModel = hiltViewModel(key = "edit")
|
||||||
fun openImportForm(form: EventForm, source: ImportSource, fromRequest: Boolean = false) {
|
fun openImportForm(form: EventForm, source: ImportSource, fromRequest: Boolean = false) {
|
||||||
importFormSource = source
|
importFormSource = source
|
||||||
importForm = form
|
importForm = form
|
||||||
@@ -306,7 +283,7 @@ fun CalendarHost(
|
|||||||
importForm = null
|
importForm = null
|
||||||
if (importFromRequest) {
|
if (importFromRequest) {
|
||||||
importFromRequest = false
|
importFromRequest = false
|
||||||
onExternalFormClosed()
|
requests.onExternalFormClosed()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -314,7 +291,7 @@ fun CalendarHost(
|
|||||||
// 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
|
||||||
// keeps routing a single event straight into the prefilled create form.
|
// keeps routing a single event straight into the prefilled create form.
|
||||||
var importForceMany by remember { mutableStateOf(false) }
|
var importForceMany by rememberSaveable { mutableStateOf(false) }
|
||||||
// Where a restore came from, so closing the import puts it back: the import
|
// Where a restore came from, so closing the import puts it back: the import
|
||||||
// overlays are declared under Backup & restore and the manager, so starting
|
// overlays are declared under Backup & restore and the manager, so starting
|
||||||
// one has to close them — without this, finishing a restore drops you on the
|
// one has to close them — without this, finishing a restore drops you on the
|
||||||
@@ -325,41 +302,64 @@ fun CalendarHost(
|
|||||||
// what tells it a *re-import of the same file* is new work and not the run
|
// what tells it a *re-import of the same file* is new work and not the run
|
||||||
// it already finished; a rotation keeps the number and keeps the result.
|
// it already finished; a rotation keeps the number and keeps the result.
|
||||||
var importSession by rememberSaveable { mutableStateOf(0) }
|
var importSession by rememberSaveable { mutableStateOf(0) }
|
||||||
|
// A recreation re-reads the launch intent; when the import it carries came
|
||||||
|
// back with the saved state, that replay is the same work, not a new one.
|
||||||
|
fun isReplayOfRestoredImport(): Boolean {
|
||||||
|
val replay = requests.replayed && (importUri != null || importForm != null)
|
||||||
|
requests.replayed = false
|
||||||
|
return replay
|
||||||
|
}
|
||||||
|
val requestedImportUri = requests.importUri
|
||||||
LaunchedEffect(requestedImportUri) {
|
LaunchedEffect(requestedImportUri) {
|
||||||
if (requestedImportUri != null) {
|
if (requestedImportUri != null) {
|
||||||
|
if (isReplayOfRestoredImport()) {
|
||||||
|
requests.importUri = null
|
||||||
|
return@LaunchedEffect
|
||||||
|
}
|
||||||
importUri = requestedImportUri
|
importUri = requestedImportUri
|
||||||
importForceMany = false
|
importForceMany = false
|
||||||
importSession++
|
importSession++
|
||||||
onImportConsumed()
|
requests.importUri = null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// An external ACTION_INSERT launch (another app/widget creating an event,
|
// An external ACTION_INSERT launch (another app/widget creating an event,
|
||||||
// issue #30) arrives already prefilled — open it in the same create form the
|
// issue #30) arrives already prefilled — open it in the same create form the
|
||||||
// single-event .ics path uses. [importForm] is the topmost overlay, so it
|
// single-event .ics path uses. [importForm] is the topmost overlay, so it
|
||||||
// reveals on top of whatever was open without extra dismissal.
|
// reveals on top of whatever was open without extra dismissal.
|
||||||
LaunchedEffect(requestedInsertForm) {
|
val requestedInsert = requests.insert
|
||||||
if (requestedInsertForm != null) {
|
LaunchedEffect(requestedInsert) {
|
||||||
if (importForm == null) {
|
if (requestedInsert != null) {
|
||||||
openImportForm(requestedInsertForm, requestedInsertSource, fromRequest = true)
|
if (isReplayOfRestoredImport()) {
|
||||||
} else {
|
requests.insert = null
|
||||||
pendingInsert = requestedInsertForm to requestedInsertSource
|
return@LaunchedEffect
|
||||||
}
|
}
|
||||||
onInsertConsumed()
|
if (importForm == null) {
|
||||||
|
openImportForm(requestedInsert.form, requestedInsert.source, fromRequest = true)
|
||||||
|
} else {
|
||||||
|
pendingInsert = requestedInsert.form to requestedInsert.source
|
||||||
|
}
|
||||||
|
requests.insert = null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Close every overlay that can sit over the calendar, so an externally
|
// Close every overlay that can sit over the calendar, so an externally
|
||||||
// requested destination (a widget/shortcut/QS-tile launch) is revealed on
|
// requested destination (a widget/shortcut/QS-tile launch) is revealed on
|
||||||
// top instead of underneath whatever the user had open.
|
// top instead of underneath whatever the user had open. The create form,
|
||||||
fun dismissCoveringOverlays() {
|
// declared under the edit form, can stay for an edit to open over it.
|
||||||
|
fun dismissCoveringOverlays(keepCreate: Boolean = false) {
|
||||||
showSettings = false
|
showSettings = false
|
||||||
|
showSearch = false
|
||||||
showCalendars = false
|
showCalendars = false
|
||||||
showBackup = false
|
showBackup = false
|
||||||
detailKey = null
|
detailKey = null
|
||||||
editKey = null
|
editKey = null
|
||||||
|
if (!keepCreate) createRequest = null
|
||||||
importUri = null
|
importUri = null
|
||||||
importForm = null
|
importForm = null
|
||||||
importFromRequest = false
|
if (importFromRequest) {
|
||||||
|
importFromRequest = false
|
||||||
|
requests.onExternalFormClosed()
|
||||||
|
}
|
||||||
pendingInsert = null
|
pendingInsert = null
|
||||||
importViewModel.reset()
|
importViewModel.reset()
|
||||||
}
|
}
|
||||||
@@ -367,21 +367,25 @@ fun CalendarHost(
|
|||||||
// 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
|
||||||
// widget) opens the occurrence straight in the edit form. Drop any covering
|
// widget) opens the occurrence straight in the edit form. Drop any covering
|
||||||
// overlay first — the edit overlay sits below Settings/import in the Box, so
|
// overlay first — the edit overlay sits below Settings/import in the Box, so
|
||||||
// without this it would open hidden underneath them. Same held-key pattern as
|
// without this it would open hidden underneath them. A saved edit just
|
||||||
// a detail-screen "Edit" tap; a saved edit just returns to the calendar.
|
// returns to the calendar.
|
||||||
|
val requestedEditKey = requests.editKey
|
||||||
LaunchedEffect(requestedEditKey) {
|
LaunchedEffect(requestedEditKey) {
|
||||||
if (requestedEditKey != null) {
|
if (requestedEditKey != null) {
|
||||||
dismissCoveringOverlays()
|
// An open edit form stays on screen, so it starts over here rather
|
||||||
heldEditKey = requestedEditKey
|
// than once it has slid away.
|
||||||
|
if (editKey != null) editViewModel.reset()
|
||||||
|
dismissCoveringOverlays(keepCreate = true)
|
||||||
editKey = requestedEditKey
|
editKey = requestedEditKey
|
||||||
onEditKeyConsumed()
|
requests.editKey = null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// A home-screen widget launch asks to open a date (→ day view), open an
|
// A home-screen widget launch asks to open a date (→ day view), open an
|
||||||
// event's detail, or start a create. Handled once and cleared, mirroring
|
// event's detail, or start a create. Handled once and cleared, mirroring
|
||||||
// [requestedDetailKey]. Date/event opens root the stack in the widget's own
|
// the detail request. Date/event opens root the stack in the widget's own
|
||||||
// view so backing out returns there (then home), not to the default.
|
// view so backing out returns there (then home), not to the default.
|
||||||
|
val widgetNavRequest = requests.nav
|
||||||
LaunchedEffect(widgetNavRequest) {
|
LaunchedEffect(widgetNavRequest) {
|
||||||
if (widgetNavRequest != null) {
|
if (widgetNavRequest != null) {
|
||||||
navigationVersion++
|
navigationVersion++
|
||||||
@@ -392,23 +396,19 @@ fun CalendarHost(
|
|||||||
// 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
|
||||||
// that would cover it, so the open doesn't land under Settings/form.
|
// that would cover it, so the open doesn't land under Settings/form.
|
||||||
dismissCoveringOverlays()
|
dismissCoveringOverlays()
|
||||||
createDateIso = null
|
|
||||||
focus.navigateTo(LocalDate.parse(req.dateIso))
|
focus.navigateTo(LocalDate.parse(req.dateIso))
|
||||||
// No widget source (an external date tap) roots over the default
|
// No widget source (an external date tap) roots over the default
|
||||||
// home view, so backing out of the day returns home then exits.
|
// home view, so backing out of the day returns home then exits.
|
||||||
viewStack = viewBaseStack(defaultView, req.source ?: defaultView).drillToDay()
|
viewStack = viewBaseStack(defaultView, req.source ?: defaultView).drillToDay()
|
||||||
onWidgetNavConsumed()
|
requests.nav = null
|
||||||
}
|
}
|
||||||
is WidgetNavRequest.OpenEvent -> {
|
is WidgetNavRequest.OpenEvent -> {
|
||||||
// Root the stack in the widget's view, then open the occurrence
|
// Root the stack in the widget's view, then open the occurrence
|
||||||
// detail over it (same key shape as a tapped event / reminder).
|
// detail over it (same key shape as a tapped event / reminder).
|
||||||
dismissCoveringOverlays()
|
dismissCoveringOverlays()
|
||||||
createDateIso = null
|
|
||||||
viewStack = viewBaseStack(defaultView, req.source)
|
viewStack = viewBaseStack(defaultView, req.source)
|
||||||
val key = longArrayOf(req.eventId, req.beginMillis, req.endMillis)
|
detailKey = longArrayOf(req.eventId, req.beginMillis, req.endMillis)
|
||||||
heldKey = key
|
requests.nav = null
|
||||||
detailKey = key
|
|
||||||
onWidgetNavConsumed()
|
|
||||||
}
|
}
|
||||||
is WidgetNavRequest.OpenView -> {
|
is WidgetNavRequest.OpenView -> {
|
||||||
// A widget header tap: land on a top-level view with no date
|
// A widget header tap: land on a top-level view with no date
|
||||||
@@ -416,26 +416,19 @@ fun CalendarHost(
|
|||||||
// the stack on the target (null → the default home) over the
|
// the stack on the target (null → the default home) over the
|
||||||
// default home — so backing out returns to the default, then exits.
|
// default home — so backing out returns to the default, then exits.
|
||||||
dismissCoveringOverlays()
|
dismissCoveringOverlays()
|
||||||
createDateIso = null
|
focus.navigateTo(currentDate())
|
||||||
focus.navigateTo(localToday())
|
|
||||||
viewStack = viewBaseStack(defaultView, req.view ?: defaultView)
|
viewStack = viewBaseStack(defaultView, req.view ?: defaultView)
|
||||||
onWidgetNavConsumed()
|
requests.nav = null
|
||||||
}
|
}
|
||||||
is WidgetNavRequest.Create -> {
|
is WidgetNavRequest.Create -> {
|
||||||
// External "new event" entries (QS tile / launcher shortcut /
|
// External "new event" entries (QS tile / launcher shortcut /
|
||||||
// widget) must land on top of whatever is open — the form overlay
|
// widget) must land on top of whatever is open — the form overlay
|
||||||
// sits below Settings/calendars in the Box, so without this it
|
// sits below Settings/calendars in the Box, so without this it
|
||||||
// would open hidden underneath them.
|
// would open hidden underneath them.
|
||||||
|
if (createRequest != null) createViewModel.reset()
|
||||||
dismissCoveringOverlays()
|
dismissCoveringOverlays()
|
||||||
val iso = req.dateIso ?: Clock.System.now()
|
openCreate(req.dateIso ?: currentDate().toString())
|
||||||
.toLocalDateTime(TimeZone.currentSystemDefault()).date.toString()
|
requests.nav = null
|
||||||
heldCreateIso = iso
|
|
||||||
createDateIso = iso
|
|
||||||
heldCreateMinutes = null
|
|
||||||
createStartMinutes = null
|
|
||||||
heldCreateDraftMillis = null
|
|
||||||
createDraftMillis = null
|
|
||||||
onWidgetNavConsumed()
|
|
||||||
}
|
}
|
||||||
null -> {}
|
null -> {}
|
||||||
}
|
}
|
||||||
@@ -448,23 +441,28 @@ fun CalendarHost(
|
|||||||
val eventActions: EventActionsViewModel = hiltViewModel()
|
val eventActions: EventActionsViewModel = hiltViewModel()
|
||||||
val moveOutcome by reschedule.outcome.collectAsStateWithLifecycle()
|
val moveOutcome by reschedule.outcome.collectAsStateWithLifecycle()
|
||||||
val selectionFailure by eventActions.failure.collectAsStateWithLifecycle()
|
val selectionFailure by eventActions.failure.collectAsStateWithLifecycle()
|
||||||
val onEditEvent: (EventInstance) -> Unit = { event ->
|
val onEditEvent: (EventInstance) -> Unit = { event -> editKey = event.occurrenceKey() }
|
||||||
val key = longArrayOf(
|
|
||||||
event.eventId,
|
|
||||||
event.start.toEpochMilliseconds(),
|
|
||||||
event.end.toEpochMilliseconds(),
|
|
||||||
)
|
|
||||||
heldEditKey = key
|
|
||||||
editKey = key
|
|
||||||
}
|
|
||||||
// A tap opens the edit form instead of the detail screen when the user chose
|
// 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
|
// 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.
|
// tap time, so a tap before they've loaded still routes right.
|
||||||
val tapScope = rememberCoroutineScope()
|
val tapScope = rememberCoroutineScope()
|
||||||
val tapContext = LocalContext.current
|
val tapContext = LocalContext.current
|
||||||
val requireWriteOr = rememberWriteGateOr()
|
|
||||||
// A refused write upgrade is asked once; later taps just open the details.
|
// A refused write upgrade is asked once; later taps just open the details.
|
||||||
var tapWriteRefused by rememberSaveable { mutableStateOf(false) }
|
var tapWriteRefused by rememberSaveable { mutableStateOf(false) }
|
||||||
|
// The tap waiting on the WRITE_CALENDAR prompt, saved so a rotation keeps it.
|
||||||
|
var tapAwaitingWrite by rememberSaveable { mutableStateOf<LongArray?>(null) }
|
||||||
|
val editAwaitingTap = rememberWriteAction(
|
||||||
|
onDenied = {
|
||||||
|
tapAwaitingWrite?.let { key ->
|
||||||
|
tapWriteRefused = true
|
||||||
|
detailKey = key
|
||||||
|
}
|
||||||
|
tapAwaitingWrite = null
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
tapAwaitingWrite?.let { editKey = it }
|
||||||
|
tapAwaitingWrite = null
|
||||||
|
}
|
||||||
val onEventClick: (EventInstance) -> Unit = { event ->
|
val onEventClick: (EventInstance) -> Unit = { event ->
|
||||||
tapScope.launch {
|
tapScope.launch {
|
||||||
val toEditor = viewModel.tapOpensEditor() && eventActions.canModify(event.calendarId)
|
val toEditor = viewModel.tapOpensEditor() && eventActions.canModify(event.calendarId)
|
||||||
@@ -472,9 +470,9 @@ fun CalendarHost(
|
|||||||
!toEditor -> onOpenDetail(event)
|
!toEditor -> onOpenDetail(event)
|
||||||
tapContext.canWriteCalendar() -> onEditEvent(event)
|
tapContext.canWriteCalendar() -> onEditEvent(event)
|
||||||
tapWriteRefused -> onOpenDetail(event)
|
tapWriteRefused -> onOpenDetail(event)
|
||||||
else -> requireWriteOr({ onEditEvent(event) }) {
|
else -> {
|
||||||
tapWriteRefused = true
|
tapAwaitingWrite = event.occurrenceKey()
|
||||||
onOpenDetail(event)
|
editAwaitingTap()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -487,22 +485,16 @@ fun CalendarHost(
|
|||||||
movableCalendarIds = movableCalendarIds,
|
movableCalendarIds = movableCalendarIds,
|
||||||
dragEnabled = dragToReschedule,
|
dragEnabled = dragToReschedule,
|
||||||
move = { reschedule.move(it) },
|
move = { reschedule.move(it) },
|
||||||
inFlight = reschedule.inFlight,
|
drops = reschedule.drops,
|
||||||
undoStarted = reschedule.undoStarted,
|
undoStarted = reschedule.undoStarted,
|
||||||
abandoned = reschedule.abandoned,
|
|
||||||
edit = onEditEvent,
|
edit = onEditEvent,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
val slideSpec = rememberCalendarSlideSpec()
|
|
||||||
// Overlays leave from the predictive-back preview (#184): shrinking on from
|
|
||||||
// where the gesture let go instead of snapping back and sliding off.
|
|
||||||
val overlayExit = predictiveBackExit()
|
|
||||||
|
|
||||||
// Base-level back: pop the view stack while no overlay covers it (each overlay
|
// Base-level back: pop the view stack while no overlay covers it (each overlay
|
||||||
// owns its own BackHandler and takes precedence). Disabled at the home view,
|
// owns its own BackHandler and takes precedence). Disabled at the home view,
|
||||||
// so back there falls through to the system and exits the app.
|
// so back there falls through to the system and exits the app.
|
||||||
val anyOverlayVisible = showSearch || detailKey != null || createDateIso != null ||
|
val anyOverlayVisible = showSearch || detailKey != null || createRequest != null ||
|
||||||
editKey != null || showSettings || showCalendars || showBackup ||
|
editKey != null || showSettings || showCalendars || showBackup ||
|
||||||
importUri != null || importForm != null
|
importUri != null || importForm != null
|
||||||
// The view switch runs on a seekable transition, so a back gesture can scrub
|
// The view switch runs on a seekable transition, so a back gesture can scrub
|
||||||
@@ -696,11 +688,7 @@ fun CalendarHost(
|
|||||||
|
|
||||||
// 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.
|
||||||
AnimatedVisibility(
|
SlideOverlay(visible = showSearch) {
|
||||||
visible = showSearch,
|
|
||||||
enter = slideInHorizontally(slideSpec) { it } + fadeIn(),
|
|
||||||
exit = overlayExit,
|
|
||||||
) {
|
|
||||||
SearchScreen(
|
SearchScreen(
|
||||||
onBack = { showSearch = false },
|
onBack = { showSearch = false },
|
||||||
onEventClick = onEventClick,
|
onEventClick = onEventClick,
|
||||||
@@ -708,23 +696,15 @@ fun CalendarHost(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Prefer the live key; fall back to the held one only while sliding out.
|
val shownDetailKey = rememberHeld(detailKey)
|
||||||
val activeKey = detailKey ?: heldKey
|
SlideOverlay(visible = detailKey != null) {
|
||||||
AnimatedVisibility(
|
shownDetailKey?.let { key ->
|
||||||
visible = detailKey != null,
|
|
||||||
enter = slideInHorizontally(slideSpec) { it } + fadeIn(),
|
|
||||||
exit = overlayExit,
|
|
||||||
) {
|
|
||||||
activeKey?.let { key ->
|
|
||||||
EventDetailScreen(
|
EventDetailScreen(
|
||||||
eventId = key[0],
|
eventId = key[0],
|
||||||
beginMillis = key[1],
|
beginMillis = key[1],
|
||||||
endMillis = key[2],
|
endMillis = key[2],
|
||||||
onBack = { detailKey = null },
|
onBack = { detailKey = null },
|
||||||
onEdit = {
|
onEdit = { editKey = key },
|
||||||
heldEditKey = key
|
|
||||||
editKey = key
|
|
||||||
},
|
|
||||||
onDuplicate = { form ->
|
onDuplicate = { form ->
|
||||||
// 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
|
||||||
@@ -738,32 +718,28 @@ fun CalendarHost(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Event form (v1.2) — full-screen destination, slides over the calendar.
|
// Event form (v1.2) — full-screen destination, slides over the calendar.
|
||||||
AnimatedVisibility(
|
val shownCreate = rememberHeld(createRequest)
|
||||||
visible = createDateIso != null,
|
SlideOverlay(visible = createRequest != null, onHidden = createViewModel::reset) {
|
||||||
enter = slideInHorizontally(slideSpec) { it } + fadeIn(),
|
shownCreate?.let { create ->
|
||||||
exit = overlayExit,
|
key(create) {
|
||||||
) {
|
EventEditScreen(
|
||||||
(createDateIso ?: heldCreateIso)?.let { iso ->
|
initialDateIso = create.dateIso,
|
||||||
EventEditScreen(
|
initialStartMinutes = create.startMinutes,
|
||||||
initialDateIso = iso,
|
initialDraft = create.draftMillis,
|
||||||
initialStartMinutes = createStartMinutes ?: heldCreateMinutes,
|
onClose = { createRequest = null },
|
||||||
initialDraft = createDraftMillis ?: heldCreateDraftMillis,
|
onSaved = { createRequest = null },
|
||||||
onClose = { createDateIso = null },
|
onManageCalendars = { showCalendars = true },
|
||||||
onSaved = { createDateIso = null },
|
visible = createRequest != null,
|
||||||
onManageCalendars = { showCalendars = true },
|
viewModel = createViewModel,
|
||||||
visible = createDateIso != null,
|
)
|
||||||
viewModel = hiltViewModel(key = "create"),
|
}
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Edit form (v1.3) — slides over the detail screen.
|
// Edit form (v1.3) — slides over the detail screen.
|
||||||
AnimatedVisibility(
|
val shownEditKey = rememberHeld(editKey)
|
||||||
visible = editKey != null,
|
SlideOverlay(visible = editKey != null, onHidden = editViewModel::reset) {
|
||||||
enter = slideInHorizontally(slideSpec) { it } + fadeIn(),
|
shownEditKey?.let { key ->
|
||||||
exit = overlayExit,
|
|
||||||
) {
|
|
||||||
(editKey ?: heldEditKey)?.let { key ->
|
|
||||||
EventEditScreen(
|
EventEditScreen(
|
||||||
initialDateIso = null,
|
initialDateIso = null,
|
||||||
editKey = key,
|
editKey = key,
|
||||||
@@ -780,23 +756,16 @@ fun CalendarHost(
|
|||||||
// below to show why, so open it.
|
// below to show why, so open it.
|
||||||
onLoadFailed = {
|
onLoadFailed = {
|
||||||
editKey = null
|
editKey = null
|
||||||
if (detailKey == null) {
|
if (detailKey == null) detailKey = key
|
||||||
heldKey = key
|
|
||||||
detailKey = key
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
visible = editKey != null,
|
visible = editKey != null,
|
||||||
viewModel = hiltViewModel(key = "edit"),
|
viewModel = editViewModel,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Settings (M4) — full-screen destination, slides over the calendar.
|
// Settings (M4) — full-screen destination, slides over the calendar.
|
||||||
AnimatedVisibility(
|
SlideOverlay(visible = showSettings) {
|
||||||
visible = showSettings,
|
|
||||||
enter = slideInHorizontally(slideSpec) { it } + fadeIn(),
|
|
||||||
exit = overlayExit,
|
|
||||||
) {
|
|
||||||
SettingsScreen(
|
SettingsScreen(
|
||||||
onBack = { showSettings = false },
|
onBack = { showSettings = false },
|
||||||
onManageCalendars = { showCalendars = true },
|
onManageCalendars = { showCalendars = true },
|
||||||
@@ -854,11 +823,7 @@ fun CalendarHost(
|
|||||||
|
|
||||||
// Declared last so it covers every overlay that can open it: Settings,
|
// Declared last so it covers every overlay that can open it: Settings,
|
||||||
// both event forms, and the .ics import picker (#76).
|
// both event forms, and the .ics import picker (#76).
|
||||||
AnimatedVisibility(
|
SlideOverlay(visible = showCalendars) {
|
||||||
visible = showCalendars,
|
|
||||||
enter = slideInHorizontally(slideSpec) { it } + fadeIn(),
|
|
||||||
exit = overlayExit,
|
|
||||||
) {
|
|
||||||
CalendarsScreen(
|
CalendarsScreen(
|
||||||
onBack = { showCalendars = false },
|
onBack = { showCalendars = false },
|
||||||
onOpenBackup = { showBackup = true },
|
onOpenBackup = { showBackup = true },
|
||||||
@@ -867,11 +832,7 @@ fun CalendarHost(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Backup & restore — over the manager, since the manager links into it.
|
// Backup & restore — over the manager, since the manager links into it.
|
||||||
AnimatedVisibility(
|
SlideOverlay(visible = showBackup) {
|
||||||
visible = showBackup,
|
|
||||||
enter = slideInHorizontally(slideSpec) { it } + fadeIn(),
|
|
||||||
exit = overlayExit,
|
|
||||||
) {
|
|
||||||
// Settings can open this screen without the manager underneath, so
|
// Settings can open this screen without the manager underneath, so
|
||||||
// its failure states' "Manage calendars" way out has to open the
|
// its failure states' "Manage calendars" way out has to open the
|
||||||
// manager rather than just pop — popping alone lands on Settings
|
// manager rather than just pop — popping alone lands on Settings
|
||||||
@@ -910,5 +871,48 @@ private val viewStackSaver = listSaver<List<CalendarView>, Int>(
|
|||||||
restore = { ordinals -> ordinals.map { CalendarView.entries[it] } },
|
restore = { ordinals -> ordinals.map { CalendarView.entries[it] } },
|
||||||
)
|
)
|
||||||
|
|
||||||
private fun localToday(): LocalDate =
|
/**
|
||||||
Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).date
|
* An overlay's slide-in from the end edge, leaving from the predictive-back
|
||||||
|
* preview (#184): shrinking on from where the gesture let go instead of
|
||||||
|
* snapping back and sliding off.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
private fun SlideOverlay(
|
||||||
|
visible: Boolean,
|
||||||
|
onHidden: () -> Unit = {},
|
||||||
|
content: @Composable AnimatedVisibilityScope.() -> Unit,
|
||||||
|
) {
|
||||||
|
val state = remember { MutableTransitionState(visible) }
|
||||||
|
state.targetState = visible
|
||||||
|
val hidden = state.isIdle && !state.currentState
|
||||||
|
LaunchedEffect(hidden) {
|
||||||
|
if (hidden) onHidden()
|
||||||
|
}
|
||||||
|
AnimatedVisibility(
|
||||||
|
visibleState = state,
|
||||||
|
enter = slideInHorizontally(rememberCalendarSlideSpec()) { it } + fadeIn(),
|
||||||
|
exit = predictiveBackExit(),
|
||||||
|
content = content,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The detail and edit overlays' key for one occurrence: eventId, begin, end. */
|
||||||
|
private fun EventInstance.occurrenceKey(): LongArray =
|
||||||
|
longArrayOf(eventId, start.toEpochMilliseconds(), end.toEpochMilliseconds())
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A create-form open: its date, plus the tapped slot's start (minutes from
|
||||||
|
* midnight) from a day/week grid tap, or a drafted block's start and end (#153)
|
||||||
|
* as epoch millis. Instants rather than minutes into a day, so the form opens at
|
||||||
|
* the times drawn even across a DST change (#387).
|
||||||
|
*/
|
||||||
|
private class CreateRequest(
|
||||||
|
val dateIso: String,
|
||||||
|
val startMinutes: Int?,
|
||||||
|
val draftMillis: LongArray?,
|
||||||
|
)
|
||||||
|
|
||||||
|
private val createRequestSaver = Saver<CreateRequest?, List<Any?>>(
|
||||||
|
save = { request -> request?.let { listOf(it.dateIso, it.startMinutes, it.draftMillis) } },
|
||||||
|
restore = { CreateRequest(it[0] as String, it[1] as Int?, it[2] as LongArray?) },
|
||||||
|
)
|
||||||
@@ -8,11 +8,10 @@ import de.jeanlucmakiola.calendula.data.time.TodaySource
|
|||||||
import de.jeanlucmakiola.calendula.data.time.currentDate
|
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.first
|
import kotlinx.coroutines.flow.first
|
||||||
import kotlinx.coroutines.flow.stateIn
|
|
||||||
import kotlinx.datetime.LocalDate
|
import kotlinx.datetime.LocalDate
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
@@ -29,40 +28,35 @@ class CalendarHostViewModel @Inject constructor(
|
|||||||
) : ViewModel() {
|
) : ViewModel() {
|
||||||
|
|
||||||
/** Today, kept current across midnight so the shared focus can follow it (#373). */
|
/** Today, kept current across midnight so the shared focus can follow it (#373). */
|
||||||
val today: StateFlow<LocalDate> = todaySource.today.stateIn(
|
val today: StateFlow<LocalDate> = todaySource.today.stateWhileSubscribed(
|
||||||
scope = viewModelScope,
|
scope = viewModelScope,
|
||||||
started = SharingStarted.WhileSubscribed(5_000L),
|
|
||||||
initialValue = currentDate(),
|
initialValue = currentDate(),
|
||||||
)
|
)
|
||||||
|
|
||||||
val defaultView: StateFlow<CalendarView?> = prefs.defaultView.stateIn(
|
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,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -74,9 +68,8 @@ 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,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.ui
|
||||||
|
|
||||||
|
import android.net.Uri
|
||||||
|
import androidx.compose.runtime.Stable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import de.jeanlucmakiola.calendula.domain.EventForm
|
||||||
|
import de.jeanlucmakiola.calendula.ui.edit.ImportSource
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What a notification, widget, shortcut or another app asked the running app to
|
||||||
|
* open. MainActivity fills it from each intent (singleTop + onNewIntent route a
|
||||||
|
* new one into the running activity); CalendarHost acts on a request and clears
|
||||||
|
* it, so a later recomposition can't act on it twice.
|
||||||
|
*
|
||||||
|
* [onExternalFormClosed] runs when a form opened for [insert] closes, so the
|
||||||
|
* activity can hand control back to the app that asked.
|
||||||
|
*/
|
||||||
|
@Stable
|
||||||
|
class ExternalRequests(val onExternalFormClosed: () -> Unit = {}) {
|
||||||
|
/** A tapped reminder notification's occurrence (eventId, begin, end), for the detail screen. */
|
||||||
|
var detailKey by mutableStateOf<LongArray?>(null)
|
||||||
|
|
||||||
|
/** A home-screen widget, shortcut or tile navigation (open a date, an event, a view, or create). */
|
||||||
|
var nav by mutableStateOf<WidgetNavRequest?>(null)
|
||||||
|
|
||||||
|
/** An .ics file opened or shared into the app (ACTION_VIEW/SEND). */
|
||||||
|
var importUri by mutableStateOf<Uri?>(null)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A prefilled new-event form from an external ACTION_INSERT launch (#30) or
|
||||||
|
* shared text (#306), opened in the create form for review.
|
||||||
|
*/
|
||||||
|
var insert by mutableStateOf<InsertRequest?>(null)
|
||||||
|
|
||||||
|
/** An external "edit this event" (ACTION_EDIT), in the detail key's shape. */
|
||||||
|
var editKey by mutableStateOf<LongArray?>(null)
|
||||||
|
|
||||||
|
/** Whether these came from re-reading the launch intent on a recreation. */
|
||||||
|
var replayed = false
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A prefilled create form from an external launch, with the source it came from. */
|
||||||
|
data class InsertRequest(val form: EventForm, val source: ImportSource)
|
||||||
@@ -1,7 +1,5 @@
|
|||||||
package de.jeanlucmakiola.calendula.ui
|
package de.jeanlucmakiola.calendula.ui
|
||||||
|
|
||||||
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,11 +18,11 @@ 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
|
||||||
import de.jeanlucmakiola.calendula.data.contacts.hasContactsPermission
|
import de.jeanlucmakiola.calendula.data.contacts.hasContactsPermission
|
||||||
|
import de.jeanlucmakiola.calendula.ui.common.canReadCalendar
|
||||||
import de.jeanlucmakiola.calendula.ui.common.rememberCalendarFadeSpec
|
import de.jeanlucmakiola.calendula.ui.common.rememberCalendarFadeSpec
|
||||||
import de.jeanlucmakiola.calendula.ui.onboarding.OnboardingStep
|
import de.jeanlucmakiola.calendula.ui.onboarding.OnboardingStep
|
||||||
import de.jeanlucmakiola.calendula.ui.onboarding.OnboardingSteps
|
import de.jeanlucmakiola.calendula.ui.onboarding.OnboardingSteps
|
||||||
@@ -43,27 +41,12 @@ private sealed interface RootTarget {
|
|||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun RootScreen(
|
fun RootScreen(
|
||||||
|
requests: ExternalRequests,
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
requestedDetailKey: LongArray? = null,
|
|
||||||
onDetailKeyConsumed: () -> Unit = {},
|
|
||||||
widgetNavRequest: WidgetNavRequest? = null,
|
|
||||||
onWidgetNavConsumed: () -> Unit = {},
|
|
||||||
requestedImportUri: android.net.Uri? = null,
|
|
||||||
onImportConsumed: () -> Unit = {},
|
|
||||||
requestedInsertForm: de.jeanlucmakiola.calendula.domain.EventForm? = null,
|
|
||||||
requestedInsertSource: de.jeanlucmakiola.calendula.ui.edit.ImportSource =
|
|
||||||
de.jeanlucmakiola.calendula.ui.edit.ImportSource.Insert,
|
|
||||||
onInsertConsumed: () -> Unit = {},
|
|
||||||
onExternalFormClosed: () -> Unit = {},
|
|
||||||
requestedEditKey: LongArray? = null,
|
|
||||||
onEditKeyConsumed: () -> Unit = {},
|
|
||||||
) {
|
) {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
var hasPermission by remember {
|
var hasPermission by remember {
|
||||||
mutableStateOf(
|
mutableStateOf(context.canReadCalendar())
|
||||||
ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CALENDAR)
|
|
||||||
== PackageManager.PERMISSION_GRANTED
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// A launch scan already covers the app coming up with the permission, so
|
// A launch scan already covers the app coming up with the permission, so
|
||||||
@@ -74,9 +57,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.canReadCalendar()
|
||||||
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.
|
||||||
@@ -146,19 +127,8 @@ fun RootScreen(
|
|||||||
when (shown) {
|
when (shown) {
|
||||||
RootTarget.Loading -> Unit
|
RootTarget.Loading -> Unit
|
||||||
RootTarget.App -> CalendarHost(
|
RootTarget.App -> CalendarHost(
|
||||||
|
requests = requests,
|
||||||
modifier = modifier,
|
modifier = modifier,
|
||||||
requestedDetailKey = requestedDetailKey,
|
|
||||||
onDetailKeyConsumed = onDetailKeyConsumed,
|
|
||||||
widgetNavRequest = widgetNavRequest,
|
|
||||||
onWidgetNavConsumed = onWidgetNavConsumed,
|
|
||||||
requestedImportUri = requestedImportUri,
|
|
||||||
onImportConsumed = onImportConsumed,
|
|
||||||
requestedInsertForm = requestedInsertForm,
|
|
||||||
requestedInsertSource = requestedInsertSource,
|
|
||||||
onInsertConsumed = onInsertConsumed,
|
|
||||||
onExternalFormClosed = onExternalFormClosed,
|
|
||||||
requestedEditKey = requestedEditKey,
|
|
||||||
onEditKeyConsumed = onEditKeyConsumed,
|
|
||||||
)
|
)
|
||||||
// Both halves of a transition read their position out of the live
|
// Both halves of a transition read their position out of the live
|
||||||
// plan; the one the outgoing step was drawn with is already gone.
|
// plan; the one the outgoing step was drawn with is already gone.
|
||||||
|
|||||||
@@ -3,8 +3,9 @@ package de.jeanlucmakiola.calendula.ui.agenda
|
|||||||
import de.jeanlucmakiola.floret.locale.localizedDateFormatter
|
import de.jeanlucmakiola.floret.locale.localizedDateFormatter
|
||||||
import kotlinx.datetime.DayOfWeek
|
import kotlinx.datetime.DayOfWeek
|
||||||
import kotlinx.datetime.LocalDate
|
import kotlinx.datetime.LocalDate
|
||||||
import java.time.YearMonth
|
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
|
import kotlinx.datetime.toJavaLocalDate
|
||||||
|
import kotlinx.datetime.yearMonth
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* How far ahead the agenda (screen or widget) shows events, starting at today.
|
* How far ahead the agenda (screen or widget) shows events, starting at today.
|
||||||
@@ -50,7 +51,7 @@ fun AgendaRange.dayCount(anchor: LocalDate, weekStart: DayOfWeek): Int = when (t
|
|||||||
DAYS_PER_WEEK - sinceWeekStart
|
DAYS_PER_WEEK - sinceWeekStart
|
||||||
}
|
}
|
||||||
AgendaRange.ThisMonth -> {
|
AgendaRange.ThisMonth -> {
|
||||||
val daysInMonth = YearMonth.of(anchor.year, anchor.month.ordinal + 1).lengthOfMonth()
|
val daysInMonth = anchor.yearMonth.numberOfDays
|
||||||
daysInMonth - anchor.day + 1
|
daysInMonth - anchor.day + 1
|
||||||
}
|
}
|
||||||
is AgendaRange.Custom -> days.coerceIn(AgendaRange.MIN_CUSTOM_DAYS, AgendaRange.MAX_CUSTOM_DAYS)
|
is AgendaRange.Custom -> days.coerceIn(AgendaRange.MIN_CUSTOM_DAYS, AgendaRange.MAX_CUSTOM_DAYS)
|
||||||
@@ -105,8 +106,8 @@ fun agendaRangeWindowSummary(
|
|||||||
locale: Locale,
|
locale: Locale,
|
||||||
monthAsSpan: Boolean = false,
|
monthAsSpan: Boolean = false,
|
||||||
): String {
|
): String {
|
||||||
val javaStart = java.time.LocalDate.of(start.year, start.month.ordinal + 1, start.day)
|
val javaStart = start.toJavaLocalDate()
|
||||||
val javaEnd = java.time.LocalDate.of(end.year, end.month.ordinal + 1, end.day)
|
val javaEnd = end.toJavaLocalDate()
|
||||||
val dayMonth = localizedDateFormatter(locale, "dMMM")
|
val dayMonth = localizedDateFormatter(locale, "dMMM")
|
||||||
val dayMonthYear = localizedDateFormatter(locale, "dMMMy")
|
val dayMonthYear = localizedDateFormatter(locale, "dMMMy")
|
||||||
return when {
|
return when {
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
package de.jeanlucmakiola.calendula.ui.agenda
|
package de.jeanlucmakiola.calendula.ui.agenda
|
||||||
|
|
||||||
|
import androidx.annotation.StringRes
|
||||||
|
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
@@ -9,6 +11,8 @@ 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.lazy.LazyListScope
|
||||||
|
import androidx.compose.foundation.lazy.itemsIndexed
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.filled.Coffee
|
import androidx.compose.material.icons.filled.Coffee
|
||||||
@@ -28,36 +32,43 @@ import androidx.compose.ui.text.style.TextAlign
|
|||||||
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.domain.EventInstance
|
import de.jeanlucmakiola.calendula.domain.EventInstance
|
||||||
import de.jeanlucmakiola.calendula.domain.isDeclined
|
import de.jeanlucmakiola.calendula.domain.isCrossedOut
|
||||||
import de.jeanlucmakiola.calendula.ui.common.EventDimAlpha
|
import de.jeanlucmakiola.calendula.ui.common.EventDimAlpha
|
||||||
|
import de.jeanlucmakiola.calendula.ui.common.ViewMorphKey
|
||||||
import de.jeanlucmakiola.calendula.ui.common.declinedTitle
|
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.calendula.ui.common.morphEvent
|
||||||
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.positionOf
|
||||||
import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme
|
import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme
|
||||||
|
import de.jeanlucmakiola.floret.identity.animateItemMotion
|
||||||
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
|
||||||
import kotlinx.datetime.LocalDate
|
import kotlinx.datetime.LocalDate
|
||||||
import kotlinx.datetime.TimeZone
|
import kotlinx.datetime.TimeZone
|
||||||
import kotlinx.datetime.plus
|
import kotlinx.datetime.plus
|
||||||
import kotlinx.datetime.toLocalDateTime
|
import kotlinx.datetime.toJavaLocalDate
|
||||||
import kotlin.time.Instant
|
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
|
|
||||||
// The agenda's row vocabulary, split out of AgendaScreen so the month view's
|
// The agenda's row vocabulary, split out of AgendaScreen so the month view's
|
||||||
// split style can list a day with exactly the same visual language instead of
|
// split style can list a day with exactly the same visual language instead of
|
||||||
// growing a parallel set of event rows.
|
// growing a parallel set of event rows.
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A day's header; tapping it opens the Day view. [compact] trims the padding for
|
||||||
|
* the month view's split pane, where vertical space is short (#142).
|
||||||
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
internal fun AgendaDayHeader(
|
internal fun AgendaDayHeader(
|
||||||
date: LocalDate,
|
date: LocalDate,
|
||||||
today: LocalDate,
|
today: LocalDate,
|
||||||
onOpenDay: (LocalDate) -> Unit,
|
onOpenDay: (LocalDate) -> Unit,
|
||||||
|
compact: Boolean = false,
|
||||||
) {
|
) {
|
||||||
Surface(
|
Surface(
|
||||||
color = MaterialTheme.colorScheme.surface,
|
color = MaterialTheme.colorScheme.surface,
|
||||||
@@ -73,7 +84,12 @@ internal fun AgendaDayHeader(
|
|||||||
} else {
|
} else {
|
||||||
MaterialTheme.colorScheme.onSurfaceVariant
|
MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
},
|
},
|
||||||
modifier = Modifier.padding(start = 28.dp, end = 28.dp, top = 16.dp, bottom = 8.dp),
|
modifier = Modifier.padding(
|
||||||
|
start = 28.dp,
|
||||||
|
end = 28.dp,
|
||||||
|
top = if (compact) 8.dp else 16.dp,
|
||||||
|
bottom = if (compact) 4.dp else 8.dp,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -132,7 +148,7 @@ internal fun AgendaEventRow(
|
|||||||
val title = event.title.ifBlank { stringResource(R.string.event_untitled) }
|
val title = event.title.ifBlank { stringResource(R.string.event_untitled) }
|
||||||
GroupedRow(
|
GroupedRow(
|
||||||
modifier = if (dimmed) modifier.alpha(EventDimAlpha) else modifier,
|
modifier = if (dimmed) modifier.alpha(EventDimAlpha) else modifier,
|
||||||
title = declinedTitle(title, event.isDeclined),
|
title = declinedTitle(title, event.isCrossedOut),
|
||||||
summary = AnnotatedString(agendaTimeSummary(event, day, zone)),
|
summary = AnnotatedString(agendaTimeSummary(event, day, zone)),
|
||||||
position = position,
|
position = position,
|
||||||
minHeight = 64.dp,
|
minHeight = 64.dp,
|
||||||
@@ -177,34 +193,75 @@ internal fun agendaTimeSummary(event: EventInstance, day: LocalDate, zone: TimeZ
|
|||||||
AgendaTimeLabel.AllDay -> stringResource(R.string.event_detail_all_day)
|
AgendaTimeLabel.AllDay -> stringResource(R.string.event_detail_all_day)
|
||||||
is AgendaTimeLabel.Starts -> stringResource(
|
is AgendaTimeLabel.Starts -> stringResource(
|
||||||
R.string.agenda_span_starts,
|
R.string.agenda_span_starts,
|
||||||
formatTime(label.start, zone, is24Hour, locale),
|
formatTimeOfDay(label.start, zone, is24Hour, locale),
|
||||||
)
|
)
|
||||||
is AgendaTimeLabel.Ends -> stringResource(
|
is AgendaTimeLabel.Ends -> stringResource(
|
||||||
R.string.agenda_span_ends,
|
R.string.agenda_span_ends,
|
||||||
formatTime(label.end, zone, is24Hour, locale),
|
formatTimeOfDay(label.end, zone, is24Hour, locale),
|
||||||
)
|
)
|
||||||
is AgendaTimeLabel.Range -> "${formatTime(label.start, zone, is24Hour, locale)} – " +
|
is AgendaTimeLabel.Range -> "${formatTimeOfDay(label.start, zone, is24Hour, locale)} – " +
|
||||||
formatTime(label.end, zone, is24Hour, locale)
|
formatTimeOfDay(label.end, zone, is24Hour, locale)
|
||||||
}
|
}
|
||||||
|
|
||||||
val location = event.location?.takeIf { it.isNotBlank() }
|
val location = event.location?.takeIf { it.isNotBlank() }
|
||||||
return if (location != null) "$time · $location" else time
|
return if (location != null) "$time · $location" else time
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun formatTime(
|
|
||||||
instant: Instant,
|
|
||||||
zone: TimeZone,
|
|
||||||
is24Hour: Boolean,
|
|
||||||
locale: Locale,
|
|
||||||
): String {
|
|
||||||
val t = instant.toLocalDateTime(zone).time
|
|
||||||
return formatTimeOfDay(t.hour, t.minute, is24Hour, locale)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun formatAgendaDate(date: LocalDate): String {
|
private fun formatAgendaDate(date: LocalDate): String {
|
||||||
val locale = Locale.getDefault()
|
val locale = Locale.getDefault()
|
||||||
val java = java.time.LocalDate.of(date.year, date.month.ordinal + 1, date.day)
|
val java = date.toJavaLocalDate()
|
||||||
// Weekday + date in the locale's own field order (e.g. "Wed, Jun 17, 2026"
|
// Weekday + date in the locale's own field order (e.g. "Wed, Jun 17, 2026"
|
||||||
// vs "Mi., 17. Juni 2026") rather than a hardcoded day-month-year layout.
|
// vs "Mi., 17. Juni 2026") rather than a hardcoded day-month-year layout.
|
||||||
return localizedDateFormatter(locale, "EEEdMMMy").format(java)
|
return localizedDateFormatter(locale, "EEEdMMMy").format(java)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The agenda's day-by-day list body: a sticky header per day, its events or a
|
||||||
|
* placeholder row for an event-less day, then a gap. Shared by the Agenda screen
|
||||||
|
* and the month view's split pane so both lists read the same.
|
||||||
|
*/
|
||||||
|
@OptIn(ExperimentalFoundationApi::class)
|
||||||
|
internal fun LazyListScope.agendaDays(
|
||||||
|
days: List<AgendaDay>,
|
||||||
|
today: LocalDate,
|
||||||
|
zone: TimeZone,
|
||||||
|
@StringRes emptyText: Int,
|
||||||
|
onEmptyClick: (LocalDate) -> Unit,
|
||||||
|
dimmed: (EventInstance, LocalDate) -> Boolean,
|
||||||
|
onOpenDay: (LocalDate) -> Unit,
|
||||||
|
onEventClick: (EventInstance) -> Unit,
|
||||||
|
compact: Boolean = false,
|
||||||
|
) {
|
||||||
|
days.forEach { day ->
|
||||||
|
stickyHeader(key = "header-${day.date}") {
|
||||||
|
AgendaDayHeader(date = day.date, today = today, onOpenDay = onOpenDay, compact = compact)
|
||||||
|
}
|
||||||
|
if (day.events.isEmpty()) {
|
||||||
|
item(key = "placeholder-${day.date}") {
|
||||||
|
AgendaEmptyDayRow(
|
||||||
|
text = stringResource(emptyText),
|
||||||
|
onClick = { onEmptyClick(day.date) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
itemsIndexed(
|
||||||
|
items = day.events,
|
||||||
|
// Scope the key by day: a multi-day event appears under every
|
||||||
|
// day it spans, so its instanceId alone is not unique across
|
||||||
|
// the list (LazyColumn requires unique keys).
|
||||||
|
key = { _, event -> "${day.date}-${event.instanceId}" },
|
||||||
|
) { index, event ->
|
||||||
|
AgendaEventRow(
|
||||||
|
event = event,
|
||||||
|
day = day.date,
|
||||||
|
zone = zone,
|
||||||
|
position = positionOf(index, day.events.size),
|
||||||
|
dimmed = dimmed(event, day.date),
|
||||||
|
modifier = animateItemMotion().morphEvent(ViewMorphKey.event(event, day.date)),
|
||||||
|
onClick = { onEventClick(event) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
item(key = "gap-${day.date}") { Spacer(Modifier.height(if (compact) 4.dp else 8.dp)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package de.jeanlucmakiola.calendula.ui.agenda
|
package de.jeanlucmakiola.calendula.ui.agenda
|
||||||
|
|
||||||
|
import de.jeanlucmakiola.calendula.ui.common.FabClearance
|
||||||
import de.jeanlucmakiola.calendula.ui.common.PublishChrome
|
import de.jeanlucmakiola.calendula.ui.common.PublishChrome
|
||||||
import de.jeanlucmakiola.calendula.ui.common.ScreenActions
|
import de.jeanlucmakiola.calendula.ui.common.ScreenActions
|
||||||
import de.jeanlucmakiola.calendula.ui.common.ScreenBody
|
import de.jeanlucmakiola.calendula.ui.common.ScreenBody
|
||||||
@@ -10,9 +11,6 @@ import androidx.compose.runtime.getValue
|
|||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.runtime.snapshotFlow
|
import androidx.compose.runtime.snapshotFlow
|
||||||
import androidx.compose.runtime.rememberUpdatedState
|
import androidx.compose.runtime.rememberUpdatedState
|
||||||
import de.jeanlucmakiola.calendula.ui.common.ViewMorphKey
|
|
||||||
import de.jeanlucmakiola.calendula.ui.common.morphEvent
|
|
||||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.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
|
||||||
@@ -26,7 +24,6 @@ import androidx.compose.foundation.layout.padding
|
|||||||
import androidx.compose.foundation.layout.size
|
import androidx.compose.foundation.layout.size
|
||||||
import androidx.compose.foundation.lazy.LazyColumn
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
import androidx.compose.foundation.lazy.LazyListState
|
import androidx.compose.foundation.lazy.LazyListState
|
||||||
import androidx.compose.foundation.lazy.itemsIndexed
|
|
||||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.filled.Coffee
|
import androidx.compose.material.icons.filled.Coffee
|
||||||
@@ -66,11 +63,9 @@ 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
|
||||||
import de.jeanlucmakiola.calendula.ui.common.agendaRangeLabel
|
import de.jeanlucmakiola.calendula.ui.common.agendaRangeLabel
|
||||||
import de.jeanlucmakiola.floret.identity.animateItemMotion
|
|
||||||
import de.jeanlucmakiola.calendula.ui.common.CalendarFailure
|
import de.jeanlucmakiola.calendula.ui.common.CalendarFailure
|
||||||
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 de.jeanlucmakiola.floret.components.positionOf
|
|
||||||
import de.jeanlucmakiola.calendula.ui.common.rememberCurrentMinute
|
import de.jeanlucmakiola.calendula.ui.common.rememberCurrentMinute
|
||||||
import de.jeanlucmakiola.floret.locale.currentLocale
|
import de.jeanlucmakiola.floret.locale.currentLocale
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
@@ -379,7 +374,6 @@ internal fun AgendaContent(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@OptIn(ExperimentalFoundationApi::class)
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun AgendaList(
|
private fun AgendaList(
|
||||||
days: List<AgendaDay>,
|
days: List<AgendaDay>,
|
||||||
@@ -400,11 +394,8 @@ private fun AgendaList(
|
|||||||
val itemDates = agendaItemDates(days)
|
val itemDates = agendaItemDates(days)
|
||||||
val anchorRow = itemDates.indexOfFirst { it >= anchor }.coerceAtLeast(0)
|
val anchorRow = itemDates.indexOfFirst { it >= anchor }.coerceAtLeast(0)
|
||||||
SideEffect { anchorIndex.intValue = anchorRow }
|
SideEffect { anchorIndex.intValue = anchorRow }
|
||||||
// A new anchor opens the list on its row from the first frame, with past
|
// A new anchor opens on its row from the first frame; keyed on the anchor
|
||||||
// days above. Keyed on the anchor the days arrived with, not the one just
|
// the days arrived with, not the one requested. The first run may restore.
|
||||||
// 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) }
|
val pendingRestore = remember { arrayOf(initialTopDate) }
|
||||||
DisposableEffect(anchor) {
|
DisposableEffect(anchor) {
|
||||||
val target = pendingRestore[0]
|
val target = pendingRestore[0]
|
||||||
@@ -442,41 +433,19 @@ private fun AgendaList(
|
|||||||
modifier = modifier.nestedScroll(loadOnScrollUp),
|
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 = FabClearance),
|
||||||
) {
|
) {
|
||||||
days.forEach { day ->
|
agendaDays(
|
||||||
stickyHeader(key = "header-${day.date}") {
|
days = days,
|
||||||
AgendaDayHeader(date = day.date, today = today, onOpenDay = onOpenDay)
|
today = today,
|
||||||
}
|
zone = zone,
|
||||||
if (day.events.isEmpty()) {
|
// An anchored, event-less today (#35) — "nothing left today".
|
||||||
// An anchored, event-less today (#35) — "nothing left today".
|
emptyText = R.string.agenda_no_more_today,
|
||||||
item(key = "placeholder-${day.date}") {
|
onEmptyClick = onOpenDay,
|
||||||
AgendaEmptyDayRow(
|
dimmed = { event, day -> dimPast && event.isPastOn(day, now, zone) },
|
||||||
text = stringResource(R.string.agenda_no_more_today),
|
onOpenDay = onOpenDay,
|
||||||
onClick = { onOpenDay(day.date) },
|
onEventClick = onEventClick,
|
||||||
)
|
)
|
||||||
}
|
|
||||||
} else {
|
|
||||||
itemsIndexed(
|
|
||||||
items = day.events,
|
|
||||||
// Scope the key by day: a multi-day event appears under every
|
|
||||||
// day it spans, so its instanceId alone is not unique across
|
|
||||||
// the list (LazyColumn requires unique keys).
|
|
||||||
key = { _, event -> "${day.date}-${event.instanceId}" },
|
|
||||||
) { index, event ->
|
|
||||||
AgendaEventRow(
|
|
||||||
event = event,
|
|
||||||
day = day.date,
|
|
||||||
zone = zone,
|
|
||||||
position = positionOf(index, day.events.size),
|
|
||||||
dimmed = dimPast && event.isPastOn(day.date, now, zone),
|
|
||||||
modifier = animateItemMotion().morphEvent(ViewMorphKey.event(event, day.date)),
|
|
||||||
onClick = { onEventClick(event) },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
item(key = "gap-${day.date}") { Spacer(Modifier.height(8.dp)) }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
package de.jeanlucmakiola.calendula.ui.agenda
|
package de.jeanlucmakiola.calendula.ui.agenda
|
||||||
|
|
||||||
import de.jeanlucmakiola.calendula.domain.EventInstance
|
import de.jeanlucmakiola.calendula.domain.EventInstance
|
||||||
import de.jeanlucmakiola.calendula.domain.eventDisplayComparator
|
import de.jeanlucmakiola.calendula.domain.coversWholeDays
|
||||||
|
import de.jeanlucmakiola.calendula.domain.sortedForDisplay
|
||||||
import de.jeanlucmakiola.calendula.domain.FailureReason
|
import de.jeanlucmakiola.calendula.domain.FailureReason
|
||||||
import de.jeanlucmakiola.calendula.domain.spanFirstDay
|
import de.jeanlucmakiola.calendula.domain.spanFirstDay
|
||||||
import de.jeanlucmakiola.calendula.domain.spanLastDay
|
import de.jeanlucmakiola.calendula.domain.spanLastDay
|
||||||
@@ -18,7 +19,7 @@ import kotlin.time.Instant
|
|||||||
* surface only formats the instants into its own locale/24h string.
|
* surface only formats the instants into its own locale/24h string.
|
||||||
*/
|
*/
|
||||||
sealed interface AgendaTimeLabel {
|
sealed interface AgendaTimeLabel {
|
||||||
/** An all-day event, or a whole in-between day of a multi-day span. */
|
/** An event filling whole days (#296), or a whole in-between day of a multi-day span. */
|
||||||
data object AllDay : AgendaTimeLabel
|
data object AllDay : AgendaTimeLabel
|
||||||
/** The first day of a multi-day timed event: when it begins. */
|
/** The first day of a multi-day timed event: when it begins. */
|
||||||
data class Starts(val start: Instant) : AgendaTimeLabel
|
data class Starts(val start: Instant) : AgendaTimeLabel
|
||||||
@@ -30,7 +31,7 @@ sealed interface AgendaTimeLabel {
|
|||||||
|
|
||||||
/** The [AgendaTimeLabel] for [event] as it appears on [day], resolved in [zone]. */
|
/** The [AgendaTimeLabel] for [event] as it appears on [day], resolved in [zone]. */
|
||||||
fun agendaTimeLabel(event: EventInstance, day: LocalDate, zone: TimeZone): AgendaTimeLabel {
|
fun agendaTimeLabel(event: EventInstance, day: LocalDate, zone: TimeZone): AgendaTimeLabel {
|
||||||
if (event.isAllDay) return AgendaTimeLabel.AllDay
|
if (event.coversWholeDays(zone)) return AgendaTimeLabel.AllDay
|
||||||
val firstDay = event.spanFirstDay(zone)
|
val firstDay = event.spanFirstDay(zone)
|
||||||
val lastDay = event.spanLastDay(zone)
|
val lastDay = event.spanLastDay(zone)
|
||||||
return when {
|
return when {
|
||||||
@@ -87,7 +88,7 @@ fun groupAgendaDays(
|
|||||||
return byDay.map { (date, dayEvents) ->
|
return byDay.map { (date, dayEvents) ->
|
||||||
AgendaDay(
|
AgendaDay(
|
||||||
date = date,
|
date = date,
|
||||||
events = dayEvents.sortedWith(eventDisplayComparator(zone)),
|
events = dayEvents.sortedForDisplay(zone),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,19 +1,22 @@
|
|||||||
package de.jeanlucmakiola.calendula.ui.agenda
|
package de.jeanlucmakiola.calendula.ui.agenda
|
||||||
|
|
||||||
|
import de.jeanlucmakiola.calendula.ui.common.dayRange
|
||||||
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.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.TodaySource
|
||||||
import de.jeanlucmakiola.calendula.data.time.currentDate
|
import de.jeanlucmakiola.calendula.data.time.currentDate
|
||||||
|
import de.jeanlucmakiola.calendula.data.time.stateFollowingDays
|
||||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
import de.jeanlucmakiola.calendula.domain.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
|
||||||
@@ -24,17 +27,13 @@ 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.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
|
||||||
import kotlinx.datetime.LocalDate
|
import kotlinx.datetime.LocalDate
|
||||||
import kotlinx.datetime.TimeZone
|
import kotlinx.datetime.TimeZone
|
||||||
import kotlinx.datetime.atStartOfDayIn
|
|
||||||
import kotlinx.datetime.atTime
|
|
||||||
import kotlinx.datetime.minus
|
import kotlinx.datetime.minus
|
||||||
import kotlinx.datetime.plus
|
import kotlinx.datetime.plus
|
||||||
import kotlinx.datetime.toInstant
|
|
||||||
import kotlin.time.Instant
|
import kotlin.time.Instant
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
@@ -66,9 +65,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,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -79,9 +77,8 @@ 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,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -101,21 +98,14 @@ class AgendaViewModel @Inject constructor(
|
|||||||
var lastTopDate: LocalDate? = null
|
var lastTopDate: LocalDate? = null
|
||||||
private set
|
private set
|
||||||
|
|
||||||
private var lastToday = todayDate
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Today, kept current across midnight (#373). An agenda still starting on
|
* Today, kept current across midnight (#373). An agenda still starting on
|
||||||
* yesterday moves on to the new day; one jumped elsewhere stays put.
|
* yesterday moves on to the new day; one jumped elsewhere stays put.
|
||||||
*/
|
*/
|
||||||
private val today: StateFlow<LocalDate> = todaySource.today
|
private val today: StateFlow<LocalDate> =
|
||||||
.onEach { date ->
|
todaySource.today.stateFollowingDays(viewModelScope, todayDate) { old, date ->
|
||||||
val old = lastToday
|
if (_window.value.anchor == old) _window.value = _window.value.copy(anchor = date)
|
||||||
lastToday = date
|
|
||||||
if (old != date && _window.value.anchor == old) {
|
|
||||||
_window.value = _window.value.copy(anchor = date)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000L), 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
|
||||||
@@ -156,9 +146,8 @@ class AgendaViewModel @Inject constructor(
|
|||||||
}
|
}
|
||||||
.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,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -174,15 +163,17 @@ class AgendaViewModel @Inject constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Extend the window [PAST_CHUNK_DAYS] further back (#367). Ignored while the
|
* Extend the window further back (#367), doubling what's loaded (at least
|
||||||
* previous extension is still loading, so a scroll that keeps asking only
|
* [PAST_CHUNK_DAYS], at most [MAX_PAST_STEP_DAYS]) so a long scroll back
|
||||||
* moves one chunk at a time.
|
* re-queries only a few times. Ignored while the previous extension is
|
||||||
|
* still loading.
|
||||||
*/
|
*/
|
||||||
fun loadEarlier() {
|
fun loadEarlier() {
|
||||||
val loaded = (state.value as? AgendaUiState.Success)?.windowStart ?: return
|
val loaded = (state.value as? AgendaUiState.Success)?.windowStart ?: return
|
||||||
val window = _window.value
|
val window = _window.value
|
||||||
if (loaded != window.start) return
|
if (loaded != window.start) return
|
||||||
_window.value = window.copy(pastDays = window.pastDays + PAST_CHUNK_DAYS)
|
val step = window.pastDays.coerceIn(PAST_CHUNK_DAYS, MAX_PAST_STEP_DAYS)
|
||||||
|
_window.value = window.copy(pastDays = window.pastDays + step)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun rememberTopDay(date: LocalDate) {
|
fun rememberTopDay(date: LocalDate) {
|
||||||
@@ -244,9 +235,9 @@ class AgendaViewModel @Inject constructor(
|
|||||||
/** How many days each scroll back into the past loads (#367). */
|
/** How many days each scroll back into the past loads (#367). */
|
||||||
internal const val PAST_CHUNK_DAYS = 30
|
internal const val PAST_CHUNK_DAYS = 30
|
||||||
|
|
||||||
|
/** The most one scroll back adds, so an empty past grows the window by years, not exponentially. */
|
||||||
|
internal const val MAX_PAST_STEP_DAYS = 365
|
||||||
|
|
||||||
/** Inclusive instant range from the start of [anchor] through [days] days ahead. */
|
/** 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)
|
dayRange(anchor, anchor.plus(days, DateTimeUnit.DAY), zone)
|
||||||
val to = anchor.plus(days, DateTimeUnit.DAY).atTime(23, 59, 59).toInstant(zone)
|
|
||||||
return from..to
|
|
||||||
}
|
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -54,13 +53,17 @@ import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip
|
|||||||
import de.jeanlucmakiola.calendula.ui.common.CalendarFailure
|
import de.jeanlucmakiola.calendula.ui.common.CalendarFailure
|
||||||
import de.jeanlucmakiola.calendula.ui.common.LeadingAvatar
|
import de.jeanlucmakiola.calendula.ui.common.LeadingAvatar
|
||||||
import de.jeanlucmakiola.calendula.ui.common.LocalManageCalendars
|
import de.jeanlucmakiola.calendula.ui.common.LocalManageCalendars
|
||||||
|
import de.jeanlucmakiola.calendula.ui.common.orUnnamed
|
||||||
import de.jeanlucmakiola.floret.components.CollapsingScaffold
|
import de.jeanlucmakiola.floret.components.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 +225,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 +236,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 +275,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,12 +312,13 @@ 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(
|
||||||
title = calendar.displayName.ifBlank { stringResource(R.string.calendar_unnamed) },
|
title = calendar.displayName.orUnnamed(),
|
||||||
summary = calendar.description,
|
summary = calendar.description,
|
||||||
position = positionOf(index, calendars.size),
|
position = positionOf(index, calendars.size),
|
||||||
leading = { CalendarColorChip(calendar.color) },
|
leading = { CalendarColorChip(calendar.color) },
|
||||||
@@ -376,9 +380,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 {
|
||||||
|
|||||||
@@ -12,27 +12,21 @@ 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
|
||||||
@@ -40,20 +34,14 @@ 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.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
|
||||||
@@ -84,6 +72,7 @@ import de.jeanlucmakiola.calendula.domain.stateLabels
|
|||||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarColorPalette
|
import de.jeanlucmakiola.calendula.data.calendar.CalendarColorPalette
|
||||||
import de.jeanlucmakiola.calendula.ui.common.AccountKey
|
import de.jeanlucmakiola.calendula.ui.common.AccountKey
|
||||||
import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip
|
import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip
|
||||||
|
import de.jeanlucmakiola.calendula.ui.common.CalendarVisibilitySwitch
|
||||||
import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle
|
import de.jeanlucmakiola.calendula.ui.common.accountGroupTitle
|
||||||
import de.jeanlucmakiola.calendula.ui.common.groupByAccount
|
import de.jeanlucmakiola.calendula.ui.common.groupByAccount
|
||||||
import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors
|
import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors
|
||||||
@@ -93,12 +82,14 @@ import de.jeanlucmakiola.calendula.ui.common.eventInk
|
|||||||
import de.jeanlucmakiola.calendula.ui.common.LeadingAvatar
|
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.calendula.ui.common.orUnnamed
|
||||||
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.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 +215,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,24 +236,13 @@ 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
|
CalendarManagerRow(
|
||||||
GroupedRow(
|
calendar = calendar,
|
||||||
title = calendar.displayName.ifBlank { stringResource(R.string.calendar_unnamed) },
|
last = index == local.lastIndex,
|
||||||
summary = calendarRowSummary(calendar),
|
onSetVisible = onSetVisible,
|
||||||
position = if (index == local.lastIndex) Position.Bottom else Position.Middle,
|
|
||||||
container = MaterialTheme.colorScheme.surfaceContainerHighest,
|
|
||||||
dimmed = disabled,
|
|
||||||
leading = { CalendarColorChip(calendar.color, dimIf(disabled)) },
|
|
||||||
trailing = {
|
|
||||||
EnableSwitch(
|
|
||||||
calendarName = calendar.displayName.ifBlank { stringResource(R.string.calendar_unnamed) },
|
|
||||||
enabled = !disabled,
|
|
||||||
onToggle = { enabled -> onSetVisible(calendar.id, enabled) },
|
|
||||||
)
|
|
||||||
},
|
|
||||||
onClick = { onEdit(calendar) },
|
onClick = { onEdit(calendar) },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -291,8 +271,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 ->
|
||||||
@@ -333,27 +313,10 @@ private fun CalendarsList(
|
|||||||
// bottom, dimmed and switchless.
|
// bottom, dimmed and switchless.
|
||||||
val ordered = cals.orderedForManager()
|
val ordered = cals.orderedForManager()
|
||||||
ordered.forEachIndexed { index, calendar ->
|
ordered.forEachIndexed { index, calendar ->
|
||||||
val disabled = !calendar.isVisibleInSystem || calendar.isNotSynced
|
CalendarManagerRow(
|
||||||
GroupedRow(
|
calendar = calendar,
|
||||||
title = calendar.displayName.ifBlank { stringResource(R.string.calendar_unnamed) },
|
last = index == ordered.lastIndex,
|
||||||
summary = calendarRowSummary(calendar),
|
onSetVisible = onSetVisible,
|
||||||
position = if (index == ordered.lastIndex) Position.Bottom else Position.Middle,
|
|
||||||
container = MaterialTheme.colorScheme.surfaceContainerHighest,
|
|
||||||
dimmed = disabled,
|
|
||||||
leading = { CalendarColorChip(calendar.color, dimIf(disabled)) },
|
|
||||||
trailing = if (calendar.hasVisibilitySwitch) {
|
|
||||||
{
|
|
||||||
EnableSwitch(
|
|
||||||
calendarName = calendar.displayName.ifBlank { stringResource(R.string.calendar_unnamed) },
|
|
||||||
enabled = calendar.isVisibleInSystem,
|
|
||||||
onToggle = { enabled ->
|
|
||||||
onSetVisible(calendar.id, enabled)
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
null
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -692,17 +655,37 @@ private fun calendarRowSummary(calendar: CalendarSource): String? {
|
|||||||
* `Calendars.VISIBLE`. Unchecked drops the calendar out of every surface and
|
* `Calendars.VISIBLE`. Unchecked drops the calendar out of every surface and
|
||||||
* stops its reminders. Carries its own content description.
|
* stops its reminders. Carries its own content description.
|
||||||
*/
|
*/
|
||||||
|
/**
|
||||||
|
* One calendar in a group: dimmed while switched off or not syncing, with the
|
||||||
|
* visibility switch only where it can change anything.
|
||||||
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
private fun EnableSwitch(
|
private fun CalendarManagerRow(
|
||||||
calendarName: String,
|
calendar: CalendarSource,
|
||||||
enabled: Boolean,
|
last: Boolean,
|
||||||
onToggle: (Boolean) -> Unit,
|
onSetVisible: (Long, Boolean) -> Unit,
|
||||||
|
onClick: (() -> Unit)? = null,
|
||||||
) {
|
) {
|
||||||
val label = stringResource(R.string.calendars_visibility_a11y, calendarName)
|
val disabled = !calendar.isVisibleInSystem || calendar.isNotSynced
|
||||||
Switch(
|
GroupedRow(
|
||||||
checked = enabled,
|
title = calendar.displayName.orUnnamed(),
|
||||||
onCheckedChange = onToggle,
|
summary = calendarRowSummary(calendar),
|
||||||
modifier = Modifier.semantics { contentDescription = label },
|
position = if (last) Position.Bottom else Position.Middle,
|
||||||
|
container = MaterialTheme.colorScheme.surfaceContainerHighest,
|
||||||
|
dimmed = disabled,
|
||||||
|
leading = { CalendarColorChip(calendar.color, dimIf(disabled)) },
|
||||||
|
trailing = if (calendar.hasVisibilitySwitch) {
|
||||||
|
{
|
||||||
|
CalendarVisibilitySwitch(
|
||||||
|
calendarName = calendar.displayName.orUnnamed(),
|
||||||
|
enabled = calendar.isVisibleInSystem,
|
||||||
|
onToggle = { enabled -> onSetVisible(calendar.id, enabled) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
},
|
||||||
|
onClick = onClick,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -841,33 +824,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(),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ fun List<CalendarSource>.groupByAccount(): List<CalendarAccountGroup> {
|
|||||||
*/
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
fun accountGroupTitle(group: CalendarAccountGroup): String {
|
fun accountGroupTitle(group: CalendarAccountGroup): String {
|
||||||
val label = group.label.ifBlank { stringResource(R.string.calendar_unnamed) }
|
val label = group.label.orUnnamed()
|
||||||
return if (!group.ambiguous) {
|
return if (!group.ambiguous) {
|
||||||
label
|
label
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -77,6 +77,8 @@ class EventSelection(
|
|||||||
val event: EventInstance,
|
val event: EventInstance,
|
||||||
val dismiss: () -> Unit,
|
val dismiss: () -> Unit,
|
||||||
val create: (() -> Unit)? = null,
|
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. */
|
||||||
@@ -126,10 +128,12 @@ fun PublishSelection(
|
|||||||
compact: Boolean,
|
compact: Boolean,
|
||||||
onDismiss: () -> Unit,
|
onDismiss: () -> Unit,
|
||||||
onCreate: (() -> Unit)? = null,
|
onCreate: (() -> Unit)? = null,
|
||||||
|
preview: () -> EventInstance? = { null },
|
||||||
) {
|
) {
|
||||||
val slot = LocalChromeSlot.current ?: return
|
val slot = LocalChromeSlot.current ?: return
|
||||||
val currentDismiss by rememberUpdatedState(onDismiss)
|
val currentDismiss by rememberUpdatedState(onDismiss)
|
||||||
val currentCreate by rememberUpdatedState(onCreate)
|
val currentCreate by rememberUpdatedState(onCreate)
|
||||||
|
val currentPreview by rememberUpdatedState(preview)
|
||||||
val drafted = onCreate != null
|
val drafted = onCreate != null
|
||||||
val selection = remember(event, drafted) {
|
val selection = remember(event, drafted) {
|
||||||
event?.let {
|
event?.let {
|
||||||
@@ -137,6 +141,7 @@ fun PublishSelection(
|
|||||||
event = it,
|
event = it,
|
||||||
dismiss = { currentDismiss() },
|
dismiss = { currentDismiss() },
|
||||||
create = if (drafted) ({ currentCreate?.invoke() }) else null,
|
create = if (drafted) ({ currentCreate?.invoke() }) else null,
|
||||||
|
preview = { currentPreview() },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,7 +30,9 @@ fun CalendarDatePickerDialog(
|
|||||||
onDismiss: () -> Unit,
|
onDismiss: () -> Unit,
|
||||||
) {
|
) {
|
||||||
val state = rememberDatePickerState(
|
val state = rememberDatePickerState(
|
||||||
initialSelectedDateMillis = initial.toEpochDays() * MILLIS_PER_DAY,
|
initialSelectedDateMillis = initial.coerceIn(CalendarSpan.FIRST_DAY, CalendarSpan.LAST_DAY)
|
||||||
|
.toEpochDays() * MILLIS_PER_DAY,
|
||||||
|
yearRange = CalendarSpan.years,
|
||||||
)
|
)
|
||||||
DatePickerDialog(
|
DatePickerDialog(
|
||||||
onDismissRequest = onDismiss,
|
onDismissRequest = onDismiss,
|
||||||
|
|||||||
@@ -26,8 +26,6 @@ import androidx.compose.material3.Text
|
|||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.Stable
|
import androidx.compose.runtime.Stable
|
||||||
import androidx.compose.runtime.getValue
|
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.Modifier
|
||||||
import androidx.compose.ui.graphics.graphicsLayer
|
import androidx.compose.ui.graphics.graphicsLayer
|
||||||
@@ -40,6 +38,9 @@ import de.jeanlucmakiola.calendula.R
|
|||||||
/** The standard FAB's size, shared by the selection bar that unrolls from it (#141). */
|
/** The standard FAB's size, shared by the selection bar that unrolls from it (#141). */
|
||||||
val FabSize = 56.dp
|
val FabSize = 56.dp
|
||||||
|
|
||||||
|
/** Bottom inset that lets a scrolling view's last row or hour scroll clear of the FAB. */
|
||||||
|
val FabClearance = 96.dp
|
||||||
|
|
||||||
/** What the FAB is while an event is selected (#141): the toggle for its action bar. */
|
/** What the FAB is while an event is selected (#141): the toggle for its action bar. */
|
||||||
@Stable
|
@Stable
|
||||||
class FabSelection(
|
class FabSelection(
|
||||||
@@ -82,8 +83,7 @@ fun CalendarFabColumn(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
// Held past the selection clearing, so the bar has something to fold away.
|
// Held past the selection clearing, so the bar has something to fold away.
|
||||||
val heldBar = remember { mutableStateOf<(@Composable () -> Unit)?>(null) }
|
val heldBar = rememberHeld(selection?.bar)
|
||||||
if (selection != null && heldBar.value !== selection.bar) heldBar.value = selection.bar
|
|
||||||
// Held at the FAB's height so the taller bar can't shift the FAB.
|
// Held at the FAB's height so the taller bar can't shift the FAB.
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.height(FabSize),
|
modifier = Modifier.height(FabSize),
|
||||||
@@ -101,7 +101,7 @@ fun CalendarFabColumn(
|
|||||||
shrinkTowards = Alignment.End,
|
shrinkTowards = Alignment.End,
|
||||||
) + fadeOut(),
|
) + fadeOut(),
|
||||||
) {
|
) {
|
||||||
heldBar.value?.invoke()
|
heldBar?.invoke()
|
||||||
}
|
}
|
||||||
val label = stringResource(
|
val label = stringResource(
|
||||||
when {
|
when {
|
||||||
|
|||||||
@@ -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.orUnnamed(),
|
||||||
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) },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.ui.common
|
||||||
|
|
||||||
|
import kotlinx.datetime.LocalDate
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The dates every view can show and every date picker offers. One span for all
|
||||||
|
* of them, so no view can hand another a date it has no page for (#457).
|
||||||
|
*/
|
||||||
|
object CalendarSpan {
|
||||||
|
val FIRST_DAY: LocalDate = LocalDate(1600, 1, 1)
|
||||||
|
val LAST_DAY: LocalDate = LocalDate(2399, 12, 31)
|
||||||
|
|
||||||
|
val years: IntRange get() = FIRST_DAY.year..LAST_DAY.year
|
||||||
|
}
|
||||||
@@ -3,10 +3,12 @@ package de.jeanlucmakiola.calendula.ui.common
|
|||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.ui.platform.LocalDensity
|
import androidx.compose.ui.platform.LocalDensity
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.text.TextStyle
|
import androidx.compose.ui.text.TextStyle
|
||||||
import androidx.compose.ui.text.rememberTextMeasurer
|
import androidx.compose.ui.text.rememberTextMeasurer
|
||||||
import androidx.compose.ui.text.style.LineHeightStyle
|
import androidx.compose.ui.text.style.LineHeightStyle
|
||||||
import androidx.compose.ui.unit.Dp
|
import androidx.compose.ui.unit.Dp
|
||||||
|
import de.jeanlucmakiola.calendula.R
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The calendar surfaces' line-height treatment. Material wraps an 11sp glyph in
|
* The calendar surfaces' line-height treatment. Material wraps an 11sp glyph in
|
||||||
@@ -55,3 +57,7 @@ fun rememberTrimmedLineHeight(style: TextStyle): Dp {
|
|||||||
with(density) { measurer.measure(LINE_SAMPLE, style.trimmedLines()).size.height.toDp() }
|
with(density) { measurer.measure(LINE_SAMPLE, style.trimmedLines()).size.height.toDp() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A calendar or account name, or the "unnamed" label when it is blank. */
|
||||||
|
@Composable
|
||||||
|
fun String.orUnnamed(): String = ifBlank { stringResource(R.string.calendar_unnamed) }
|
||||||
@@ -8,9 +8,9 @@ import java.util.Locale
|
|||||||
* out in [locale]'s own order, with the year shown only when [date] falls outside
|
* out in [locale]'s own order, with the year shown only when [date] falls outside
|
||||||
* [currentYear].
|
* [currentYear].
|
||||||
*
|
*
|
||||||
* Pass [skeleton] *without* a year field — "LLLL" for a month, "EEEdMMM" for a
|
* Pass [skeleton] *without* a year field, e.g. "LLLL" for a month. A skeleton
|
||||||
* day. A skeleton is a field list, so wanting the year is just asking for one
|
* is a field list, so wanting the year is just asking for one more field; the
|
||||||
* more field; the locale still decides where it lands ("July 2026" vs "2026年7月").
|
* locale still decides where it lands ("July 2026" vs "2026年7月").
|
||||||
*
|
*
|
||||||
* Dropping the year in the current year is the one bit of policy here: the title
|
* Dropping the year in the current year is the one bit of policy here: the title
|
||||||
* sits directly above a grid that already says which year it is, and the year's
|
* sits directly above a grid that already says which year it is, and the year's
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.ui.common
|
||||||
|
|
||||||
|
import androidx.compose.material3.Switch
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.semantics.contentDescription
|
||||||
|
import androidx.compose.ui.semantics.semantics
|
||||||
|
import de.jeanlucmakiola.calendula.R
|
||||||
|
|
||||||
|
/** The per-row switch writing the device's own `Calendars.VISIBLE`, as Settings does (#75). */
|
||||||
|
@Composable
|
||||||
|
fun CalendarVisibilitySwitch(
|
||||||
|
calendarName: String,
|
||||||
|
enabled: Boolean,
|
||||||
|
onToggle: (Boolean) -> Unit,
|
||||||
|
) {
|
||||||
|
val label = stringResource(R.string.calendars_visibility_a11y, calendarName)
|
||||||
|
Switch(
|
||||||
|
checked = enabled,
|
||||||
|
onCheckedChange = onToggle,
|
||||||
|
modifier = Modifier.semantics { contentDescription = label },
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.ui.common
|
||||||
|
|
||||||
|
import kotlinx.datetime.DateTimeUnit
|
||||||
|
import kotlinx.datetime.DayOfWeek
|
||||||
|
import kotlinx.datetime.LocalDate
|
||||||
|
import kotlinx.datetime.TimeZone
|
||||||
|
import kotlinx.datetime.atStartOfDayIn
|
||||||
|
import kotlinx.datetime.atTime
|
||||||
|
import kotlinx.datetime.minus
|
||||||
|
import kotlinx.datetime.toInstant
|
||||||
|
import kotlin.time.Instant
|
||||||
|
|
||||||
|
/** Instant range from the start of [first] through the last second of [last] in [zone]. */
|
||||||
|
internal fun dayRange(first: LocalDate, last: LocalDate, zone: TimeZone): ClosedRange<Instant> =
|
||||||
|
first.atStartOfDayIn(zone)..last.atTime(23, 59, 59).toInstant(zone)
|
||||||
|
|
||||||
|
/** Beginning of the week (at [weekStart]) that contains this date. */
|
||||||
|
internal fun LocalDate.startOfWeek(weekStart: DayOfWeek): LocalDate {
|
||||||
|
// DayOfWeek.ordinal: MONDAY=0..SUNDAY=6 → identical to ISO ordering.
|
||||||
|
val offset = ((dayOfWeek.ordinal - weekStart.ordinal) + 7) % 7
|
||||||
|
return minus(offset, DateTimeUnit.DAY)
|
||||||
|
}
|
||||||
@@ -3,7 +3,6 @@ package de.jeanlucmakiola.calendula.ui.common
|
|||||||
import android.Manifest
|
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.util.Log
|
import android.util.Log
|
||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
@@ -18,12 +17,12 @@ import androidx.compose.runtime.Composable
|
|||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberUpdatedState
|
||||||
import androidx.compose.runtime.saveable.rememberSaveable
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
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.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.core.content.ContextCompat
|
|
||||||
import de.jeanlucmakiola.calendula.R
|
import de.jeanlucmakiola.calendula.R
|
||||||
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
|
||||||
@@ -32,6 +31,7 @@ import de.jeanlucmakiola.calendula.domain.EventDetail
|
|||||||
import de.jeanlucmakiola.calendula.domain.RecurringWriteScope
|
import de.jeanlucmakiola.calendula.domain.RecurringWriteScope
|
||||||
import de.jeanlucmakiola.calendula.domain.ics.IcsWriter
|
import de.jeanlucmakiola.calendula.domain.ics.IcsWriter
|
||||||
import de.jeanlucmakiola.calendula.domain.ics.toShareIcsEvent
|
import de.jeanlucmakiola.calendula.domain.ics.toShareIcsEvent
|
||||||
|
import de.jeanlucmakiola.floret.android.hasPermission
|
||||||
import de.jeanlucmakiola.floret.components.OptionCard
|
import de.jeanlucmakiola.floret.components.OptionCard
|
||||||
import kotlin.coroutines.cancellation.CancellationException
|
import kotlin.coroutines.cancellation.CancellationException
|
||||||
import kotlin.time.Clock
|
import kotlin.time.Clock
|
||||||
@@ -73,10 +73,13 @@ suspend fun CalendarRepository.deleteEvent(
|
|||||||
/** How a [tryDeleteEvent] ended. */
|
/** How a [tryDeleteEvent] ended. */
|
||||||
enum class DeleteOutcome { Deleted, Gone, NeedsPermission, Failed }
|
enum class DeleteOutcome { Deleted, Gone, NeedsPermission, Failed }
|
||||||
|
|
||||||
|
/** Whether this install may read the calendar at all. */
|
||||||
|
fun Context.canReadCalendar(): Boolean =
|
||||||
|
hasPermission(Manifest.permission.READ_CALENDAR)
|
||||||
|
|
||||||
/** Whether this install may write to the calendar; v1.0 installs only hold read access. */
|
/** Whether this install may write to the calendar; v1.0 installs only hold read access. */
|
||||||
fun Context.canWriteCalendar(): Boolean =
|
fun Context.canWriteCalendar(): Boolean =
|
||||||
ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) ==
|
hasPermission(Manifest.permission.WRITE_CALENDAR)
|
||||||
PackageManager.PERMISSION_GRANTED
|
|
||||||
|
|
||||||
/** [deleteEvent], with the provider's failures mapped to a [DeleteOutcome]. */
|
/** [deleteEvent], with the provider's failures mapped to a [DeleteOutcome]. */
|
||||||
suspend fun CalendarRepository.tryDeleteEvent(
|
suspend fun CalendarRepository.tryDeleteEvent(
|
||||||
@@ -98,33 +101,28 @@ suspend fun CalendarRepository.tryDeleteEvent(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Runs an action that writes to the calendar, asking for `WRITE_CALENDAR` first
|
* [action], which writes to the calendar, as a handler that asks for
|
||||||
* where the install only holds read access (v1.0 installs). A grant continues
|
* `WRITE_CALENDAR` first where the install only holds read access (v1.0
|
||||||
* straight into the action that asked for it.
|
* installs). A grant continues into [action], also when it returns after a
|
||||||
|
* rotation; a refusal runs [onDenied].
|
||||||
*/
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
fun rememberWriteGate(): (() -> Unit) -> Unit {
|
fun rememberWriteAction(onDenied: () -> Unit = {}, action: () -> 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
|
val context = LocalContext.current
|
||||||
var pending by remember { mutableStateOf<Pair<() -> Unit, () -> Unit>?>(null) }
|
val currentAction by rememberUpdatedState(action)
|
||||||
|
val currentDenied by rememberUpdatedState(onDenied)
|
||||||
val launcher = rememberLauncherForActivityResult(
|
val launcher = rememberLauncherForActivityResult(
|
||||||
contract = ActivityResultContracts.RequestPermission(),
|
contract = ActivityResultContracts.RequestPermission(),
|
||||||
) { granted ->
|
) { granted ->
|
||||||
pending?.let { (action, fallback) -> if (granted) action() else fallback() }
|
if (granted) currentAction() else currentDenied()
|
||||||
pending = null
|
|
||||||
}
|
}
|
||||||
return { action, fallback ->
|
return remember(context, launcher) {
|
||||||
if (context.canWriteCalendar()) {
|
{
|
||||||
action()
|
if (context.canWriteCalendar()) {
|
||||||
} else {
|
currentAction()
|
||||||
pending = action to fallback
|
} else {
|
||||||
launcher.launch(Manifest.permission.WRITE_CALENDAR)
|
launcher.launch(Manifest.permission.WRITE_CALENDAR)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ 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.data.time.ZoneSource
|
||||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||||
import de.jeanlucmakiola.calendula.domain.EventDetail
|
import de.jeanlucmakiola.calendula.domain.EventDetail
|
||||||
import de.jeanlucmakiola.calendula.domain.EventForm
|
import de.jeanlucmakiola.calendula.domain.EventForm
|
||||||
@@ -15,19 +15,18 @@ import de.jeanlucmakiola.calendula.domain.EventInstance
|
|||||||
import de.jeanlucmakiola.calendula.domain.RecurringWriteScope
|
import de.jeanlucmakiola.calendula.domain.RecurringWriteScope
|
||||||
import de.jeanlucmakiola.calendula.domain.atOccurrence
|
import de.jeanlucmakiola.calendula.domain.atOccurrence
|
||||||
import de.jeanlucmakiola.calendula.domain.toDuplicateForm
|
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.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.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 kotlinx.datetime.TimeZone
|
|
||||||
import kotlin.coroutines.cancellation.CancellationException
|
import kotlin.coroutines.cancellation.CancellationException
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
@@ -43,6 +42,7 @@ class EventActionsViewModel @Inject constructor(
|
|||||||
private val repository: CalendarRepository,
|
private val repository: CalendarRepository,
|
||||||
private val icsExporter: IcsExporter,
|
private val icsExporter: IcsExporter,
|
||||||
@IoDispatcher private val io: CoroutineDispatcher,
|
@IoDispatcher private val io: CoroutineDispatcher,
|
||||||
|
private val zoneSource: ZoneSource,
|
||||||
) : ViewModel() {
|
) : ViewModel() {
|
||||||
|
|
||||||
/** Every calendar by id, for what a selected event's bar may offer. */
|
/** Every calendar by id, for what a selected event's bar may offer. */
|
||||||
@@ -50,9 +50,8 @@ class EventActionsViewModel @Inject constructor(
|
|||||||
.map { list -> list.associateBy { it.id } }
|
.map { list -> list.associateBy { it.id } }
|
||||||
.catch { emit(emptyMap()) }
|
.catch { emit(emptyMap()) }
|
||||||
.flowOn(io)
|
.flowOn(io)
|
||||||
.stateIn(
|
.stateWhileSubscribed(
|
||||||
scope = viewModelScope,
|
scope = viewModelScope,
|
||||||
started = SharingStarted.WhileSubscribed(5_000L),
|
|
||||||
initialValue = emptyMap(),
|
initialValue = emptyMap(),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -66,7 +65,7 @@ class EventActionsViewModel @Inject constructor(
|
|||||||
suspend fun duplicateForm(event: EventInstance): EventForm? {
|
suspend fun duplicateForm(event: EventInstance): EventForm? {
|
||||||
val detail = load(event) ?: return null
|
val detail = load(event) ?: return null
|
||||||
val canModify = calendars.value[event.calendarId]?.canModifyContents == true
|
val canModify = calendars.value[event.calendarId]?.canModifyContents == true
|
||||||
return detail.toDuplicateForm(canModify, TimeZone.currentSystemDefault())
|
return detail.toDuplicateForm(canModify, zoneSource.current())
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A staged `.ics` for [event], or null — reported — when it can't be built. */
|
/** A staged `.ics` for [event], or null — reported — when it can't be built. */
|
||||||
|
|||||||
@@ -212,11 +212,21 @@ private fun rememberPickUpSurface(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 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
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import androidx.compose.material.icons.filled.People
|
|||||||
import androidx.compose.material.icons.filled.Place
|
import androidx.compose.material.icons.filled.Place
|
||||||
import androidx.compose.material.icons.filled.Public
|
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.TaskAlt
|
||||||
import androidx.compose.ui.graphics.vector.ImageVector
|
import androidx.compose.ui.graphics.vector.ImageVector
|
||||||
import de.jeanlucmakiola.calendula.R
|
import de.jeanlucmakiola.calendula.R
|
||||||
import de.jeanlucmakiola.calendula.domain.EventFormField
|
import de.jeanlucmakiola.calendula.domain.EventFormField
|
||||||
@@ -29,6 +30,7 @@ fun eventFormFieldLabel(field: EventFormField): Int = when (field) {
|
|||||||
EventFormField.Reminders -> R.string.event_detail_reminders
|
EventFormField.Reminders -> R.string.event_detail_reminders
|
||||||
EventFormField.Recurrence -> R.string.event_detail_recurrence
|
EventFormField.Recurrence -> R.string.event_detail_recurrence
|
||||||
EventFormField.Availability -> R.string.event_edit_availability
|
EventFormField.Availability -> R.string.event_edit_availability
|
||||||
|
EventFormField.Status -> R.string.event_edit_status
|
||||||
EventFormField.Visibility -> R.string.event_edit_visibility
|
EventFormField.Visibility -> R.string.event_edit_visibility
|
||||||
EventFormField.Color -> R.string.event_edit_color
|
EventFormField.Color -> R.string.event_edit_color
|
||||||
EventFormField.Attendees -> R.string.event_edit_attendees
|
EventFormField.Attendees -> R.string.event_edit_attendees
|
||||||
@@ -41,6 +43,7 @@ fun eventFormFieldIcon(field: EventFormField): ImageVector = when (field) {
|
|||||||
EventFormField.Reminders -> Icons.Default.Notifications
|
EventFormField.Reminders -> Icons.Default.Notifications
|
||||||
EventFormField.Recurrence -> Icons.Default.Repeat
|
EventFormField.Recurrence -> Icons.Default.Repeat
|
||||||
EventFormField.Availability -> Icons.Default.EventAvailable
|
EventFormField.Availability -> Icons.Default.EventAvailable
|
||||||
|
EventFormField.Status -> Icons.Default.TaskAlt
|
||||||
EventFormField.Visibility -> Icons.Default.Lock
|
EventFormField.Visibility -> Icons.Default.Lock
|
||||||
EventFormField.Color -> Icons.Default.Palette
|
EventFormField.Color -> Icons.Default.Palette
|
||||||
EventFormField.Attendees -> Icons.Default.People
|
EventFormField.Attendees -> Icons.Default.People
|
||||||
|
|||||||
@@ -90,7 +90,11 @@ fun EventMoveHost(
|
|||||||
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)
|
||||||
|
MoveOutcome.Stale -> stringResource(R.string.event_move_stale)
|
||||||
|
MoveOutcome.Skipped -> stringResource(R.string.event_move_skipped)
|
||||||
|
MoveOutcome.QueueFull -> stringResource(R.string.event_move_queue_full)
|
||||||
MoveOutcome.BlockedSeriesEnd -> stringResource(R.string.event_move_blocked_series_end)
|
MoveOutcome.BlockedSeriesEnd -> stringResource(R.string.event_move_blocked_series_end)
|
||||||
|
MoveOutcome.BlockedCancelledSeries -> stringResource(R.string.event_move_blocked_cancelled_series)
|
||||||
MoveOutcome.Failed -> stringResource(R.string.event_move_failed)
|
MoveOutcome.Failed -> stringResource(R.string.event_move_failed)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,15 @@
|
|||||||
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 kotlinx.coroutines.delay
|
||||||
|
import androidx.compose.animation.core.tween
|
||||||
|
import androidx.compose.runtime.rememberUpdatedState
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.Immutable
|
import androidx.compose.runtime.Immutable
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
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.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
@@ -16,6 +19,7 @@ import de.jeanlucmakiola.calendula.R
|
|||||||
import de.jeanlucmakiola.calendula.domain.EventInstance
|
import de.jeanlucmakiola.calendula.domain.EventInstance
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import java.util.concurrent.atomic.AtomicLong
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Drag-to-reschedule wiring (#68), provided once at `CalendarHost` and read by
|
* Drag-to-reschedule wiring (#68), provided once at `CalendarHost` and read by
|
||||||
@@ -37,24 +41,18 @@ class EventMoveScope(
|
|||||||
val dragEnabled: Boolean,
|
val dragEnabled: Boolean,
|
||||||
/**
|
/**
|
||||||
* Hand a drop to the writer. Returns nothing on purpose: a drop is answered
|
* Hand a drop to the writer. Returns nothing on purpose: a drop is answered
|
||||||
* before its write resolves, so [abandoned] — not a return value — is what
|
* before its write resolves, so [drops] — not a return value — is what tells
|
||||||
* tells a held copy that nothing landed.
|
* a held copy whether anything landed.
|
||||||
*/
|
*/
|
||||||
val move: (MoveRequest) -> Unit,
|
val move: (MoveRequest) -> Unit,
|
||||||
/**
|
/**
|
||||||
* True while a dropped event is being written, including the time its scope
|
* Each drop's progress by its token — see `RescheduleViewModel.drops`. A flow
|
||||||
* dialog is up. A flow rather than a value so this scope stays the same
|
* rather than a value so this scope stays the same object across a move —
|
||||||
* object across a move — every visible block reads it as a composition local.
|
* every visible block reads it as a composition local.
|
||||||
*/
|
*/
|
||||||
val inFlight: StateFlow<Boolean>,
|
val drops: StateFlow<DropStates>,
|
||||||
/** Ticks when an undo write begins — see `RescheduleViewModel.undoStarted`. */
|
/** The undo write that just began — see `RescheduleViewModel.undoStarted`. */
|
||||||
val undoStarted: StateFlow<Int>,
|
val undoStarted: StateFlow<UndoStart?>,
|
||||||
/**
|
|
||||||
* Ticks when a drop ends with nothing landing — see
|
|
||||||
* `RescheduleViewModel.abandoned`. [move] answers before the write is
|
|
||||||
* resolved, so this is what tells a held copy to stop waiting.
|
|
||||||
*/
|
|
||||||
val abandoned: StateFlow<Int>,
|
|
||||||
/** Open an event in the edit form — the pointer-free route to the same change. */
|
/** Open an event in the edit form — the pointer-free route to the same change. */
|
||||||
val edit: (EventInstance) -> Unit,
|
val edit: (EventInstance) -> Unit,
|
||||||
) {
|
) {
|
||||||
@@ -63,30 +61,42 @@ class EventMoveScope(
|
|||||||
|
|
||||||
val LocalEventMove = compositionLocalOf<EventMoveScope?> { null }
|
val LocalEventMove = compositionLocalOf<EventMoveScope?> { null }
|
||||||
|
|
||||||
private val NEVER_IN_FLIGHT = MutableStateFlow(false)
|
private val moveTokens = AtomicLong()
|
||||||
|
|
||||||
private val NEVER_UNDONE = MutableStateFlow(0)
|
/** A fresh identity for one drop or undo, unique for the process. */
|
||||||
|
fun nextMoveToken(): Long = moveTokens.incrementAndGet()
|
||||||
|
|
||||||
private val NEVER_ABANDONED = MutableStateFlow(0)
|
/** How many abandoned drops [DropStates] remembers — far more than can be on screen at once. */
|
||||||
|
private const val ABANDONED_KEPT = 32
|
||||||
|
|
||||||
/**
|
/** Per-drop progress, by token — see `RescheduleViewModel.drops`. */
|
||||||
* Whether a dropped event is still being written — false wherever moving is off.
|
@Immutable
|
||||||
* The drag overlays hold a landed block on its target for this window.
|
data class DropStates(
|
||||||
*/
|
val pending: Set<Long> = emptySet(),
|
||||||
@Composable
|
val abandoned: Set<Long> = emptySet(),
|
||||||
fun moveInFlight(): Boolean {
|
) {
|
||||||
val flow = LocalEventMove.current?.inFlight ?: NEVER_IN_FLIGHT
|
fun started(token: Long): DropStates = copy(pending = pending + token)
|
||||||
return flow.collectAsStateWithLifecycle().value
|
|
||||||
|
fun ended(token: Long, landed: Boolean): DropStates = copy(
|
||||||
|
pending = pending - token,
|
||||||
|
// Insertion-ordered, so the oldest go first.
|
||||||
|
abandoned = if (landed) abandoned else (abandoned + token).let { kept ->
|
||||||
|
if (kept.size > ABANDONED_KEPT) kept.drop(kept.size - ABANDONED_KEPT).toSet() else kept
|
||||||
|
},
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private val NO_DROPS = MutableStateFlow(DropStates())
|
||||||
|
|
||||||
|
private val NEVER_UNDONE = MutableStateFlow<UndoStart?>(null)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* How many drops have ended with nothing landing. Read as a plain count so a
|
* Every drop's progress — empty wherever moving is off. A drag overlay keeps
|
||||||
* drag overlay can capture it at the moment of the drop and tell, later, whether
|
* the token of its own drop and holds its copy while that token is pending.
|
||||||
* *its own* drop was one of them.
|
|
||||||
*/
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
fun abandonedMoves(): Int {
|
fun dropStates(): DropStates {
|
||||||
val flow = LocalEventMove.current?.abandoned ?: NEVER_ABANDONED
|
val flow = LocalEventMove.current?.drops ?: NO_DROPS
|
||||||
return flow.collectAsStateWithLifecycle().value
|
return flow.collectAsStateWithLifecycle().value
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -95,17 +105,53 @@ fun abandonedMoves(): Int {
|
|||||||
* this composable came on screen.
|
* this composable came on screen.
|
||||||
*/
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
fun OnUndoStarted(onUndo: () -> Unit) {
|
fun OnUndoStarted(onUndo: (UndoStart) -> Unit) {
|
||||||
val flow = LocalEventMove.current?.undoStarted ?: NEVER_UNDONE
|
val flow = LocalEventMove.current?.undoStarted ?: NEVER_UNDONE
|
||||||
val tick by flow.collectAsStateWithLifecycle()
|
val start by flow.collectAsStateWithLifecycle()
|
||||||
var seen by remember { mutableIntStateOf(tick) }
|
var seen by remember { mutableStateOf(start) }
|
||||||
LaunchedEffect(tick) {
|
LaunchedEffect(start) {
|
||||||
if (tick == seen) return@LaunchedEffect
|
val started = start
|
||||||
seen = tick
|
if (started == null || started == seen) return@LaunchedEffect
|
||||||
onUndo()
|
seen = started
|
||||||
|
onUndo(started)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The life of a drop parked by a newer pickup (#494): held while its [token]
|
||||||
|
* is pending, then a beat after the grid [seated] it — or [timeoutMillis] if it
|
||||||
|
* never does — handed over and faded, then released. Returns the copy's alpha.
|
||||||
|
* An abandoned drop skips the wait; nothing is coming to seat it.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun rememberHeldSettle(
|
||||||
|
token: Long,
|
||||||
|
seated: Boolean,
|
||||||
|
timeoutMillis: Long,
|
||||||
|
onHandOver: () -> Unit,
|
||||||
|
onRelease: () -> Unit,
|
||||||
|
): Float {
|
||||||
|
val drops = dropStates()
|
||||||
|
val pending = token in drops.pending
|
||||||
|
val abandoned = token in drops.abandoned
|
||||||
|
val handOver by rememberUpdatedState(onHandOver)
|
||||||
|
val release by rememberUpdatedState(onRelease)
|
||||||
|
var fading by remember(token) { mutableStateOf(false) }
|
||||||
|
LaunchedEffect(token, pending, abandoned, seated) {
|
||||||
|
if (pending) return@LaunchedEffect
|
||||||
|
if (!abandoned) delay(if (seated) SETTLE_GRACE_MILLIS else timeoutMillis)
|
||||||
|
fading = true
|
||||||
|
handOver()
|
||||||
|
delay(SETTLE_FADE_MILLIS.toLong())
|
||||||
|
release()
|
||||||
|
}
|
||||||
|
return animateFloatAsState(
|
||||||
|
targetValue = if (fading) 0f else 1f,
|
||||||
|
animationSpec = tween(SETTLE_FADE_MILLIS),
|
||||||
|
label = "held-settle",
|
||||||
|
).value
|
||||||
|
}
|
||||||
|
|
||||||
/** Opacity the source block keeps while its floating copy travels. */
|
/** Opacity the source block keeps while its floating copy travels. */
|
||||||
const val GHOST_ALPHA: Float = 0.3f
|
const val GHOST_ALPHA: Float = 0.3f
|
||||||
|
|
||||||
|
|||||||
@@ -21,8 +21,8 @@ import androidx.compose.ui.text.style.TextDecoration
|
|||||||
import androidx.compose.ui.unit.LayoutDirection
|
import androidx.compose.ui.unit.LayoutDirection
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import de.jeanlucmakiola.calendula.domain.EventInstance
|
import de.jeanlucmakiola.calendula.domain.EventInstance
|
||||||
import de.jeanlucmakiola.calendula.domain.EventResponse
|
import de.jeanlucmakiola.calendula.domain.isCrossedOut
|
||||||
import de.jeanlucmakiola.calendula.domain.isDeclined
|
import de.jeanlucmakiola.calendula.domain.isOutlined
|
||||||
|
|
||||||
/** Stroke an invitation you have not answered is outlined with. */
|
/** Stroke an invitation you have not answered is outlined with. */
|
||||||
val EVENT_OUTLINE_WIDTH = 1.dp
|
val EVENT_OUTLINE_WIDTH = 1.dp
|
||||||
@@ -60,13 +60,13 @@ fun timedBlockCuts(continuesBefore: Boolean, continuesAfter: Boolean): ChipCuts
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* How one event's chip or block is painted, which turns on your answer to its
|
* How one event's chip or block is painted, which turns on your answer to its
|
||||||
* invitation (#180, #230).
|
* invitation (#180, #230) and on the event's own status (#388).
|
||||||
*
|
*
|
||||||
* An invitation you have not answered is drawn as an outline: its calendar's
|
* An invitation you have not answered, or a tentative event, is drawn as an
|
||||||
* colour on the border and on the title, over the surface the chip sits on. So
|
* outline: its calendar's colour on the border and on the title, over the
|
||||||
* it holds a chip's shape and a chip's weight without claiming the filled
|
* surface the chip sits on. So it holds a chip's shape and a chip's weight
|
||||||
* container an event you are going to gets. A declined one keeps the fill and
|
* without claiming the filled container an event you are going to gets. A
|
||||||
* its strike-through.
|
* declined or cancelled one keeps the fill and its strike-through.
|
||||||
*/
|
*/
|
||||||
@Immutable
|
@Immutable
|
||||||
data class EventPaint(
|
data class EventPaint(
|
||||||
@@ -87,7 +87,7 @@ data class EventPaint(
|
|||||||
@Composable
|
@Composable
|
||||||
fun eventPaint(event: EventInstance, dark: Boolean): EventPaint {
|
fun eventPaint(event: EventInstance, dark: Boolean): EventPaint {
|
||||||
val soften = LocalSoftenColors.current
|
val soften = LocalSoftenColors.current
|
||||||
if (event.response == EventResponse.Invited) {
|
if (event.isOutlined) {
|
||||||
// Harmonised even when the setting is off. Raw mode exists so a filled
|
// Harmonised even when the setting is off. Raw mode exists so a filled
|
||||||
// container matches what the sync source paints, and an outlined chip
|
// container matches what the sync source paints, and an outlined chip
|
||||||
// has no container — what it has is coloured *text*, which needs the
|
// has no container — what it has is coloured *text*, which needs the
|
||||||
@@ -117,7 +117,7 @@ fun eventPaint(event: EventInstance, dark: Boolean): EventPaint {
|
|||||||
outline = null,
|
outline = null,
|
||||||
titleInk = eventInk(fill, alpha = TITLE_INK_ALPHA),
|
titleInk = eventInk(fill, alpha = TITLE_INK_ALPHA),
|
||||||
secondaryInk = eventInk(fill, alpha = SECONDARY_INK_ALPHA),
|
secondaryInk = eventInk(fill, alpha = SECONDARY_INK_ALPHA),
|
||||||
decoration = declinedDecoration(event.isDeclined),
|
decoration = declinedDecoration(event.isCrossedOut),
|
||||||
titleWeight = null,
|
titleWeight = null,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import androidx.compose.runtime.rememberUpdatedState
|
|||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
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.unit.dp
|
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import de.jeanlucmakiola.calendula.R
|
import de.jeanlucmakiola.calendula.R
|
||||||
import de.jeanlucmakiola.calendula.domain.EventForm
|
import de.jeanlucmakiola.calendula.domain.EventForm
|
||||||
@@ -33,7 +32,6 @@ fun rememberFabSelection(
|
|||||||
val calendars by viewModel.calendars.collectAsStateWithLifecycle()
|
val calendars by viewModel.calendars.collectAsStateWithLifecycle()
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
val requireWrite = rememberWriteGate()
|
|
||||||
val chooserTitle = stringResource(R.string.event_share_chooser_title)
|
val chooserTitle = stringResource(R.string.event_share_chooser_title)
|
||||||
|
|
||||||
// What the FAB has been told for this selection, over what the coverage says.
|
// What the FAB has been told for this selection, over what the coverage says.
|
||||||
@@ -44,10 +42,28 @@ fun rememberFabSelection(
|
|||||||
val currentEdit by rememberUpdatedState(onEdit)
|
val currentEdit by rememberUpdatedState(onEdit)
|
||||||
val currentDuplicate by rememberUpdatedState(onDuplicate)
|
val currentDuplicate by rememberUpdatedState(onDuplicate)
|
||||||
val currentDismissChip by rememberUpdatedState(onDismissChip)
|
val currentDismissChip by rememberUpdatedState(onDismissChip)
|
||||||
val currentWrite by rememberUpdatedState(requireWrite)
|
// Each reads the selection at grant time, which may come after a rotation.
|
||||||
|
val onCreate = rememberWriteAction { host.selection?.create?.invoke() }
|
||||||
|
val onEditSelected = rememberWriteAction {
|
||||||
|
host.selection?.takeIf { it.create == null }?.let { selected ->
|
||||||
|
selected.dismiss()
|
||||||
|
currentEdit(selected.event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val onDuplicateSelected = rememberWriteAction {
|
||||||
|
val selected = host.selection?.takeIf { it.create == null } ?: return@rememberWriteAction
|
||||||
|
scope.launch {
|
||||||
|
val form = viewModel.duplicateForm(selected.event) ?: return@launch
|
||||||
|
selected.dismiss()
|
||||||
|
currentDuplicate(form)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val onDeleteSelected = rememberWriteAction {
|
||||||
|
host.selection?.takeIf { it.create == null }?.let { viewModel.requestDelete(it.event) }
|
||||||
|
}
|
||||||
|
|
||||||
val selection = host.selection ?: return null
|
val selection = host.selection ?: return null
|
||||||
selection.create?.let { create ->
|
if (selection.create != null) {
|
||||||
return remember(selection, expanded, chipShown) {
|
return remember(selection, expanded, chipShown) {
|
||||||
FabSelection(
|
FabSelection(
|
||||||
expanded = expanded,
|
expanded = expanded,
|
||||||
@@ -57,7 +73,7 @@ fun rememberFabSelection(
|
|||||||
},
|
},
|
||||||
bar = {
|
bar = {
|
||||||
DraftSelectionBar(
|
DraftSelectionBar(
|
||||||
onCreate = { currentWrite { create() } },
|
onCreate = onCreate,
|
||||||
onDiscard = selection.dismiss,
|
onDiscard = selection.dismiss,
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
@@ -79,28 +95,15 @@ fun rememberFabSelection(
|
|||||||
EventSelectionBar(
|
EventSelectionBar(
|
||||||
canEdit = canEdit,
|
canEdit = canEdit,
|
||||||
canDelete = canDelete,
|
canDelete = canDelete,
|
||||||
onEdit = {
|
onEdit = onEditSelected,
|
||||||
currentWrite {
|
onDuplicate = onDuplicateSelected,
|
||||||
selection.dismiss()
|
|
||||||
currentEdit(event)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onDuplicate = {
|
|
||||||
currentWrite {
|
|
||||||
scope.launch {
|
|
||||||
val form = viewModel.duplicateForm(event) ?: return@launch
|
|
||||||
selection.dismiss()
|
|
||||||
currentDuplicate(form)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onShare = {
|
onShare = {
|
||||||
scope.launch {
|
scope.launch {
|
||||||
val uri = viewModel.shareUri(event) ?: return@launch
|
val uri = viewModel.shareUri(event) ?: return@launch
|
||||||
if (!context.sendEventShare(uri, chooserTitle)) viewModel.reportShareFailed()
|
if (!context.sendEventShare(uri, chooserTitle)) viewModel.reportShareFailed()
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onDelete = { currentWrite { viewModel.requestDelete(event) } },
|
onDelete = onDeleteSelected,
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -3,15 +3,12 @@ package de.jeanlucmakiola.calendula.ui.common
|
|||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
import androidx.compose.ui.platform.LocalDensity
|
|
||||||
import androidx.compose.ui.text.AnnotatedString
|
import androidx.compose.ui.text.AnnotatedString
|
||||||
import androidx.compose.ui.text.SpanStyle
|
import androidx.compose.ui.text.SpanStyle
|
||||||
import androidx.compose.ui.text.TextStyle
|
import androidx.compose.ui.text.TextStyle
|
||||||
import androidx.compose.ui.text.buildAnnotatedString
|
import androidx.compose.ui.text.buildAnnotatedString
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
import androidx.compose.ui.text.rememberTextMeasurer
|
|
||||||
import androidx.compose.ui.text.withStyle
|
import androidx.compose.ui.text.withStyle
|
||||||
import androidx.compose.ui.unit.Dp
|
|
||||||
import androidx.compose.ui.unit.sp
|
import androidx.compose.ui.unit.sp
|
||||||
import de.jeanlucmakiola.floret.locale.currentLocale
|
import de.jeanlucmakiola.floret.locale.currentLocale
|
||||||
|
|
||||||
@@ -45,33 +42,17 @@ fun inlineTimeLabel(time: String?, title: String, timeInk: Color): AnnotatedStri
|
|||||||
append(title)
|
append(title)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* The characters of title that have to survive a time prefix for it to be worth
|
|
||||||
* its place — lowercase Latin of average advance, priced at the surface's own
|
|
||||||
* text style rather than guessed in dp.
|
|
||||||
*/
|
|
||||||
private const val TITLE_SAMPLE = "notepad"
|
|
||||||
|
|
||||||
/** The widest wall-clock time in either convention: two-digit hour, and a meridiem in 12-hour. */
|
/** The widest wall-clock time in either convention: two-digit hour, and a meridiem in 12-hour. */
|
||||||
private const val SAMPLE_HOUR = 12
|
private const val SAMPLE_HOUR = 12
|
||||||
private const val SAMPLE_MINUTE = 45
|
private const val SAMPLE_MINUTE = 45
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The narrowest run of [style] text that may carry a time in front of a title:
|
* The widest time the current convention writes, for pricing a time prefix by
|
||||||
* wide enough for the widest time in the current convention plus [TITLE_SAMPLE].
|
* measurement: it follows the 12/24-hour setting and the locale's own format.
|
||||||
*
|
|
||||||
* Measured rather than a device breakpoint, so it follows the font scale, the
|
|
||||||
* 12/24-hour setting, the locale's own time format and whatever else has
|
|
||||||
* already been taken off the width.
|
|
||||||
*/
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
fun rememberInlineTimeWidth(style: TextStyle): Dp {
|
fun rememberWidestTimeSample(): String {
|
||||||
val measurer = rememberTextMeasurer()
|
|
||||||
val density = LocalDensity.current
|
|
||||||
val locale = currentLocale()
|
val locale = currentLocale()
|
||||||
val sample = formatTimeOfDay(SAMPLE_HOUR, SAMPLE_MINUTE, LocalUse24HourFormat.current, locale)
|
val is24Hour = LocalUse24HourFormat.current
|
||||||
return remember(sample, style, density, measurer) {
|
return remember(is24Hour, locale) { formatTimeOfDay(SAMPLE_HOUR, SAMPLE_MINUTE, is24Hour, locale) }
|
||||||
val label = inlineTimeLabel(sample, TITLE_SAMPLE, Color.Unspecified)
|
|
||||||
with(density) { measurer.measure(label, style).size.width.toDp() }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -20,7 +20,6 @@ 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.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
|
||||||
@@ -57,7 +56,8 @@ private const val DIMMED_HOUR_ALPHA = 0.3f
|
|||||||
* The timeline's hour gutter. Scrolls in sync with the day columns through the
|
* The timeline's hour gutter. Scrolls in sync with the day columns through the
|
||||||
* shared [scrollState], and while [dragController] holds a lifted block it dims
|
* shared [scrollState], and while [dragController] holds a lifted block it dims
|
||||||
* the hour labels and floats a badge with the drag's current start time at the
|
* the hour labels and floats a badge with the drag's current start time at the
|
||||||
* row the block would land on.
|
* row the block would land on. Its content ends in the same [FabClearance]
|
||||||
|
* the day columns do, or the two drift apart at the bottom of the scroll.
|
||||||
*/
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
fun HourGutter(
|
fun HourGutter(
|
||||||
@@ -87,7 +87,8 @@ fun HourGutter(
|
|||||||
.width(GUTTER_WIDTH)
|
.width(GUTTER_WIDTH)
|
||||||
.padding(start = GUTTER_CONTENT_START_INSET)
|
.padding(start = GUTTER_CONTENT_START_INSET)
|
||||||
.fillMaxHeight()
|
.fillMaxHeight()
|
||||||
.verticalScroll(scrollState),
|
.verticalScroll(scrollState)
|
||||||
|
.padding(bottom = FabClearance),
|
||||||
) {
|
) {
|
||||||
Column {
|
Column {
|
||||||
(0 until 24).forEach { h ->
|
(0 until 24).forEach { h ->
|
||||||
@@ -111,14 +112,13 @@ fun HourGutter(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Held while it fades, so it goes out where it was rather than blinking off.
|
// Held while it fades, so it goes out where it was rather than blinking off.
|
||||||
val badgeMin = remember { mutableStateOf<Int?>(null) }
|
val badgeMin = rememberHeld(dragStartMin)
|
||||||
dragStartMin?.let { badgeMin.value = it }
|
|
||||||
val badgeIn by animateFloatAsState(
|
val badgeIn by animateFloatAsState(
|
||||||
targetValue = if (dragStartMin != null) 1f else 0f,
|
targetValue = if (dragStartMin != null) 1f else 0f,
|
||||||
animationSpec = MaterialTheme.motionScheme.fastEffectsSpec(),
|
animationSpec = MaterialTheme.motionScheme.fastEffectsSpec(),
|
||||||
label = "gutterBadge",
|
label = "gutterBadge",
|
||||||
)
|
)
|
||||||
badgeMin.value?.takeIf { badgeIn > 0f }?.let { startMin ->
|
badgeMin?.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
|
||||||
|
|||||||
@@ -70,27 +70,24 @@ data class OutOfViewEvents(val above: TimedBlock?, val below: TimedBlock?) {
|
|||||||
/** Which edge of the viewport a hidden event sits past. */
|
/** Which edge of the viewport a hidden event sits past. */
|
||||||
enum class ViewportEdge { Top, Bottom }
|
enum class ViewportEdge { Top, Bottom }
|
||||||
|
|
||||||
/** Where [block]'s rendered bottom lands, in minutes — short blocks keep a floor. */
|
|
||||||
internal fun renderedEndMin(block: TimedBlock): Float =
|
|
||||||
maxOf(block.endMin.toFloat(), block.startMin + MIN_EVENT_FRACTION * 60f)
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The blocks of one column lying out of a viewport spanning [topMin]..[bottomMin]
|
* The blocks of one column lying out of a viewport spanning [topMin]..[bottomMin]
|
||||||
* (minutes of the day), nearest first. A block leaves this set as soon as any
|
* (minutes of the day), nearest first. A block leaves this set as soon as any
|
||||||
* part of its rendered height enters the viewport.
|
* part of its [renderedSpan] enters the viewport.
|
||||||
*/
|
*/
|
||||||
fun outOfViewEvents(
|
fun outOfViewEvents(
|
||||||
blocks: List<TimedBlock>,
|
blocks: List<TimedBlock>,
|
||||||
topMin: Float,
|
topMin: Float,
|
||||||
bottomMin: Float,
|
bottomMin: Float,
|
||||||
): OutOfViewEvents {
|
): OutOfViewEvents {
|
||||||
val above = blocks
|
val spans = blocks.map { it to it.renderedSpan() }
|
||||||
.filter { renderedEndMin(it) <= topMin }
|
val above = spans
|
||||||
.maxWithOrNull(compareBy<TimedBlock>({ renderedEndMin(it) }, { it.startMin }))
|
.filter { (_, span) -> span.bottomMin <= topMin }
|
||||||
val below = blocks
|
.maxWithOrNull(compareBy({ it.second.bottomMin }, { it.first.startMin }))
|
||||||
.filter { it.startMin >= bottomMin }
|
val below = spans
|
||||||
.minWithOrNull(compareBy<TimedBlock>({ it.startMin }, { -renderedEndMin(it) }))
|
.filter { (_, span) -> span.topMin >= bottomMin }
|
||||||
return OutOfViewEvents(above, below)
|
.minWithOrNull(compareBy({ it.second.topMin }, { -it.second.bottomMin }))
|
||||||
|
return OutOfViewEvents(above?.first, below?.first)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -107,8 +104,9 @@ fun revealScrollTarget(
|
|||||||
marginPx: Float,
|
marginPx: Float,
|
||||||
maxScroll: Int,
|
maxScroll: Int,
|
||||||
): Int {
|
): Int {
|
||||||
val startPx = block.startMin / 60f * hourPx
|
val span = block.renderedSpan()
|
||||||
val endPx = renderedEndMin(block) / 60f * hourPx
|
val startPx = span.topMin / 60f * hourPx
|
||||||
|
val endPx = span.bottomMin / 60f * hourPx
|
||||||
val target = when (edge) {
|
val target = when (edge) {
|
||||||
ViewportEdge.Top -> startPx - marginPx
|
ViewportEdge.Top -> startPx - marginPx
|
||||||
ViewportEdge.Bottom -> minOf(endPx + marginPx - viewportPx, startPx - marginPx)
|
ViewportEdge.Bottom -> minOf(endPx + marginPx - viewportPx, startPx - marginPx)
|
||||||
@@ -293,6 +291,7 @@ private fun EdgeBar(
|
|||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
) {
|
) {
|
||||||
block ?: return
|
block ?: return
|
||||||
|
val span = remember(block) { block.renderedSpan() }
|
||||||
val color = eventFill(block.event.color, dark, LocalSoftenColors.current)
|
val color = eventFill(block.event.color, dark, LocalSoftenColors.current)
|
||||||
val label = stringResource(
|
val label = stringResource(
|
||||||
if (edge == ViewportEdge.Top) R.string.timeline_earlier_events else R.string.timeline_later_events,
|
if (edge == ViewportEdge.Top) R.string.timeline_earlier_events else R.string.timeline_later_events,
|
||||||
@@ -303,8 +302,8 @@ private fun EdgeBar(
|
|||||||
.height(EDGE_TOUCH_HEIGHT)
|
.height(EDGE_TOUCH_HEIGHT)
|
||||||
.graphicsLayer {
|
.graphicsLayer {
|
||||||
val gapPx = when (edge) {
|
val gapPx = when (edge) {
|
||||||
ViewportEdge.Top -> scrollState.value - renderedEndMin(block) / 60f * hourPx
|
ViewportEdge.Top -> scrollState.value - span.bottomMin / 60f * hourPx
|
||||||
ViewportEdge.Bottom -> block.startMin / 60f * hourPx -
|
ViewportEdge.Bottom -> span.topMin / 60f * hourPx -
|
||||||
(scrollState.value + scrollState.viewportSize)
|
(scrollState.value + scrollState.viewportSize)
|
||||||
}
|
}
|
||||||
alpha = edgeBarAlpha(gapPx, fadeLeadPx)
|
alpha = edgeBarAlpha(gapPx, fadeLeadPx)
|
||||||
|
|||||||
@@ -1,22 +1,26 @@
|
|||||||
package de.jeanlucmakiola.calendula.ui.common
|
package de.jeanlucmakiola.calendula.ui.common
|
||||||
|
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.ExperimentalForInheritanceCoroutinesApi
|
||||||
import kotlinx.coroutines.Job
|
import kotlinx.coroutines.Job
|
||||||
import kotlinx.coroutines.SupervisorJob
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
import kotlinx.coroutines.flow.SharingStarted
|
import kotlinx.coroutines.flow.FlowCollector
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.stateIn
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.plus
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* One shared state per pager page — a week, a day, a month — so a page and the
|
* One shared state per pager page — a week, a day, a month — so a page and the
|
||||||
* screen's anchor read the same query, and the pages either side stay loaded
|
* screen's anchor read the same query, and the pages either side stay loaded
|
||||||
* across a swipe.
|
* across a swipe.
|
||||||
*
|
*
|
||||||
* Every entry shares on its own job, cancelled when [keep] lets it go: a
|
* An entry queries only while something collects it, stopping [STOP_TIMEOUT_MILLIS]
|
||||||
* `stateIn` on the ViewModel's scope would stay running, holding its last state,
|
* after the last collector leaves, and starts again when one comes back. Letting
|
||||||
* until the ViewModel itself was cleared. Main thread only.
|
* an entry go only forgets it: a page still holding it keeps a working state
|
||||||
|
* however far the pager composes or prefetches, and however long the screen sat
|
||||||
|
* stopped (#440, #454). A forgotten entry nobody collects holds no coroutine, so
|
||||||
|
* paging through a year doesn't keep a year of queries around. Main thread only.
|
||||||
*
|
*
|
||||||
* @param keep whether a cached key is still worth holding once [get] asks for another.
|
* @param keep whether a cached key is still worth holding once [get] asks for another.
|
||||||
*/
|
*/
|
||||||
@@ -26,28 +30,54 @@ class PageStateCache<K, S>(
|
|||||||
private val keep: (cached: K, requested: K) -> Boolean,
|
private val keep: (cached: K, requested: K) -> Boolean,
|
||||||
private val load: (K) -> Flow<S>,
|
private val load: (K) -> Flow<S>,
|
||||||
) {
|
) {
|
||||||
private class Entry<S>(val state: StateFlow<S>, val job: Job)
|
private val entries = HashMap<K, Entry>()
|
||||||
|
|
||||||
private val entries = HashMap<K, Entry<S>>()
|
|
||||||
|
|
||||||
/** The number of entries held, for tests. */
|
/** The number of entries held, for tests. */
|
||||||
internal val size: Int get() = entries.size
|
internal val size: Int get() = entries.size
|
||||||
|
|
||||||
fun get(key: K): StateFlow<S> {
|
fun get(key: K): StateFlow<S> {
|
||||||
val iterator = entries.iterator()
|
// One still collected stays, so the anchor asking for it again shares its query.
|
||||||
while (iterator.hasNext()) {
|
entries.entries.removeAll { (cached, entry) ->
|
||||||
val (cached, entry) = iterator.next()
|
cached != key && !keep(cached, key) && !entry.isCollected
|
||||||
if (cached != key && !keep(cached, key)) {
|
}
|
||||||
entry.job.cancel()
|
return entries.getOrPut(key) { Entry(key) }
|
||||||
iterator.remove()
|
}
|
||||||
|
|
||||||
|
@OptIn(ExperimentalForInheritanceCoroutinesApi::class)
|
||||||
|
private inner class Entry(private val key: K) : StateFlow<S> {
|
||||||
|
private val state = MutableStateFlow(initial)
|
||||||
|
private var collectors = 0
|
||||||
|
private var loading: Job? = null
|
||||||
|
private var stopping: Job? = null
|
||||||
|
|
||||||
|
val isCollected: Boolean get() = collectors > 0
|
||||||
|
|
||||||
|
override val value: S get() = state.value
|
||||||
|
override val replayCache: List<S> get() = state.replayCache
|
||||||
|
|
||||||
|
override suspend fun collect(collector: FlowCollector<S>): Nothing {
|
||||||
|
collectors++
|
||||||
|
stopping?.cancel()
|
||||||
|
stopping = null
|
||||||
|
if (loading?.isActive != true) {
|
||||||
|
loading = scope.launch { load(key).collect { state.value = it } }
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
state.collect(collector)
|
||||||
|
} finally {
|
||||||
|
if (--collectors == 0) {
|
||||||
|
stopping = scope.launch {
|
||||||
|
delay(STOP_TIMEOUT_MILLIS)
|
||||||
|
loading?.cancel()
|
||||||
|
loading = null
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return entries.getOrPut(key) {
|
}
|
||||||
val job = SupervisorJob(scope.coroutineContext[Job])
|
|
||||||
Entry(
|
private companion object {
|
||||||
state = load(key).stateIn(scope + job, SharingStarted.WhileSubscribed(5_000L), initial),
|
/** Long enough to ride out a configuration change, as `stateWhileSubscribed` does. */
|
||||||
job = job,
|
const val STOP_TIMEOUT_MILLIS = 5_000L
|
||||||
)
|
|
||||||
}.state
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -30,7 +30,7 @@ fun EventInstance.isPastOn(
|
|||||||
day: LocalDate,
|
day: LocalDate,
|
||||||
now: Instant,
|
now: Instant,
|
||||||
zone: TimeZone = TimeZone.currentSystemDefault(),
|
zone: TimeZone = TimeZone.currentSystemDefault(),
|
||||||
): Boolean = hasEnded(now) || day < now.toLocalDateTime(zone).date
|
): Boolean = hasEnded(now, zone) || 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
|
||||||
@@ -41,19 +41,19 @@ const val EventDimAlpha = 0.4f
|
|||||||
* is still something the organiser expects you at. Null for everything else, so
|
* is still something the organiser expects you at. Null for everything else, so
|
||||||
* it drops straight into a `Text`'s `textDecoration`.
|
* it drops straight into a `Text`'s `textDecoration`.
|
||||||
*/
|
*/
|
||||||
fun declinedDecoration(isDeclined: Boolean): TextDecoration? =
|
fun declinedDecoration(isCrossedOut: Boolean): TextDecoration? =
|
||||||
if (isDeclined) TextDecoration.LineThrough else null
|
if (isCrossedOut) TextDecoration.LineThrough else null
|
||||||
|
|
||||||
/** [declinedDecoration] for the rows that take styled text rather than a `String`. */
|
/** [declinedDecoration] for the rows that take styled text rather than a `String`. */
|
||||||
fun declinedTitle(title: String, isDeclined: Boolean): AnnotatedString = if (isDeclined) {
|
fun declinedTitle(title: String, isCrossedOut: Boolean): AnnotatedString = if (isCrossedOut) {
|
||||||
AnnotatedString(title, SpanStyle(textDecoration = TextDecoration.LineThrough))
|
AnnotatedString(title, SpanStyle(textDecoration = TextDecoration.LineThrough))
|
||||||
} else {
|
} else {
|
||||||
AnnotatedString(title)
|
AnnotatedString(title)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** [declinedTitle] over already-styled text, e.g. a search hit's marked runs. */
|
/** [declinedTitle] over already-styled text, e.g. a search hit's marked runs. */
|
||||||
fun declinedTitle(title: AnnotatedString, isDeclined: Boolean): AnnotatedString =
|
fun declinedTitle(title: AnnotatedString, isCrossedOut: Boolean): AnnotatedString =
|
||||||
if (!isDeclined) {
|
if (!isCrossedOut) {
|
||||||
title
|
title
|
||||||
} else {
|
} else {
|
||||||
buildAnnotatedString {
|
buildAnnotatedString {
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ import androidx.compose.ui.text.font.FontStyle
|
|||||||
import de.jeanlucmakiola.calendula.R
|
import de.jeanlucmakiola.calendula.R
|
||||||
import de.jeanlucmakiola.calendula.domain.SimpleRecurrence
|
import de.jeanlucmakiola.calendula.domain.SimpleRecurrence
|
||||||
import de.jeanlucmakiola.calendula.domain.occurrencesSpanYears
|
import de.jeanlucmakiola.calendula.domain.occurrencesSpanYears
|
||||||
|
import de.jeanlucmakiola.calendula.domain.rruleParts
|
||||||
|
import de.jeanlucmakiola.calendula.domain.ics.parseBasicDate
|
||||||
import de.jeanlucmakiola.calendula.domain.upcomingOccurrences
|
import de.jeanlucmakiola.calendula.domain.upcomingOccurrences
|
||||||
import de.jeanlucmakiola.floret.locale.localizedDateFormatter
|
import de.jeanlucmakiola.floret.locale.localizedDateFormatter
|
||||||
import kotlinx.datetime.toJavaLocalDate
|
import kotlinx.datetime.toJavaLocalDate
|
||||||
@@ -32,10 +34,7 @@ import java.util.Locale
|
|||||||
*/
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
fun recurrenceText(rrule: String, locale: Locale): AnnotatedString {
|
fun recurrenceText(rrule: String, locale: Locale): AnnotatedString {
|
||||||
val parts = rrule.removePrefix("RRULE:").split(';').mapNotNull { token ->
|
val parts = rruleParts(rrule).mapNotNull { part -> part.key?.let { it to part.value } }.toMap()
|
||||||
val eq = token.indexOf('=')
|
|
||||||
if (eq <= 0) null else token.substring(0, eq).uppercase() to token.substring(eq + 1)
|
|
||||||
}.toMap()
|
|
||||||
|
|
||||||
val freq = parts["FREQ"]?.uppercase()
|
val freq = parts["FREQ"]?.uppercase()
|
||||||
val interval = parts["INTERVAL"]?.toIntOrNull() ?: 1
|
val interval = parts["INTERVAL"]?.toIntOrNull() ?: 1
|
||||||
@@ -171,12 +170,5 @@ internal fun untilLocalDate(raw: String, zone: ZoneId = ZoneId.systemDefault()):
|
|||||||
.atOffset(ZoneOffset.UTC)
|
.atOffset(ZoneOffset.UTC)
|
||||||
.atZoneSameInstant(zone)
|
.atZoneSameInstant(zone)
|
||||||
.toLocalDate()
|
.toLocalDate()
|
||||||
}.recoverCatching {
|
}.getOrNull() ?: parseBasicDate(value.takeWhile { it.isDigit() })?.toJavaLocalDate()
|
||||||
val digits = value.takeWhile { it.isDigit() }
|
|
||||||
LocalDate.of(
|
|
||||||
digits.substring(0, 4).toInt(),
|
|
||||||
digits.substring(4, 6).toInt(),
|
|
||||||
digits.substring(6, 8).toInt(),
|
|
||||||
)
|
|
||||||
}.getOrNull()
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package de.jeanlucmakiola.calendula.ui.common
|
||||||
|
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [live], or after it goes null the last value it had, so an overlay keeps
|
||||||
|
* drawing what it showed through its slide-out instead of flashing empty. Never
|
||||||
|
* a placeholder: until [live] is first set this is null, so a destination never
|
||||||
|
* loads a bogus key on its first frame. Not saved — after a recreation the
|
||||||
|
* saveable [live] is the value again.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun <T : Any> rememberHeld(live: T?): T? {
|
||||||
|
val held = remember { HeldValue<T>() }
|
||||||
|
if (live != null) held.value = live
|
||||||
|
return live ?: held.value
|
||||||
|
}
|
||||||
|
|
||||||
|
private class HeldValue<T : Any> {
|
||||||
|
var value: T? = null
|
||||||
|
}
|
||||||
@@ -6,7 +6,7 @@ import dagger.hilt.android.lifecycle.HiltViewModel
|
|||||||
import de.jeanlucmakiola.calendula.data.time.ZoneSource
|
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.canSaveApartFromSeries
|
||||||
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
|
||||||
@@ -23,30 +23,39 @@ 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.flow.update
|
||||||
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.Duration.Companion.seconds
|
||||||
import kotlin.time.Instant
|
import kotlin.time.Instant
|
||||||
|
import kotlin.time.TimeMark
|
||||||
|
import kotlin.time.TimeSource
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
private const val MILLIS_PER_MINUTE = 60_000
|
private const val MILLIS_PER_MINUTE = 60_000
|
||||||
private const val MINUTES_PER_DAY = 24 * 60
|
private const val MINUTES_PER_DAY = 24 * 60
|
||||||
|
|
||||||
|
/** How many drops may wait behind the one in flight before more are refused. */
|
||||||
|
private const val MAX_QUEUED = 8
|
||||||
|
|
||||||
|
/** How long after a write its event's drawn times may still be the old ones. */
|
||||||
|
private val RECENT_WRITE = 3.seconds
|
||||||
|
|
||||||
/** Where a dragged event should land. */
|
/** Where a dragged event should land. */
|
||||||
sealed interface MoveTarget {
|
sealed interface MoveTarget {
|
||||||
/** A new start instant — a timeline drag, which moves time and day at once. */
|
/** A new start instant — a timeline drag, which moves time and day at once. */
|
||||||
@@ -59,7 +68,10 @@ sealed interface MoveTarget {
|
|||||||
*/
|
*/
|
||||||
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. */
|
/**
|
||||||
|
* New start and end instants — a timeline resize, which changes the length,
|
||||||
|
* or an all-day event dragged into the time grid, which becomes timed.
|
||||||
|
*/
|
||||||
data class Span(val start: Instant, val end: Instant) : MoveTarget
|
data class Span(val start: Instant, val end: Instant) : MoveTarget
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,6 +84,10 @@ data class MoveRequest(
|
|||||||
val beginMillis: Long,
|
val beginMillis: Long,
|
||||||
val endMillis: Long,
|
val endMillis: Long,
|
||||||
val target: MoveTarget,
|
val target: MoveTarget,
|
||||||
|
/** Whether the dragged occurrence is all-day, which decides the zone its day is read in. */
|
||||||
|
val isAllDay: Boolean,
|
||||||
|
/** The drop's own identity, from [nextMoveToken], which the view holding its copy waits on. */
|
||||||
|
val token: Long,
|
||||||
)
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -90,8 +106,13 @@ data class MoveUndo(
|
|||||||
val moved: EventForm,
|
val moved: EventForm,
|
||||||
/** The form as it stood before the move. */
|
/** The form as it stood before the move. */
|
||||||
val restored: EventForm,
|
val restored: EventForm,
|
||||||
|
/** The token of the drop this undoes, so the view that drew it carries the right chip back. */
|
||||||
|
val dropToken: Long,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/** An undo write that just began: its own [token], and the [dropToken] of the drop it undoes. */
|
||||||
|
data class UndoStart(val token: Long, val dropToken: Long)
|
||||||
|
|
||||||
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
|
||||||
@@ -113,9 +134,28 @@ sealed interface MoveOutcome {
|
|||||||
/** The event vanished (sync, another device) between the read and the write. */
|
/** The event vanished (sync, another device) between the read and the write. */
|
||||||
data object Gone : MoveOutcome
|
data object Gone : MoveOutcome
|
||||||
|
|
||||||
|
/** Drops that waited behind a scope dialog, cancelled rather than run after it (#494). */
|
||||||
|
data object Skipped : MoveOutcome
|
||||||
|
|
||||||
|
/** More drops waiting than the queue holds; this one was not taken. */
|
||||||
|
data object QueueFull : MoveOutcome
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The drop's recurring occurrence may no longer be where it was picked up —
|
||||||
|
* its series was just written — and can't be followed there, so it is not
|
||||||
|
* written (#494).
|
||||||
|
*/
|
||||||
|
data object Stale : MoveOutcome
|
||||||
|
|
||||||
/** The drop would push the series past its own `UNTIL`, generating nothing. */
|
/** The drop would push the series past its own `UNTIL`, generating nothing. */
|
||||||
data object BlockedSeriesEnd : MoveOutcome
|
data object BlockedSeriesEnd : MoveOutcome
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A cancelled series only moves as a whole, and this drop would change which
|
||||||
|
* days it falls on (#388).
|
||||||
|
*/
|
||||||
|
data object BlockedCancelledSeries : MoveOutcome
|
||||||
|
|
||||||
data object Failed : MoveOutcome
|
data object Failed : MoveOutcome
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -144,36 +184,32 @@ class RescheduleViewModel @Inject constructor(
|
|||||||
|
|
||||||
private val _inFlight = MutableStateFlow(false)
|
private val _inFlight = MutableStateFlow(false)
|
||||||
|
|
||||||
/**
|
/** True while any drop or undo runs or waits — what the confirmation chip holds for. */
|
||||||
* True from the moment a drop is accepted until its write settles — the
|
|
||||||
* window the dropped block holds its landing position for.
|
|
||||||
*/
|
|
||||||
val inFlight: StateFlow<Boolean> = _inFlight.asStateFlow()
|
val inFlight: StateFlow<Boolean> = _inFlight.asStateFlow()
|
||||||
|
|
||||||
private val _abandoned = MutableStateFlow(0)
|
private val _drops = MutableStateFlow(DropStates())
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ticks when a drop ends with nothing on the target day: refused outright,
|
* Each drop's own state, by its [MoveRequest.token]: pending from the moment
|
||||||
* refused before the write, written and failed, or its scope dialog
|
* it is accepted until its write settles, and abandoned once it ends with
|
||||||
* dismissed. [move] answers before any of that is known, so without this
|
* nothing on the target day — refused, failed, or its scope dialog dismissed.
|
||||||
* signal the view that drew the drop held its copy out for the full settle
|
* Per drop, so a queued drop's held copy waits on its own write and is never
|
||||||
* timeout waiting for a grid that was never going to draw it (#253).
|
* let go by another drop's failure (#253, #494).
|
||||||
*/
|
*/
|
||||||
val abandoned: StateFlow<Int> = _abandoned.asStateFlow()
|
val drops: StateFlow<DropStates> = _drops.asStateFlow()
|
||||||
|
|
||||||
private val _undoStarted = MutableStateFlow(0)
|
private val _undoStarted = MutableStateFlow<UndoStart?>(null)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ticks the moment an undo write begins, before the provider has anything to
|
* An undo write the moment it begins, before the provider has anything to
|
||||||
* re-read, so the view that drew the drop can carry its chip back rather than
|
* re-read, so the view that drew the drop can carry its chip back rather than
|
||||||
* let it reappear on the old day.
|
* let it reappear on the old day. Its fate then reads off [drops].
|
||||||
*/
|
*/
|
||||||
val undoStarted: StateFlow<Int> = _undoStarted.asStateFlow()
|
val undoStarted: StateFlow<UndoStart?> = _undoStarted.asStateFlow()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set from the moment a drop is accepted until its write settles. Two drops
|
* Set while a drop is being prepared, waits on its scope dialog, or is
|
||||||
* of the same recurring event inside that window would compute their shift
|
* written. Drops arriving in that window wait in [queue] and run in order.
|
||||||
* from the same pre-move occurrence, and the shifts would compound.
|
|
||||||
*/
|
*/
|
||||||
private var busy = false
|
private var busy = false
|
||||||
set(value) {
|
set(value) {
|
||||||
@@ -181,6 +217,22 @@ class RescheduleViewModel @Inject constructor(
|
|||||||
_inFlight.value = value
|
_inFlight.value = value
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Whether a move has been announced since the pipeline was last idle — see [report]. */
|
||||||
|
private var movedThisRun = false
|
||||||
|
|
||||||
|
/** Outcomes waiting for the chip, shown one after another as each is consumed. */
|
||||||
|
private val notices = ArrayDeque<MoveOutcome>()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* When each event's series (by id) or single occurrence (by id and begin)
|
||||||
|
* was last written. The grid draws the old times until it re-reads, so a
|
||||||
|
* drop on a recurring event written moments ago may carry stale times (#494).
|
||||||
|
*/
|
||||||
|
private val written = mutableMapOf<Pair<Long, Long?>, TimeMark>()
|
||||||
|
|
||||||
|
/** Drops that arrived while another was in flight, oldest first (#494). */
|
||||||
|
private val queue = ArrayDeque<MoveRequest>()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The calendars whose events may be dragged. Nothing below the UI guards
|
* The calendars whose events may be dragged. Nothing below the UI guards
|
||||||
* this, so a block outside this set registers no drag gesture at all.
|
* this, so a block outside this set registers no drag gesture at all.
|
||||||
@@ -189,9 +241,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(),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -206,43 +257,63 @@ class RescheduleViewModel @Inject constructor(
|
|||||||
val canRealign: Boolean,
|
val canRealign: Boolean,
|
||||||
/** The series row's DTSTART date after the move — what its `UNTIL` must clear. */
|
/** The series row's DTSTART date after the move — what its `UNTIL` must clear. */
|
||||||
val newAnchorDate: LocalDate,
|
val newAnchorDate: LocalDate,
|
||||||
)
|
) {
|
||||||
|
/** A timed event's new length, rather than an all-day one dragged into the grid. */
|
||||||
|
val isResize: Boolean get() = request.target is MoveTarget.Span && !original.isAllDay
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Take a drop, unless one is already being written. False means nothing will
|
* Take a drop: run it now, or queue it behind the ones in flight. False means
|
||||||
* be written; [abandoned] ticks for that refusal too, so a held copy is let
|
* nothing will be written — the queue is full — and the drop is marked
|
||||||
* go by the one signal rather than by every caller remembering to.
|
* abandoned in [drops], so its held copy is let go by the one signal rather
|
||||||
|
* than by every caller remembering to.
|
||||||
*
|
*
|
||||||
* The Boolean is diagnostic — the tests read it, [EventMoveScope] does not
|
* The Boolean is diagnostic — the tests read it, [EventMoveScope] does not
|
||||||
* hand it on. A caller that gated on it would be back to releasing its copy
|
* hand it on. It answers before the write is resolved anyway.
|
||||||
* from two places, and it answers before the write is resolved anyway.
|
|
||||||
*/
|
*/
|
||||||
fun move(request: MoveRequest): Boolean {
|
fun move(request: MoveRequest): Boolean {
|
||||||
if (busy || _scopePrompt.value != null) {
|
if (queue.size >= MAX_QUEUED) {
|
||||||
_abandoned.value += 1
|
_drops.update { it.ended(request.token, landed = false) }
|
||||||
|
report(MoveOutcome.QueueFull)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
if (_scopePrompt.value != null) {
|
||||||
|
_drops.update { it.ended(request.token, landed = false) }
|
||||||
|
report(MoveOutcome.Skipped)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
_drops.update { it.started(request.token) }
|
||||||
|
if (busy) queue.addLast(request) else run(request)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun run(request: MoveRequest) {
|
||||||
busy = true
|
busy = true
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
val prepared = prepare(request)
|
val prepared = prepare(request)
|
||||||
if (prepared == null) {
|
if (prepared == null) {
|
||||||
_abandoned.value += 1
|
settle(request.token, landed = false)
|
||||||
busy = false
|
|
||||||
return@launch
|
return@launch
|
||||||
}
|
}
|
||||||
if (!prepared.isRecurring) {
|
// A cancelled series only moves as a whole (#388).
|
||||||
write(prepared, RecurringWriteScope.AllEvents)
|
val seriesOnly = !prepared.original.canSaveApartFromSeries()
|
||||||
busy = false
|
if (!prepared.isRecurring || (seriesOnly && prepared.canRealign)) {
|
||||||
|
settle(request.token, write(prepared, RecurringWriteScope.AllEvents))
|
||||||
|
} else if (seriesOnly) {
|
||||||
|
report(MoveOutcome.BlockedCancelledSeries)
|
||||||
|
settle(request.token, landed = false)
|
||||||
} else {
|
} else {
|
||||||
// Still busy: the scope dialog is now the thing in flight.
|
// Still busy: the scope dialog is now the thing in flight. Drops
|
||||||
|
// waiting behind it are cancelled, not held behind a question
|
||||||
|
// about another event.
|
||||||
|
skipQueued()
|
||||||
pending = prepared
|
pending = prepared
|
||||||
_scopePrompt.value = MoveScopePrompt(
|
_scopePrompt.value = MoveScopePrompt(
|
||||||
occurrenceOnly = !prepared.canRealign,
|
occurrenceOnly = !prepared.canRealign,
|
||||||
resize = request.target is MoveTarget.Span,
|
resize = prepared.isResize,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Answer the scope dialog. */
|
/** Answer the scope dialog. */
|
||||||
@@ -253,35 +324,92 @@ class RescheduleViewModel @Inject constructor(
|
|||||||
pending = null
|
pending = null
|
||||||
_scopePrompt.value = null
|
_scopePrompt.value = null
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
write(prepared, scope)
|
settle(prepared.request.token, write(prepared, scope))
|
||||||
busy = false
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Dismiss the scope dialog without writing. */
|
/** Dismiss the scope dialog without writing. */
|
||||||
fun cancelScope() {
|
fun cancelScope() {
|
||||||
|
val prepared = pending ?: return
|
||||||
pending = null
|
pending = null
|
||||||
busy = false
|
|
||||||
_scopePrompt.value = null
|
_scopePrompt.value = null
|
||||||
_abandoned.value += 1
|
settle(prepared.request.token, landed = false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** End the drop [token], then run the next queued one, if any. */
|
||||||
|
private fun settle(token: Long, landed: Boolean) {
|
||||||
|
_drops.update { it.ended(token, landed) }
|
||||||
|
// Straight on to the next, so busy never reads false between two drops.
|
||||||
|
val next = queue.removeFirstOrNull()
|
||||||
|
if (next != null) {
|
||||||
|
run(next)
|
||||||
|
} else {
|
||||||
|
busy = false
|
||||||
|
movedThisRun = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun skipQueued() {
|
||||||
|
if (queue.isEmpty()) return
|
||||||
|
val skipped = queue.map { it.token }
|
||||||
|
queue.clear()
|
||||||
|
_drops.update { states -> skipped.fold(states) { acc, token -> acc.ended(token, landed = false) } }
|
||||||
|
report(MoveOutcome.Skipped)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Queue [outcome] for the chip. While drops run back to back only the first
|
||||||
|
* move is announced, so its Undo stays on offer; every failure gets its own
|
||||||
|
* turn after it, since the grid shows what moved but only the chip says what
|
||||||
|
* didn't. A later write to the announced move's event takes that Undo away,
|
||||||
|
* as putting the event back would undo the later move too.
|
||||||
|
*/
|
||||||
|
private fun report(outcome: MoveOutcome, eventId: Long? = null) {
|
||||||
|
if (outcome is MoveOutcome.Moved) {
|
||||||
|
if (movedThisRun) {
|
||||||
|
dropUndoFor(eventId)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
movedThisRun = true
|
||||||
|
} else if (outcome == (notices.lastOrNull() ?: _outcome.value)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (_outcome.value == null) _outcome.value = outcome else notices.addLast(outcome)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun dropUndoFor(eventId: Long?) {
|
||||||
|
fun MoveOutcome.withoutUndo(): MoveOutcome =
|
||||||
|
if (this is MoveOutcome.Moved && undo?.eventId == eventId) copy(undo = null) else this
|
||||||
|
_outcome.value = _outcome.value?.withoutUndo()
|
||||||
|
val rest = notices.map { it.withoutUndo() }
|
||||||
|
notices.clear()
|
||||||
|
notices.addAll(rest)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun markWritten(eventId: Long, beginMillis: Long?) {
|
||||||
|
written[eventId to beginMillis] = TimeSource.Monotonic.markNow()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun writtenRecently(eventId: Long, beginMillis: Long): Boolean {
|
||||||
|
written.entries.removeAll { it.value.elapsedNow() > RECENT_WRITE }
|
||||||
|
return (eventId to null) in written || (eventId to beginMillis) in written
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Put a completed move back where it came from. The outcome stands until the
|
* Put a completed move back where it came from. The outcome stands until the
|
||||||
* inverse write reports back, so the one chip changes what it says rather
|
* inverse write reports back, so the one chip changes what it says rather
|
||||||
* than closing and reopening. False when another write is already running —
|
* than closing and reopening. False when another write is already running —
|
||||||
* the chip hides its action for that window, so this is the backstop.
|
* the chip hides its action for that window, so this is the backstop. An
|
||||||
*
|
* undo is a journey of its own: [undoStarted] names its token, and [drops]
|
||||||
* [abandoned] ticks once an inverse that *started* fails to land: [undoStarted]
|
* reports whether it landed.
|
||||||
* has sent the chip back on its journey by then and nothing else will seat it.
|
|
||||||
* A refusal ticks nothing — it launched no journey of its own, and the counter
|
|
||||||
* is global, so a tick here would release some other drop's held copy before
|
|
||||||
* the grid has drawn it.
|
|
||||||
*/
|
*/
|
||||||
fun undo(undo: MoveUndo): Boolean {
|
fun undo(undo: MoveUndo): Boolean {
|
||||||
if (busy) return false
|
if (busy) return false
|
||||||
|
val token = nextMoveToken()
|
||||||
|
_drops.update { it.started(token) }
|
||||||
busy = true
|
busy = true
|
||||||
_undoStarted.value += 1
|
_undoStarted.value = UndoStart(token, undo.dropToken)
|
||||||
|
markWritten(undo.eventId, null)
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
_outcome.value = try {
|
_outcome.value = try {
|
||||||
repository.updateEvent(undo.eventId, undo.moved, undo.restored)
|
repository.updateEvent(undo.eventId, undo.moved, undo.restored)
|
||||||
@@ -295,33 +423,40 @@ class RescheduleViewModel @Inject constructor(
|
|||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
MoveOutcome.Failed
|
MoveOutcome.Failed
|
||||||
}
|
}
|
||||||
// Read off the outcome, the way [write] does — no second copy of the
|
settle(token, landed = _outcome.value is MoveOutcome.Undone)
|
||||||
// same fact to drift from it.
|
|
||||||
if (_outcome.value !is MoveOutcome.Undone) _abandoned.value += 1
|
|
||||||
busy = false
|
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Clear the outcome once the screen has shown it. */
|
/** Clear the outcome once the screen has shown it, bringing on the next one waiting. */
|
||||||
fun consumeOutcome() {
|
fun consumeOutcome() {
|
||||||
_outcome.value = null
|
_outcome.value = notices.removeFirstOrNull()
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun prepare(request: MoveRequest): PreparedMove? {
|
private suspend fun prepare(dropped: MoveRequest): PreparedMove? {
|
||||||
|
val zone = zoneSource.current()
|
||||||
val detail = try {
|
val detail = try {
|
||||||
repository.eventDetail(request.eventId)
|
repository.eventDetail(dropped.eventId)
|
||||||
} catch (e: CancellationException) {
|
} catch (e: CancellationException) {
|
||||||
throw e
|
throw e
|
||||||
} catch (e: NoSuchEventException) {
|
} catch (e: NoSuchEventException) {
|
||||||
_outcome.value = MoveOutcome.Gone
|
report(MoveOutcome.Gone)
|
||||||
return null
|
return null
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
_outcome.value = MoveOutcome.Failed
|
report(MoveOutcome.Failed)
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
// The drop carries the times the grid drew, which an earlier write may
|
||||||
|
// have moved on since (#494).
|
||||||
|
val request = if (detail.rrule == null || detail.isException) {
|
||||||
|
followed(dropped, detail, zone)
|
||||||
|
} else if (writtenRecently(dropped.eventId, dropped.beginMillis)) {
|
||||||
|
report(MoveOutcome.Stale)
|
||||||
|
return null
|
||||||
|
} else {
|
||||||
|
dropped
|
||||||
|
}
|
||||||
|
|
||||||
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)
|
||||||
@@ -334,7 +469,7 @@ class RescheduleViewModel @Inject constructor(
|
|||||||
// 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(zone) - EventFormProblem.RecurrenceEndsBeforeStart).isNotEmpty()) {
|
if ((shifted.problems(zone) - EventFormProblem.RecurrenceEndsBeforeStart).isNotEmpty()) {
|
||||||
_outcome.value = MoveOutcome.Failed
|
report(MoveOutcome.Failed)
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -379,14 +514,14 @@ class RescheduleViewModel @Inject constructor(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun write(prepared: PreparedMove, scope: RecurringWriteScope) {
|
/** Write [prepared] in [scope]; true when it landed. */
|
||||||
|
private suspend fun write(prepared: PreparedMove, scope: RecurringWriteScope): Boolean {
|
||||||
val request = prepared.request
|
val request = prepared.request
|
||||||
if (endsBeforeItStarts(prepared, scope)) {
|
if (endsBeforeItStarts(prepared, scope)) {
|
||||||
_outcome.value = MoveOutcome.BlockedSeriesEnd
|
report(MoveOutcome.BlockedSeriesEnd)
|
||||||
_abandoned.value += 1
|
return false
|
||||||
return
|
|
||||||
}
|
}
|
||||||
_outcome.value = try {
|
val outcome = try {
|
||||||
when {
|
when {
|
||||||
!prepared.isRecurring || scope == RecurringWriteScope.AllEvents ->
|
!prepared.isRecurring || scope == RecurringWriteScope.AllEvents ->
|
||||||
repository.updateEvent(request.eventId, prepared.original, prepared.updated)
|
repository.updateEvent(request.eventId, prepared.original, prepared.updated)
|
||||||
@@ -421,9 +556,37 @@ class RescheduleViewModel @Inject constructor(
|
|||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
MoveOutcome.Failed
|
MoveOutcome.Failed
|
||||||
}
|
}
|
||||||
// Nothing landed, so the copy the view is holding has nothing to fade
|
if (outcome is MoveOutcome.Moved) {
|
||||||
// into — let it go now rather than at the end of the settle timeout.
|
markWritten(request.eventId, request.beginMillis.takeIf { scope == RecurringWriteScope.ThisEvent && prepared.isRecurring })
|
||||||
if (_outcome.value !is MoveOutcome.Moved) _abandoned.value += 1
|
}
|
||||||
|
report(outcome, request.eventId)
|
||||||
|
return outcome is MoveOutcome.Moved
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A one-off [dropped] rebased onto where its event now is, so the last drop
|
||||||
|
* wins: absolute targets stand as they are, and a whole-day shift is re-aimed
|
||||||
|
* at the day it was dropped on. Unchanged when the event hasn't moved.
|
||||||
|
*/
|
||||||
|
private fun followed(dropped: MoveRequest, detail: EventDetail, zone: TimeZone): MoveRequest {
|
||||||
|
val now = detail.instance
|
||||||
|
val target = when (val target = dropped.target) {
|
||||||
|
is MoveTarget.ByDays -> {
|
||||||
|
// Each day read the way its own kind anchors it: all-day at UTC.
|
||||||
|
val aimed = Instant.fromEpochMilliseconds(dropped.beginMillis)
|
||||||
|
.toLocalDateTime(if (dropped.isAllDay) TimeZone.UTC else zone).date
|
||||||
|
.plus(target.days, DateTimeUnit.DAY)
|
||||||
|
val from = now.start.toLocalDateTime(if (now.isAllDay) TimeZone.UTC else zone).date
|
||||||
|
MoveTarget.ByDays((aimed.toEpochDays() - from.toEpochDays()).toInt())
|
||||||
|
}
|
||||||
|
else -> target
|
||||||
|
}
|
||||||
|
return dropped.copy(
|
||||||
|
beginMillis = now.start.toEpochMilliseconds(),
|
||||||
|
endMillis = now.end.toEpochMilliseconds(),
|
||||||
|
target = target,
|
||||||
|
isAllDay = now.isAllDay,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -462,9 +625,9 @@ class RescheduleViewModel @Inject constructor(
|
|||||||
val anchorZone = if (original.isAllDay) TimeZone.UTC else original.resolvedZone(zone)
|
val anchorZone = if (original.isAllDay) TimeZone.UTC else original.resolvedZone(zone)
|
||||||
val anchorMinute = detail.instance.start.toLocalDateTime(anchorZone)
|
val anchorMinute = detail.instance.start.toLocalDateTime(anchorZone)
|
||||||
.time.toMillisecondOfDay() / MILLIS_PER_MINUTE
|
.time.toMillisecondOfDay() / MILLIS_PER_MINUTE
|
||||||
val delta = (
|
// An all-day form's time is a placeholder; its anchor sits at midnight.
|
||||||
shifted.start.time.toMillisecondOfDay() - original.start.time.toMillisecondOfDay()
|
val fromMillis = if (original.isAllDay) 0 else original.start.time.toMillisecondOfDay()
|
||||||
) / MILLIS_PER_MINUTE
|
val delta = (shifted.start.time.toMillisecondOfDay() - fromMillis) / MILLIS_PER_MINUTE
|
||||||
return anchorMinute + delta in 0 until MINUTES_PER_DAY
|
return anchorMinute + delta in 0 until MINUTES_PER_DAY
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -490,6 +653,7 @@ class RescheduleViewModel @Inject constructor(
|
|||||||
eventId = prepared.request.eventId,
|
eventId = prepared.request.eventId,
|
||||||
moved = prepared.updated,
|
moved = prepared.updated,
|
||||||
restored = prepared.original,
|
restored = prepared.original,
|
||||||
|
dropToken = prepared.request.token,
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
null
|
null
|
||||||
@@ -497,7 +661,7 @@ class RescheduleViewModel @Inject constructor(
|
|||||||
|
|
||||||
/** Where a resized occurrence now ends; null for a move, which keeps its length. */
|
/** Where a resized occurrence now ends; null for a move, which keeps its length. */
|
||||||
private fun resizedEndMillis(prepared: PreparedMove): Long? {
|
private fun resizedEndMillis(prepared: PreparedMove): Long? {
|
||||||
if (prepared.request.target !is MoveTarget.Span) return null
|
if (!prepared.isResize) return null
|
||||||
val form = prepared.updated
|
val form = prepared.updated
|
||||||
return form.endInstant(form.resolvedZone(zoneSource.current())).toEpochMilliseconds()
|
return form.endInstant(form.resolvedZone(zoneSource.current())).toEpochMilliseconds()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ import androidx.compose.material3.Text
|
|||||||
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
|
||||||
|
import androidx.compose.runtime.derivedStateOf
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
@@ -30,10 +32,13 @@ import kotlin.time.toJavaInstant
|
|||||||
@Composable
|
@Composable
|
||||||
fun SelectionTopBar(selection: EventSelection) {
|
fun SelectionTopBar(selection: EventSelection) {
|
||||||
val event = selection.event
|
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 use24Hour = LocalUse24HourFormat.current
|
||||||
val locale = currentLocale()
|
val locale = currentLocale()
|
||||||
val whenText = remember(event.start, event.end, use24Hour, locale) {
|
val whenText = remember(shown.start, shown.end, use24Hour, locale) {
|
||||||
formatSelectionWhen(event, use24Hour, locale)
|
formatSelectionWhen(shown, use24Hour, locale)
|
||||||
}
|
}
|
||||||
TopAppBar(
|
TopAppBar(
|
||||||
navigationIcon = {
|
navigationIcon = {
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import kotlin.time.Instant
|
|||||||
import kotlin.time.toJavaInstant
|
import kotlin.time.toJavaInstant
|
||||||
import java.time.format.DateTimeFormatter
|
import java.time.format.DateTimeFormatter
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
|
import kotlinx.datetime.toLocalDateTime
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The resolved clock convention for the whole UI: `true` = 24-hour ("14:00"),
|
* The resolved clock convention for the whole UI: `true` = 24-hour ("14:00"),
|
||||||
@@ -37,6 +38,12 @@ fun formatTimeOfDay(hour: Int, minute: Int, is24Hour: Boolean, locale: Locale):
|
|||||||
LocalTime.of(hour.coerceIn(0, 23), minute.coerceIn(0, 59))
|
LocalTime.of(hour.coerceIn(0, 23), minute.coerceIn(0, 59))
|
||||||
.format(timeOfDayFormatter(is24Hour, locale))
|
.format(timeOfDayFormatter(is24Hour, locale))
|
||||||
|
|
||||||
|
/** [instant]'s wall-clock time in [zone], as [formatTimeOfDay] renders it. */
|
||||||
|
fun formatTimeOfDay(instant: Instant, zone: TimeZone, is24Hour: Boolean, locale: Locale): String {
|
||||||
|
val time = instant.toLocalDateTime(zone).time
|
||||||
|
return formatTimeOfDay(time.hour, time.minute, is24Hour, locale)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Format minutes-from-midnight (0..1440) as a time label. The end-of-day value
|
* Format minutes-from-midnight (0..1440) as a time label. The end-of-day value
|
||||||
* 1440 renders as "24:00" in 24h (its established reading) and as midnight
|
* 1440 renders as "24:00" in 24h (its established reading) and as midnight
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -103,9 +101,10 @@ fun TimeZonePickerDialog(
|
|||||||
onDismiss = onDismiss,
|
onDismiss = onDismiss,
|
||||||
scrollable = false,
|
scrollable = false,
|
||||||
) {
|
) {
|
||||||
SearchField(
|
PickerSearchField(
|
||||||
query = query,
|
query = query,
|
||||||
onQueryChange = { query = it },
|
onQueryChange = { query = it },
|
||||||
|
placeholder = stringResource(R.string.event_edit_timezone_search),
|
||||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||||
)
|
)
|
||||||
LazyColumn(contentPadding = PaddingValues(top = 8.dp, bottom = 24.dp)) {
|
LazyColumn(contentPadding = PaddingValues(top = 8.dp, bottom = 24.dp)) {
|
||||||
@@ -118,19 +117,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 +139,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))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -188,9 +182,10 @@ fun TimeZonePickerDialog(
|
|||||||
* which has a top bar to put it in) because the picker's bar is the title.
|
* which has a top bar to put it in) because the picker's bar is the title.
|
||||||
*/
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
private fun SearchField(
|
internal fun PickerSearchField(
|
||||||
query: String,
|
query: String,
|
||||||
onQueryChange: (String) -> Unit,
|
onQueryChange: (String) -> Unit,
|
||||||
|
placeholder: String,
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
) {
|
) {
|
||||||
val keyboard = LocalSoftwareKeyboardController.current
|
val keyboard = LocalSoftwareKeyboardController.current
|
||||||
@@ -213,7 +208,7 @@ private fun SearchField(
|
|||||||
InlineTextField(
|
InlineTextField(
|
||||||
value = query,
|
value = query,
|
||||||
onValueChange = onQueryChange,
|
onValueChange = onQueryChange,
|
||||||
placeholder = stringResource(R.string.event_edit_timezone_search),
|
placeholder = placeholder,
|
||||||
capitalization = KeyboardCapitalization.None,
|
capitalization = KeyboardCapitalization.None,
|
||||||
imeAction = ImeAction.Search,
|
imeAction = ImeAction.Search,
|
||||||
onImeAction = { keyboard?.hide() },
|
onImeAction = { keyboard?.hide() },
|
||||||
@@ -234,23 +229,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 +240,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,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -5,7 +5,6 @@ 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.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,8 +18,11 @@ 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.key
|
||||||
import androidx.compose.runtime.mutableStateListOf
|
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
|
||||||
@@ -59,7 +61,6 @@ 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
|
||||||
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
|
||||||
@@ -77,6 +78,9 @@ 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. */
|
||||||
const val DRAG_SNAP_MINUTES: Int = 15
|
const val DRAG_SNAP_MINUTES: Int = 15
|
||||||
|
|
||||||
|
/** How far below a strip drag's timed block top the finger holds it, in minutes. */
|
||||||
|
private const val STRIP_GRAB_MINUTES = 15
|
||||||
|
|
||||||
/** How close to a timeline edge the finger must get before the view scrolls. */
|
/** How close to a timeline edge the finger must get before the view scrolls. */
|
||||||
private val AUTO_SCROLL_EDGE = 64.dp
|
private val AUTO_SCROLL_EDGE = 64.dp
|
||||||
|
|
||||||
@@ -125,6 +129,29 @@ data class TimelineDrag(
|
|||||||
val slot: Triple<LocalDate, Int, Int> get() = Triple(date, startMin, eventSpanMin)
|
val slot: Triple<LocalDate, Int, Int> get() = Triple(date, startMin, eventSpanMin)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An event lifted off the all-day strip: held over the strip it moves [dayShift]
|
||||||
|
* days and stays whole-day, held over the time grid it becomes a timed block.
|
||||||
|
*/
|
||||||
|
data class StripDrag(val event: EventInstance, val dayShift: Int = 0, val overGrid: Boolean = false)
|
||||||
|
|
||||||
|
/** Where a strip drag asks its event to go. */
|
||||||
|
sealed interface StripDrop {
|
||||||
|
val event: EventInstance
|
||||||
|
|
||||||
|
/** The drop's identity, which its held copy waits on. */
|
||||||
|
val token: Long
|
||||||
|
|
||||||
|
data class Days(override val event: EventInstance, val days: Int, override val token: Long) : StripDrop
|
||||||
|
|
||||||
|
data class Timed(
|
||||||
|
override val event: EventInstance,
|
||||||
|
val start: Instant,
|
||||||
|
val end: Instant,
|
||||||
|
override val token: Long,
|
||||||
|
) : StripDrop
|
||||||
|
}
|
||||||
|
|
||||||
/** The event a long press left selected (#141). */
|
/** The event a long press left selected (#141). */
|
||||||
data class TimelineSelection(
|
data class TimelineSelection(
|
||||||
val event: EventInstance,
|
val event: EventInstance,
|
||||||
@@ -248,9 +275,10 @@ internal fun dragPieceBounds(
|
|||||||
): DragPieceBounds {
|
): DragPieceBounds {
|
||||||
val top = if (slice.continuesBefore) 0f else insetPx
|
val top = if (slice.continuesBefore) 0f else insetPx
|
||||||
val bottom = if (slice.continuesAfter) 0f else insetPx
|
val bottom = if (slice.continuesAfter) 0f else insetPx
|
||||||
val full = maxOf(slice.spanMin / 60f * hourPx, MIN_EVENT_FRACTION * hourPx)
|
val span = renderedSpan(slice.startMin, slice.startMin + slice.spanMin, slice.continuesAfter)
|
||||||
|
val full = (span.bottomMin - span.topMin) / 60f * hourPx
|
||||||
return DragPieceBounds(
|
return DragPieceBounds(
|
||||||
top = slice.startMin / 60f * hourPx + top,
|
top = span.topMin / 60f * hourPx + top,
|
||||||
height = (full - top - bottom).coerceAtLeast(0f),
|
height = (full - top - bottom).coerceAtLeast(0f),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -277,7 +305,9 @@ data class TimelineDrop(
|
|||||||
val date: LocalDate,
|
val date: LocalDate,
|
||||||
val startMin: Int,
|
val startMin: Int,
|
||||||
/** Minutes from the event's start to the dragged block's top edge. */
|
/** Minutes from the event's start to the dragged block's top edge. */
|
||||||
val clipOffsetMin: Int = 0,
|
val clipOffsetMin: Int,
|
||||||
|
/** The drop's identity, which its held copy waits on. */
|
||||||
|
val token: Long,
|
||||||
)
|
)
|
||||||
|
|
||||||
/** The id a drafted block's stand-in event carries, which no provider row has (#153). */
|
/** The id a drafted block's stand-in event carries, which no provider row has (#153). */
|
||||||
@@ -308,19 +338,49 @@ internal fun draftStartMin(minutes: Float): Int =
|
|||||||
internal fun draftBlock(draft: EventInstance, date: LocalDate, zone: TimeZone): TimedBlock? {
|
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).
|
// 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.
|
// The end is exclusive, so a draft ending at midnight belongs to the day before.
|
||||||
|
val dayEnd = date.plus(1, DateTimeUnit.DAY).atStartOfDayIn(zone)
|
||||||
val start = maxOf(draft.start, date.atStartOfDayIn(zone))
|
val start = maxOf(draft.start, date.atStartOfDayIn(zone))
|
||||||
val end = minOf(draft.end, date.plus(1, DateTimeUnit.DAY).atStartOfDayIn(zone))
|
val end = minOf(draft.end, dayEnd)
|
||||||
if (end <= start) return null
|
if (end <= start) return null
|
||||||
val startMin = wallClockMinutes(start, date, zone)
|
val startMin = wallClockMinutes(start, date, zone)
|
||||||
val endMin = wallClockEndMinutes(startMin, start, end, date, zone).coerceAtMost(MINUTES_PER_DAY)
|
val endMin = wallClockEndMinutes(startMin, start, end, date, zone).coerceAtMost(MINUTES_PER_DAY)
|
||||||
return TimedBlock(draft, startMin, endMin, lane = 0, laneCount = 1)
|
return TimedBlock(draft, startMin, endMin, lane = 0, laneCount = 1, continuesAfter = draft.end > dayEnd)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Which end of an event a resize handle moves (#141). */
|
/** Which end of an event a resize handle moves (#141). */
|
||||||
enum class ResizeEdge { Top, Bottom }
|
enum class ResizeEdge { Top, Bottom }
|
||||||
|
|
||||||
|
/** A drop parked by a newer pickup while its write still runs — see [TimelineDragController.held]. */
|
||||||
|
data class HeldDrop(
|
||||||
|
val copy: TimelineDrag,
|
||||||
|
val token: Long,
|
||||||
|
val instanceId: Long,
|
||||||
|
/** The event row and start the drop came from, as [TimelineDragController.ghosts] matches them. */
|
||||||
|
val origin: Pair<Long, Instant>,
|
||||||
|
/** A resize's new end, which has to have landed too before the drop counts as seated. */
|
||||||
|
val end: Instant?,
|
||||||
|
/** Whether the grid now draws the drop at its landing slot. */
|
||||||
|
val seated: Boolean = false,
|
||||||
|
val handedOver: Boolean = false,
|
||||||
|
) {
|
||||||
|
fun ghosts(block: TimedBlock): Boolean = block.event.instanceId == instanceId ||
|
||||||
|
(block.event.eventId == origin.first && block.event.start == origin.second)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A strip drop parked by a newer one while its write still runs — see [TimelineDragController.heldStrips]. */
|
||||||
|
data class HeldStrip(val drag: StripDrag, val token: Long, val seated: Boolean = false)
|
||||||
|
|
||||||
|
/** An event's new start and end, as a resize leaves them. */
|
||||||
|
data class ResizedSpan(val start: Instant, val end: Instant)
|
||||||
|
|
||||||
/** Where a finished resize asks its event to begin and end. */
|
/** Where a finished resize asks its event to begin and end. */
|
||||||
data class TimelineResizeDrop(val event: EventInstance, val start: Instant, val end: Instant)
|
data class TimelineResizeDrop(
|
||||||
|
val event: EventInstance,
|
||||||
|
val start: Instant,
|
||||||
|
val end: Instant,
|
||||||
|
/** The drop's identity, which its held copy waits on. */
|
||||||
|
val token: Long,
|
||||||
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* [event] resized by its [edge] to the span [startMin]..+[spanMin] from [date]'s
|
* [event] resized by its [edge] to the span [startMin]..+[spanMin] from [date]'s
|
||||||
@@ -331,17 +391,16 @@ data class TimelineResizeDrop(val event: EventInstance, val start: Instant, val
|
|||||||
* it was drawn (see [repicked]). An end takes a pass the grid draws at the drop
|
* it was drawn (see [repicked]). An end takes a pass the grid draws at the drop
|
||||||
* point, so the block settles under the finger.
|
* point, so the block settles under the finger.
|
||||||
*/
|
*/
|
||||||
internal fun resizedDrop(
|
internal fun resizedSpan(
|
||||||
event: EventInstance,
|
event: EventInstance,
|
||||||
edge: ResizeEdge?,
|
edge: ResizeEdge?,
|
||||||
date: LocalDate,
|
date: LocalDate,
|
||||||
startMin: Int,
|
startMin: Int,
|
||||||
spanMin: Int,
|
spanMin: Int,
|
||||||
zone: TimeZone,
|
zone: TimeZone,
|
||||||
): TimelineResizeDrop {
|
): ResizedSpan {
|
||||||
val drawn = wallClockSpan(event, zone)
|
val drawn = wallClockSpan(event, zone)
|
||||||
return TimelineResizeDrop(
|
return ResizedSpan(
|
||||||
event = event,
|
|
||||||
start = if (edge == ResizeEdge.Top) {
|
start = if (edge == ResizeEdge.Top) {
|
||||||
event.start.toFormTime(zone).repicked(
|
event.start.toFormTime(zone).repicked(
|
||||||
wallClockTime(date, startMin),
|
wallClockTime(date, startMin),
|
||||||
@@ -389,17 +448,20 @@ internal fun resizedSpan(
|
|||||||
}
|
}
|
||||||
if (wrongWay) return startMin to endMin
|
if (wrongWay) return startMin to endMin
|
||||||
}
|
}
|
||||||
val snapped = (edgeMin / DRAG_SNAP_MINUTES).roundToInt() * DRAG_SNAP_MINUTES
|
val snapped = snapToSlot(edgeMin)
|
||||||
return when (edge) {
|
return when (edge) {
|
||||||
ResizeEdge.Top -> minOf(snapped, endMin - DRAG_SNAP_MINUTES) to endMin
|
ResizeEdge.Top -> minOf(snapped, endMin - DRAG_SNAP_MINUTES) to endMin
|
||||||
ResizeEdge.Bottom -> startMin to maxOf(snapped, startMin + DRAG_SNAP_MINUTES)
|
ResizeEdge.Bottom -> startMin to maxOf(snapped, startMin + DRAG_SNAP_MINUTES)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** [minutes] rounded to the nearest [DRAG_SNAP_MINUTES] slot. */
|
||||||
|
internal fun snapToSlot(minutes: Float): Int = (minutes / DRAG_SNAP_MINUTES).roundToInt() * DRAG_SNAP_MINUTES
|
||||||
|
|
||||||
/** [minutes] snapped, kept at [held] until three quarters of a step away. */
|
/** [minutes] snapped, kept at [held] until three quarters of a step away. */
|
||||||
internal fun stickySnap(minutes: Float, held: Int?): Int {
|
internal fun stickySnap(minutes: Float, held: Int?): Int {
|
||||||
if (held != null && kotlin.math.abs(minutes - held) < DRAG_SNAP_MINUTES * 0.75f) return held
|
if (held != null && kotlin.math.abs(minutes - held) < DRAG_SNAP_MINUTES * 0.75f) return held
|
||||||
return (minutes / DRAG_SNAP_MINUTES).roundToInt() * DRAG_SNAP_MINUTES
|
return snapToSlot(minutes)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** How far past its column's side the finger has to go before a resize changes day. */
|
/** How far past its column's side the finger has to go before a resize changes day. */
|
||||||
@@ -467,6 +529,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
|
||||||
@@ -485,6 +551,14 @@ class TimelineDragController {
|
|||||||
*/
|
*/
|
||||||
private var settledOrigin: Pair<Long, Instant>? by mutableStateOf(null)
|
private var settledOrigin: Pair<Long, Instant>? by mutableStateOf(null)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Earlier drops still being written when another block was picked up. They
|
||||||
|
* keep their copy and their ghost until their own token settles, rather than
|
||||||
|
* vanishing and flashing back at the old slot (#494).
|
||||||
|
*/
|
||||||
|
var held: List<HeldDrop> by mutableStateOf(emptyList())
|
||||||
|
private set
|
||||||
|
|
||||||
/** How long a block drafted on an empty slot starts out, in minutes (#153). */
|
/** How long a block drafted on an empty slot starts out, in minutes (#153). */
|
||||||
var draftMinutes: Int = SettingsPrefs.DEFAULT_EVENT_DURATION
|
var draftMinutes: Int = SettingsPrefs.DEFAULT_EVENT_DURATION
|
||||||
|
|
||||||
@@ -583,14 +657,8 @@ class TimelineDragController {
|
|||||||
var settlingSelected: Boolean = false
|
var settlingSelected: Boolean = false
|
||||||
private set
|
private set
|
||||||
|
|
||||||
/**
|
/** The token of the drop [settling] waits on. */
|
||||||
* The abandoned-move counter, read at the drop so the mark can't be a
|
var settledToken: Long = 0L
|
||||||
* composition behind the tick it is compared against.
|
|
||||||
*/
|
|
||||||
var abandonedTicks: StateFlow<Int>? = null
|
|
||||||
|
|
||||||
/** What [abandonedTicks] stood at when the settling drop was let go. */
|
|
||||||
var settledAbandonedMark: Int = 0
|
|
||||||
private set
|
private set
|
||||||
|
|
||||||
private var source: TimedBlock? = null
|
private var source: TimedBlock? = null
|
||||||
@@ -618,25 +686,34 @@ class TimelineDragController {
|
|||||||
*/
|
*/
|
||||||
private var originSlot: Triple<LocalDate, Int, Int>? = null
|
private var originSlot: Triple<LocalDate, Int, Int>? = null
|
||||||
|
|
||||||
/** The edge a resize is dragging, or null for a plain drag (#141). */
|
/** The resize in progress, or null for a plain drag (#141). */
|
||||||
private var resizeEdge: ResizeEdge? = null
|
private var resize: ResizeSession? = null
|
||||||
|
|
||||||
/** The day the resized event starts on; its edges are minutes from that midnight. */
|
/** The strip drag in progress; over the grid it drives [drag] through a timed stand-in. */
|
||||||
private var resizeDay: LocalDate? = null
|
var stripDrag: StripDrag? by mutableStateOf(null)
|
||||||
private var resizeStartMin = 0
|
private set
|
||||||
private var resizeEndMin = 0
|
|
||||||
|
|
||||||
/** How far the finger sits past the edge it grabbed, so the edge doesn't jump to it. */
|
/** A strip drop held at its new days until the strip redraws the event there. */
|
||||||
private var resizeGrabMin = 0f
|
var stripSettling: StripDrag? by mutableStateOf(null)
|
||||||
|
private set
|
||||||
|
|
||||||
/** The column the resized edge is in, held until the finger is well into another. */
|
/** Whether the strip now draws [stripSettling] at its new days itself. */
|
||||||
private var resizeColumn: Int? = null
|
var stripSeated: Boolean by mutableStateOf(false)
|
||||||
|
private set
|
||||||
|
|
||||||
/** The slot the resized edge sits on, held against a finger trembling between two. */
|
/** Strip drops parked by a newer strip drop while their writes still run (#494). */
|
||||||
private var resizeSlot: Int? = null
|
var heldStrips: List<HeldStrip> by mutableStateOf(emptyList())
|
||||||
|
private set
|
||||||
|
|
||||||
/** The day, counted from the event's start day, the finger is resizing in. */
|
/** The token of the drop [stripSettling] waits on. */
|
||||||
private var resizeEdgeDay = 0
|
var stripToken: Long = 0L
|
||||||
|
private set
|
||||||
|
|
||||||
|
/** The shown day the finger picked the strip bar up on. */
|
||||||
|
private var stripGrabIndex = 0
|
||||||
|
|
||||||
|
/** Whether a strip drag over the grid has cleared its top edge, and may now scroll up. */
|
||||||
|
private var stripScrollArmed = false
|
||||||
|
|
||||||
fun begin(
|
fun begin(
|
||||||
block: TimedBlock,
|
block: TimedBlock,
|
||||||
@@ -654,7 +731,7 @@ class TimelineDragController {
|
|||||||
dragDuration = (block.event.end - block.event.start).coerceAtLeast(Duration.ZERO)
|
dragDuration = (block.event.end - block.event.start).coerceAtLeast(Duration.ZERO)
|
||||||
dragKept = zone.repeatedHourOffsetAt(block.event.start)
|
dragKept = zone.repeatedHourOffsetAt(block.event.start)
|
||||||
this.titleLines = titleLines
|
this.titleLines = titleLines
|
||||||
settling = null
|
parkSettling()
|
||||||
isDragging = true
|
isDragging = true
|
||||||
liftedInstanceId = block.event.instanceId
|
liftedInstanceId = block.event.instanceId
|
||||||
grab = pointerInRoot - blockInRoot
|
grab = pointerInRoot - blockInRoot
|
||||||
@@ -676,6 +753,86 @@ class TimelineDragController {
|
|||||||
begin(block, clipOffsetMin = 0, zone, titleLines = 1, pointerInRoot = pointerInRoot, blockInRoot = blockInRoot)
|
begin(block, clipOffsetMin = 0, zone, titleLines = 1, pointerInRoot = pointerInRoot, blockInRoot = blockInRoot)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lift [event] off the all-day strip. Over the time grid it is dragged as a
|
||||||
|
* block [draftMinutes] long, whose top sits a little above the finger.
|
||||||
|
*/
|
||||||
|
fun beginStrip(event: EventInstance, zone: TimeZone, pointerInRoot: Offset) {
|
||||||
|
val grid = geometry.grid?.takeIf { it.isAttached } ?: return
|
||||||
|
if (geometry.columnWidthPx <= 0f || geometry.days.isEmpty()) return
|
||||||
|
deselect()
|
||||||
|
if (stripSettling?.event?.instanceId == event.instanceId) releaseStrip()
|
||||||
|
stripScrollArmed = false
|
||||||
|
val timed = event.copy(isAllDay = false, end = event.start + draftMinutes.minutes)
|
||||||
|
source = TimedBlock(timed, 0, draftMinutes, lane = 0, laneCount = 1)
|
||||||
|
clipOffsetMin = 0
|
||||||
|
dragZone = zone
|
||||||
|
dragDuration = draftMinutes.minutes
|
||||||
|
dragKept = null
|
||||||
|
titleLines = 1
|
||||||
|
parkSettling()
|
||||||
|
isDragging = true
|
||||||
|
liftedInstanceId = event.instanceId
|
||||||
|
grab = Offset(0f, geometry.hourPx * STRIP_GRAB_MINUTES / 60f)
|
||||||
|
pointer = pointerInRoot
|
||||||
|
pickupPointer = pointerInRoot
|
||||||
|
pointerMoved = false
|
||||||
|
originSlot = null
|
||||||
|
stripGrabIndex = dayIndexAt(pointerInRoot.x, grid.positionInRoot().x)
|
||||||
|
stripDrag = StripDrag(event)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The shown day under [x], clamped to the days on screen. */
|
||||||
|
private fun dayIndexAt(x: Float, originX: Float): Int =
|
||||||
|
column(((x - originX) / geometry.columnWidthPx).toInt().coerceIn(0, geometry.days.lastIndex))
|
||||||
|
|
||||||
|
/** End a strip drag, handing back where it landed — null when it went nowhere. */
|
||||||
|
fun finishStrip(): StripDrop? {
|
||||||
|
val held = stripDrag ?: return null
|
||||||
|
val landed = drag
|
||||||
|
val zone = dragZone
|
||||||
|
cancel()
|
||||||
|
if (held.overGrid && landed != null && zone != null && !landed.edgeOnly) {
|
||||||
|
val token = settle(landed)
|
||||||
|
val start = dropStartInstant(landed.event, landed.date, landed.startMin, clipOffsetMin = 0, zone)
|
||||||
|
return StripDrop.Timed(held.event, start, start + draftMinutes.minutes, token)
|
||||||
|
}
|
||||||
|
if (held.overGrid || held.dayShift == 0) return null
|
||||||
|
// One still settling keeps its place on the strip until its own write lands (#494).
|
||||||
|
stripSettling?.let { heldStrips = heldStrips + HeldStrip(it, stripToken, stripSeated) }
|
||||||
|
stripSettling = held
|
||||||
|
stripSeated = false
|
||||||
|
stripToken = nextMoveToken()
|
||||||
|
drops++
|
||||||
|
return StripDrop.Days(held.event, held.dayShift, stripToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Let the held strip drop go, once the strip shows the event at its new days or the move failed. */
|
||||||
|
fun releaseStrip() {
|
||||||
|
stripSettling = null
|
||||||
|
stripSeated = false
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Note that the strip draws the settling drop at its new days. */
|
||||||
|
fun seatStrip() {
|
||||||
|
if (stripSettling != null) stripSeated = true
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Note that the strip draws the parked strip drop [token] at its new days. */
|
||||||
|
fun seatHeldStrip(token: Long) {
|
||||||
|
if (heldStrips.any { it.token == token && !it.seated }) {
|
||||||
|
heldStrips = heldStrips.map { if (it.token == token) it.copy(seated = true) else it }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Let the parked strip drop [token] go. */
|
||||||
|
fun releaseHeldStrip(token: Long) {
|
||||||
|
heldStrips = heldStrips.filterNot { it.token == token }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every strip drop still shown at its new days: the parked ones, then the latest. */
|
||||||
|
fun stripPreviews(): List<StripDrag> = heldStrips.map { it.drag } + listOfNotNull(stripDrag ?: stripSettling)
|
||||||
|
|
||||||
fun move(pointerInRoot: Offset) {
|
fun move(pointerInRoot: Offset) {
|
||||||
pointer = pointerInRoot
|
pointer = pointerInRoot
|
||||||
if (!pointerMoved && (pointerInRoot - pickupPointer).getDistance() > slopPx) pointerMoved = true
|
if (!pointerMoved && (pointerInRoot - pickupPointer).getDistance() > slopPx) pointerMoved = true
|
||||||
@@ -683,10 +840,8 @@ class TimelineDragController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun cancel() {
|
fun cancel() {
|
||||||
resizeEdge = null
|
resize = null
|
||||||
resizeDay = null
|
stripDrag = null
|
||||||
resizeColumn = null
|
|
||||||
resizeSlot = null
|
|
||||||
source = null
|
source = null
|
||||||
clipOffsetMin = 0
|
clipOffsetMin = 0
|
||||||
dragZone = null
|
dragZone = null
|
||||||
@@ -712,12 +867,36 @@ class TimelineDragController {
|
|||||||
* an event that crosses midnight (#253).
|
* an event that crosses midnight (#253).
|
||||||
*/
|
*/
|
||||||
fun ghosts(block: TimedBlock): Boolean {
|
fun ghosts(block: TimedBlock): Boolean {
|
||||||
|
if (held.any { !it.handedOver && it.ghosts(block) }) return true
|
||||||
if (liftedInstanceId == null) return false
|
if (liftedInstanceId == null) return false
|
||||||
if (block.event.instanceId == liftedInstanceId) return true
|
if (block.event.instanceId == liftedInstanceId) return true
|
||||||
val (eventId, start) = settledOrigin ?: return false
|
val (eventId, start) = settledOrigin ?: return false
|
||||||
return block.event.eventId == eventId && block.event.start == start
|
return block.event.eventId == eventId && block.event.start == start
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Move a still-settling drop to [held] before a new pickup takes the slot. */
|
||||||
|
private fun parkSettling() {
|
||||||
|
val landed = settling
|
||||||
|
val origin = settledOrigin
|
||||||
|
if (landed != null && origin != null && !landed.event.isDraft) {
|
||||||
|
held = held + HeldDrop(landed, settledToken, landed.event.instanceId, origin, settledEnd, settledOnGrid)
|
||||||
|
}
|
||||||
|
settling = null
|
||||||
|
settledOnGrid = false
|
||||||
|
settledOrigin = null
|
||||||
|
settledEnd = null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stop ghosting the held drop [token]'s source while its copy fades. */
|
||||||
|
fun handOverHeld(token: Long) {
|
||||||
|
held = held.map { if (it.token == token) it.copy(handedOver = true) else it }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Drop the held copy [token] once it has faded. */
|
||||||
|
fun releaseHeld(token: Long) {
|
||||||
|
held = held.filterNot { it.token == token }
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* What a day column now holds, so a settled drop can tell when the grid has
|
* What a day column now holds, so a settled drop can tell when the grid has
|
||||||
* caught up with it. Matched on the landing slot plus either the event row
|
* caught up with it. Matched on the landing slot plus either the event row
|
||||||
@@ -725,16 +904,23 @@ class TimelineDragController {
|
|||||||
* blank title matches nothing: every untitled event has one (#253).
|
* blank title matches nothing: every untitled event has one (#253).
|
||||||
*/
|
*/
|
||||||
fun noteGrid(date: LocalDate, blocks: List<TimedBlock>) {
|
fun noteGrid(date: LocalDate, blocks: List<TimedBlock>) {
|
||||||
|
if (held.any { !it.seated && drawsDrop(it.copy, it.end, date, blocks) }) {
|
||||||
|
held = held.map { if (!it.seated && drawsDrop(it.copy, it.end, date, blocks)) it.copy(seated = true) else it }
|
||||||
|
}
|
||||||
val landed = settling ?: return
|
val landed = settling ?: return
|
||||||
if (settledOnGrid) return
|
if (settledOnGrid) return
|
||||||
|
settledOnGrid = drawsDrop(landed, settledEnd, date, blocks)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether [blocks], [date]'s column, draws the drop [landed] where it landed. */
|
||||||
|
private fun drawsDrop(landed: TimelineDrag, end: Instant?, date: LocalDate, blocks: List<TimedBlock>): Boolean {
|
||||||
// Where this day would draw it, which for a drop clipped at midnight is
|
// Where this day would draw it, which for a drop clipped at midnight is
|
||||||
// the day's own start rather than the edge the finger held (#253) — and
|
// the day's own start rather than the edge the finger held (#253) — and
|
||||||
// which for a tail dragged clear of its day is the day before it.
|
// which for a tail dragged clear of its day is the day before it.
|
||||||
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 false
|
||||||
val end = settledEnd
|
return 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.
|
// A resize may keep its start, so its end has to have landed too.
|
||||||
(end == null || block.event.end == end) &&
|
(end == null || block.event.end == end) &&
|
||||||
@@ -761,16 +947,31 @@ class TimelineDragController {
|
|||||||
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).
|
// 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
|
if (landed.edgeOnly && landed.event.isDraft) return null
|
||||||
|
val token = settle(landed)
|
||||||
|
return TimelineDrop(landed.event, landed.date, landed.startMin, clipOffset, token)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keep [landed]'s copy on the target as [settling] until [release]; [end] is a
|
||||||
|
* resize's. Returns the drop's fresh token.
|
||||||
|
*/
|
||||||
|
private fun settle(landed: TimelineDrag, end: Instant? = null): Long {
|
||||||
|
// Landed on midnight to midnight, the event moves to the all-day strip (#296).
|
||||||
|
val leavesGrid = !landed.event.isDraft && landed.eventSpanMin > 0 &&
|
||||||
|
landed.eventStartMin.mod(MINUTES_PER_DAY) == 0 &&
|
||||||
|
landed.eventSpanMin % MINUTES_PER_DAY == 0
|
||||||
settlingSelected = selection?.event?.instanceId == landed.event.instanceId
|
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
|
||||||
// the whole settle timeout, long after the event moved off-screen.
|
// the whole settle timeout, long after the event moved off-screen.
|
||||||
settling = if (landed.edgeOnly) landed.copy(pieces = emptyList()) else landed
|
settling = if (landed.edgeOnly || leavesGrid) landed.copy(pieces = emptyList()) else landed
|
||||||
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
|
settledToken = nextMoveToken()
|
||||||
return TimelineDrop(landed.event, landed.date, landed.startMin, clipOffset)
|
settledEnd = end
|
||||||
|
drops++
|
||||||
|
return settledToken
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -785,30 +986,49 @@ class TimelineDragController {
|
|||||||
pointerInRoot: Offset,
|
pointerInRoot: Offset,
|
||||||
) {
|
) {
|
||||||
val span = wallClockSpan(block.event, zone)
|
val span = wallClockSpan(block.event, zone)
|
||||||
|
val session = ResizeSession(edge, span.day, span.startMin, span.endMin)
|
||||||
source = block
|
source = block
|
||||||
resizeEdge = edge
|
resize = session
|
||||||
resizeDay = span.day
|
|
||||||
resizeStartMin = span.startMin
|
|
||||||
resizeEndMin = span.endMin
|
|
||||||
clipOffsetMin = 0
|
clipOffsetMin = 0
|
||||||
this.titleLines = titleLines
|
this.titleLines = titleLines
|
||||||
settling = null
|
parkSettling()
|
||||||
isDragging = true
|
isDragging = true
|
||||||
pointerMoved = true
|
pointerMoved = true
|
||||||
liftedInstanceId = block.event.instanceId
|
liftedInstanceId = block.event.instanceId
|
||||||
pointer = pointerInRoot
|
pointer = pointerInRoot
|
||||||
// Measured from the edge's own column: the handle overhangs into the next.
|
// 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 edgeDay = if (edge == ResizeEdge.Top) 0 else (session.endMin - 1).floorDiv(MINUTES_PER_DAY).coerceAtLeast(0)
|
||||||
val edgeIndex = geometry.days.indexOf(span.day.plus(edgeDay, DateTimeUnit.DAY))
|
val edgeIndex = geometry.days.indexOf(span.day.plus(edgeDay, DateTimeUnit.DAY))
|
||||||
resizeColumn = edgeIndex.takeIf { it >= 0 }
|
session.column = edgeIndex.takeIf { it >= 0 }
|
||||||
?.let { if (geometry.isRtl) geometry.days.lastIndex - it else it }
|
?.let { column(it) }
|
||||||
resizeGrabMin = (pointerResizeMinutes() ?: 0f) -
|
// The top handle sits on the drawn top, which a short block near midnight lifts (#483).
|
||||||
if (edge == ResizeEdge.Top) resizeStartMin else resizeEndMin
|
val lift = if (edge == ResizeEdge.Top) block.startMin - block.renderedSpan().topMin else 0f
|
||||||
|
session.grabMin = (pointerResizeMinutes(session) ?: 0f) + lift -
|
||||||
|
if (edge == ResizeEdge.Top) session.startMin else session.endMin
|
||||||
originSlot = null
|
originSlot = null
|
||||||
recompute()
|
recompute()
|
||||||
originSlot = drag?.slot
|
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 = resize?.edge
|
||||||
|
if (edge != null) {
|
||||||
|
val drop = resizedSpan(event, edge, date, startMin, spanMin, zone)
|
||||||
|
return event.copy(start = drop.start, end = drop.end)
|
||||||
|
}
|
||||||
|
val start = dropStartInstant(event, date, startMin, clipOffsetMin, zone)
|
||||||
|
return event.copy(start = start, end = start + dragDuration)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* End a resize, handing back the event's new span — null when it never
|
* 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.
|
* resolved or came back to the length it started at. Settles as [finish] does.
|
||||||
@@ -816,53 +1036,46 @@ class TimelineDragController {
|
|||||||
fun finishResize(zone: TimeZone): TimelineResizeDrop? {
|
fun finishResize(zone: TimeZone): TimelineResizeDrop? {
|
||||||
val landed = drag
|
val landed = drag
|
||||||
val origin = originSlot
|
val origin = originSlot
|
||||||
val edge = resizeEdge
|
val edge = resize?.edge
|
||||||
cancel()
|
cancel()
|
||||||
if (landed == null || landed.slot == origin) return null
|
if (landed == null || landed.slot == origin) return null
|
||||||
val drop = resizedDrop(landed.event, edge, landed.date, landed.eventStartMin, landed.eventSpanMin, zone)
|
val span = resizedSpan(landed.event, edge, landed.date, landed.eventStartMin, landed.eventSpanMin, zone)
|
||||||
settlingSelected = selection?.event?.instanceId == landed.event.instanceId
|
return TimelineResizeDrop(landed.event, span.start, span.end, settle(landed, end = span.end))
|
||||||
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
|
|
||||||
return drop
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Where the finger is, in minutes from the resized event's start day —
|
* Where the finger is, in minutes from the resized event's start day —
|
||||||
* past 1440 in a later column, negative in an earlier one.
|
* past 1440 in a later column, negative in an earlier one.
|
||||||
*/
|
*/
|
||||||
private fun pointerResizeMinutes(): Float? {
|
private fun pointerResizeMinutes(session: ResizeSession): Float? {
|
||||||
val grid = geometry.grid?.takeIf { it.isAttached } ?: return null
|
val grid = geometry.grid?.takeIf { it.isAttached } ?: return null
|
||||||
val day = resizeDay ?: return null
|
|
||||||
val hourPx = geometry.hourPx
|
val hourPx = geometry.hourPx
|
||||||
val columnPx = geometry.columnWidthPx
|
val columnPx = geometry.columnWidthPx
|
||||||
val days = geometry.days
|
val days = geometry.days
|
||||||
if (hourPx <= 0f || columnPx <= 0f || days.isEmpty()) return null
|
if (hourPx <= 0f || columnPx <= 0f || days.isEmpty()) return null
|
||||||
val origin = grid.positionInRoot()
|
val origin = grid.positionInRoot()
|
||||||
val column = stickyColumn(
|
val held = stickyColumn(
|
||||||
position = (pointer.x - origin.x) / columnPx,
|
position = (pointer.x - origin.x) / columnPx,
|
||||||
held = resizeColumn,
|
held = session.column,
|
||||||
lastIndex = days.lastIndex,
|
lastIndex = days.lastIndex,
|
||||||
)
|
)
|
||||||
resizeColumn = column
|
session.column = held
|
||||||
val dayIndex = if (geometry.isRtl) days.lastIndex - column else column
|
val dayOffset = (days[column(held)].toEpochDays() - session.day.toEpochDays()).toInt()
|
||||||
val dayOffset = (days[dayIndex].toEpochDays() - day.toEpochDays()).toInt()
|
session.edgeDay = dayOffset
|
||||||
resizeEdgeDay = dayOffset
|
// Held to its column's midnight: the clearance under it is not the next day.
|
||||||
return dayOffset * MINUTES_PER_DAY + (pointer.y - origin.y) / hourPx * 60f
|
val minutes = ((pointer.y - origin.y) / hourPx * 60f).coerceAtMost(MINUTES_PER_DAY.toFloat())
|
||||||
|
return dayOffset * MINUTES_PER_DAY + minutes
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun recomputeResize(edge: ResizeEdge) {
|
private fun recomputeResize(session: ResizeSession) {
|
||||||
val block = source ?: return
|
val block = source ?: return
|
||||||
val day = resizeDay ?: return
|
val edge = session.edge
|
||||||
val raw = pointerResizeMinutes() ?: return
|
val day = session.day
|
||||||
val slot = stickySnap(raw - resizeGrabMin, resizeSlot)
|
val raw = pointerResizeMinutes(session) ?: return
|
||||||
resizeSlot = slot
|
val slot = stickySnap(raw - session.grabMin, session.slot)
|
||||||
val (start, end) = resizedSpan(edge, resizeStartMin, resizeEndMin, slot.toFloat(), resizeEdgeDay)
|
session.slot = slot
|
||||||
|
val (start, end) = resizedSpan(edge, session.startMin, session.endMin, slot.toFloat(), session.edgeDay)
|
||||||
val days = geometry.days
|
val days = geometry.days
|
||||||
val hourPx = geometry.hourPx
|
|
||||||
val columnPx = geometry.columnWidthPx
|
|
||||||
val origin = geometry.grid?.takeIf { it.isAttached }?.positionInRoot() ?: return
|
val origin = geometry.grid?.takeIf { it.isAttached }?.positionInRoot() ?: return
|
||||||
// Which column the start day sits in, possibly off either end of the view.
|
// Which column the start day sits in, possibly off either end of the view.
|
||||||
val startIndex = (day.toEpochDays() - days.first().toEpochDays()).toInt()
|
val startIndex = (day.toEpochDays() - days.first().toEpochDays()).toInt()
|
||||||
@@ -875,20 +1088,7 @@ class TimelineDragController {
|
|||||||
eventStartMin = start,
|
eventStartMin = start,
|
||||||
eventSpanMin = end - start,
|
eventSpanMin = end - start,
|
||||||
titleLines = titleLines,
|
titleLines = titleLines,
|
||||||
pieces = slices.map { slice ->
|
pieces = pieces(slices, startIndex, origin),
|
||||||
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(),
|
edgeOnly = slices.isEmpty(),
|
||||||
markerMin = if (edge == ResizeEdge.Top) {
|
markerMin = if (edge == ResizeEdge.Top) {
|
||||||
start.mod(MINUTES_PER_DAY)
|
start.mod(MINUTES_PER_DAY)
|
||||||
@@ -933,10 +1133,33 @@ 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 {
|
resize?.let {
|
||||||
recomputeResize(it)
|
recomputeResize(it)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
stripDrag?.let {
|
||||||
|
recomputeStrip(it)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
recomputeDrag()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Over the strip the bar moves by whole days; past its bottom edge it is a timed block. */
|
||||||
|
private fun recomputeStrip(held: StripDrag) {
|
||||||
|
val grid = geometry.grid?.takeIf { it.isAttached } ?: return
|
||||||
|
val viewport = geometry.viewport?.takeIf { it.isAttached } ?: return
|
||||||
|
if (geometry.columnWidthPx <= 0f || geometry.days.isEmpty()) return
|
||||||
|
if (pointer.y >= viewport.boundsInRoot().top) {
|
||||||
|
stripDrag = held.copy(overGrid = true)
|
||||||
|
recomputeDrag()
|
||||||
|
} else {
|
||||||
|
drag = null
|
||||||
|
val shift = dayIndexAt(pointer.x, grid.positionInRoot().x) - stripGrabIndex
|
||||||
|
stripDrag = held.copy(dayShift = shift, overGrid = false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun recomputeDrag() {
|
||||||
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
|
||||||
@@ -946,10 +1169,9 @@ 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 = snapToSlot(rawMinutes)
|
||||||
val zone = dragZone ?: return
|
val zone = dragZone ?: return
|
||||||
val column = ((pointer.x - origin.x) / columnPx).toInt().coerceIn(0, days.lastIndex)
|
val dayIndex = column(((pointer.x - origin.x) / columnPx).toInt().coerceIn(0, days.lastIndex))
|
||||||
val dayIndex = if (geometry.isRtl) days.lastIndex - column else column
|
|
||||||
val target = days[dayIndex]
|
val target = days[dayIndex]
|
||||||
val keep = dragKept
|
val keep = dragKept
|
||||||
// Measured where it would land: the drop keeps the real duration, which in
|
// Measured where it would land: the drop keeps the real duration, which in
|
||||||
@@ -977,28 +1199,34 @@ class TimelineDragController {
|
|||||||
titleLines = titleLines,
|
titleLines = titleLines,
|
||||||
// Bounded to the columns this timeline actually shows: a day it
|
// Bounded to the columns this timeline actually shows: a day it
|
||||||
// doesn't has no piece to draw. The write is unaffected.
|
// doesn't has no piece to draw. The write is unaffected.
|
||||||
pieces = slices
|
pieces = pieces(slices, dayIndex, origin),
|
||||||
.map { slice ->
|
|
||||||
val day = dayIndex + slice.dayOffset
|
|
||||||
val col = if (geometry.isRtl) days.lastIndex - day else day
|
|
||||||
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 = onGrid.isEmpty(),
|
edgeOnly = onGrid.isEmpty(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** [slices] as floating pieces, the first slice's day being [dayIndex] in the shown days. */
|
||||||
|
private fun pieces(slices: List<DragSlice>, dayIndex: Int, origin: Offset): List<TimelineDragPiece> {
|
||||||
|
val columnPx = geometry.columnWidthPx
|
||||||
|
return slices.map { slice ->
|
||||||
|
val bounds = dragPieceBounds(slice, geometry.hourPx, geometry.blockInsetPx)
|
||||||
|
TimelineDragPiece(
|
||||||
|
topLeftInRoot = Offset(
|
||||||
|
x = origin.x + column(dayIndex + slice.dayOffset) * columnPx,
|
||||||
|
y = origin.y + bounds.top,
|
||||||
|
),
|
||||||
|
sizePx = IntSize(
|
||||||
|
(columnPx - geometry.columnGapPx).roundToInt(),
|
||||||
|
bounds.height.roundToInt(),
|
||||||
|
),
|
||||||
|
continuesBefore = slice.continuesBefore,
|
||||||
|
continuesAfter = slice.continuesAfter,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The on-screen column of a day index, and back: right-to-left lays the days out mirrored. */
|
||||||
|
private fun column(index: Int): Int = if (geometry.isRtl) geometry.days.lastIndex - index else index
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Hold the scroll for the whole drag and nudge it once per frame while the
|
* Hold the scroll for the whole drag and nudge it once per frame while the
|
||||||
* finger sits near an edge. One `scroll` call, since a loop of
|
* finger sits near an edge. One `scroll` call, since a loop of
|
||||||
@@ -1017,11 +1245,18 @@ class TimelineDragController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun edgeStep(): Float {
|
private fun edgeStep(): Float {
|
||||||
|
val strip = stripDrag
|
||||||
|
if (strip?.overGrid == false) return 0f
|
||||||
val viewport = geometry.viewport?.takeIf { it.isAttached } ?: return 0f
|
val viewport = geometry.viewport?.takeIf { it.isAttached } ?: return 0f
|
||||||
val edge = geometry.edgePx
|
val edge = geometry.edgePx
|
||||||
if (edge <= 0f) return 0f
|
if (edge <= 0f) return 0f
|
||||||
val bounds = viewport.boundsInRoot()
|
val bounds = viewport.boundsInRoot()
|
||||||
val fromTop = pointer.y - bounds.top
|
val fromTop = pointer.y - bounds.top
|
||||||
|
// Coming down out of the strip the finger starts inside the top edge.
|
||||||
|
if (strip != null && !stripScrollArmed) {
|
||||||
|
if (fromTop < edge) return 0f
|
||||||
|
stripScrollArmed = true
|
||||||
|
}
|
||||||
val fromBottom = bounds.bottom - pointer.y
|
val fromBottom = bounds.bottom - pointer.y
|
||||||
return when {
|
return when {
|
||||||
fromTop < edge -> -(edge - fromTop) / edge * geometry.stepPx
|
fromTop < edge -> -(edge - fromTop) / edge * geometry.stepPx
|
||||||
@@ -1031,6 +1266,27 @@ class TimelineDragController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** One resize gesture (#141): the edge it drags, and the edges as minutes from [day]'s midnight. */
|
||||||
|
private class ResizeSession(
|
||||||
|
val edge: ResizeEdge,
|
||||||
|
/** The day the resized event starts on. */
|
||||||
|
val day: LocalDate,
|
||||||
|
val startMin: Int,
|
||||||
|
val endMin: Int,
|
||||||
|
) {
|
||||||
|
/** How far the finger sits past the edge it grabbed, so the edge doesn't jump to it. */
|
||||||
|
var grabMin = 0f
|
||||||
|
|
||||||
|
/** The column the resized edge is in, held until the finger is well into another. */
|
||||||
|
var column: Int? = null
|
||||||
|
|
||||||
|
/** The slot the resized edge sits on, held against a finger trembling between two. */
|
||||||
|
var slot: Int? = null
|
||||||
|
|
||||||
|
/** The day, counted from the event's start day, the finger is resizing in. */
|
||||||
|
var edgeDay = 0
|
||||||
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun rememberTimelineDragController(): TimelineDragController {
|
fun rememberTimelineDragController(): TimelineDragController {
|
||||||
val controller = remember { TimelineDragController() }
|
val controller = remember { TimelineDragController() }
|
||||||
@@ -1038,7 +1294,6 @@ fun rememberTimelineDragController(): TimelineDragController {
|
|||||||
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.slopPx = LocalViewConfiguration.current.touchSlop
|
||||||
controller.abandonedTicks = LocalEventMove.current?.abandoned
|
|
||||||
return controller
|
return controller
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1060,10 +1315,6 @@ fun TimedBlock.clipOffsetMinutes(day: LocalDate, zone: TimeZone): Int {
|
|||||||
fun TimedBlock.continuesBefore(day: LocalDate, zone: TimeZone): Boolean =
|
fun TimedBlock.continuesBefore(day: LocalDate, zone: TimeZone): Boolean =
|
||||||
event.start < day.atStartOfDayIn(zone)
|
event.start < day.atStartOfDayIn(zone)
|
||||||
|
|
||||||
/** True when the event runs past [day]'s midnight, so this block is cut there. */
|
|
||||||
fun TimedBlock.continuesAfter(day: LocalDate, zone: TimeZone): Boolean =
|
|
||||||
event.end > day.plus(1, DateTimeUnit.DAY).atStartOfDayIn(zone)
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The instant a drop asks for — the *event's* new start, so the tail of an
|
* The instant a drop asks for — the *event's* new start, so the tail of an
|
||||||
* overnight event drops back onto the day its own start belongs to. Read in the
|
* overnight event drops back onto the day its own start belongs to. Read in the
|
||||||
@@ -1072,7 +1323,16 @@ fun TimedBlock.continuesAfter(day: LocalDate, zone: TimeZone): Boolean =
|
|||||||
* visibly settles there.
|
* visibly settles there.
|
||||||
*/
|
*/
|
||||||
fun TimelineDrop.startInstant(zone: TimeZone): Instant =
|
fun TimelineDrop.startInstant(zone: TimeZone): Instant =
|
||||||
wallClockInstant(date, startMin - clipOffsetMin, zone, kept = zone.repeatedHourOffsetAt(event.start))
|
dropStartInstant(event, date, startMin, clipOffsetMin, zone)
|
||||||
|
|
||||||
|
/** Where [event] starts when its block's top edge lands [startMin] past [date]'s midnight — see [TimelineDrop]. */
|
||||||
|
internal fun dropStartInstant(
|
||||||
|
event: EventInstance,
|
||||||
|
date: LocalDate,
|
||||||
|
startMin: Int,
|
||||||
|
clipOffsetMin: Int,
|
||||||
|
zone: TimeZone,
|
||||||
|
): Instant = wallClockInstant(date, startMin - clipOffsetMin, zone, kept = zone.repeatedHourOffsetAt(event.start))
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The wall-clock minutes an event lasting [duration] covers when it starts
|
* The wall-clock minutes an event lasting [duration] covers when it starts
|
||||||
@@ -1144,6 +1404,7 @@ private const val SETTLE_TIMEOUT_MILLIS = 900L
|
|||||||
*/
|
*/
|
||||||
const val SETTLE_FADE_MILLIS: Int = 250
|
const val SETTLE_FADE_MILLIS: Int = 250
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The floating block, drawn over the whole calendar so it is free of the day
|
* The floating block, drawn over the whole calendar so it is free of the day
|
||||||
* column's clip and of the scroll viewport's rounded corners.
|
* column's clip and of the scroll viewport's rounded corners.
|
||||||
@@ -1151,16 +1412,14 @@ const val SETTLE_FADE_MILLIS: Int = 250
|
|||||||
@Composable
|
@Composable
|
||||||
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 dark = LocalFloretDarkTheme.current
|
|
||||||
val use24Hour = LocalUse24HourFormat.current
|
|
||||||
val locale = currentLocale()
|
|
||||||
val reduceMotion = rememberReduceMotion()
|
val reduceMotion = rememberReduceMotion()
|
||||||
val moveInFlight = moveInFlight()
|
val drops = dropStates()
|
||||||
|
val moveInFlight = controller.settledToken in drops.pending
|
||||||
|
val stripInFlight = controller.stripToken in drops.pending
|
||||||
|
|
||||||
// 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.stripDrag?.dayShift, controller.drops)
|
||||||
// Only once the finger has moved: a long press held near an edge must not
|
// Only once the finger has moved: a long press held near an edge must not
|
||||||
// scroll the drop target out from under a finger that only means to select.
|
// scroll the drop target out from under a finger that only means to select.
|
||||||
LaunchedEffect(controller.isDragging && controller.pointerMoved) {
|
LaunchedEffect(controller.isDragging && controller.pointerMoved) {
|
||||||
@@ -1170,12 +1429,11 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
|
|||||||
// 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
|
||||||
// drop itself.
|
// drop itself.
|
||||||
var handingOver by remember(controller.settling) { mutableStateOf(false) }
|
var handingOver by remember(controller.settling) { mutableStateOf(false) }
|
||||||
val abandoned = abandonedMoves()
|
val abandoned = controller.settledToken in drops.abandoned
|
||||||
LaunchedEffect(controller.settling, moveInFlight, controller.settledOnGrid, abandoned) {
|
LaunchedEffect(controller.settling, moveInFlight, controller.settledOnGrid, abandoned) {
|
||||||
if (controller.settling == null || moveInFlight) return@LaunchedEffect
|
if (controller.settling == null || moveInFlight) return@LaunchedEffect
|
||||||
// Past the mark this drop was let go on, it was abandoned: nothing will
|
// An abandoned drop: nothing will land and there is nothing to wait for.
|
||||||
// land and there is nothing to wait for.
|
if (!abandoned) {
|
||||||
if (abandoned == controller.settledAbandonedMark) {
|
|
||||||
delay(if (controller.settledOnGrid) SETTLE_GRACE_MILLIS else SETTLE_TIMEOUT_MILLIS)
|
delay(if (controller.settledOnGrid) SETTLE_GRACE_MILLIS else SETTLE_TIMEOUT_MILLIS)
|
||||||
}
|
}
|
||||||
handingOver = true
|
handingOver = true
|
||||||
@@ -1184,6 +1442,16 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
|
|||||||
controller.release()
|
controller.release()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The same hold for a bar moved along the all-day strip.
|
||||||
|
val stripAbandoned = controller.stripToken in drops.abandoned
|
||||||
|
LaunchedEffect(controller.stripSettling, stripInFlight, controller.stripSeated, stripAbandoned) {
|
||||||
|
if (controller.stripSettling == null || stripInFlight) return@LaunchedEffect
|
||||||
|
if (!stripAbandoned) {
|
||||||
|
delay(if (controller.stripSeated) SETTLE_GRACE_MILLIS else SETTLE_TIMEOUT_MILLIS)
|
||||||
|
}
|
||||||
|
controller.releaseStrip()
|
||||||
|
}
|
||||||
|
|
||||||
Box(
|
Box(
|
||||||
modifier = modifier
|
modifier = modifier
|
||||||
.fillMaxSize()
|
.fillMaxSize()
|
||||||
@@ -1192,6 +1460,12 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
|
|||||||
.clearAndSetSemantics { }
|
.clearAndSetSemantics { }
|
||||||
.onGloballyPositioned { origin = it.positionInRoot() },
|
.onGloballyPositioned { origin = it.positionInRoot() },
|
||||||
) {
|
) {
|
||||||
|
controller.held.forEach { parked ->
|
||||||
|
key(parked.token) { HeldTimelineCopy(controller, parked, origin) }
|
||||||
|
}
|
||||||
|
controller.heldStrips.forEach { parked ->
|
||||||
|
key(parked.token) { HeldStripSettle(controller, parked) }
|
||||||
|
}
|
||||||
val drag = controller.drag ?: controller.settling ?: return@Box
|
val drag = controller.drag ?: controller.settling ?: return@Box
|
||||||
// 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
|
||||||
@@ -1205,6 +1479,58 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
|
|||||||
animationSpec = tween(SETTLE_FADE_MILLIS),
|
animationSpec = tween(SETTLE_FADE_MILLIS),
|
||||||
label = "drag-handover",
|
label = "drag-handover",
|
||||||
)
|
)
|
||||||
|
TimelineCopy(drag, controller.geometry, origin, lift, copyAlpha)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [TimelineDragController.ghosts] for [block], derived so the block recomposes
|
||||||
|
* only when its own answer changes rather than on every lift, park and release.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun TimelineDragController.ghostsDerived(block: TimedBlock): Boolean {
|
||||||
|
val ghosted by remember(this, block) { derivedStateOf { ghosts(block) } }
|
||||||
|
return ghosted
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A drop parked by a newer pickup: held at its landing slot until its own write settles. */
|
||||||
|
@Composable
|
||||||
|
private fun HeldTimelineCopy(controller: TimelineDragController, parked: HeldDrop, origin: Offset) {
|
||||||
|
val alpha = rememberHeldSettle(
|
||||||
|
token = parked.token,
|
||||||
|
seated = parked.seated,
|
||||||
|
timeoutMillis = SETTLE_TIMEOUT_MILLIS,
|
||||||
|
onHandOver = { controller.handOverHeld(parked.token) },
|
||||||
|
onRelease = { controller.releaseHeld(parked.token) },
|
||||||
|
)
|
||||||
|
TimelineCopy(parked.copy, controller.geometry, origin, lift = 0f, copyAlpha = alpha)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A strip drop parked by a newer one: shown at its new days until its own write settles. */
|
||||||
|
@Composable
|
||||||
|
private fun HeldStripSettle(controller: TimelineDragController, parked: HeldStrip) {
|
||||||
|
rememberHeldSettle(
|
||||||
|
token = parked.token,
|
||||||
|
seated = parked.seated,
|
||||||
|
timeoutMillis = SETTLE_TIMEOUT_MILLIS,
|
||||||
|
onHandOver = {},
|
||||||
|
onRelease = { controller.releaseHeldStrip(parked.token) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** [drag]'s pieces drawn over the calendar, clipped to the timeline's viewport. */
|
||||||
|
@Composable
|
||||||
|
private fun TimelineCopy(
|
||||||
|
drag: TimelineDrag,
|
||||||
|
geometry: TimelineGeometry,
|
||||||
|
origin: Offset,
|
||||||
|
lift: Float,
|
||||||
|
copyAlpha: Float,
|
||||||
|
) {
|
||||||
|
val density = LocalDensity.current
|
||||||
|
val dark = LocalFloretDarkTheme.current
|
||||||
|
val use24Hour = LocalUse24HourFormat.current
|
||||||
|
val locale = currentLocale()
|
||||||
val paint = eventPaint(drag.event, dark)
|
val paint = eventPaint(drag.event, dark)
|
||||||
val title = drag.event.title.ifBlank { stringResource(R.string.event_untitled) }
|
val title = drag.event.title.ifBlank { stringResource(R.string.event_untitled) }
|
||||||
// Read off the event rather than the held block, so grabbing either half
|
// Read off the event rather than the held block, so grabbing either half
|
||||||
@@ -1220,7 +1546,7 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
|
|||||||
// so no column clip or rounded corner cuts it, but it still belongs to
|
// so no column clip or rounded corner cuts it, but it still belongs to
|
||||||
// the timeline: a piece a whole day tall reaches far past both ends of
|
// the timeline: a piece a whole day tall reaches far past both ends of
|
||||||
// the viewport, and unclipped it paints over the headers above (#267).
|
// the viewport, and unclipped it paints over the headers above (#267).
|
||||||
val port = controller.geometry.viewport?.takeIf { it.isAttached }?.boundsInRoot()
|
val port = geometry.viewport?.takeIf { it.isAttached }?.boundsInRoot()
|
||||||
// How much of each piece the viewport actually shows. A multi-day event
|
// How much of each piece the viewport actually shows. A multi-day event
|
||||||
// has a piece per day, and the widest one is a full 24 hours — taller
|
// has a piece per day, and the widest one is a full 24 hours — taller
|
||||||
// than the screen, its top at a midnight scrolled out of sight. Picking
|
// than the screen, its top at a midnight scrolled out of sight. Picking
|
||||||
@@ -1272,7 +1598,6 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** One piece of a dragged block, floating over the calendar. */
|
/** One piece of a dragged block, floating over the calendar. */
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -45,14 +43,21 @@ data class TimelineHours(
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* The scroll offset that puts [startHour] at the top of a timeline laid out
|
* The scroll offset that puts [startHour] at the top of a timeline laid out
|
||||||
* with [maxValue] scroll range over a [viewportPx] viewport, or null while that
|
* with [maxValue] scroll range over a [viewportPx] viewport, [clearancePx] of
|
||||||
|
* which is the empty inset under midnight, or null while that
|
||||||
* layout is not yet at [hourPx] per hour — the scale changes a frame before the
|
* layout is not yet at [hourPx] per hour — the scale changes a frame before the
|
||||||
* content grows to match it, and scrolling against the old layout would land on
|
* content grows to match it, and scrolling against the old layout would land on
|
||||||
* the wrong hour.
|
* the wrong hour.
|
||||||
*/
|
*/
|
||||||
internal fun startHourScroll(maxValue: Int, viewportPx: Int, startHour: Int, hourPx: Float): Int? {
|
internal fun startHourScroll(
|
||||||
|
maxValue: Int,
|
||||||
|
viewportPx: Int,
|
||||||
|
startHour: Int,
|
||||||
|
hourPx: Float,
|
||||||
|
clearancePx: Int = 0,
|
||||||
|
): Int? {
|
||||||
if (viewportPx <= 0 || maxValue < 0 || maxValue == Int.MAX_VALUE) return null
|
if (viewportPx <= 0 || maxValue < 0 || maxValue == Int.MAX_VALUE) return null
|
||||||
val laidOutHourPx = (maxValue + viewportPx) / 24f
|
val laidOutHourPx = (maxValue + viewportPx - clearancePx) / 24f
|
||||||
if (abs(laidOutHourPx - hourPx) > 1f) return null
|
if (abs(laidOutHourPx - hourPx) > 1f) return null
|
||||||
return (startHour * laidOutHourPx).roundToInt().coerceIn(0, maxValue)
|
return (startHour * laidOutHourPx).roundToInt().coerceIn(0, maxValue)
|
||||||
}
|
}
|
||||||
Loaded 100 of 421 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user