Compare commits

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

No files matched your search

+21
View File
@@ -7,6 +7,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [2.24.1] — 2026-11-12
### Added
- **A classic style for the agenda widget.** Its settings now have a Style option: Cards keeps the new look, Classic brings back the 2.23 layout with a line per day and a colour stripe beside each event, under the current header. Dates in another year show the year. Classic has an Invert text colour switch, so its text stays readable on light and dark wallpapers ([#489]).
- **Widget opacity.** Every widget with a Solid or Tinted background has an Opacity slider from 20 to 100%. Below 50%, the card-style widgets back their content like a Transparent widget so it stays readable ([#489]).
### Fixed
- **Week numbers match your region.** With weeks starting on Sunday, the month and week views showed every week number one too low. Rows are now numbered by your region's rules, so ISO regions such as Germany are unchanged ([#493]).
- **The month widget shows events at every height.** At some sizes a week row had room for a little more than the date but not a full line of events, and drew none. It now fits a slimmer line there, and a row with a single line shows "+N" on days with more events than fit ([#491]).
- **Dimmed past events in dark widgets are readable again.** They used to turn pastel with white text on top ([#475]).
- **A widget set to Light or Dark matches the system colours.** With Material You, the + button and today's date could look different from a widget that follows the app ([#475]).
### Changed
- **Fewer permissions.** Calendula no longer asks for network state, wake lock or foreground service access, which a library added without the app needing them ([#448]).
- Translation updates from [Calendula's Weblate](https://weblate.dev.jeanlucmakiola.de/projects/calendula/).
## [2.24.0] — 2026-11-06
### Added
@@ -1952,3 +1968,8 @@ automatically, with zero telemetry and no internet permission.
[#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
+2 -2
View File
@@ -32,8 +32,8 @@ android {
// (up to 2.22.3: 2.22.3 -> 22203; from 2.22.4: 2.23.0-beta.1 -> 2230001,
// 2.22.4 -> 2220499), and CI fails if the committed one doesn't match.
// See docs/RELEASING.md.
versionCode = 2240099
versionName = "2.24.0"
versionCode = 2240199
versionName = "2.24.1"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
+5
View File
@@ -41,6 +41,11 @@
-->
<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
returns null and the calendar manager's per-account "manage" button can't
open the source sync app (DAVx5, ICSx5, Google Calendar, …). The LAUNCHER
@@ -485,9 +485,8 @@ fun CalendarHost(
movableCalendarIds = movableCalendarIds,
dragEnabled = dragToReschedule,
move = { reschedule.move(it) },
inFlight = reschedule.inFlight,
drops = reschedule.drops,
undoStarted = reschedule.undoStarted,
abandoned = reschedule.abandoned,
edit = onEditEvent,
)
}
@@ -90,6 +90,9 @@ fun EventMoveHost(
MoveOutcome.Undone -> stringResource(R.string.event_move_undone)
MoveOutcome.WriteDenied -> stringResource(R.string.event_move_write_denied)
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.BlockedCancelledSeries -> stringResource(R.string.event_move_blocked_cancelled_series)
MoveOutcome.Failed -> stringResource(R.string.event_move_failed)
@@ -1,12 +1,15 @@
package de.jeanlucmakiola.calendula.ui.common
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.Immutable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.res.stringResource
@@ -16,6 +19,7 @@ import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.domain.EventInstance
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import java.util.concurrent.atomic.AtomicLong
/**
* Drag-to-reschedule wiring (#68), provided once at `CalendarHost` and read by
@@ -37,24 +41,18 @@ class EventMoveScope(
val dragEnabled: Boolean,
/**
* 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
* tells a held copy that nothing landed.
* before its write resolves, so [drops] — not a return value — is what tells
* a held copy whether anything landed.
*/
val move: (MoveRequest) -> Unit,
/**
* True while a dropped event is being written, including the time its scope
* dialog is up. A flow rather than a value so this scope stays the same
* object across a move — every visible block reads it as a composition local.
* Each drop's progress by its token — see `RescheduleViewModel.drops`. A flow
* rather than a value so this scope stays the same object across a move —
* every visible block reads it as a composition local.
*/
val inFlight: StateFlow<Boolean>,
/** Ticks when an undo write begins — see `RescheduleViewModel.undoStarted`. */
val undoStarted: StateFlow<Int>,
/**
* 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>,
val drops: StateFlow<DropStates>,
/** The undo write that just began — see `RescheduleViewModel.undoStarted`. */
val undoStarted: StateFlow<UndoStart?>,
/** Open an event in the edit form — the pointer-free route to the same change. */
val edit: (EventInstance) -> Unit,
) {
@@ -63,30 +61,42 @@ class EventMoveScope(
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
/**
* Whether a dropped event is still being written — false wherever moving is off.
* The drag overlays hold a landed block on its target for this window.
*/
@Composable
fun moveInFlight(): Boolean {
val flow = LocalEventMove.current?.inFlight ?: NEVER_IN_FLIGHT
return flow.collectAsStateWithLifecycle().value
/** Per-drop progress, by token — see `RescheduleViewModel.drops`. */
@Immutable
data class DropStates(
val pending: Set<Long> = emptySet(),
val abandoned: Set<Long> = emptySet(),
) {
fun started(token: Long): DropStates = copy(pending = pending + token)
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
* drag overlay can capture it at the moment of the drop and tell, later, whether
* *its own* drop was one of them.
* Every drop's progress — empty wherever moving is off. A drag overlay keeps
* the token of its own drop and holds its copy while that token is pending.
*/
@Composable
fun abandonedMoves(): Int {
val flow = LocalEventMove.current?.abandoned ?: NEVER_ABANDONED
fun dropStates(): DropStates {
val flow = LocalEventMove.current?.drops ?: NO_DROPS
return flow.collectAsStateWithLifecycle().value
}
@@ -95,17 +105,53 @@ fun abandonedMoves(): Int {
* this composable came on screen.
*/
@Composable
fun OnUndoStarted(onUndo: () -> Unit) {
fun OnUndoStarted(onUndo: (UndoStart) -> Unit) {
val flow = LocalEventMove.current?.undoStarted ?: NEVER_UNDONE
val tick by flow.collectAsStateWithLifecycle()
var seen by remember { mutableIntStateOf(tick) }
LaunchedEffect(tick) {
if (tick == seen) return@LaunchedEffect
seen = tick
onUndo()
val start by flow.collectAsStateWithLifecycle()
var seen by remember { mutableStateOf(start) }
LaunchedEffect(start) {
val started = start
if (started == null || started == seen) return@LaunchedEffect
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. */
const val GHOST_ALPHA: Float = 0.3f
@@ -32,6 +32,7 @@ import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.LocalDate
@@ -40,12 +41,21 @@ import kotlinx.datetime.atStartOfDayIn
import kotlinx.datetime.plus
import kotlinx.datetime.toLocalDateTime
import kotlin.coroutines.cancellation.CancellationException
import kotlin.time.Duration.Companion.seconds
import kotlin.time.Instant
import kotlin.time.TimeMark
import kotlin.time.TimeSource
import javax.inject.Inject
private const val MILLIS_PER_MINUTE = 60_000
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. */
sealed interface MoveTarget {
/** A new start instant — a timeline drag, which moves time and day at once. */
@@ -74,6 +84,10 @@ data class MoveRequest(
val beginMillis: Long,
val endMillis: Long,
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,
)
/**
@@ -92,8 +106,13 @@ data class MoveUndo(
val moved: EventForm,
/** The form as it stood before the move. */
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 {
/**
* Written. [startMillis] is where the dragged occurrence now begins, for the
@@ -115,6 +134,19 @@ sealed interface MoveOutcome {
/** The event vanished (sync, another device) between the read and the write. */
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. */
data object BlockedSeriesEnd : MoveOutcome
@@ -152,36 +184,32 @@ class RescheduleViewModel @Inject constructor(
private val _inFlight = MutableStateFlow(false)
/**
* True from the moment a drop is accepted until its write settles — the
* window the dropped block holds its landing position for.
*/
/** True while any drop or undo runs or waits — what the confirmation chip holds for. */
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,
* refused before the write, written and failed, or its scope dialog
* dismissed. [move] answers before any of that is known, so without this
* signal the view that drew the drop held its copy out for the full settle
* timeout waiting for a grid that was never going to draw it (#253).
* Each drop's own state, by its [MoveRequest.token]: pending from the moment
* it is accepted until its write settles, and abandoned once it ends with
* nothing on the target day — refused, failed, or its scope dialog dismissed.
* Per drop, so a queued drop's held copy waits on its own write and is never
* 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
* 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
* of the same recurring event inside that window would compute their shift
* from the same pre-move occurrence, and the shifts would compound.
* Set while a drop is being prepared, waits on its scope dialog, or is
* written. Drops arriving in that window wait in [queue] and run in order.
*/
private var busy = false
set(value) {
@@ -189,6 +217,22 @@ class RescheduleViewModel @Inject constructor(
_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
* this, so a block outside this set registers no drag gesture at all.
@@ -219,38 +263,50 @@ class RescheduleViewModel @Inject constructor(
}
/**
* Take a drop, unless one is already being written. False means nothing will
* be written; [abandoned] ticks for that refusal too, so a held copy is let
* go by the one signal rather than by every caller remembering to.
* Take a drop: run it now, or queue it behind the ones in flight. False means
* nothing will be written — the queue is full — and the drop is marked
* 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
* hand it on. A caller that gated on it would be back to releasing its copy
* from two places, and it answers before the write is resolved anyway.
* hand it on. It answers before the write is resolved anyway.
*/
fun move(request: MoveRequest): Boolean {
if (busy || _scopePrompt.value != null) {
_abandoned.value += 1
if (queue.size >= MAX_QUEUED) {
_drops.update { it.ended(request.token, landed = false) }
report(MoveOutcome.QueueFull)
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
viewModelScope.launch {
val prepared = prepare(request)
if (prepared == null) {
_abandoned.value += 1
busy = false
settle(request.token, landed = false)
return@launch
}
// A cancelled series only moves as a whole (#388).
val seriesOnly = !prepared.original.canSaveApartFromSeries()
if (!prepared.isRecurring || (seriesOnly && prepared.canRealign)) {
write(prepared, RecurringWriteScope.AllEvents)
busy = false
settle(request.token, write(prepared, RecurringWriteScope.AllEvents))
} else if (seriesOnly) {
_outcome.value = MoveOutcome.BlockedCancelledSeries
_abandoned.value += 1
busy = false
report(MoveOutcome.BlockedCancelledSeries)
settle(request.token, landed = false)
} 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
_scopePrompt.value = MoveScopePrompt(
occurrenceOnly = !prepared.canRealign,
@@ -258,7 +314,6 @@ class RescheduleViewModel @Inject constructor(
)
}
}
return true
}
/** Answer the scope dialog. */
@@ -269,35 +324,92 @@ class RescheduleViewModel @Inject constructor(
pending = null
_scopePrompt.value = null
viewModelScope.launch {
write(prepared, scope)
busy = false
settle(prepared.request.token, write(prepared, scope))
}
}
/** Dismiss the scope dialog without writing. */
fun cancelScope() {
val prepared = pending ?: return
pending = null
busy = false
_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
* inverse write reports back, so the one chip changes what it says rather
* than closing and reopening. False when another write is already running —
* the chip hides its action for that window, so this is the backstop.
*
* [abandoned] ticks once an inverse that *started* fails to land: [undoStarted]
* 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.
* 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]
* reports whether it landed.
*/
fun undo(undo: MoveUndo): Boolean {
if (busy) return false
val token = nextMoveToken()
_drops.update { it.started(token) }
busy = true
_undoStarted.value += 1
_undoStarted.value = UndoStart(token, undo.dropToken)
markWritten(undo.eventId, null)
viewModelScope.launch {
_outcome.value = try {
repository.updateEvent(undo.eventId, undo.moved, undo.restored)
@@ -311,33 +423,40 @@ class RescheduleViewModel @Inject constructor(
} catch (e: Exception) {
MoveOutcome.Failed
}
// Read off the outcome, the way [write] does — no second copy of the
// same fact to drift from it.
if (_outcome.value !is MoveOutcome.Undone) _abandoned.value += 1
busy = false
settle(token, landed = _outcome.value is MoveOutcome.Undone)
}
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() {
_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 {
repository.eventDetail(request.eventId)
repository.eventDetail(dropped.eventId)
} catch (e: CancellationException) {
throw e
} catch (e: NoSuchEventException) {
_outcome.value = MoveOutcome.Gone
report(MoveOutcome.Gone)
return null
} catch (e: Exception) {
_outcome.value = MoveOutcome.Failed
report(MoveOutcome.Failed)
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 shifted = when (val target = request.target) {
is MoveTarget.Start -> original.shiftedTo(target.instant, zone)
@@ -350,7 +469,7 @@ class RescheduleViewModel @Inject constructor(
// The UNTIL check is deferred to the write, which knows how far the move
// reaches and so which date has to clear it.
if ((shifted.problems(zone) - EventFormProblem.RecurrenceEndsBeforeStart).isNotEmpty()) {
_outcome.value = MoveOutcome.Failed
report(MoveOutcome.Failed)
return null
}
@@ -395,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
if (endsBeforeItStarts(prepared, scope)) {
_outcome.value = MoveOutcome.BlockedSeriesEnd
_abandoned.value += 1
return
report(MoveOutcome.BlockedSeriesEnd)
return false
}
_outcome.value = try {
val outcome = try {
when {
!prepared.isRecurring || scope == RecurringWriteScope.AllEvents ->
repository.updateEvent(request.eventId, prepared.original, prepared.updated)
@@ -437,9 +556,37 @@ class RescheduleViewModel @Inject constructor(
} catch (e: Exception) {
MoveOutcome.Failed
}
// Nothing landed, so the copy the view is holding has nothing to fade
// into — let it go now rather than at the end of the settle timeout.
if (_outcome.value !is MoveOutcome.Moved) _abandoned.value += 1
if (outcome is MoveOutcome.Moved) {
markWritten(request.eventId, request.beginMillis.takeIf { scope == RecurringWriteScope.ThisEvent && prepared.isRecurring })
}
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,
)
}
/**
@@ -506,6 +653,7 @@ class RescheduleViewModel @Inject constructor(
eventId = prepared.request.eventId,
moved = prepared.updated,
restored = prepared.original,
dropToken = prepared.request.token,
)
} else {
null
@@ -20,6 +20,7 @@ import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
@@ -60,7 +61,6 @@ import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme
import de.jeanlucmakiola.floret.identity.rememberReduceMotion
import de.jeanlucmakiola.floret.locale.currentLocale
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.StateFlow
import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.LocalDate
import kotlinx.datetime.atStartOfDayIn
@@ -139,9 +139,17 @@ data class StripDrag(val event: EventInstance, val dayShift: Int = 0, val overGr
sealed interface StripDrop {
val event: EventInstance
data class Days(override val event: EventInstance, val days: Int) : StripDrop
/** The drop's identity, which its held copy waits on. */
val token: Long
data class Timed(override val event: EventInstance, val start: Instant, val end: Instant) : StripDrop
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). */
@@ -297,7 +305,9 @@ data class TimelineDrop(
val date: LocalDate,
val startMin: Int,
/** 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). */
@@ -340,8 +350,37 @@ internal fun draftBlock(draft: EventInstance, date: LocalDate, zone: TimeZone):
/** Which end of an event a resize handle moves (#141). */
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. */
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
@@ -352,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
* point, so the block settles under the finger.
*/
internal fun resizedDrop(
internal fun resizedSpan(
event: EventInstance,
edge: ResizeEdge?,
date: LocalDate,
startMin: Int,
spanMin: Int,
zone: TimeZone,
): TimelineResizeDrop {
): ResizedSpan {
val drawn = wallClockSpan(event, zone)
return TimelineResizeDrop(
event = event,
return ResizedSpan(
start = if (edge == ResizeEdge.Top) {
event.start.toFormTime(zone).repicked(
wallClockTime(date, startMin),
@@ -513,6 +551,14 @@ class TimelineDragController {
*/
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). */
var draftMinutes: Int = SettingsPrefs.DEFAULT_EVENT_DURATION
@@ -611,14 +657,8 @@ class TimelineDragController {
var settlingSelected: Boolean = false
private set
/**
* The abandoned-move counter, read at the drop so the mark can't be a
* 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
/** The token of the drop [settling] waits on. */
var settledToken: Long = 0L
private set
private var source: TimedBlock? = null
@@ -661,8 +701,12 @@ class TimelineDragController {
var stripSeated: Boolean by mutableStateOf(false)
private set
/** What [abandonedTicks] stood at when [stripSettling] was let go. */
var stripAbandonedMark: Int = 0
/** Strip drops parked by a newer strip drop while their writes still run (#494). */
var heldStrips: List<HeldStrip> by mutableStateOf(emptyList())
private set
/** The token of the drop [stripSettling] waits on. */
var stripToken: Long = 0L
private set
/** The shown day the finger picked the strip bar up on. */
@@ -687,7 +731,7 @@ class TimelineDragController {
dragDuration = (block.event.end - block.event.start).coerceAtLeast(Duration.ZERO)
dragKept = zone.repeatedHourOffsetAt(block.event.start)
this.titleLines = titleLines
settling = null
parkSettling()
isDragging = true
liftedInstanceId = block.event.instanceId
grab = pointerInRoot - blockInRoot
@@ -726,7 +770,7 @@ class TimelineDragController {
dragDuration = draftMinutes.minutes
dragKept = null
titleLines = 1
settling = null
parkSettling()
isDragging = true
liftedInstanceId = event.instanceId
grab = Offset(0f, geometry.hourPx * STRIP_GRAB_MINUTES / 60f)
@@ -749,16 +793,18 @@ class TimelineDragController {
val zone = dragZone
cancel()
if (held.overGrid && landed != null && zone != null && !landed.edgeOnly) {
settle(landed)
val start = TimelineDrop(landed.event, landed.date, landed.startMin).startInstant(zone)
return StripDrop.Timed(held.event, start, start + draftMinutes.minutes)
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
stripAbandonedMark = abandonedTicks?.value ?: 0
stripToken = nextMoveToken()
drops++
return StripDrop.Days(held.event, held.dayShift)
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. */
@@ -772,6 +818,21 @@ class TimelineDragController {
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) {
pointer = pointerInRoot
if (!pointerMoved && (pointerInRoot - pickupPointer).getDistance() > slopPx) pointerMoved = true
@@ -806,12 +867,36 @@ class TimelineDragController {
* an event that crosses midnight (#253).
*/
fun ghosts(block: TimedBlock): Boolean {
if (held.any { !it.handedOver && it.ghosts(block) }) return true
if (liftedInstanceId == null) return false
if (block.event.instanceId == liftedInstanceId) return true
val (eventId, start) = settledOrigin ?: return false
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
* caught up with it. Matched on the landing slot plus either the event row
@@ -819,16 +904,23 @@ class TimelineDragController {
* blank title matches nothing: every untitled event has one (#253).
*/
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
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
// 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.
val offset = (date.toEpochDays() - landed.date.toEpochDays()).toInt()
val slice = dragSlices(landed.eventStartMin, landed.eventSpanMin, offset..offset)
.firstOrNull() ?: return
val end = settledEnd
settledOnGrid = blocks.any { block ->
.firstOrNull() ?: return false
return blocks.any { block ->
block.startMin == slice.startMin &&
// A resize may keep its start, so its end has to have landed too.
(end == null || block.event.end == end) &&
@@ -855,12 +947,15 @@ class TimelineDragController {
if (landed == null || landed.slot == origin) return null
// A draft dropped on a day off screen would vanish, so it stays where it was (#153).
if (landed.edgeOnly && landed.event.isDraft) return null
settle(landed)
return TimelineDrop(landed.event, landed.date, landed.startMin, clipOffset)
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. */
private fun settle(landed: TimelineDrag, end: Instant? = null) {
/**
* 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 &&
@@ -873,9 +968,10 @@ class TimelineDragController {
settling = if (landed.edgeOnly || leavesGrid) landed.copy(pieces = emptyList()) else landed
liftedInstanceId = landed.event.instanceId
settledOrigin = landed.event.eventId to landed.event.start
settledAbandonedMark = abandonedTicks?.value ?: 0
settledToken = nextMoveToken()
settledEnd = end
drops++
return settledToken
}
/**
@@ -895,7 +991,7 @@ class TimelineDragController {
resize = session
clipOffsetMin = 0
this.titleLines = titleLines
settling = null
parkSettling()
isDragging = true
pointerMoved = true
liftedInstanceId = block.event.instanceId
@@ -926,10 +1022,10 @@ class TimelineDragController {
val event = source?.event ?: return null
val edge = resize?.edge
if (edge != null) {
val drop = resizedDrop(event, edge, date, startMin, spanMin, zone)
val drop = resizedSpan(event, edge, date, startMin, spanMin, zone)
return event.copy(start = drop.start, end = drop.end)
}
val start = TimelineDrop(event, date, startMin, clipOffsetMin).startInstant(zone)
val start = dropStartInstant(event, date, startMin, clipOffsetMin, zone)
return event.copy(start = start, end = start + dragDuration)
}
@@ -943,9 +1039,8 @@ class TimelineDragController {
val edge = resize?.edge
cancel()
if (landed == null || landed.slot == origin) return null
val drop = resizedDrop(landed.event, edge, landed.date, landed.eventStartMin, landed.eventSpanMin, zone)
settle(landed, end = drop.end)
return drop
val span = resizedSpan(landed.event, edge, landed.date, landed.eventStartMin, landed.eventSpanMin, zone)
return TimelineResizeDrop(landed.event, span.start, span.end, settle(landed, end = span.end))
}
/**
@@ -1199,7 +1294,6 @@ fun rememberTimelineDragController(): TimelineDragController {
controller.geometry.edgePx = with(density) { AUTO_SCROLL_EDGE.toPx() }
controller.geometry.stepPx = with(density) { AUTO_SCROLL_STEP.toPx() }
controller.slopPx = LocalViewConfiguration.current.touchSlop
controller.abandonedTicks = LocalEventMove.current?.abandoned
return controller
}
@@ -1229,7 +1323,16 @@ fun TimedBlock.continuesBefore(day: LocalDate, zone: TimeZone): Boolean =
* visibly settles there.
*/
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
@@ -1301,6 +1404,7 @@ private const val SETTLE_TIMEOUT_MILLIS = 900L
*/
const val SETTLE_FADE_MILLIS: Int = 250
/**
* 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.
@@ -1308,12 +1412,10 @@ const val SETTLE_FADE_MILLIS: Int = 250
@Composable
fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier = Modifier) {
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 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
// changes every frame, and this composable is the one that is meant to.
@@ -1327,12 +1429,11 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
// recurring drop's scope dialog is up — and then until the grid draws the
// drop itself.
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) {
if (controller.settling == null || moveInFlight) return@LaunchedEffect
// Past the mark this drop was let go on, it was abandoned: nothing will
// land and there is nothing to wait for.
if (abandoned == controller.settledAbandonedMark) {
// An abandoned drop: nothing will land and there is nothing to wait for.
if (!abandoned) {
delay(if (controller.settledOnGrid) SETTLE_GRACE_MILLIS else SETTLE_TIMEOUT_MILLIS)
}
handingOver = true
@@ -1342,9 +1443,10 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
}
// The same hold for a bar moved along the all-day strip.
LaunchedEffect(controller.stripSettling, moveInFlight, controller.stripSeated, abandoned) {
if (controller.stripSettling == null || moveInFlight) return@LaunchedEffect
if (abandoned == controller.stripAbandonedMark) {
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()
@@ -1358,6 +1460,12 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
.clearAndSetSemantics { }
.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
// Landed: the copy sinks back to the grid's own plane while the write runs.
val landed = controller.drag == null
@@ -1371,6 +1479,58 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
animationSpec = tween(SETTLE_FADE_MILLIS),
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 title = drag.event.title.ifBlank { stringResource(R.string.event_untitled) }
// Read off the event rather than the held block, so grabbing either half
@@ -1386,7 +1546,7 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
// 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 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
// 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
@@ -1438,7 +1598,6 @@ fun TimelineDragOverlay(controller: TimelineDragController, modifier: Modifier =
)
}
}
}
}
/** One piece of a dragged block, floating over the calendar. */
@@ -0,0 +1,21 @@
package de.jeanlucmakiola.calendula.ui.common
import android.content.res.Resources
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import de.jeanlucmakiola.floret.time.rowWeekNumber
import kotlinx.datetime.LocalDate
import kotlinx.datetime.toJavaLocalDate
import java.time.temporal.WeekFields
/**
* The week number of the grid row starting on [rowStart], numbered by the
* device region's rules (#493). The region, not the app language: an English
* UI in the Netherlands still numbers weeks the ISO way. Shared by the Month
* gutter and the Week badge so the two always agree.
*/
@Composable
internal fun rememberRowWeekNumber(rowStart: LocalDate): Int {
val fields = remember { WeekFields.of(Resources.getSystem().configuration.locales[0]) }
return remember(rowStart, fields) { rowStart.toJavaLocalDate().rowWeekNumber(fields) }
}
@@ -14,8 +14,7 @@ import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.unit.IntSize
import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.ui.common.LocalEventMove
import kotlinx.coroutines.flow.StateFlow
import de.jeanlucmakiola.calendula.ui.common.nextMoveToken
import kotlinx.datetime.LocalDate
import kotlin.math.abs
@@ -107,11 +106,22 @@ data class MonthChipDrag(
val time: String? = null,
)
/** A drop parked by a newer pickup while its write still runs — see [MonthDragController.held]. */
data class HeldChip(
val copy: MonthChipDrag,
val token: Long,
val handedOver: Boolean = false,
/** Where the grid now draws the drop, in root coordinates, once a row seats it. */
val seat: Offset? = null,
)
/** Where a finished chip drag asks its event to go, as a whole-day shift. */
data class MonthChipDrop(
val event: EventInstance,
val grabDate: LocalDate,
val targetDate: LocalDate,
/** The drop's identity, which its held copy waits on — see [MonthDragController.settledToken]. */
val token: Long,
)
/**
@@ -167,19 +177,22 @@ class MonthDragController {
private set
/**
* The last drop this controller made, kept past [release] for [beginUndo] —
* the confirmation chip carries Undo long after the copy is gone.
* This controller's recent drops by token, kept past [release] for
* [beginUndo] — the confirmation chip carries Undo long after the copy is
* gone, and it may be any of them the chip offers to undo.
*/
private var undoable: MonthChipDrag? = null
private val undoable = LinkedHashMap<Long, MonthChipDrag>()
/**
* The abandoned-move counter, read at the drop so the mark can't be a
* composition behind the tick it is compared against.
* Earlier drops still being written when another chip was picked up. They
* keep their copy and their ghost until their own token settles, rather than
* vanishing and flashing back on the old day (#494).
*/
var abandonedTicks: StateFlow<Int>? = null
var held: List<HeldChip> by mutableStateOf(emptyList())
private set
/** What [abandonedTicks] stood at when the settling chip was let go. */
var settledAbandonedMark: Int = 0
/** The token of the drop (or undo) [settling] is waiting on. */
var settledToken: Long = 0L
private set
private var event: EventInstance? = null
@@ -208,7 +221,7 @@ class MonthDragController {
this.event = event
this.grabDate = grabDate
this.time = time
settling = null
parkSettling()
isDragging = true
liftedInstanceId = event.instanceId
grab = pointerInRoot - chipInRoot
@@ -234,6 +247,39 @@ class MonthDragController {
settledGhost = false
}
/**
* Whether [event]'s chip belongs to a held drop and must stay a ghost: its
* source, or once a row seats it, the chip the grid draws on its target day.
*/
fun isHeldChip(event: EventInstance, days: List<LocalDate>?): Boolean = held.any { parked ->
!parked.handedOver && (
parked.copy.event.instanceId == event.instanceId ||
(
parked.seat != null && days != null && parked.copy.targetDate in days &&
isSameEvent(event, parked.copy.event)
)
)
}
/** Move a still-settling drop to [held] before a new pickup takes the slot. */
private fun parkSettling() {
val landed = settling
if (landed != null) held = held + HeldChip(landed, settledToken)
settling = null
settledInRoot = null
settledGhost = false
}
/** 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 }
}
/**
* Whether [days] holds the chip the grid has drawn for the settled drop —
* the seat the copy is on its way to, which must ghost until it gets there.
@@ -250,6 +296,13 @@ class MonthDragController {
* nearest where the chip was let go is the one the finger was over.
*/
fun noteSettled(token: Any) {
val row = rows[token]
if (row != null && held.any { it.seat == null }) {
held = held.map { parked ->
val target = parked.copy.targetDate
if (parked.seat != null || target == null) parked else parked.copy(seat = row.seatOf(parked.copy.event, target))
}
}
val landed = settling ?: return
val target = landed.targetDate ?: return
val at = rows[token]?.seatOf(landed.event, target) ?: return
@@ -265,16 +318,16 @@ class MonthDragController {
* there is no drop of this controller's left to undo, or the grid doesn't
* seat the moved event where the chip would have to start from.
*/
fun beginUndo(): Boolean {
val last = undoable ?: return false
undoable = null
fun beginUndo(token: Long, dropToken: Long): Boolean {
val last = undoable.remove(dropToken) ?: return false
parkSettling()
val from = last.targetDate ?: return false
val at = rows.values.firstNotNullOfOrNull { it.seatOf(last.event, from) } ?: return false
settling = last.copy(grabDate = from, targetDate = last.grabDate, topLeftInRoot = at)
liftedInstanceId = last.event.instanceId
settledGhost = true
settledInRoot = null
settledAbandonedMark = abandonedTicks?.value ?: 0
settledToken = token
return true
}
@@ -294,10 +347,11 @@ class MonthDragController {
)
liftedInstanceId = landed.event.instanceId
settledGhost = true
undoable = settling
settledAbandonedMark = abandonedTicks?.value ?: 0
settledToken = nextMoveToken()
undoable[settledToken] = requireNotNull(settling)
if (undoable.size > UNDOABLE_KEPT) undoable.remove(undoable.keys.first())
drops++
return MonthChipDrop(landed.event, landed.grabDate, target)
return MonthChipDrop(landed.event, landed.grabDate, target, settledToken)
}
/**
@@ -355,9 +409,10 @@ class MonthDragController {
@Composable
fun rememberMonthDragController(): MonthDragController {
val controller = remember { MonthDragController() }
controller.abandonedTicks = LocalEventMove.current?.abandoned
return controller
return remember { MonthDragController() }
}
val LocalMonthDrag = compositionLocalOf<MonthDragController?> { null }
/** How many recent drops a month controller keeps for an undo to carry back. */
private const val UNDOABLE_KEPT = 8
@@ -125,11 +125,11 @@ import de.jeanlucmakiola.calendula.ui.common.eventTitleOverflow
import de.jeanlucmakiola.calendula.ui.common.MoveTarget
import de.jeanlucmakiola.calendula.ui.common.MoveRequest
import de.jeanlucmakiola.calendula.ui.common.LocalEventMove
import de.jeanlucmakiola.calendula.ui.common.moveInFlight
import de.jeanlucmakiola.calendula.ui.common.abandonedMoves
import de.jeanlucmakiola.calendula.ui.common.dropStates
import de.jeanlucmakiola.calendula.ui.common.OnUndoStarted
import de.jeanlucmakiola.calendula.ui.common.ghostAlpha
import de.jeanlucmakiola.calendula.ui.common.DragSnapHaptics
import de.jeanlucmakiola.calendula.ui.common.rememberHeldSettle
import de.jeanlucmakiola.calendula.ui.common.SETTLE_FADE_MILLIS
import de.jeanlucmakiola.calendula.ui.common.SETTLE_GRACE_MILLIS
import de.jeanlucmakiola.calendula.ui.common.EventMoveScope
@@ -187,7 +187,6 @@ import de.jeanlucmakiola.floret.identity.itemEnter
import de.jeanlucmakiola.floret.identity.rememberReduceMotion
import de.jeanlucmakiola.floret.locale.currentLocale
import de.jeanlucmakiola.calendula.ui.common.next
import de.jeanlucmakiola.floret.time.isoWeekNumber
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filterNotNull
@@ -205,6 +204,7 @@ import java.time.format.TextStyle as JavaTextStyle
import java.util.Locale
import kotlinx.datetime.toJavaMonth
import kotlinx.datetime.yearMonth
import de.jeanlucmakiola.calendula.ui.common.rememberRowWeekNumber
private val LocalTodayPulse = staticCompositionLocalOf { 0 }
@@ -515,7 +515,7 @@ fun MonthScreen(
val chipDrag = rememberMonthDragController()
// Undo moves the event back, so the chip travels back too. The
// signal comes from the write, not from the chip that offers it.
OnUndoStarted { chipDrag.beginUndo() }
OnUndoStarted { start -> chipDrag.beginUndo(start.token, start.dropToken) }
Box(
modifier = Modifier
.padding(innerPadding)
@@ -591,11 +591,11 @@ private const val MONTH_SETTLE_TIMEOUT_MILLIS = 450L
@Composable
private fun MonthDragOverlay(controller: MonthDragController, showStartTimes: Boolean) {
var origin by remember { mutableStateOf(Offset.Zero) }
val dark = LocalFloretDarkTheme.current
val density = LocalDensity.current
val timeFit = rememberMonthChipTimeFit(showStartTimes)
val reduceMotion = rememberReduceMotion()
val moveInFlight = moveInFlight()
val drops = dropStates()
val moveInFlight = controller.settledToken in drops.pending
val abandoned = controller.settledToken in drops.abandoned
// Here rather than beside the controller: this reads [drag], which changes
// every frame, and this composable is the one that is meant to.
DragSnapHaptics(controller.drag?.targetDate, controller.drops)
@@ -608,14 +608,12 @@ private fun MonthDragOverlay(controller: MonthDragController, showStartTimes: Bo
val glide = remember { Animatable(Offset.Zero, Offset.VectorConverter) }
val glideSpec = MaterialTheme.motionScheme.fastSpatialSpec<Offset>()
val seat = controller.settledInRoot
val abandoned = abandonedMoves()
LaunchedEffect(controller.settling, moveInFlight, seat, abandoned) {
val landed = controller.settling
if (landed == null || moveInFlight) return@LaunchedEffect
if (seat == null) {
// Past the mark this drop was let go on, it was abandoned and no
// seat is ever coming.
if (abandoned == controller.settledAbandonedMark) delay(MONTH_SETTLE_TIMEOUT_MILLIS)
// An abandoned drop has no seat coming.
if (!abandoned) delay(MONTH_SETTLE_TIMEOUT_MILLIS)
} else {
if (!gliding) glide.snapTo(landed.topLeftInRoot)
gliding = true
@@ -635,6 +633,9 @@ private fun MonthDragOverlay(controller: MonthDragController, showStartTimes: Bo
.clearAndSetSemantics { }
.onGloballyPositioned { origin = it.positionInRoot() },
) {
controller.held.forEach { parked ->
key(parked.token) { HeldMonthChip(controller, parked, origin, timeFit) }
}
val drag = controller.drag ?: controller.settling ?: return@Box
// Landed: the copy sinks back to the grid's own plane while the write runs.
val lift by animateFloatAsState(
@@ -646,42 +647,93 @@ private fun MonthDragOverlay(controller: MonthDragController, showStartTimes: Bo
animationSpec = tween(SETTLE_FADE_MILLIS),
label = "chip-handover",
)
MonthBar(
event = drag.event,
dark = dark,
continuesLeft = false,
continuesRight = false,
// The time the source chip carried, drawn only if this one-column
// cut-out of it has the room — which a slice of a multi-day bar has
// not, however wide the bar was.
time = drag.time,
MonthChipCopy(
drag = drag,
// Read at layout, so the glide doesn't recompose every frame.
at = { if (gliding) glide.value else drag.topLeftInRoot },
origin = origin,
lift = lift,
alpha = copyAlpha,
timeFit = timeFit,
chipWidth = with(density) { drag.sizePx.width.toDp() },
modifier = Modifier
// Absolute: these are root coordinates, and the direction-aware
// offset would mirror them across the screen in an RTL layout.
.absoluteOffset {
val at = if (gliding) glide.value else drag.topLeftInRoot
IntOffset(
(at.x - origin.x).roundToInt(),
(at.y - origin.y).roundToInt(),
)
}
.width(with(density) { drag.sizePx.width.toDp() })
.height(with(density) { drag.sizePx.height.toDp() })
.padding(horizontal = MONTH_CHIP_INSET, vertical = 1.dp)
.graphicsLayer {
scaleX = 1f + 0.04f * lift
scaleY = 1f + 0.04f * lift
shadowElevation = 8.dp.toPx() * lift
alpha = copyAlpha
shape = EventChipShape
clip = false
},
)
}
}
/** A drop parked by a newer pickup: held on its landing day until its own write settles. */
@Composable
private fun HeldMonthChip(
controller: MonthDragController,
parked: HeldChip,
origin: Offset,
timeFit: MonthChipTimeFit?,
) {
val reduceMotion = rememberReduceMotion()
val glide = remember { Animatable(parked.copy.topLeftInRoot, Offset.VectorConverter) }
val glideSpec = MaterialTheme.motionScheme.fastSpatialSpec<Offset>()
val seat = parked.seat
val landed = parked.token !in dropStates().pending
// Carried onto its seat once the write is in, as the settling chip is.
LaunchedEffect(seat, landed) {
if (seat == null || !landed) return@LaunchedEffect
if (reduceMotion) glide.snapTo(seat) else glide.animateTo(seat, glideSpec)
}
val alpha = rememberHeldSettle(
token = parked.token,
seated = seat != null,
timeoutMillis = MONTH_SETTLE_TIMEOUT_MILLIS,
onHandOver = { controller.handOverHeld(parked.token) },
onRelease = { controller.releaseHeld(parked.token) },
)
MonthChipCopy(parked.copy, { glide.value }, origin, lift = 0f, alpha = alpha, timeFit = timeFit)
}
/** [drag]'s chip floating over the grid with its top left at [at], in root coordinates. */
@Composable
private fun MonthChipCopy(
drag: MonthChipDrag,
at: () -> Offset,
origin: Offset,
lift: Float,
alpha: Float,
timeFit: MonthChipTimeFit?,
) {
val density = LocalDensity.current
val dark = LocalFloretDarkTheme.current
MonthBar(
event = drag.event,
dark = dark,
continuesLeft = false,
continuesRight = false,
// The time the source chip carried, drawn only if this one-column
// cut-out of it has the room — which a slice of a multi-day bar has
// not, however wide the bar was.
time = drag.time,
timeFit = timeFit,
chipWidth = with(density) { drag.sizePx.width.toDp() },
modifier = Modifier
// Absolute: these are root coordinates, and the direction-aware
// offset would mirror them across the screen in an RTL layout.
.absoluteOffset {
val topLeft = at()
IntOffset(
(topLeft.x - origin.x).roundToInt(),
(topLeft.y - origin.y).roundToInt(),
)
}
.width(with(density) { drag.sizePx.width.toDp() })
.height(with(density) { drag.sizePx.height.toDp() })
.padding(horizontal = MONTH_CHIP_INSET, vertical = 1.dp)
.graphicsLayer {
scaleX = 1f + 0.04f * lift
scaleY = 1f + 0.04f * lift
shadowElevation = 8.dp.toPx() * lift
this.alpha = alpha
shape = EventChipShape
clip = false
},
)
}
/**
* Content for both scrolling styles. No swipe detector and no [AnimatedContent]:
* vertical scrolling owns the gesture, and the list never swaps wholesale — it
@@ -2258,7 +2310,7 @@ private fun MonthWeekRow(
// Once the grid holds the settled chip, tell the controller where this row
// has seated it, so the copy in flight can glide onto it. Keyed on the week,
// which is what changes when the re-read lands.
LaunchedEffect(week, dragController?.settling) {
LaunchedEffect(week, dragController?.settling, dragController?.held) {
dragController?.noteSettled(rowToken)
}
@@ -2691,6 +2743,8 @@ private fun monthChipDragModifier(
beginMillis = drop.event.start.toEpochMilliseconds(),
endMillis = drop.event.end.toEpochMilliseconds(),
target = MoveTarget.ByDays(delta),
isAllDay = drop.event.isAllDay,
token = drop.token,
),
)
}
@@ -2701,13 +2755,13 @@ private fun monthChipDragModifier(
/**
* Left-gutter calendar-week cell (#25): a full-height tonal pill mirroring the
* day cells' geometry, set apart by the secondaryContainer tint (matching the
* Week view's badge), with the ISO week number centred like a day number. The
* week is computed on the row's first day — the same basis as the Week view — so
* the two agree.
* Week view's badge), with the week number centred like a day number. It is
* numbered by the device region from the row's mid-week day, as in the Week
* view, so it is right for any first weekday (#493).
*/
@Composable
private fun WeekNumberGutter(weekStart: LocalDate, modifier: Modifier = Modifier) {
val weekNumber = remember(weekStart) { weekStart.toJavaLocalDate().isoWeekNumber() }
val weekNumber = rememberRowWeekNumber(weekStart)
val label = stringResource(R.string.week_number_label)
val openLabel = stringResource(R.string.month_open_week, weekNumber)
val onOpenWeek = LocalOpenWeek.current
@@ -2836,8 +2890,17 @@ private fun MonthBar(
val moveAction = eventMoveAction(event)
// The source stays put as a ghost while its floating copy travels.
val monthDrag = LocalMonthDrag.current
val lifted = monthDrag?.liftedInstanceId == event.instanceId ||
monthDrag?.isSettledChip(event, days) == true
// Derived, so a chip recomposes only when its own answer changes rather than
// on every lift, park and release anywhere in the grid.
val lifted by remember(monthDrag, event, days) {
derivedStateOf {
monthDrag != null && (
monthDrag.liftedInstanceId == event.instanceId ||
monthDrag.isSettledChip(event, days) ||
monthDrag.isHeldChip(event, days)
)
}
}
val ghost = ghostAlpha(lifted)
val shape = monthBarShape(continuesLeft, continuesRight)
Box(
@@ -157,6 +157,7 @@ import de.jeanlucmakiola.calendula.ui.common.LocalEventMove
import de.jeanlucmakiola.calendula.ui.common.MoveRequest
import de.jeanlucmakiola.calendula.ui.common.MoveTarget
import de.jeanlucmakiola.calendula.ui.common.TimelineDragController
import de.jeanlucmakiola.calendula.ui.common.ghostsDerived
import de.jeanlucmakiola.calendula.ui.common.StripDrag
import de.jeanlucmakiola.calendula.ui.common.StripDrop
import de.jeanlucmakiola.calendula.ui.common.TimelineDragOverlay
@@ -209,7 +210,6 @@ import de.jeanlucmakiola.calendula.ui.common.TIMELINE_CONTENT_END_INSET
import de.jeanlucmakiola.calendula.ui.common.hourCellBlockInset
import de.jeanlucmakiola.calendula.ui.common.hourGridCells
import de.jeanlucmakiola.calendula.ui.common.tappedMinuteOfDay
import de.jeanlucmakiola.floret.time.isoWeekNumber
import kotlinx.coroutines.launch
import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.LocalDate
@@ -221,6 +221,7 @@ import kotlinx.datetime.toLocalDateTime
import java.time.format.TextStyle as JavaTextStyle
import java.util.Locale
import kotlinx.datetime.yearMonth
import de.jeanlucmakiola.calendula.ui.common.rememberRowWeekNumber
/** One lane of the all-day strip, sized to a trimmed bar line (#190). */
private val ALL_DAY_ROW_HEIGHT = 20.dp
@@ -591,7 +592,9 @@ private fun WeekContent(
eventId = drop.event.eventId,
beginMillis = drop.event.start.toEpochMilliseconds(),
endMillis = drop.event.end.toEpochMilliseconds(),
isAllDay = drop.event.isAllDay,
target = MoveTarget.Start(start),
token = drop.token,
),
)
}
@@ -610,7 +613,9 @@ private fun WeekContent(
eventId = drop.event.eventId,
beginMillis = drop.event.start.toEpochMilliseconds(),
endMillis = drop.event.end.toEpochMilliseconds(),
isAllDay = drop.event.isAllDay,
target = MoveTarget.Span(drop.start, drop.end),
token = drop.token,
),
)
}
@@ -622,10 +627,12 @@ private fun WeekContent(
eventId = drop.event.eventId,
beginMillis = drop.event.start.toEpochMilliseconds(),
endMillis = drop.event.end.toEpochMilliseconds(),
isAllDay = drop.event.isAllDay,
target = when (drop) {
is StripDrop.Days -> MoveTarget.ByDays(drop.days)
is StripDrop.Timed -> MoveTarget.Span(drop.start, drop.end)
},
token = drop.token,
),
)
}
@@ -767,8 +774,7 @@ private fun WeekPager(
// Until its days arrive a page shows their frame without events.
val empty = remember(pageSpan, today) { emptySpan(pageSpan, today) }
// A bar held over other days in the strip makes room there before it is dropped.
val held = (dragController.stripDrag ?: dragController.stripSettling)
?.takeIf { page == pagerState.currentPage }
val held = dragController.stripPreviews().takeIf { page == pagerState.currentPage }.orEmpty()
val zone = LocalTimelineZone.current
val shown = remember(loaded, held, zone) { loaded?.withStripPreview(held, zone) }
val stripHeight = shown?.allDayStripHeight()
@@ -793,17 +799,24 @@ private fun WeekPager(
}
/**
* [this] with the strip bar [held] sideways laid out at the days it is over, so
* the bars there move aside live. The bar keeps its own event, and with it its
* key and the gesture on it; one moved off the page keeps a lane it is not seen in.
* [this] with the strip bars [held] sideways laid out at the days they are over,
* so the bars there move aside live. Each bar keeps its own event, and with it
* its key and the gesture on it; one moved off the page keeps a lane it is not
* seen in.
*/
internal fun WeekUiState.Success.withStripPreview(held: StripDrag?, zone: TimeZone): WeekUiState.Success {
if (held == null || held.overGrid || held.dayShift == 0) return this
val id = held.event.instanceId
val original = allDaySpans.firstOrNull { it.event.instanceId == id } ?: return this
val events = allDaySpans.map { if (it.event.instanceId == id) it.event.shiftedDays(held.dayShift, zone) else it.event }
val spans = layoutAllDay(events, days, zone).map { if (it.event.instanceId == id) it.copy(event = original.event) else it }
return copy(allDaySpans = if (spans.any { it.event.instanceId == id }) spans else spans + original.copy(lane = 0))
internal fun WeekUiState.Success.withStripPreview(held: List<StripDrag>, zone: TimeZone): WeekUiState.Success {
val shifts = held.filter { !it.overGrid && it.dayShift != 0 }.associate { it.event.instanceId to it.dayShift }
if (shifts.isEmpty()) return this
val originals = allDaySpans.filter { it.event.instanceId in shifts }.associateBy { it.event.instanceId }
if (originals.isEmpty()) return this
val events = allDaySpans.map { span ->
shifts[span.event.instanceId]?.let { span.event.shiftedDays(it, zone) } ?: span.event
}
val spans = layoutAllDay(events, days, zone).map { span ->
originals[span.event.instanceId]?.let { span.copy(event = it.event) } ?: span
}
val laidOut = spans.mapTo(HashSet()) { it.event.instanceId }
return copy(allDaySpans = spans + originals.values.filter { it.event.instanceId !in laidOut }.map { it.copy(lane = 0) })
}
private fun EventInstance.shiftedDays(days: Int, zone: TimeZone): EventInstance {
@@ -811,6 +824,17 @@ private fun EventInstance.shiftedDays(days: Int, zone: TimeZone): EventInstance
return copy(start = start.plus(days, DateTimeUnit.DAY, dates), end = end.plus(days, DateTimeUnit.DAY, dates))
}
/** Whether these bars draw the strip drop [drop] at the days it was dropped on. */
private fun List<PlacedBar>.drawStripDrop(drop: StripDrag, zone: TimeZone): Boolean {
val target = drop.event.spanFirstDay(zone).plus(drop.dayShift, DateTimeUnit.DAY)
return any { bar ->
bar.event.instanceId != drop.event.instanceId &&
(bar.event.eventId == drop.event.eventId ||
(drop.event.title.isNotBlank() && bar.event.title == drop.event.title)) &&
bar.event.spanFirstDay(zone) == target
}
}
/** A page with no events yet, for one whose days are still loading. */
private fun emptySpan(span: DaySpan, today: LocalDate): WeekUiState.Success {
val days = (0 until span.count).map { span.start.plus(it, kotlinx.datetime.DateTimeUnit.DAY) }
@@ -1137,7 +1161,7 @@ private fun WeekDayHeader(
*/
@Composable
private fun WeekNumberCell(weekStart: LocalDate, showBadge: Boolean, modifier: Modifier = Modifier) {
val weekNumber = remember(weekStart) { weekStart.toJavaLocalDate().isoWeekNumber() }
val weekNumber = rememberRowWeekNumber(weekStart)
Column(
modifier = modifier
.fillMaxWidth()
@@ -1193,17 +1217,11 @@ private fun AllDayStrip(
val sideways = held?.takeIf { !it.overGrid }
val lifted = dragController.liftedInstanceId?.takeIf { active && dragController.stripDrag?.overGrid != false }
val settling = dragController.stripSettling?.takeIf { active }
val heldStrips = dragController.heldStrips.takeIf { active }.orEmpty()
// Seated once the re-read draws the event at the days it was dropped on.
LaunchedEffect(settling, bars) {
if (settling == null) return@LaunchedEffect
val target = settling.event.spanFirstDay(zone).plus(settling.dayShift, DateTimeUnit.DAY)
val landed = bars.any { bar ->
bar.event.instanceId != settling.event.instanceId &&
(bar.event.eventId == settling.event.eventId ||
(settling.event.title.isNotBlank() && bar.event.title == settling.event.title)) &&
bar.event.spanFirstDay(zone) == target
}
if (landed) dragController.seatStrip()
LaunchedEffect(settling, heldStrips, bars) {
if (settling != null && bars.drawStripDrop(settling, zone)) dragController.seatStrip()
heldStrips.forEach { if (!it.seated && bars.drawStripDrop(it.drag, zone)) dragController.seatHeldStrip(it.token) }
}
Row(
@@ -1588,7 +1606,7 @@ private fun DayColumnCard(
widthFraction = 1f / block.laneCount,
y = top,
height = height,
landing = dragController.ghosts(block),
landing = dragController.ghostsDerived(block),
)
val topInset = hourCellBlockInset(showHourGrid, cuts.top)
val bottomInset = hourCellBlockInset(showHourGrid, cuts.bottom)
@@ -1756,7 +1774,7 @@ private fun EventBlock(
onCancel = dragController::cancel,
onRelease = { dragController.select(block.event, fromLift = draggable) },
)
val lifted = draggable && dragController.ghosts(block)
val lifted = draggable && dragController.ghostsDerived(block)
// Released in place, the block takes over the copy's lift without a dip.
val takesOverLift = selected && dragController.selection?.fromLift == true
val ghostFade = ghostAlpha(lifted)
@@ -4,6 +4,7 @@ import android.content.Context
import androidx.datastore.preferences.core.MutablePreferences
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.floatPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.core.stringSetPreferencesKey
import androidx.glance.GlanceId
@@ -26,14 +27,22 @@ enum class WidgetTheme { FOLLOW_APP, LIGHT, DARK }
data class WidgetAppearance(
val background: WidgetBackground = WidgetBackground.TINTED,
val theme: WidgetTheme = WidgetTheme.FOLLOW_APP,
/** How opaque a Solid or Tinted fill is (#489). */
val opacity: Float = 1f,
)
/** The agenda widget's look: the 2.24 day cards, or v2.23's plain day headers and stripes (#489). */
enum class AgendaWidgetStyle { CARDS, CLASSIC }
/** What the agenda widget lists, per placed widget. */
data class AgendaWidgetOptions(
val range: AgendaRange,
val textSize: WidgetSize,
val showToday: Boolean,
val pastDisplay: PastEventDisplay,
val style: AgendaWidgetStyle = AgendaWidgetStyle.CARDS,
/** Classic style only: draw the text in the opposite theme's colours, for a faded fill over the wallpaper. */
val invertText: Boolean = false,
)
internal fun WidgetTheme.resolve(app: ThemeMode): WidgetThemeMode = when (this) {
@@ -48,6 +57,9 @@ internal fun WidgetTheme.resolve(app: ThemeMode): WidgetThemeMode = when (this)
private val BackgroundKey = stringPreferencesKey("cfg_background")
private val ThemeKey = stringPreferencesKey("cfg_theme")
private val OpacityKey = floatPreferencesKey("cfg_opacity")
private val AgendaStyleKey = stringPreferencesKey("cfg_agenda_style")
private val InvertTextKey = booleanPreferencesKey("cfg_invert_text")
private val AgendaRangeKey = stringPreferencesKey("cfg_agenda_range")
private val TextSizeKey = stringPreferencesKey("cfg_text_size")
private val ShowTodayKey = booleanPreferencesKey("cfg_show_today")
@@ -58,6 +70,7 @@ internal val Preferences.widgetAppearance: WidgetAppearance
get() = WidgetAppearance(
background = this[BackgroundKey].toEnum(WidgetBackground.TINTED),
theme = this[ThemeKey].toEnum(WidgetTheme.FOLLOW_APP),
opacity = this[OpacityKey] ?: 1f,
)
/**
@@ -70,6 +83,8 @@ internal fun Preferences.agendaWidgetOptions(defaults: AgendaWidgetOptions) = Ag
textSize = this[TextSizeKey].toEnum(defaults.textSize),
showToday = this[ShowTodayKey] ?: defaults.showToday,
pastDisplay = this[PastDisplayKey].toEnum(defaults.pastDisplay),
style = this[AgendaStyleKey].toEnum(defaults.style),
invertText = this[InvertTextKey] ?: defaults.invertText,
)
/** Whether this widget has agenda options of its own, rather than following the app's. */
@@ -78,6 +93,7 @@ internal val Preferences.hasAgendaOptions: Boolean get() = this[AgendaRangeKey]
internal fun MutablePreferences.putAppearance(appearance: WidgetAppearance) {
this[BackgroundKey] = appearance.background.name
this[ThemeKey] = appearance.theme.name
this[OpacityKey] = appearance.opacity
}
internal fun MutablePreferences.putAgendaOptions(options: AgendaWidgetOptions) {
@@ -85,6 +101,8 @@ internal fun MutablePreferences.putAgendaOptions(options: AgendaWidgetOptions) {
this[TextSizeKey] = options.textSize.name
this[ShowTodayKey] = options.showToday
this[PastDisplayKey] = options.pastDisplay.name
this[AgendaStyleKey] = options.style.name
this[InvertTextKey] = options.invertText
}
/**
@@ -126,6 +126,8 @@ sealed interface AgendaWidgetData {
/** "Always show today" (#35): anchor today at the top even with no events left. */
val showToday: Boolean,
val textSize: WidgetSize,
val style: AgendaWidgetStyle = AgendaWidgetStyle.CARDS,
val invertText: Boolean = false,
/** Snapshot instant the data was read at, for "has this event ended?" tests. */
val now: Instant,
) : AgendaWidgetData
@@ -184,6 +186,8 @@ internal suspend fun Context.loadAgendaWidgetData(
pastDisplay = options.pastDisplay,
showToday = options.showToday,
textSize = options.textSize,
style = options.style,
invertText = options.invertText,
now = Clock.System.now(),
)
}
@@ -2,6 +2,7 @@ package de.jeanlucmakiola.calendula.widget
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.compositeOver
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
@@ -18,7 +19,6 @@ import androidx.glance.layout.padding
import androidx.glance.text.FontWeight
import androidx.glance.text.Text
import androidx.glance.text.TextStyle
import de.jeanlucmakiola.calendula.MainActivity
import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.domain.isCrossedOut
@@ -26,20 +26,33 @@ import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.common.SECONDARY_INK_ALPHA
import de.jeanlucmakiola.calendula.ui.common.eventFill
import de.jeanlucmakiola.calendula.ui.common.eventInk
import de.jeanlucmakiola.calendula.ui.theme.CalendulaDarkFallback
import de.jeanlucmakiola.calendula.widget.agenda.metricsFor
import de.jeanlucmakiola.floret.components.Position
import de.jeanlucmakiola.floret.glance.WidgetGroupedRow
import de.jeanlucmakiola.floret.glance.themedColor
/** A past event's fill when dimmed: fainter than the app's whole-row dim, so its text can stay readable (#90). */
internal const val WidgetDimFillAlpha = 0.3f
/** How much of a past event's tone stays in its dimmed fill (#90). */
private const val WidgetDimFillAlpha = 0.3f
/** A dimmed event's ink, held above its fill. */
private const val WidgetDimInkAlpha = 0.65f
/** Ink for an event on [fill], picked against the opaque tone and faded when the fill is dimmed. */
internal fun widgetEventInk(fill: Color, alpha: Float): Color =
eventInk(fill.copy(alpha = 1f), if (fill.alpha < 1f) alpha * WidgetDimInkAlpha else alpha)
/**
* An event's fill in the light or [dark] theme. A dimmed one is its tone faded
* into that theme's surface, kept opaque: a translucent tint lands on the row
* shape's white, not on the widget, and its ink would be picked for the wrong tone (#475).
*/
internal fun widgetEventFill(rawArgb: Int, dark: Boolean, soften: Boolean, dimmed: Boolean): Color {
val tone = eventFill(rawArgb, dark, soften)
if (!dimmed) return tone
val surface = if (dark) CalendulaDarkFallback.surface else Color.White
return tone.copy(alpha = WidgetDimFillAlpha).compositeOver(surface)
}
/** Ink for an event on [fill], faded when the row is [dimmed]. */
internal fun widgetEventInk(fill: Color, alpha: Float, dimmed: Boolean): Color =
eventInk(fill, if (dimmed) alpha * WidgetDimInkAlpha else alpha)
/** Text and row sizes of a compact event list, from a widget's [WidgetSize]. */
internal data class EventRowMetrics(val title: TextUnit, val time: TextUnit, val rowHeight: Dp, val message: TextUnit)
@@ -72,9 +85,8 @@ internal fun WidgetEventRow(
quiet: Boolean = false,
) {
val context = LocalContext.current
fun tone(dark: Boolean): Color = eventFill(event.color, dark, soften).let { if (dimmed) it.copy(alpha = WidgetDimFillAlpha) else it }
val day = tone(dark = false)
val night = tone(dark = true)
val day = widgetEventFill(event.color, dark = false, soften, dimmed)
val night = widgetEventFill(event.color, dark = true, soften, dimmed)
val card = widgetCardColor()
WidgetGroupedRow(position = position, color = if (quiet) card else themedColor(day = day, night = night)) {
Column(
@@ -84,13 +96,7 @@ internal fun WidgetEventRow(
.padding(horizontal = 12.dp)
.clickable(
actionStartActivity(
MainActivity.openEventIntent(
context = context,
eventId = event.eventId,
beginMillis = event.start.toEpochMilliseconds(),
endMillis = event.end.toEpochMilliseconds(),
source = source,
),
event.openIntent(context, source),
),
),
verticalAlignment = Alignment.CenterVertically,
@@ -98,12 +104,12 @@ internal fun WidgetEventRow(
val titleInk = if (quiet) {
GlanceTheme.colors.onSurface
} else {
themedColor(day = widgetEventInk(day, 1f), night = widgetEventInk(night, 1f))
themedColor(day = widgetEventInk(day, 1f, dimmed), night = widgetEventInk(night, 1f, dimmed))
}
val timeInk = if (quiet) {
GlanceTheme.colors.onSurfaceVariant
} else {
themedColor(day = widgetEventInk(day, SECONDARY_INK_ALPHA), night = widgetEventInk(night, SECONDARY_INK_ALPHA))
themedColor(day = widgetEventInk(day, SECONDARY_INK_ALPHA, dimmed), night = widgetEventInk(night, SECONDARY_INK_ALPHA, dimmed))
}
Text(
text = event.title.ifBlank { context.getString(R.string.event_untitled) },
@@ -26,7 +26,7 @@ import de.jeanlucmakiola.calendula.widget.split.MonthDayWidget
import de.jeanlucmakiola.calendula.widget.split.MonthDayWidgetReceiver
/** A content option a widget's config screen offers, besides background and theme. */
enum class WidgetOption { RANGE, TEXT_SIZE, PAST_DISPLAY, SHOW_TODAY, CALENDARS }
enum class WidgetOption { STYLE, RANGE, TEXT_SIZE, PAST_DISPLAY, SHOW_TODAY, CALENDARS }
/**
* Every widget the app ships, told apart by their receiver: what redraws,
@@ -42,7 +42,14 @@ enum class WidgetKind(
AGENDA(
AgendaWidgetReceiver::class.java,
R.string.widget_agenda_label,
setOf(WidgetOption.RANGE, WidgetOption.TEXT_SIZE, WidgetOption.PAST_DISPLAY, WidgetOption.SHOW_TODAY, WidgetOption.CALENDARS),
setOf(
WidgetOption.STYLE,
WidgetOption.RANGE,
WidgetOption.TEXT_SIZE,
WidgetOption.PAST_DISPLAY,
WidgetOption.SHOW_TODAY,
WidgetOption.CALENDARS,
),
DpSize(260.dp, 280.dp),
),
MONTH(
@@ -19,6 +19,9 @@ import kotlinx.datetime.toJavaDayOfWeek
import kotlinx.datetime.toJavaLocalDate
import kotlinx.datetime.toLocalDateTime
import kotlin.time.Instant
import de.jeanlucmakiola.calendula.MainActivity
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import androidx.glance.appwidget.action.actionStartActivity
/** Cards sit one tone off the root fill, and stay opaque over a wallpaper (#292). */
@Composable
@@ -27,6 +30,19 @@ internal fun widgetCardColor(): ColorProvider = when (LocalWidgetBackground.curr
WidgetBackground.TINTED, WidgetBackground.TRANSPARENT -> GlanceTheme.colors.widgetBackground
}
/** Opens this occurrence in the app, backing out to [source]. */
internal fun EventInstance.openIntent(context: Context, source: CalendarView) = MainActivity.openEventIntent(
context = context,
eventId = eventId,
beginMillis = start.toEpochMilliseconds(),
endMillis = end.toEpochMilliseconds(),
source = source,
)
/** Opens [date] in the app's agenda. */
internal fun openDayAction(context: Context, date: LocalDate) =
actionStartActivity(MainActivity.openDateIntent(context, date, CalendarView.Agenda))
/** An event's time on [day]: "All day", "Starts 14:00", "Ends 9:00" or "14:00 – 15:30". */
internal fun widgetTimeLabel(context: Context, event: EventInstance, day: LocalDate, is24Hour: Boolean): String =
when (val label = agendaTimeLabel(event, day, systemZone())) {
@@ -34,7 +34,7 @@ fun CalendulaGlanceTheme(mode: WidgetThemeMode, content: @Composable () -> Unit)
@Composable
internal fun CalendulaWidgetRoot(appearance: WidgetAppearance, appTheme: ThemeMode, content: @Composable () -> Unit) {
CalendulaGlanceTheme(appearance.theme.resolve(appTheme)) {
WidgetSurface(background = appearance.background, content = content)
WidgetSurface(background = appearance.background, opacity = appearance.opacity, content = content)
}
}
@@ -12,6 +12,15 @@ internal val ROW_H_PAD = 12.dp
/** Space between the date-pill gutter and a day's card. */
internal val GUTTER_GAP = 6.dp
/** The classic style's row inset, colour stripe and the gap after it (#489). */
internal val CLASSIC_ROW_H_PAD = 4.dp
internal val STRIPE_WIDTH = 5.dp
internal val STRIPE_GAP = 10.dp
/** The stripe and its gap, and where the classic style's event text starts, so its placeholder lines up with the titles. */
internal val STRIPE_INSET = STRIPE_WIDTH + STRIPE_GAP
internal val TEXT_INDENT = CLASSIC_ROW_H_PAD + STRIPE_INSET
/**
* Every size the agenda widget varies by [WidgetSize]. Values that genuinely
* shouldn't grow (the horizontal row constants above, corner radii) stay
@@ -29,6 +38,8 @@ internal data class AgendaMetrics(
val rowVPad: Dp, // event row vertical padding
val dayGap: Dp, // space between two days' cards
val monthLabel: TextUnit, // month name above a new month's first day
val dayHeader: TextUnit, // classic style's day label ("Today · …")
val dayHeaderTopPad: Dp, // classic style's space above a day label
) {
/** One event row's height, shared by the date pill beside it and the placeholder row. */
val rowHeight: Dp get() = contentH + rowVPad * 2
@@ -61,6 +72,8 @@ private val SMALL_METRICS = AgendaMetrics(
rowVPad = 4.dp,
dayGap = 8.dp,
monthLabel = 12.sp,
dayHeader = 13.sp,
dayHeaderTopPad = 10.dp,
)
private val MEDIUM_METRICS = AgendaMetrics(
@@ -75,6 +88,8 @@ private val MEDIUM_METRICS = AgendaMetrics(
rowVPad = 5.dp,
dayGap = 9.dp,
monthLabel = 14.sp,
dayHeader = 14.sp, // M3 Title Small
dayHeaderTopPad = 11.dp,
)
private val LARGE_METRICS = AgendaMetrics(
@@ -89,6 +104,8 @@ private val LARGE_METRICS = AgendaMetrics(
rowVPad = 6.dp,
dayGap = 10.dp,
monthLabel = 14.sp,
dayHeader = 16.sp, // M3 Title Medium
dayHeaderTopPad = 12.dp,
)
private val EXTRA_LARGE_METRICS = AgendaMetrics(
@@ -103,6 +120,8 @@ private val EXTRA_LARGE_METRICS = AgendaMetrics(
rowVPad = 8.dp,
dayGap = 12.dp,
monthLabel = 16.sp,
dayHeader = 18.sp, // †
dayHeaderTopPad = 14.dp,
)
/** Indexed by [WidgetSize.ordinal] so lookup allocates nothing per recomposition. */
@@ -11,6 +11,7 @@ import de.jeanlucmakiola.calendula.widget.glanceDeclinedDecoration
import android.content.Context
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.glance.GlanceId
import androidx.glance.GlanceModifier
@@ -55,8 +56,15 @@ import de.jeanlucmakiola.calendula.ui.agenda.anchorTodayIfMissing
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.ui.common.formatCalendarTitle
import de.jeanlucmakiola.floret.locale.localizedDateFormatter
import de.jeanlucmakiola.calendula.ui.common.eventFill
import de.jeanlucmakiola.calendula.widget.WidgetDimFillAlpha
import de.jeanlucmakiola.calendula.widget.widgetEventFill
import de.jeanlucmakiola.calendula.ui.common.eventAccent
import de.jeanlucmakiola.calendula.ui.common.EventDimAlpha
import de.jeanlucmakiola.calendula.widget.AgendaWidgetStyle
import de.jeanlucmakiola.floret.glance.LocalWidgetBackground
import de.jeanlucmakiola.floret.glance.LocalWidgetSeeThrough
import androidx.compose.runtime.CompositionLocalProvider
import de.jeanlucmakiola.floret.glance.WidgetBackground
import de.jeanlucmakiola.floret.glance.withAlpha
import de.jeanlucmakiola.calendula.widget.widgetEventInk
import de.jeanlucmakiola.calendula.ui.common.SECONDARY_INK_ALPHA
import de.jeanlucmakiola.calendula.widget.AgendaWidgetData
@@ -65,6 +73,8 @@ import de.jeanlucmakiola.calendula.widget.CalendulaWidgetRoot
import de.jeanlucmakiola.calendula.widget.WidgetAppearance
import de.jeanlucmakiola.calendula.widget.widgetCardColor
import de.jeanlucmakiola.calendula.widget.widgetTimeLabel
import de.jeanlucmakiola.calendula.widget.openIntent
import de.jeanlucmakiola.calendula.widget.openDayAction
import de.jeanlucmakiola.calendula.widget.loadAgendaWidget
import de.jeanlucmakiola.calendula.widget.widgetAppearance
import de.jeanlucmakiola.floret.components.Position
@@ -87,7 +97,8 @@ import kotlinx.datetime.toJavaDayOfWeek
/**
* "Upcoming" agenda widget — a continuously scrolling list of the next ~30 days
* of events, each day one card of grouped rows with its date pill beside it.
* of events: each day one card of grouped rows with its date pill beside it, or
* in the classic style a label line over plain colour-stripe rows (#489).
* Reuses the app's [groupAgendaDays] grouping so it matches the in-app agenda.
*/
class AgendaWidget : GlanceAppWidget() {
@@ -150,10 +161,10 @@ private const val PREVIEW_ROWS = 10
* user scrolling a home-screen widget past a hundred rows is not a case worth
* risking a failed update for.
*/
private const val MAX_AGENDA_ROWS = 100
internal const val MAX_AGENDA_ROWS = 100
/** Flat row model: one [LazyColumn] item per event or placeholder, a day's first one carrying its date pill. */
private sealed interface AgendaRow {
internal sealed interface AgendaRow {
val date: LocalDate
data class Event(override val date: LocalDate, val event: EventInstance) : AgendaRow
@@ -168,16 +179,21 @@ private fun AgendaWidgetBody(data: AgendaWidgetData, preview: Boolean) {
val size = (data as? AgendaWidgetData.Ready)?.textSize ?: WidgetSize.SMALL
val fontScale = androidx.glance.LocalContext.current.resources.configuration.fontScale
val metrics = metricsFor(size).scaledForFont(fontScale)
Column(
modifier = GlanceModifier
.fillMaxSize()
.padding(horizontal = 8.dp, vertical = 6.dp),
) {
AgendaHeader()
Spacer(GlanceModifier.height(6.dp))
when (data) {
AgendaWidgetData.NeedsPermission -> WidgetMessage(R.string.widget_needs_permission, metrics)
is AgendaWidgetData.Ready -> AgendaRows(data = data, metrics = metrics, preview = preview)
// The classic style adds no backings for a faded fill, only on a transparent one (#489).
val classic = (data as? AgendaWidgetData.Ready)?.style == AgendaWidgetStyle.CLASSIC
val seeThrough = if (classic) LocalWidgetBackground.current == WidgetBackground.TRANSPARENT else LocalWidgetSeeThrough.current
CompositionLocalProvider(LocalWidgetSeeThrough provides seeThrough) {
Column(
modifier = GlanceModifier
.fillMaxSize()
.padding(horizontal = 8.dp, vertical = 6.dp),
) {
AgendaHeader()
Spacer(GlanceModifier.height(6.dp))
when (data) {
AgendaWidgetData.NeedsPermission -> WidgetMessage(R.string.widget_needs_permission, metrics)
is AgendaWidgetData.Ready -> AgendaRows(data = data, metrics = metrics, preview = preview)
}
}
}
}
@@ -219,60 +235,248 @@ private fun AgendaRows(
day.events.forEach { add(AgendaRow.Event(day.date, it)) }
}
}
}.take(MAX_AGENDA_ROWS)
// Each day is one card of grouped rows (#71), with its date pill
// beside the first row.
val positions = dayPositions(rows)
val cardColor = widgetCardColor()
val item: @Composable (Int) -> Unit = { index ->
val row = rows[index]
val position = positions[index]
val first = position == Position.Top || position == Position.Alone
val dayRow: @Composable (GlanceModifier) -> Unit = { modifier ->
Row(modifier = modifier.fillMaxWidth()) {
Box(modifier = GlanceModifier.width(metrics.pillWidth)) {
if (first) DatePill(row.date, data.today, cardColor, metrics)
}
Spacer(GlanceModifier.width(GUTTER_GAP))
Box(modifier = GlanceModifier.defaultWeight()) {
val rowColor = when (row) {
is AgendaRow.Event -> row.fill(data).let { themedColor(day = it.day, night = it.night) }
is AgendaRow.Placeholder -> cardColor
}
WidgetGroupedRow(position = position, color = rowColor) {
AgendaRowContent(row, data, metrics)
}
}
}
}
val gap = GlanceModifier.padding(top = if (first && index > 0) metrics.dayGap else 0.dp)
// The pills carry no month, so a new month gets its name above its first day.
if (first && index > 0 && row.date.month != rows[index - 1].date.month) {
Column(modifier = gap.fillMaxWidth()) {
MonthLabel(row.date, data.today, metrics)
dayRow(GlanceModifier)
}
} else {
dayRow(gap)
}
}
if (preview) {
Column(modifier = GlanceModifier.fillMaxSize()) {
repeat(minOf(rows.size, PREVIEW_ROWS)) { item(it) }
}
} else {
LazyColumn(modifier = GlanceModifier.fillMaxSize()) {
items(rows.size) { item(it) }
}
when (data.style) {
AgendaWidgetStyle.CARDS -> CardRows(rows, data, metrics, preview)
AgendaWidgetStyle.CLASSIC -> ClassicRows(rows, data, metrics, preview)
}
}
}
/** Where each row sits among the rows of its day, for the grouped-card shapes. */
private fun dayPositions(rows: List<AgendaRow>): List<Position> = buildList {
/** Each day is one card of grouped rows (#71), with its date pill beside the first row. */
@Composable
private fun CardRows(allRows: List<AgendaRow>, data: AgendaWidgetData.Ready, metrics: AgendaMetrics, preview: Boolean) {
val rows = allRows.take(MAX_AGENDA_ROWS)
val positions = dayPositions(rows.map { it.date })
val cardColor = widgetCardColor()
val item: @Composable (Int) -> Unit = { index ->
val row = rows[index]
val position = positions[index]
val first = position == Position.Top || position == Position.Alone
val dayRow: @Composable (GlanceModifier) -> Unit = { modifier ->
Row(modifier = modifier.fillMaxWidth()) {
Box(modifier = GlanceModifier.width(metrics.pillWidth)) {
if (first) DatePill(row.date, data.today, cardColor, metrics)
}
Spacer(GlanceModifier.width(GUTTER_GAP))
Box(modifier = GlanceModifier.defaultWeight()) {
val rowColor = when (row) {
is AgendaRow.Event -> row.fill(data).let { themedColor(day = it.day, night = it.night) }
is AgendaRow.Placeholder -> cardColor
}
WidgetGroupedRow(position = position, color = rowColor) {
AgendaRowContent(row, data, metrics)
}
}
}
}
val gap = GlanceModifier.padding(top = if (first && index > 0) metrics.dayGap else 0.dp)
// The pills carry no month, so a new month gets its name above its first day.
if (first && index > 0 && row.date.month != rows[index - 1].date.month) {
Column(modifier = gap.fillMaxWidth()) {
MonthLabel(row.date, data.today, metrics)
dayRow(GlanceModifier)
}
} else {
dayRow(gap)
}
}
RowList(rows.size, preview, item)
}
/** [count] rows of [item]: a plain column in a [preview], else a [LazyColumn]. */
@Composable
private fun RowList(count: Int, preview: Boolean, item: @Composable (Int) -> Unit) {
if (preview) {
Column(modifier = GlanceModifier.fillMaxSize()) {
repeat(minOf(count, PREVIEW_ROWS)) { item(it) }
}
} else {
LazyColumn(modifier = GlanceModifier.fillMaxSize()) {
items(count) { item(it) }
}
}
}
/** A classic list entry: a day's label line, or one of its rows. */
internal sealed interface ClassicItem {
val date: LocalDate
data class Header(override val date: LocalDate) : ClassicItem
data class Entry(val row: AgendaRow) : ClassicItem {
override val date: LocalDate get() = row.date
}
}
/**
* [rows] with a label before each day's first, held to [limit] items in all,
* headers included; a label the cut leaves with nothing under it is dropped.
*/
internal fun classicItems(rows: List<AgendaRow>, limit: Int = MAX_AGENDA_ROWS): List<ClassicItem> = buildList {
rows.forEachIndexed { index, row ->
if (index == 0 || row.date != rows[index - 1].date) add(ClassicItem.Header(row.date))
add(ClassicItem.Entry(row))
}
}.take(limit).dropLastWhile { it is ClassicItem.Header }
/**
* v2.23's look (#489): a label line per day over plain rows with a colour
* stripe. On a transparent root each day sits on its own backing card, so the
* text stays readable over the wallpaper; a faded fill is left to the opacity
* and "Invert text colour" options.
*/
@Composable
private fun ClassicRows(rows: List<AgendaRow>, data: AgendaWidgetData.Ready, metrics: AgendaMetrics, preview: Boolean) {
val items = classicItems(rows, if (preview) PREVIEW_ROWS else MAX_AGENDA_ROWS)
val backed = LocalWidgetBackground.current == WidgetBackground.TRANSPARENT
val ink = classicInk(inverted = data.invertText && !backed)
val positions = if (backed) dayPositions(items.map { it.date }) else emptyList()
val cardColor = widgetCardColor()
val item: @Composable (Int) -> Unit = { index ->
val entry = items[index]
val content: @Composable () -> Unit = {
when (entry) {
is ClassicItem.Header -> DayHeaderRow(
date = entry.date,
today = data.today,
startPad = if (backed) CLASSIC_CARD_H_PAD else 8.dp,
topPad = when {
backed -> CLASSIC_CARD_TOP_PAD
index == 0 -> 0.dp
else -> metrics.dayHeaderTopPad
},
ink = ink,
metrics = metrics,
)
is ClassicItem.Entry -> when (val row = entry.row) {
is AgendaRow.Placeholder -> ClassicPlaceholderRow(row.date, backed, ink, metrics)
is AgendaRow.Event -> ClassicEventRow(row, data, backed, ink, metrics)
}
}
}
if (backed) {
val gap = if (entry is ClassicItem.Header && index > 0) metrics.dayGap else 0.dp
WidgetGroupedRow(
position = positions[index],
modifier = GlanceModifier.padding(top = gap),
color = cardColor,
gapBelow = false,
content = content,
)
} else {
content()
}
}
RowList(items.size, preview, item)
}
/** The classic style's text colours: the theme's, or its inverse for the "Invert text colour" option. */
private data class ClassicInk(val title: ColorProvider, val secondary: ColorProvider, val today: ColorProvider)
@Composable
private fun classicInk(inverted: Boolean): ClassicInk = with(GlanceTheme.colors) {
if (inverted) {
ClassicInk(inverseOnSurface, inverseOnSurface.withAlpha(INVERTED_SECONDARY_INK), inversePrimary)
} else {
ClassicInk(onSurface, onSurfaceVariant, primary)
}
}
/** A classic day label, "Today · Wed, 17 Jun"; opens that day in the app. */
@Composable
private fun DayHeaderRow(date: LocalDate, today: LocalDate, startPad: Dp, topPad: Dp, ink: ClassicInk, metrics: AgendaMetrics) {
val context = androidx.glance.LocalContext.current
Text(
text = agendaDayLabel(context, date, today),
maxLines = 1,
style = TextStyle(
color = if (date == today) ink.today else ink.secondary,
fontSize = metrics.dayHeader,
fontWeight = FontWeight.Medium,
),
modifier = GlanceModifier
.fillMaxWidth()
.padding(start = startPad, end = 8.dp, top = topPad, bottom = metrics.rowVPad)
.clickable(openDayAction(context, date)),
)
}
/** "No more events today" as a muted line under an anchored, event-less today (#35), indented to the titles. */
@Composable
private fun ClassicPlaceholderRow(date: LocalDate, backed: Boolean, ink: ClassicInk, metrics: AgendaMetrics) {
val context = androidx.glance.LocalContext.current
Text(
text = context.getString(R.string.agenda_no_more_today),
maxLines = 1,
style = TextStyle(color = ink.secondary, fontSize = metrics.placeholder),
modifier = GlanceModifier
.fillMaxWidth()
.padding(start = if (backed) CLASSIC_CARD_H_PAD + STRIPE_INSET else TEXT_INDENT, end = 8.dp, top = 2.dp, bottom = metrics.rowVPad + 2.dp)
.clickable(openDayAction(context, date)),
)
}
/** A classic event row: the calendar's colour stripe beside the title and time; a dimmed one fades both. */
@Composable
private fun ClassicEventRow(row: AgendaRow.Event, data: AgendaWidgetData.Ready, backed: Boolean, ink: ClassicInk, metrics: AgendaMetrics) {
val context = androidx.glance.LocalContext.current
val event = row.event
val dimmed = row.dimmed(data)
fun accent(dark: Boolean) = eventAccent(event.color, dark, data.soften).let {
if (dimmed) it.copy(alpha = EventDimAlpha) else it
}
Row(
modifier = GlanceModifier
.fillMaxWidth()
.padding(horizontal = if (backed) CLASSIC_CARD_H_PAD else CLASSIC_ROW_H_PAD, vertical = metrics.rowVPad)
.clickable(actionStartActivity(event.openIntent(context, CalendarView.Agenda))),
verticalAlignment = Alignment.CenterVertically,
) {
Box(
modifier = GlanceModifier
.width(STRIPE_WIDTH)
.height(metrics.contentH)
.cornerRadius(3.dp)
.background(themedColor(day = accent(dark = false), night = accent(dark = true))),
) {}
Spacer(GlanceModifier.width(STRIPE_GAP))
Column(modifier = GlanceModifier.defaultWeight()) {
Text(
text = event.title.ifBlank { context.getString(R.string.event_untitled) },
maxLines = 1,
style = TextStyle(
color = if (dimmed) ink.title.withAlpha(CLASSIC_DIM_INK) else ink.title,
fontSize = metrics.eventTitle,
textDecoration = glanceDeclinedDecoration(event.isCrossedOut),
),
)
Text(
text = eventTimeSummary(context, event, row.date, data.is24Hour),
maxLines = 1,
style = TextStyle(
color = if (dimmed) ink.secondary.withAlpha(CLASSIC_DIM_INK) else ink.secondary,
fontSize = metrics.eventTime,
),
)
}
}
}
/** Space above a day's label on its own backing card, and its rows' inset, clear of the card's corners. */
private val CLASSIC_CARD_TOP_PAD = 8.dp
private val CLASSIC_CARD_H_PAD = 10.dp
/** How strongly a finished event's text shows in the classic style, on any fill. */
private const val CLASSIC_DIM_INK = 0.5f
/** The inverted secondary text's strength, as `onSurfaceVariant` sits below `onSurface`. */
private const val INVERTED_SECONDARY_INK = 0.75f
/** Where each row sits among the rows of its day, from each row's date, for the grouped-card shapes. */
private fun dayPositions(dates: List<LocalDate>): List<Position> = buildList {
var start = 0
for (end in 1..rows.size) {
if (end == rows.size || rows[end].date != rows[start].date) {
for (end in 1..dates.size) {
if (end == dates.size || dates[end] != dates[start]) {
for (i in start until end) add(positionOf(i - start, end - start))
start = end
}
@@ -343,7 +547,7 @@ private fun DatePill(date: LocalDate, today: LocalDate, cardColor: ColorProvider
.height(metrics.rowHeight)
.cornerRadius(metrics.pillWidth / 2)
.background(container)
.clickable(actionStartActivity(MainActivity.openDateIntent(context, date, CalendarView.Agenda)))
.clickable(openDayAction(context, date))
.semantics { contentDescription = label },
horizontalAlignment = Alignment.CenterHorizontally,
verticalAlignment = Alignment.CenterVertically,
@@ -375,11 +579,7 @@ private fun PlaceholderRow(date: LocalDate, metrics: AgendaMetrics) {
.fillMaxWidth()
.height(metrics.rowHeight)
.padding(horizontal = ROW_H_PAD)
.clickable(
actionStartActivity(
MainActivity.openDateIntent(context, date, CalendarView.Agenda),
),
),
.clickable(openDayAction(context, date)),
contentAlignment = Alignment.CenterStart,
) {
Text(
@@ -391,14 +591,19 @@ private fun PlaceholderRow(date: LocalDate, metrics: AgendaMetrics) {
}
/** An event row's light and dark fill: its calendar's container tone, faded when the row is dimmed. */
private data class EventFill(val day: Color, val night: Color)
private data class EventFill(val day: Color, val night: Color, val dimmed: Boolean)
/** Whether this row is drawn faded as a finished event. */
private fun AgendaRow.Event.dimmed(data: AgendaWidgetData.Ready): Boolean =
data.pastDisplay == PastEventDisplay.DIM && event.hasEnded(data.now)
private fun AgendaRow.Event.fill(data: AgendaWidgetData.Ready): EventFill {
val dimmed = data.pastDisplay == PastEventDisplay.DIM && event.hasEnded(data.now)
fun tone(dark: Boolean) = eventFill(event.color, dark, data.soften).let {
if (dimmed) it.copy(alpha = WidgetDimFillAlpha) else it
}
return EventFill(day = tone(dark = false), night = tone(dark = true))
val dimmed = dimmed(data)
return EventFill(
day = widgetEventFill(event.color, dark = false, data.soften, dimmed),
night = widgetEventFill(event.color, dark = true, data.soften, dimmed),
dimmed = dimmed,
)
}
@Composable
@@ -411,27 +616,17 @@ private fun EventRow(
) {
val context = androidx.glance.LocalContext.current
val title = event.title.ifBlank { context.getString(R.string.event_untitled) }
val titleInk = themedColor(day = widgetEventInk(fill.day, 1f), night = widgetEventInk(fill.night, 1f))
val titleInk = themedColor(day = widgetEventInk(fill.day, 1f, fill.dimmed), night = widgetEventInk(fill.night, 1f, fill.dimmed))
val timeInk = themedColor(
day = widgetEventInk(fill.day, SECONDARY_INK_ALPHA),
night = widgetEventInk(fill.night, SECONDARY_INK_ALPHA),
day = widgetEventInk(fill.day, SECONDARY_INK_ALPHA, fill.dimmed),
night = widgetEventInk(fill.night, SECONDARY_INK_ALPHA, fill.dimmed),
)
Column(
modifier = GlanceModifier
.fillMaxWidth()
.height(metrics.rowHeight)
.padding(horizontal = ROW_H_PAD)
.clickable(
actionStartActivity(
MainActivity.openEventIntent(
context = context,
eventId = event.eventId,
beginMillis = event.start.toEpochMilliseconds(),
endMillis = event.end.toEpochMilliseconds(),
source = CalendarView.Agenda,
),
),
),
.clickable(actionStartActivity(event.openIntent(context, CalendarView.Agenda))),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
@@ -474,7 +669,7 @@ private fun agendaDayLabel(context: Context, date: LocalDate, today: LocalDate):
val java = java.time.LocalDate.of(date.year, date.month.ordinal + 1, date.day)
// Weekday + date in the locale's own field order (compact: no year), rather
// than a hardcoded day-month layout.
val formatted = localizedDateFormatter(locale, "EEEdMMM").format(java)
val formatted = localizedDateFormatter(locale, if (date.year == today.year) "EEEdMMM" else "EEEdMMMy").format(java)
return if (relative != null) "$relative · $formatted" else formatted
}
@@ -69,6 +69,16 @@ import de.jeanlucmakiola.floret.glance.GlanceWidgetPreview
import de.jeanlucmakiola.floret.glance.WallpaperWindow
import de.jeanlucmakiola.floret.glance.WidgetBackground
import kotlin.math.roundToInt
import de.jeanlucmakiola.floret.components.GroupedSliderRow
import de.jeanlucmakiola.floret.components.InfoPopover
import de.jeanlucmakiola.calendula.widget.AgendaWidgetStyle
import java.text.NumberFormat
import de.jeanlucmakiola.floret.locale.currentLocale
import androidx.compose.runtime.remember
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.material.icons.outlined.Info
import androidx.compose.material3.Switch
import androidx.compose.foundation.layout.Row
private val PreviewMaxHeight = 280.dp
@@ -236,6 +246,42 @@ private fun ConfigOptions(
onSelect = { onAppearance(state.appearance.copy(background = it)) },
position = Position.Top,
)
val faded = state.appearance.background != WidgetBackground.TRANSPARENT
val content = state.draft.content
val classic = state.kind == WidgetKind.AGENDA && content.style == AgendaWidgetStyle.CLASSIC
if (faded) {
val opacity = state.appearance.opacity
GroupedSliderRow(
title = stringResource(R.string.widget_config_opacity),
value = opacity,
onValueChange = { onAppearance(state.appearance.copy(opacity = it)) },
position = Position.Middle,
valueLabel = currentLocale().let { locale ->
remember(opacity, locale) { NumberFormat.getPercentInstance(locale).format(opacity) }
},
valueRange = MIN_OPACITY..1f,
steps = OPACITY_STEPS,
titleAccessory = {
InfoPopover(
text = stringResource(
if (classic) R.string.widget_config_readability_hint_classic else R.string.widget_config_readability_hint,
),
contentDescription = stringResource(R.string.widget_config_readability_info),
)
},
)
}
if (faded && classic) {
GroupedRow(
title = stringResource(R.string.widget_config_invert_text),
summary = stringResource(R.string.widget_config_invert_text_summary),
position = Position.Middle,
trailing = {
Switch(checked = content.invertText, onCheckedChange = { onContent(content.copy(invertText = it)) })
},
onClick = { onContent(content.copy(invertText = !content.invertText)) },
)
}
GroupedChoiceRow(
title = stringResource(R.string.settings_theme),
options = WidgetTheme.entries,
@@ -265,6 +311,7 @@ private fun ContentOptions(
onCalendarShown: (Long, Boolean) -> Unit,
) {
val options = state.draft.content
var showStyle by rememberSaveable { mutableStateOf(false) }
var showRange by rememberSaveable { mutableStateOf(false) }
var showSize by rememberSaveable { mutableStateOf(false) }
var showPast by rememberSaveable { mutableStateOf(false) }
@@ -277,6 +324,12 @@ private fun ContentOptions(
GroupedSectionHeader(stringResource(R.string.widget_config_content))
rows.forEach { option ->
when (option) {
WidgetOption.STYLE -> GroupedRow(
title = stringResource(R.string.widget_config_style),
summary = agendaStyleLabel(options.style),
position = position(option),
onClick = { showStyle = true },
)
WidgetOption.RANGE -> GroupedRow(
title = stringResource(R.string.widget_config_range),
summary = agendaRangeLabel(options.range),
@@ -319,6 +372,17 @@ private fun ContentOptions(
)
}
if (showStyle) {
OptionPicker(
title = stringResource(R.string.widget_config_style),
predictiveBack = true,
options = AgendaWidgetStyle.entries,
selected = options.style,
label = { agendaStyleLabel(it) },
onSelect = { onChange(options.copy(style = it)) },
onDismiss = { showStyle = false },
)
}
if (showRange) {
AgendaRangePicker(
title = stringResource(R.string.widget_config_range),
@@ -356,6 +420,18 @@ private fun ContentOptions(
}
}
@Composable
private fun agendaStyleLabel(style: AgendaWidgetStyle): String = stringResource(
when (style) {
AgendaWidgetStyle.CARDS -> R.string.widget_config_style_cards
AgendaWidgetStyle.CLASSIC -> R.string.widget_config_style_classic
},
)
/** The faintest fill the opacity slider allows, and its 10% steps between that and opaque. */
private const val MIN_OPACITY = 0.2f
private const val OPACITY_STEPS = 7
@Composable
internal fun backgroundLabel(background: WidgetBackground): String = stringResource(
when (background) {
@@ -42,6 +42,7 @@ import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.domain.EventInstance
import de.jeanlucmakiola.calendula.domain.coversWholeDays
import de.jeanlucmakiola.calendula.ui.common.CalendarView
import de.jeanlucmakiola.calendula.widget.openIntent
import de.jeanlucmakiola.calendula.ui.common.eventAccent
import de.jeanlucmakiola.calendula.widget.CalendulaWidgetReceiver
import de.jeanlucmakiola.calendula.widget.CalendulaWidgetRoot
@@ -132,13 +133,7 @@ private fun EventCountdown(event: EventInstance, data: CountdownData.Ready) {
val context = LocalContext.current
val label = countdownLabel(event.counted(systemZone()), data.now, systemZone())
val open = actionStartActivity(
MainActivity.openEventIntent(
context = context,
eventId = event.eventId,
beginMillis = event.start.toEpochMilliseconds(),
endMillis = event.end.toEpochMilliseconds(),
source = CalendarView.Agenda,
),
event.openIntent(context, CalendarView.Agenda),
)
// Over a wallpaper the text sits on its own card, as every other widget's rows do.
val card = GlanceModifier.wallpaperBacking(radius = 16.dp)
@@ -36,11 +36,25 @@ internal fun <T : Any> mergeGaps(columns: Int, cellAt: (Int) -> GridCell<T>?): L
return cells
}
/** What a cell of the single mixed lane shows: an event's bar, or a day's event count. */
internal sealed interface LaneItem {
data class Bar(val event: EventInstance) : LaneItem
data class Count(val count: Int) : LaneItem
}
/**
* One week of the grid seated with [laneCap] lanes. [showsOverflow] is off when
* the week has no room for even the "+N" row.
* One week of the grid seated with [laneCap] lanes, drawn [compact] when the
* row is too short for a full one. [showsOverflow] is off when the week has no
* room for the "+N" row; a [mixed] single lane then shows each day's count in
* place of its bar where the day has more than fits (#491).
*/
internal class WeekLayout(val week: MonthWeek, val laneCap: Int, val showsOverflow: Boolean = true) {
internal class WeekLayout(
val week: MonthWeek,
val laneCap: Int,
val showsOverflow: Boolean = true,
val compact: Boolean = false,
val mixed: Boolean = false,
) {
private val seating: List<DaySeating> = week.days.indices.map { week.seating(it, laneCap) }
/** Lanes filled from the top; empty lanes below are not drawn. */
@@ -55,6 +69,16 @@ internal class WeekLayout(val week: MonthWeek, val laneCap: Int, val showsOverfl
}
}
/** The single lane of a [mixed] week, bars cut short where a day shows its count instead; null otherwise. */
val mixedLane: List<GridCell<LaneItem>>? = if (!mixed) null else mergeGaps(week.days.size) { col ->
val day = seating[col]
if (day.hidden.isNotEmpty()) return@mergeGaps GridCell(LaneItem.Count(week.countByDay[week.days[col]] ?: day.hidden.size), 1)
val seat = day.seated.firstOrNull() ?: return@mergeGaps null
val spanEnd = if (seat.bar) week.spanAt(col, seat.lane)?.endCol ?: col else col
val end = (col + 1..spanEnd).firstOrNull { seating[it].hidden.isNotEmpty() }?.minus(1) ?: spanEnd
GridCell(LaneItem.Bar(seat.event), end - col + 1)
}
/** The "+N" row as counts and merged gaps; empty when everything fits. */
val overflow: List<GridCell<Int>> = seating.map { it.hidden.size }.let { hidden ->
if (hidden.none { it > 0 }) emptyList()
@@ -62,19 +86,31 @@ internal class WeekLayout(val week: MonthWeek, val laneCap: Int, val showsOverfl
}
}
/**
* Event lanes a week row [weekHeight] tall holds under its day number, held to
* [MAX_LANES] so a tall widget's payload stays bounded (#214).
*/
internal fun lanesFitting(weekHeight: Dp): Int =
((weekHeight.value - DAY_ROW_DP - LANES_TOP_DP) / LANE_ROW_DP).toInt().coerceIn(0, MAX_LANES)
/** How many lanes a week row holds, and whether they're the [compact] height. */
internal data class LaneFit(val lanes: Int, val compact: Boolean = false)
/**
* Seats each week in [lanes] lanes. A week whose events need more gives its
* last lane to the "+N" row instead.
* Event lanes a week row [weekHeight] tall holds under its day number, held to
* [MAX_LANES] so a tall widget's payload stays bounded (#214). A row too short
* for one full lane still gets a compact one when its text fits at [fontScale] (#491).
*/
internal fun fitWeeks(weeks: List<MonthWeek>, lanes: Int): List<WeekLayout> = weeks.map { week ->
if (lanes == 0) return@map WeekLayout(week, laneCap = 0, showsOverflow = false)
internal fun lanesFitting(weekHeight: Dp, fontScale: Float): LaneFit {
val room = weekHeight.value - DAY_ROW_DP - LANES_TOP_DP
val full = (room / LANE_ROW_DP).toInt().coerceIn(0, MAX_LANES)
val compactFits = room >= COMPACT_LANE_ROW_DP && fontScale <= COMPACT_MAX_FONT_SCALE
return if (full == 0 && compactFits) LaneFit(1, compact = true) else LaneFit(full)
}
/**
* Seats each week in [fit]'s lanes. A week whose events need more gives its
* last lane to the "+N" row instead. A single lane has no room for that row,
* so it mixes bars and per-day counts (#491).
*/
internal fun fitWeeks(weeks: List<MonthWeek>, fit: LaneFit): List<WeekLayout> = weeks.map { week ->
val lanes = fit.lanes
if (lanes <= 1) {
return@map WeekLayout(week, laneCap = lanes, showsOverflow = false, compact = fit.compact, mixed = lanes == 1)
}
val needed = WeekLayout(week, UNCAPPED_LANES).usedLanes
WeekLayout(week, if (needed <= lanes) lanes else lanes - 1)
}
@@ -85,4 +121,7 @@ internal const val MAX_LANES = 8
private const val DAY_ROW_DP = 18f
private const val LANES_TOP_DP = 2f
private const val LANE_ROW_DP = 15f
/** Matches `widget_month_lane_compact`'s height; its 9sp text clips past [COMPACT_MAX_FONT_SCALE]. */
private const val COMPACT_LANE_ROW_DP = 12f
private const val COMPACT_MAX_FONT_SCALE = 1f
private const val UNCAPPED_LANES = 64
@@ -91,6 +91,21 @@ private fun weekViews(
week.setViewVisibility(TODAY_IDS[col], if (isToday) View.VISIBLE else View.GONE)
if (isToday) week.setImageTint(context, TODAY_IDS[col], colors.primary)
}
layout.mixedLane?.let { cells ->
val lane = laneViews(context, layout.compact)
cells.forEach { cell ->
lane.addView(
R.id.lane,
when (val item = cell.item) {
null -> gap(context, cell.cols)
is LaneItem.Bar -> bar(context, item.event, cell.cols, soften, mode)
is LaneItem.Count -> more(context, item.count, colors)
},
)
}
week.addView(R.id.week_lanes, lane)
return week
}
layout.lanes.forEach { cells ->
val lane = laneViews(context)
cells.forEach { cell ->
@@ -106,10 +121,7 @@ private fun weekViews(
if (count == null) {
lane.addView(R.id.lane, gap(context, cell.cols))
} else {
val more = RemoteViews(context.packageName, R.layout.widget_month_more)
more.setTextViewText(R.id.more, "+$count")
more.setTextColor(context, R.id.more, colors.onSurfaceVariant)
lane.addView(R.id.lane, more)
lane.addView(R.id.lane, more(context, count, colors))
}
}
week.addView(R.id.week_lanes, lane)
@@ -117,8 +129,15 @@ private fun weekViews(
return week
}
private fun laneViews(context: Context) =
RemoteViews(context.packageName, R.layout.widget_month_lane).apply { removeAllViews(R.id.lane) }
private fun more(context: Context, count: Int, colors: GridColors) =
RemoteViews(context.packageName, R.layout.widget_month_more).apply {
setTextViewText(R.id.more, "+$count")
setTextColor(context, R.id.more, colors.onSurfaceVariant)
}
private fun laneViews(context: Context, compact: Boolean = false) =
RemoteViews(context.packageName, if (compact) R.layout.widget_month_lane_compact else R.layout.widget_month_lane)
.apply { removeAllViews(R.id.lane) }
private fun gap(context: Context, cols: Int) = RemoteViews(context.packageName, GAP_LAYOUTS[cols - 1])
@@ -254,7 +254,7 @@ private fun MonthWidgetBody(source: MonthWidgetSource, index: Int) {
val context = LocalContext.current
val fontScale = context.resources.configuration.fontScale
val weekHeight = (LocalSize.current.height - gridChromeHeight(fontScale)) / weeks.size
val layouts = fitWeeks(weeks, lanesFitting(weekHeight))
val layouts = fitWeeks(weeks, lanesFitting(weekHeight, fontScale))
val mode = LocalWidgetThemeMode.current
val colors = GridColors(
onSurface = remoteColor(WidgetColorRole.ON_SURFACE),
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/lane"
android:layout_width="match_parent"
android:layout_height="12dp"
android:orientation="horizontal"
android:paddingBottom="1dp"
android:weightSum="7" />
+1 -1
View File
@@ -292,7 +292,7 @@
<string name="settings_dim_completed_summary">تعتيم الأحداث التي انتهت بالفعل في عرض الشهر والأسبوع</string>
<string name="settings_today_toolbar">زر اليوم في شريط الأدوات</string>
<string name="settings_today_toolbar_summary">إظهار زر الانتقال إلى اليوم في شريط الأدوات بدلاً من زر عائم</string>
<string name="settings_app_name_summary">اعرض Calendula كـ ”Calendar“ في مشغّل التطبيقات الخاص بك. فقط الاسم في المشغّل يتغير؛ وقد ينتقل الرمز إلى مكان جديد بعد التبديل.</string>
<string name="settings_app_name_summary">اعرض Calendula كـ ”التقويم“ في مشغّل التطبيقات الخاص بك. فقط الاسم في المشغّل يتغير؛ وقد ينتقل الرمز إلى مكان جديد بعد التبديل.</string>
<string name="settings_past_events_dim">تعتيم</string>
<string name="settings_past_events">الأحداث السابقة</string>
<string name="settings_agenda_range">مدى الجدول</string>
+1 -1
View File
@@ -697,7 +697,7 @@
<string name="onboarding_calendars_benefit_sync_title">Або наладзьце сынхранізацыю з уліковым запісам</string>
<string name="onboarding_calendars_created_more_title">Прастора для іншых</string>
<string name="onboarding_calendars_created_title">«%1$s» гатовы</string>
<string name="onboarding_calendars_benefit_sync_body">Calendula паказвае ўліковыя запісы, якія ўжо сынхранізуюцца. Для выкананьня сынхранізацыі сэрвэры CalDAV патрабуець DAVx\\u2075.</string>
<string name="onboarding_calendars_benefit_sync_body">Calendula паказвае ўліковыя запісы, якія ўжо сынхранізуюцца. Для выкананьня сынхранізацыі сэрвэры CalDAV патрабуець DAVx.</string>
<string name="onboarding_calendars_created_body">Ён застаецца на гэтай прыладзе. У ім будуць запісвацца новыя падзеі, пакуль ня будзе выбраны іншы каляндар.</string>
<string name="onboarding_calendars_created_more_body">Праз мэню Налады → Календары можна задаць колькасьць, назвы і колеры наяўных календароў.</string>
<string name="onboarding_calendars_created_continue">Далей</string>
+18 -18
View File
@@ -374,7 +374,7 @@
<string name="settings_special_dates_type_anniversary">Anniversaires</string>
<string name="settings_special_dates_type_custom">Autres dates</string>
<string name="settings_special_dates_template">Format du titre</string>
<string name="settings_special_dates_template_hint">Utilisez {name} pour le nom et {year} pour l’année (celle de naissance ou celle du début d’un anniversaire ; masqué si inconnu).</string>
<string name="settings_special_dates_template_hint">Utilisez {name} pour le nom et {year} pour l’année (celle de naissance ou celle du début d’un anniversaire ; masqué si inconnu).</string>
<string name="settings_special_dates_show_year">Montrer l\'année</string>
<string name="settings_special_dates_show_year_hint">Inclure {year} dans les titres lorsque l\'année est connue</string>
<string name="settings_special_dates_sync_now">Synchroniser maintenant</string>
@@ -412,7 +412,7 @@
<string name="calendars_edit_title">Editer un agenda</string>
<string name="calendars_name_label">Nom</string>
<string name="calendars_description_hint">Ajouter une description</string>
<string name="calendars_delete_confirm_title">Supprimer ce calendrier ?</string>
<string name="calendars_delete_confirm_title">Supprimer ce calendrier ?</string>
<string name="calendars_delete_confirm_message">\"%1$s\" et tous ses événements seront définitivement retirés de cet appareil.</string>
<string name="calendars_write_error">Impossible de sauvegarder les changements.</string>
<string name="calendars_backup_hint">Les calendriers locaux ne sont synchronisés nulle part, alors exportez-les vers un fichier .ics pour en garder une copie.</string>
@@ -515,16 +515,16 @@
<string name="event_edit_timezone_all">Toutes les zones horaire</string>
<string name="event_edit_timezone_none">Aucune zone horaire ne correspond à “%1$s”</string>
<string name="event_edit_recurrence_incomplete">Entrez un nombre entre 1 et 999</string>
<string name="event_edit_recurrence_next">Prochain : %1$s</string>
<string name="event_edit_recurrence_next">Prochain : %1$s</string>
<string name="event_detail_title">Titre</string>
<string name="event_access_private_summary">Les autres ne voient seulement que vous êtes occupé</string>
<string name="event_access_confidential_summary">Marqué confidentiel ; ce que cela veut dire est au bon vouloir de votre compte de calendrier</string>
<string name="event_access_confidential_summary">Marqué confidentiel ; ce que cela veut dire est au bon vouloir de votre compte de calendrier</string>
<string name="reminder_after">%1$s après</string>
<string name="duration_custom_max">Au plus %1$s</string>
<string name="onboarding_step_counter">Étape %1$d sur %2$d</string>
<string name="settings_today_toolbar_summary">Afficher un bouton pour revenir au jour présent dans la barre d\'outils au lieu d\'un bouton flottant</string>
<string name="settings_app_name">Nom de l\'application</string>
<string name="settings_app_name_summary">Afficher Calendula comme \"Calendrier\" dans votre lanceur d\'applications. Le nom change seulement dans le lanceur ; l\'icône pourrait changer d\'emplacement après le renommage.</string>
<string name="settings_app_name_summary">Afficher Calendula comme \"Calendrier\" dans votre lanceur d\'applications. Le nom change seulement dans le lanceur ; l\'icône pourrait changer d\'emplacement après le renommage.</string>
<string name="settings_timeline_scale">Hauteur d\'une heure</string>
<string name="timeline_scale_fit_day">Remplir complètement</string>
<string name="timeline_scale_fit_day_summary">Affiche les 24 heures à l\'écran, pas de défilement</string>
@@ -551,15 +551,15 @@
<string name="event_access_public_summary">Toute personne ayant accès voit tous les détails</string>
<string name="duration_hours_minutes">%1$s:%2$s</string>
<string name="onboarding_backup_title">Vos événements ne sont accessibles qu\'ici</string>
<string name="onboarding_backup_body">Aucune synchronisation n\'existe sur ce téléphone : le perdre signifierait perdre votre calendrier. Calendula peut faire des sauvegardes pour vous.</string>
<string name="onboarding_backup_body">Aucune synchronisation n\'existe sur ce téléphone : le perdre signifierait perdre votre calendrier. Calendula peut faire des sauvegardes pour vous.</string>
<string name="onboarding_backup_benefit_folder_title">Un dossier que vous choisissez</string>
<string name="onboarding_backup_benefit_folder_body">Les sauvegardes sont juste des fichiers .ics — enregistrez-les dans un dossier synchronisé, ou bien sur une carte SD.</string>
<string name="onboarding_backup_benefit_daily_title">Une fois par jour, automatiquement</string>
<string name="onboarding_backup_benefit_daily_body">Calendula exporte vos calendriers locaux en arrière-plan. Changez la fréquence dans les réglages.</string>
<string name="onboarding_backup_enable_button">Choisissez un dossier et sauvegarder</string>
<string name="onboarding_backup_skip_button">Pas pour l\'instant</string>
<string name="onboarding_view_title">Que doit s\'afficher en premier ?</string>
<string name="onboarding_month_style_title">À quoi doivent ressembler les mois ?</string>
<string name="onboarding_view_title">Que doit s\'afficher en premier ?</string>
<string name="onboarding_month_style_title">À quoi doivent ressembler les mois ?</string>
<string name="onboarding_view_continue_button">Continuer</string>
<string name="onboarding_back">Retour</string>
<string name="onboarding_visibility_button">Compris</string>
@@ -579,9 +579,9 @@
<string name="search_select_all">Tout sélectionner</string>
<string name="search_delete_selected">Supprimer la sélection</string>
<plurals name="search_delete_title">
<item quantity="one">Supprimer %d événement ?</item>
<item quantity="many">Supprimer %d événements ?</item>
<item quantity="other">Supprimer %d événements ?</item>
<item quantity="one">Supprimer %d événement ?</item>
<item quantity="many">Supprimer %d événements ?</item>
<item quantity="other">Supprimer %d événements ?</item>
</plurals>
<plurals name="search_delete_done">
<item quantity="one">%d événement supprimé</item>
@@ -595,9 +595,9 @@
<string name="settings_font_specimen_heading">Jeudi 14 mai</string>
<string name="settings_font_specimen_body">Revue d\'équipe à 10h00, puis déjeuner avec Robin au café de la Place du Marché.</string>
<string name="settings_week_start_auto_summary">Actuellement %1$s</string>
<string name="settings_today_toolbar">Bouton « aujourd\'hui » dans la barre d\'outils</string>
<string name="settings_time_format_auto_summary">Suivant le système : %1$s</string>
<string name="settings_timeline_scale_hint">Espace vertical occupé par une heure dans les vues « Semaine » et « Jour ». Ce paramètre s\'applique aux deux vues. Vous pouvez également étirer l\'affichage avec deux doigts pour utiliser n\'importe quelle hauteur.</string>
<string name="settings_today_toolbar">Bouton « aujourd\'hui » dans la barre d\'outils</string>
<string name="settings_time_format_auto_summary">Suivant le système : %1$s</string>
<string name="settings_timeline_scale_hint">Espace vertical occupé par une heure dans les vues « Semaine » et « Jour ». Ce paramètre s\'applique aux deux vues. Vous pouvez également étirer l\'affichage avec deux doigts pour utiliser n\'importe quelle hauteur.</string>
<string name="settings_widget_size_hint">Taille du texte affiché par le widget d\'agenda sur l\'écran d\'accueil. Le widget mensuel n\'a pas ce réglage — sa grille s\'adapte toujours à l\'espace que vous lui allouez.</string>
<string name="settings_widget_size_small">Petit</string>
<string name="settings_widget_size_medium">Moyen</string>
@@ -637,7 +637,7 @@
<string name="settings_week_day_header">Semaine &amp; jour</string>
<string name="settings_default_view_hint">La vue ouverte par Calendula au démarrage.</string>
<string name="settings_week_start_hint">Le jour par lequel chaque semaine commence, dans toutes les vues et widgets.</string>
<string name="settings_time_format_hint">Format d\'affichage de l\'heure dans l\'application. Le format « Automatique » suit les paramètres de votre système.</string>
<string name="settings_time_format_hint">Format d\'affichage de l\'heure dans l\'application. Le format « Automatique » suit les paramètres de votre système.</string>
<string name="settings_past_events_hint">Comment l\'agenda gère les événements déjà terminés.</string>
<string name="settings_dynamic_color_summary">Les couleurs de l\'application proviennent de votre fond d\'écran.</string>
<string name="settings_licences">Licences open source</string>
@@ -646,16 +646,16 @@
<string name="licences_title">Licences open source</string>
<string name="licences_intro">Calendula comprend les projets ci-dessous. Appuyez sur n\'importe quelle entrée pour afficher son code source.</string>
<string name="licences_footer">Chaque projet présenté ici est inclus tel quel, sans modifications, sous la licence indiquée.</string>
<string name="calendars_visibility_hint">Désactivez un calendrier pour le masquer sur cet appareil : ses événements disparaîtront de l\'application et vous ne recevrez plus de rappels. Il s\'agit du même bouton que celui utilisé par vos autres applications de calendrier, ce qui signifie qu\'il sera aussi masqué sur ces dernières. Rien n\'est supprimé, aucun autre appareil n\'est affecté et vous pouvez le réactiver ici à tout moment.</string>
<string name="calendars_visibility_hint">Désactivez un calendrier pour le masquer sur cet appareil : ses événements disparaîtront de l\'application et vous ne recevrez plus de rappels. Il s\'agit du même bouton que celui utilisé par vos autres applications de calendrier, ce qui signifie qu\'il sera aussi masqué sur ces dernières. Rien n\'est supprimé, aucun autre appareil n\'est affecté et vous pouvez le réactiver ici à tout moment.</string>
<string name="calendars_visibility_a11y">Montrer \"%1$s\"</string>
<string name="calendars_visibility_notice_title">Certains calendriers sont masqués</string>
<string name="calendars_visibility_notice_message">Calendula affiche les calendriers activés pour cet appareil, et certains des vôtres sont désactivés. Pour voir leurs événements, activez-les dans Réglages → Calendriers.</string>
<string name="calendar_picker_missing_title">Il vous manque un calendrier ?</string>
<string name="calendar_picker_missing_title">Il vous manque un calendrier ?</string>
<string name="calendar_picker_missing_summary">Il est peut-être désactivé, en lecture seule ou rempli à partir de vos contacts — gérez vos calendriers ici.</string>
<string name="calendars_state_read_only">Lecture seule</string>
<string name="calendars_state_not_synced">Non synchronisé avec cet appareil</string>
<string name="calendars_state_managed">Rempli à partir de vos contacts</string>
<string name="calendars_managed_delete_locked">Ce calendrier est rempli à partir de vos contacts ; Calendula le recréera donc lors de la prochaine synchronisation. Pour le supprimer, désactivez les dates spéciales dans Paramètres → Dates spéciales.</string>
<string name="calendars_managed_delete_locked">Ce calendrier est rempli à partir de vos contacts ; Calendula le recréera donc lors de la prochaine synchronisation. Pour le supprimer, désactivez les dates spéciales dans Paramètres → Dates spéciales.</string>
<string name="calendars_account_from_source">%1$s (%2$s)</string>
<string name="import_done_failed_label">Non ajouté</string>
<string name="import_done_failed_note">Certains événements n\'ont pas pu être ajoutés et ont donc été omis.</string>
+12
View File
@@ -110,6 +110,9 @@
<string name="event_move_failed">Couldn\'t move the event</string>
<string name="event_move_write_denied">Calendula needs write access to move events</string>
<string name="event_move_gone">That event no longer exists</string>
<string name="event_move_stale">That event moved before your drop could be saved</string>
<string name="event_move_queue_full">Too many moves at once, so that one wasn\'t saved</string>
<string name="event_move_skipped">Moves made while the question was open weren\'t saved</string>
<string name="event_move_blocked_series_end">Can\'t move an event past the end of its series</string>
<string name="event_move_blocked_cancelled_series">A cancelled series can only move as a whole, and this would change which days it falls on</string>
@@ -517,6 +520,15 @@
<string name="widget_config_background_tinted">Tinted</string>
<string name="widget_config_background_transparent">Transparent</string>
<string name="widget_config_theme_follow_app">Follow app</string>
<string name="widget_config_opacity">Opacity</string>
<string name="widget_config_invert_text">Invert text colour</string>
<string name="widget_config_invert_text_summary">Light text on a dark theme turns dark, and the other way round</string>
<string name="widget_config_readability_info">About readability</string>
<string name="widget_config_readability_hint">At low opacity the wallpaper shows through, so some text may be harder to read. Raise the opacity if it is.</string>
<string name="widget_config_readability_hint_classic">At low opacity the wallpaper shows through, so some text may be hard to read. If it is, raise the opacity or invert the text colour.</string>
<string name="widget_config_style">Style</string>
<string name="widget_config_style_cards">Cards</string>
<string name="widget_config_style_classic">Classic</string>
<string name="widget_config_content">Content</string>
<string name="widget_config_range">Time range</string>
<string name="widget_config_text_size">Text size</string>
@@ -13,10 +13,12 @@ import de.jeanlucmakiola.calendula.testEvent
import de.jeanlucmakiola.calendula.testPrefs
import de.jeanlucmakiola.calendula.testRepository
import de.jeanlucmakiola.calendula.testSettings
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
import kotlinx.datetime.LocalDate
@@ -79,15 +81,43 @@ class RescheduleViewModelTest {
status = status,
)
private fun viewModel(tempDir: Path, fake: FakeCalendarDataSource): RescheduleViewModel {
/**
* [present] are the events whose occurrence the provider still reports where
* a drop picked it up; [io] a [StandardTestDispatcher] keeps a drop in flight.
*/
private fun viewModel(
tempDir: Path,
fake: FakeCalendarDataSource,
present: List<Long> = listOf(42L, 7L),
io: CoroutineDispatcher = dispatcher,
): RescheduleViewModel {
fake.occurrencesAt(present)
val repo = testRepository(
fake, tempDir, dispatcher,
fake, tempDir, io,
prefs = testPrefs(tempDir, CoroutineScope(dispatcher)),
settings = testSettings(tempDir, CoroutineScope(dispatcher)),
)
return RescheduleViewModel(repo, dispatcher, FakeZoneSource())
return RescheduleViewModel(repo, io, FakeZoneSource())
}
private fun slowViewModel(tempDir: Path, fake: FakeCalendarDataSource): RescheduleViewModel =
viewModel(tempDir, fake, io = StandardTestDispatcher(dispatcher.scheduler))
/** Every query answers with an occurrence of each of [ids] exactly at the queried span. */
private fun FakeCalendarDataSource.occurrencesAt(ids: List<Long>) {
instancesResult = { begin, end ->
ids.map { id ->
testEvent(
id = id,
start = Instant.fromEpochMilliseconds(begin),
end = Instant.fromEpochMilliseconds(end),
)
}
}
}
private val RescheduleViewModel.abandonedCount: Int get() = drops.value.abandoned.size
private fun CoroutineScope.activate(vm: RescheduleViewModel): Job =
launch { vm.movableCalendarIds.collect {} }
@@ -97,6 +127,8 @@ class RescheduleViewModelTest {
beginMillis = beginMillis,
endMillis = endMillis,
target = MoveTarget.ByDays(2),
isAllDay = false,
token = nextMoveToken(),
)
/** A drop an hour later, expressed the way a timeline drag expresses one. */
@@ -105,6 +137,8 @@ class RescheduleViewModelTest {
beginMillis = beginMillis,
endMillis = endMillis,
target = MoveTarget.Start(Instant.fromEpochMilliseconds(beginMillis + 3_600_000L)),
isAllDay = false,
token = nextMoveToken(),
)
/** The end dragged an hour later, the start left where it is. */
@@ -116,6 +150,8 @@ class RescheduleViewModelTest {
Instant.fromEpochMilliseconds(beginMillis),
Instant.fromEpochMilliseconds(endMillis + 3_600_000L),
),
isAllDay = false,
token = nextMoveToken(),
)
@Test
@@ -259,21 +295,228 @@ class RescheduleViewModelTest {
}
@Test
fun `a second drop is refused while the first is still in flight`(
fun `a drop of another event waits for the one in flight, then lands`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply {
eventDetailResult = { detail(rrule = "FREQ=WEEKLY;BYDAY=MO") }
eventDetailResult = { detail() }
}
val vm = slowViewModel(tempDir, fake)
val first = oneHourLater()
val second = toWednesday().copy(eventId = 7L, token = nextMoveToken())
assertThat(vm.move(first)).isTrue()
assertThat(vm.move(second)).isTrue()
assertThat(vm.drops.value.pending).containsExactly(first.token, second.token)
advanceUntilIdle()
assertThat(fake.updatedEvents.map { it.first }).containsExactly(42L, 7L).inOrder()
assertThat(vm.drops.value).isEqualTo(DropStates())
assertThat(vm.inFlight.value).isFalse()
}
@Test
fun `a failed drop lets go of its own copy only, not the one queued behind it`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply {
eventDetailResult = { detail() }
}
val vm = slowViewModel(tempDir, fake)
// Zero distance: refused in prepare.
val nowhere = oneHourLater().copy(
target = MoveTarget.Start(Instant.fromEpochMilliseconds(beginMillis)),
token = nextMoveToken(),
)
val queued = toWednesday().copy(eventId = 7L, token = nextMoveToken())
vm.move(nowhere)
vm.move(queued)
advanceUntilIdle()
assertThat(vm.drops.value.abandoned).containsExactly(nowhere.token)
assertThat(fake.updatedEvents.map { it.first }).containsExactly(7L)
}
@Test
fun `the same event dropped twice ends up where it was dropped last`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val hour = 3_600_000L
val fake = FakeCalendarDataSource()
val vm = slowViewModel(tempDir, fake)
// Once the first drop is written, the event sits an hour later.
fake.eventDetailResult = {
if (fake.updatedEvents.isEmpty()) detail() else detail(anchorMillis = beginMillis + hour)
}
fake.instancesResult = { _, _ ->
val shift = if (fake.updatedEvents.isEmpty()) 0L else hour
listOf(
testEvent(
id = 42L,
start = Instant.fromEpochMilliseconds(beginMillis + shift),
end = Instant.fromEpochMilliseconds(endMillis + shift),
),
)
}
vm.move(oneHourLater())
// Picked up from where the grid still drew it, and dropped two days on.
vm.move(toWednesday())
advanceUntilIdle()
assertThat(fake.updatedEvents).hasSize(2)
val last = fake.updatedEvents.last().third
assertThat(last.start.dateTime).isEqualTo(LocalDateTime(LocalDate(2026, 6, 10), LocalTime(13, 0)))
}
@Test
fun `a drop on a series written moments ago is not written`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
// A whole-series write shifts every occurrence; the grid still draws the
// old ones, and another occurrence may now sit at the dragged time.
val fake = FakeCalendarDataSource().apply { eventDetailResult = { detail(rrule = "FREQ=DAILY") } }
val vm = viewModel(tempDir, fake)
vm.move(oneHourLater())
advanceUntilIdle()
vm.moveWithScope(RecurringWriteScope.AllEvents)
advanceUntilIdle()
vm.consumeOutcome()
assertThat(vm.move(toWednesday())).isTrue()
val again = toWednesday()
vm.move(again)
advanceUntilIdle()
// Parked on the scope dialog, so the first drop still owns the pipeline.
assertThat(vm.move(oneHourLater())).isFalse()
assertThat(vm.scopePrompt.value).isNull()
assertThat(vm.outcome.value).isEqualTo(MoveOutcome.Stale)
assertThat(vm.drops.value.abandoned).containsExactly(again.token)
assertThat(fake.updatedEvents).hasSize(1)
}
@Test
fun `a single occurrence written leaves the rest of its series movable`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { eventDetailResult = { detail(rrule = "FREQ=WEEKLY") } }
val vm = viewModel(tempDir, fake)
vm.move(oneHourLater())
advanceUntilIdle()
assertThat(fake.updatedEvents).isEmpty()
vm.moveWithScope(RecurringWriteScope.ThisEvent)
advanceUntilIdle()
// Another occurrence, a week on.
val week = 7 * 86_400_000L
vm.move(oneHourLater().copy(beginMillis = beginMillis + week, endMillis = endMillis + week, token = nextMoveToken()))
advanceUntilIdle()
assertThat(vm.scopePrompt.value).isNotNull()
}
@Test
fun `chip messages wait their turn instead of replacing each other`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply {
eventDetailResult = { id ->
if (id == 42L) detail(rrule = "FREQ=WEEKLY;BYDAY=MO,WE", status = EventStatus.Cancelled) else detail()
}
}
val vm = slowViewModel(tempDir, fake)
vm.move(toWednesday())
vm.move(toWednesday().copy(eventId = 7L, token = nextMoveToken()))
advanceUntilIdle()
assertThat(vm.outcome.value).isEqualTo(MoveOutcome.BlockedCancelledSeries)
vm.consumeOutcome()
assertThat((vm.outcome.value as MoveOutcome.Moved).undo?.eventId).isEqualTo(7L)
vm.consumeOutcome()
assertThat(vm.outcome.value).isNull()
}
@Test
fun `a full queue says so`(@TempDir tempDir: Path) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { eventDetailResult = { detail() } }
val vm = slowViewModel(tempDir, fake)
repeat(9) { i -> vm.move(toWednesday().copy(eventId = 100L + i, token = nextMoveToken())) }
val refused = toWednesday().copy(eventId = 200L, token = nextMoveToken())
assertThat(vm.move(refused)).isFalse()
assertThat(vm.drops.value.abandoned).containsExactly(refused.token)
assertThat(vm.outcome.value).isEqualTo(MoveOutcome.QueueFull)
}
@Test
fun `a deleted event reports itself as gone, not moved`(@TempDir tempDir: Path) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { eventDetailResult = { null } }
val vm = viewModel(tempDir, fake, present = emptyList())
vm.move(oneHourLater())
advanceUntilIdle()
assertThat(vm.outcome.value).isEqualTo(MoveOutcome.Gone)
}
@Test
fun `drops waiting when a scope dialog opens are cancelled, not held behind it`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply {
eventDetailResult = { id -> if (id == 42L) detail(rrule = "FREQ=WEEKLY") else detail() }
}
val vm = slowViewModel(tempDir, fake)
vm.move(oneHourLater())
val queued = toWednesday().copy(eventId = 7L, token = nextMoveToken())
vm.move(queued)
advanceUntilIdle()
assertThat(vm.scopePrompt.value).isNotNull()
assertThat(vm.drops.value.abandoned).containsExactly(queued.token)
assertThat(vm.outcome.value).isEqualTo(MoveOutcome.Skipped)
// One made while the dialog is up is refused the same way.
val during = toWednesday().copy(eventId = 7L, token = nextMoveToken())
assertThat(vm.move(during)).isFalse()
vm.moveWithScope(RecurringWriteScope.AllEvents)
advanceUntilIdle()
assertThat(fake.updatedEvents.map { it.first }).containsExactly(42L)
// The skip has its turn, then the move it waited on, with its Undo.
assertThat(vm.outcome.value).isEqualTo(MoveOutcome.Skipped)
vm.consumeOutcome()
assertThat((vm.outcome.value as MoveOutcome.Moved).undo?.eventId).isEqualTo(42L)
}
@Test
fun `the first move of a run keeps the chip and its undo`(@TempDir tempDir: Path) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { eventDetailResult = { detail() } }
val vm = slowViewModel(tempDir, fake)
vm.move(oneHourLater())
vm.move(toWednesday().copy(eventId = 7L, token = nextMoveToken()))
advanceUntilIdle()
val shown = vm.outcome.value as MoveOutcome.Moved
assertThat(fake.updatedEvents).hasSize(2)
assertThat(shown.undo?.eventId).isEqualTo(42L)
}
@Test
fun `a later move of the same event takes the first move's undo away`(
@TempDir tempDir: Path,
) = runTest(dispatcher) {
val fake = FakeCalendarDataSource().apply { eventDetailResult = { detail() } }
val vm = slowViewModel(tempDir, fake)
vm.move(oneHourLater())
vm.move(toWednesday())
advanceUntilIdle()
assertThat(fake.updatedEvents).hasSize(2)
assertThat((vm.outcome.value as MoveOutcome.Moved).undo).isNull()
}
@Test
@@ -284,19 +527,19 @@ class RescheduleViewModelTest {
advanceUntilIdle()
val undo = (vm.outcome.value as MoveOutcome.Moved).undo!!
// A second drop parks on its scope dialog, which holds the pipeline.
// A second drop, of another event, parks on its scope dialog, which holds the pipeline.
fake.eventDetailResult = { detail(rrule = "FREQ=WEEKLY;BYDAY=MO") }
vm.move(toWednesday())
vm.move(toWednesday().copy(eventId = 7L, token = nextMoveToken()))
advanceUntilIdle()
val abandoned = vm.abandoned.value
val abandoned = vm.abandonedCount
assertThat(vm.undo(undo)).isFalse()
advanceUntilIdle()
assertThat(fake.updatedEvents).hasSize(1)
// Nothing ticks: the refusal started no journey of its own, and the
// counter is global — a tick here would release the copy the drop that
// *is* in flight is holding, before the grid has drawn it.
assertThat(vm.abandoned.value).isEqualTo(abandoned)
assertThat(vm.abandonedCount).isEqualTo(abandoned)
}
@Test
@@ -311,13 +554,13 @@ class RescheduleViewModelTest {
advanceUntilIdle()
val undo = (vm.outcome.value as MoveOutcome.Moved).undo!!
val abandoned = vm.abandoned.value
val abandoned = vm.abandonedCount
fake.writeError = SecurityException("permission revoked")
assertThat(vm.undo(undo)).isTrue()
advanceUntilIdle()
assertThat(vm.outcome.value).isEqualTo(MoveOutcome.WriteDenied)
assertThat(vm.abandoned.value).isEqualTo(abandoned + 1)
assertThat(vm.abandonedCount).isEqualTo(abandoned + 1)
}
@Test
@@ -330,12 +573,12 @@ class RescheduleViewModelTest {
advanceUntilIdle()
val undo = (vm.outcome.value as MoveOutcome.Moved).undo!!
val abandoned = vm.abandoned.value
val abandoned = vm.abandonedCount
vm.undo(undo)
advanceUntilIdle()
assertThat(vm.outcome.value).isEqualTo(MoveOutcome.Undone)
assertThat(vm.abandoned.value).isEqualTo(abandoned)
assertThat(vm.abandonedCount).isEqualTo(abandoned)
}
@Test
@@ -415,6 +658,8 @@ class RescheduleViewModelTest {
target = MoveTarget.Start(
Instant.fromEpochMilliseconds(beginMillis + 26 * 3_600_000L),
),
isAllDay = false,
token = nextMoveToken(),
),
)
advanceUntilIdle()
@@ -435,6 +680,8 @@ class RescheduleViewModelTest {
beginMillis = beginMillis,
endMillis = endMillis,
target = MoveTarget.Start(Instant.fromEpochMilliseconds(beginMillis)),
isAllDay = false,
token = nextMoveToken(),
),
)
advanceUntilIdle()
@@ -556,17 +803,19 @@ class RescheduleViewModelTest {
beginMillis = beginMillis,
endMillis = endMillis,
target = MoveTarget.Start(Instant.fromEpochMilliseconds(beginMillis)),
isAllDay = false,
token = nextMoveToken(),
),
)).isTrue()
advanceUntilIdle()
assertThat(vm.abandoned.value).isEqualTo(1)
assertThat(vm.abandonedCount).isEqualTo(1)
// Refused by the provider, after the write was attempted.
fake.writeError = SecurityException("revoked")
vm.move(oneHourLater())
advanceUntilIdle()
assertThat(vm.outcome.value).isEqualTo(MoveOutcome.WriteDenied)
assertThat(vm.abandoned.value).isEqualTo(2)
assertThat(vm.abandonedCount).isEqualTo(2)
}
@Test
@@ -580,11 +829,11 @@ class RescheduleViewModelTest {
vm.move(oneHourLater())
advanceUntilIdle()
assertThat(vm.abandoned.value).isEqualTo(0)
assertThat(vm.abandonedCount).isEqualTo(0)
vm.cancelScope()
advanceUntilIdle()
assertThat(vm.abandoned.value).isEqualTo(1)
assertThat(vm.abandonedCount).isEqualTo(1)
}
@Test
@@ -596,7 +845,7 @@ class RescheduleViewModelTest {
advanceUntilIdle()
assertThat(vm.outcome.value).isInstanceOf(MoveOutcome.Moved::class.java)
assertThat(vm.abandoned.value).isEqualTo(0)
assertThat(vm.abandonedCount).isEqualTo(0)
}
@Test
@@ -668,6 +917,8 @@ class RescheduleViewModelTest {
beginMillis = beginMillis,
endMillis = endMillis,
target = MoveTarget.Span(sundayEvening, Instant.fromEpochMilliseconds(endMillis)),
isAllDay = false,
token = nextMoveToken(),
),
)
advanceUntilIdle()
@@ -709,7 +960,7 @@ class RescheduleViewModelTest {
assertThat(vm.scopePrompt.value).isNull()
assertThat(vm.outcome.value).isEqualTo(MoveOutcome.BlockedCancelledSeries)
assertThat(vm.abandoned.value).isEqualTo(1)
assertThat(vm.abandonedCount).isEqualTo(1)
assertThat(fake.updatedEvents).isEmpty()
assertThat(fake.updatedOccurrences).isEmpty()
}
@@ -739,6 +990,8 @@ class RescheduleViewModelTest {
beginMillis = dayStart,
endMillis = dayStart + 86_400_000L,
target = MoveTarget.Span(start, Instant.fromEpochMilliseconds(endMillis)),
isAllDay = true,
token = nextMoveToken(),
),
)
advanceUntilIdle()
@@ -775,6 +1028,8 @@ class RescheduleViewModelTest {
beginMillis = dayStart,
endMillis = dayStart + 86_400_000L,
target = MoveTarget.Span(eight, eight + 1.hours),
isAllDay = true,
token = nextMoveToken(),
),
)
advanceUntilIdle()
@@ -53,7 +53,7 @@ class TimelineDropTest {
@Test
fun `dropping the head asks for exactly where it landed`() {
val target = LocalDate(2026, 9, 2)
val drop = TimelineDrop(overnight, target, 20 * 60, clipOffsetMin = 0)
val drop = TimelineDrop(overnight, target, 20 * 60, clipOffsetMin = 0, token = 0L)
assertThat(drop.startInstant(zone)).isEqualTo(target.atTime(20, 0).toInstant(zone))
}
@@ -63,7 +63,7 @@ class TimelineDropTest {
val tail = blockOn(sun)
val offset = tail.clipOffsetMinutes(sun, zone)
// Dragged three days back, same height in the column: Sun 6 -> Thu 3.
val drop = TimelineDrop(overnight, LocalDate(2026, 9, 3), 0, offset)
val drop = TimelineDrop(overnight, LocalDate(2026, 9, 3), 0, offset, token = 0L)
// The event began Sat 5 Sep 20:00, so it now begins Wed 2 Sep 20:00 —
// the whole event moved three days, and no time of day was invented.
@@ -75,7 +75,7 @@ class TimelineDropTest {
fun `dragging the tail down the column re-times the event across midnight`() {
val offset = blockOn(sun).clipOffsetMinutes(sun, zone)
// Tail top pulled from 00:00 to 03:00 on its own day.
val drop = TimelineDrop(overnight, sun, 3 * 60, offset)
val drop = TimelineDrop(overnight, sun, 3 * 60, offset, token = 0L)
assertThat(drop.startInstant(zone)).isEqualTo(sat.atTime(23, 0).toInstant(zone))
}
@@ -84,7 +84,7 @@ class TimelineDropTest {
fun `pulling the tail above its own midnight moves the event earlier`() {
val offset = blockOn(sun).clipOffsetMinutes(sun, zone)
// The tail's top edge dragged an hour above the midnight it rests on.
val drop = TimelineDrop(overnight, sun, -60, offset)
val drop = TimelineDrop(overnight, sun, -60, offset, token = 0L)
// Event was Sat 20:00 to Sun 08:00; it now begins an hour earlier.
assertThat(drop.startInstant(zone)).isEqualTo(sat.atTime(19, 0).toInstant(zone))
@@ -92,7 +92,7 @@ class TimelineDropTest {
@Test
fun `a top edge dragged past the next midnight resolves onto the day after`() {
val drop = TimelineDrop(overnight, sat, 25 * 60, clipOffsetMin = 0)
val drop = TimelineDrop(overnight, sat, 25 * 60, clipOffsetMin = 0, token = 0L)
assertThat(drop.startInstant(zone)).isEqualTo(sun.atTime(1, 0).toInstant(zone))
}
@@ -130,7 +130,7 @@ class TimelineDropTest {
val tail = layoutDay(listOf(overnightIntoDst), sun, berlin).single()
val offset = tail.clipOffsetMinutes(sun, berlin)
// Dropped back onto its own slot a week earlier, clear of the boundary.
val drop = TimelineDrop(overnightIntoDst, LocalDate(2026, 3, 22), 0, offset)
val drop = TimelineDrop(overnightIntoDst, LocalDate(2026, 3, 22), 0, offset, token = 0L)
assertThat(drop.startInstant(berlin))
.isEqualTo(LocalDate(2026, 3, 21).atTime(22, 0).toInstant(berlin))
@@ -155,7 +155,7 @@ class TimelineDropTest {
)
val block = layoutDay(listOf(event), fallBack, brussels).single()
assertThat(block.clipOffsetMinutes(fallBack, brussels)).isEqualTo(0)
val drop = TimelineDrop(event, fallBack, block.startMin, clipOffsetMin = 0)
val drop = TimelineDrop(event, fallBack, block.startMin, clipOffsetMin = 0, token = 0L)
assertThat(drop.startInstant(brussels)).isEqualTo(event.start)
}
@@ -168,7 +168,7 @@ class TimelineDropTest {
val tail = layoutDay(listOf(event), fallBack, brussels).single()
val offset = tail.clipOffsetMinutes(fallBack, brussels)
assertThat(offset).isEqualTo(2 * 60)
val drop = TimelineDrop(event, fallBack, tail.startMin, clipOffsetMin = offset)
val drop = TimelineDrop(event, fallBack, tail.startMin, clipOffsetMin = offset, token = 0L)
assertThat(drop.startInstant(brussels)).isEqualTo(event.start)
}
@@ -189,7 +189,7 @@ class TimelineDropTest {
end = Instant.parse("2026-10-25T02:30:00Z"),
)
val block = layoutDay(listOf(event), fallBack, brussels).single()
val drop = TimelineDrop(event, fallBack, block.startMin + 15, clipOffsetMin = 0)
val drop = TimelineDrop(event, fallBack, block.startMin + 15, clipOffsetMin = 0, token = 0L)
assertThat(drop.startInstant(brussels)).isEqualTo(Instant.parse("2026-10-25T01:45:00Z"))
}
@@ -234,7 +234,7 @@ class TimelineDropTest {
start = Instant.parse("2026-10-25T01:30:00Z"),
end = Instant.parse("2026-10-25T03:00:00Z"),
)
val drop = resizedDrop(event, ResizeEdge.Bottom, fallBack, 2 * 60 + 30, 15, brussels)
val drop = resizedSpan(event, ResizeEdge.Bottom, fallBack, 2 * 60 + 30, 15, brussels)
assertThat(drop.start).isEqualTo(event.start)
assertThat(drop.end).isEqualTo(Instant.parse("2026-10-25T01:45:00Z"))
}
@@ -246,7 +246,7 @@ class TimelineDropTest {
start = Instant.parse("2026-10-25T00:30:00Z"),
end = Instant.parse("2026-10-25T01:15:00Z"),
)
val drop = resizedDrop(event, ResizeEdge.Top, fallBack, 2 * 60, 60, brussels)
val drop = resizedSpan(event, ResizeEdge.Top, fallBack, 2 * 60, 60, brussels)
assertThat(drop.start).isEqualTo(Instant.parse("2026-10-25T00:00:00Z"))
assertThat(drop.end).isEqualTo(event.end)
}
@@ -258,7 +258,7 @@ class TimelineDropTest {
start = Instant.parse("2026-10-25T00:20:00Z"),
end = Instant.parse("2026-10-25T01:10:00Z"),
)
val drop = resizedDrop(event, ResizeEdge.Bottom, fallBack, 2 * 60 + 20, 30, brussels)
val drop = resizedSpan(event, ResizeEdge.Bottom, fallBack, 2 * 60 + 20, 30, brussels)
assertThat(drop.end).isEqualTo(Instant.parse("2026-10-25T00:50:00Z"))
}
@@ -270,7 +270,7 @@ class TimelineDropTest {
start = Instant.parse("2026-10-24T23:00:00Z"),
end = Instant.parse("2026-10-25T03:00:00Z"),
)
val drop = resizedDrop(event, ResizeEdge.Bottom, fallBack, 60, 75, brussels)
val drop = resizedSpan(event, ResizeEdge.Bottom, fallBack, 60, 75, brussels)
assertThat(drop.end).isEqualTo(Instant.parse("2026-10-25T00:15:00Z"))
}
}
@@ -356,12 +356,12 @@ class WeekLayoutTest {
)
assertThat(state.allDaySpans.map { it.lane }).containsExactly(0, 0)
val preview = state.withStripPreview(StripDrag(held, dayShift = 2), zone).allDaySpans
val preview = state.withStripPreview(listOf(StripDrag(held, dayShift = 2)), zone).allDaySpans
val moved = preview.single { it.event.instanceId == held.instanceId }
assertThat(moved.event).isEqualTo(held)
assertThat(moved.startCol).isEqualTo(2)
assertThat(preview.map { it.lane }).containsExactly(0, 1)
assertThat(state.withStripPreview(StripDrag(held, dayShift = 2, overGrid = true), zone)).isSameInstanceAs(state)
assertThat(state.withStripPreview(listOf(StripDrag(held, dayShift = 2, overGrid = true)), zone)).isSameInstanceAs(state)
}
}
@@ -0,0 +1,33 @@
package de.jeanlucmakiola.calendula.widget
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.core.mutablePreferencesOf
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay
import de.jeanlucmakiola.calendula.ui.agenda.AgendaRange
import de.jeanlucmakiola.floret.glance.WidgetBackground
import org.junit.jupiter.api.Test
/** Per-widget options survive a save and read back (#489). */
class WidgetConfigTest {
private val defaults = AgendaWidgetOptions(AgendaRange.Week, WidgetSize.SMALL, true, PastEventDisplay.SHOW)
@Test
fun `appearance and agenda style round-trip`() {
val appearance = WidgetAppearance(WidgetBackground.SOLID, WidgetTheme.DARK, opacity = 0.6f)
val options = defaults.copy(style = AgendaWidgetStyle.CLASSIC)
val prefs = mutablePreferencesOf().apply {
putAppearance(appearance)
putAgendaOptions(options)
}
assertThat(prefs.widgetAppearance).isEqualTo(appearance)
assertThat(prefs.agendaWidgetOptions(defaults)).isEqualTo(options)
}
@Test
fun `a widget saved before 2_24_1 stays opaque cards`() {
assertThat(emptyPreferences().widgetAppearance.opacity).isEqualTo(1f)
assertThat(emptyPreferences().agendaWidgetOptions(defaults).style).isEqualTo(AgendaWidgetStyle.CARDS)
}
}
@@ -0,0 +1,28 @@
package de.jeanlucmakiola.calendula.widget.agenda
import com.google.common.truth.Truth.assertThat
import kotlinx.datetime.LocalDate
import org.junit.jupiter.api.Test
/** The classic agenda's day labels and row cap (#489). */
class ClassicItemsTest {
private val mon = LocalDate(2026, 11, 9)
private val tue = LocalDate(2026, 11, 10)
@Test
fun `each day gets one label before its rows`() {
val rows = listOf(AgendaRow.Placeholder(mon), AgendaRow.Placeholder(tue), AgendaRow.Placeholder(tue))
assertThat(classicItems(rows).map { it::class }).containsExactly(
ClassicItem.Header::class, ClassicItem.Entry::class,
ClassicItem.Header::class, ClassicItem.Entry::class, ClassicItem.Entry::class,
).inOrder()
}
@Test
fun `labels count towards the cap and a stranded one is dropped`() {
val rows = listOf(AgendaRow.Placeholder(mon), AgendaRow.Placeholder(tue))
val items = classicItems(rows, limit = 3)
assertThat(items).containsExactly(ClassicItem.Header(mon), ClassicItem.Entry(rows[0])).inOrder()
}
}
@@ -42,33 +42,80 @@ class MonthGridTest {
@Test
fun `a week that fits keeps every lane`() {
val layouts = fitWeeks(busyWeeks(perDay = 2), lanes = 3)
val layouts = fitWeeks(busyWeeks(perDay = 2), LaneFit(3))
assertThat(layouts.map { it.laneCap }.distinct()).containsExactly(3)
assertThat(layouts.all { it.overflow.isEmpty() }).isTrue()
}
@Test
fun `a week that doesn't fit gives its last lane to the overflow`() {
val layouts = fitWeeks(busyWeeks(perDay = 5), lanes = 3)
val layouts = fitWeeks(busyWeeks(perDay = 5), LaneFit(3))
assertThat(layouts.map { it.laneCap }.distinct()).containsExactly(2)
assertThat(layouts.all { it.overflow.isNotEmpty() }).isTrue()
}
@Test
fun `a taller week fits more lanes`() {
assertThat(lanesFitting(19.dp)).isEqualTo(0)
assertThat(lanesFitting(50.dp)).isEqualTo(2)
assertThat(lanesFitting(100.dp)).isEqualTo(5)
assertThat(lanesFitting(19.dp, fontScale = 1f)).isEqualTo(LaneFit(0))
assertThat(lanesFitting(50.dp, fontScale = 1f)).isEqualTo(LaneFit(2))
assertThat(lanesFitting(100.dp, fontScale = 1f)).isEqualTo(LaneFit(5))
}
@Test
fun `a row too short for a full lane gets a compact one`() {
assertThat(lanesFitting(34.dp, fontScale = 1f)).isEqualTo(LaneFit(1, compact = true))
assertThat(lanesFitting(32.dp, fontScale = 1f)).isEqualTo(LaneFit(1, compact = true))
assertThat(lanesFitting(31.dp, fontScale = 1f)).isEqualTo(LaneFit(0))
assertThat(lanesFitting(35.dp, fontScale = 1f)).isEqualTo(LaneFit(1))
}
@Test
fun `no compact lane at a large font scale`() {
assertThat(lanesFitting(34.dp, fontScale = 1.1f)).isEqualTo(LaneFit(0))
}
@Test
fun `a single lane shows counts on busy days`() {
val layouts = fitWeeks(busyWeeks(perDay = 5), LaneFit(1))
assertThat(layouts.all { it.mixedLane == List(7) { GridCell<LaneItem>(LaneItem.Count(5), 1) } }).isTrue()
}
@Test
fun `a single lane keeps bars on days that fit`() {
val lone = timedEvent(monday.plus(1, DateTimeUnit.DAY), 9, zone = zone, id = 1, title = "Lone")
val busy = (2L..4L).map { timedEvent(monday.plus(3, DateTimeUnit.DAY), it.toInt() + 8, zone = zone, id = it, title = "B$it") }
val week = fitWeeks(weeks(listOf(lone) + busy), LaneFit(1, compact = true))[1]
assertThat(week.compact).isTrue()
assertThat(week.mixedLane).containsExactly(
GridCell<LaneItem>(null, 1),
GridCell<LaneItem>(LaneItem.Bar(lone), 1),
GridCell<LaneItem>(null, 1),
GridCell<LaneItem>(LaneItem.Count(3), 1),
GridCell<LaneItem>(null, 3),
).inOrder()
}
@Test
fun `a single lane cuts a multi-day bar around a busy day`() {
val trip = allDayEvent(monday, monday.plus(3, DateTimeUnit.DAY), id = 1, title = "Trip")
val busy = timedEvent(monday.plus(1, DateTimeUnit.DAY), 9, zone = zone, id = 2, title = "Busy")
val week = fitWeeks(weeks(listOf(trip, busy)), LaneFit(1))[1]
assertThat(week.mixedLane).containsExactly(
GridCell<LaneItem>(LaneItem.Bar(trip), 1),
GridCell<LaneItem>(LaneItem.Count(2), 1),
GridCell<LaneItem>(LaneItem.Bar(trip), 2),
GridCell<LaneItem>(null, 3),
).inOrder()
}
@Test
fun `lanes stop at the cap however tall the week`() {
assertThat(lanesFitting(1000.dp)).isEqualTo(MAX_LANES)
assertThat(lanesFitting(1000.dp, fontScale = 1f)).isEqualTo(LaneFit(MAX_LANES))
}
@Test
fun `a week with no room for a lane draws no overflow row either`() {
val layouts = fitWeeks(busyWeeks(perDay = 5), lanes = 0)
val layouts = fitWeeks(busyWeeks(perDay = 5), LaneFit(0))
assertThat(layouts.none { it.showsOverflow }).isTrue()
assertThat(layouts.all { it.lanes.isEmpty() }).isTrue()
}
@@ -0,0 +1,12 @@
الجديد
• نمط كلاسيكي لأداة جدول الأعمال.
• شريط تمرير لشفافية خلفية الأدوات.
الإصلاحات
• أرقام الأسابيع كانت أقل بواحد عندما يبدأ الأسبوع يوم الأحد.
• أداة الشهر تعرض الأحداث بأي ارتفاع.
• الأحداث الباهتة في الأدوات الداكنة مقروءة من جديد.
• الأدوات المضبوطة على فاتح أو داكن تطابق ألوان النظام.
التغييرات
• أذونات أقل.
@@ -0,0 +1,12 @@
Новае
• Класічны стыль для віджэта спісу падзей.
• Паўзунок непразрыстасці для фону віджэтаў.
Выпраўлена
• Нумары тыдняў былі на адзін меншыя, калі тыдзень пачынаецца ў нядзелю.
• Віджэт месяца паказвае падзеі пры любой вышыні.
• Прыглушаныя падзеі ў цёмных віджэтах зноў чытэльныя.
• Віджэты са светлай ці цёмнай тэмай адпавядаюць колерам сістэмы.
Зменена
• Менш дазволаў.
@@ -0,0 +1,12 @@
Novinky
• Klasický styl widgetu agendy.
• Posuvník průhlednosti pozadí widgetů.
Opraveno
• Čísla týdnů byla o jedno nižší, když týden začíná nedělí.
• Widget měsíce zobrazí události v jakékoli výšce.
• Ztlumené události v tmavých widgetech jsou opět čitelné.
• Widgety se světlým nebo tmavým motivem odpovídají barvám systému.
Změněno
• Méně oprávnění.
@@ -0,0 +1,12 @@
Neu
• Klassischer Stil für das Terminliste-Widget.
• Deckkraft-Regler für Widget-Hintergründe.
Behoben
• Kalenderwochen waren bei Wochenstart Sonntag eine zu niedrig.
• Monats-Widget zeigt Termine in jeder Höhe.
• Abgedunkelte Termine in dunklen Widgets wieder lesbar.
• Widgets mit Hell oder Dunkel passen zu den Systemfarben.
Geändert
• Weniger Berechtigungen.
@@ -0,0 +1,12 @@
New
• Classic style for the agenda widget.
• Opacity slider for widget backgrounds.
Fixed
• Week numbers were one too low when weeks start on Sunday.
• The month widget shows events at every height.
• Dimmed events in dark widgets are readable again.
• Widgets set to Light or Dark match the system colours.
Changed
• Fewer permissions.
@@ -0,0 +1,12 @@
Novedades
• Estilo clásico para el widget de agenda.
• Control de opacidad para el fondo de los widgets.
Correcciones
• Los números de semana salían uno menos con semanas que empiezan en domingo.
• El widget de mes muestra eventos con cualquier altura.
• Los eventos atenuados en widgets oscuros vuelven a leerse bien.
• Los widgets en claro u oscuro coinciden con los colores del sistema.
Cambios
• Menos permisos.
@@ -0,0 +1,12 @@
Nouveautés
• Style classique pour le widget agenda.
• Curseur d’opacité pour le fond des widgets.
Corrections
• Les numéros de semaine avaient un de moins avec des semaines commençant le dimanche.
• Le widget mois affiche les événements à toutes les hauteurs.
• Les événements estompés sont de nouveau lisibles dans les widgets sombres.
• Les widgets en clair ou sombre suivent les couleurs du système.
Modifications
• Moins d’autorisations.
@@ -0,0 +1,12 @@
Újdonságok
• Klasszikus stílus a napirend widgethez.
• Átlátszóság-csúszka a widgetek hátteréhez.
Javítva
• A hetek száma eggyel kevesebb volt, ha a hét vasárnap kezdődik.
• A havi widget bármilyen magasságban mutatja az eseményeket.
• A halványított események ismét olvashatók a sötét widgeteken.
• A világos vagy sötét widgetek a rendszer színeit követik.
Változások
• Kevesebb engedély.
@@ -0,0 +1,12 @@
Novità
• Stile classico per il widget agenda.
• Cursore di opacità per lo sfondo dei widget.
Correzioni
• I numeri delle settimane erano uno in meno con settimane che iniziano di domenica.
• Il widget mese mostra gli eventi a ogni altezza.
• Gli eventi attenuati nei widget scuri sono di nuovo leggibili.
• I widget in chiaro o scuro seguono i colori di sistema.
Modifiche
• Meno autorizzazioni.
@@ -0,0 +1,12 @@
新機能
• 予定リストウィジェットにクラシックスタイルを追加。
• ウィジェット背景の不透明度スライダーを追加。
修正
• 週の始まりが日曜日のとき、週番号が1つ少なく表示されていた問題。
• 月のウィジェットがどの高さでも予定を表示するように。
• 暗いウィジェットで薄く表示された予定が再び読みやすく。
• ライト/ダーク固定のウィジェットがシステムの色に合うように。
変更
• 必要な権限を削減。
@@ -0,0 +1,12 @@
Nieuw
• Klassieke stijl voor de agendawidget.
• Schuifregelaar voor de dekking van widgetachtergronden.
Opgelost
• Weeknummers waren één te laag als de week op zondag begint.
• De maandwidget toont afspraken op elke hoogte.
• Gedimde afspraken in donkere widgets zijn weer leesbaar.
• Widgets op Licht of Donker passen bij de systeemkleuren.
Gewijzigd
• Minder machtigingen.
@@ -0,0 +1,12 @@
Nowości
• Klasyczny styl widżetu agendy.
• Suwak przezroczystości tła widżetów.
Poprawki
• Numery tygodni były o jeden za niskie, gdy tydzień zaczyna się w niedzielę.
• Widżet miesiąca pokazuje wydarzenia przy każdej wysokości.
• Przyciemnione wydarzenia w ciemnych widżetach znów są czytelne.
• Widżety z jasnym lub ciemnym motywem pasują do kolorów systemu.
Zmiany
• Mniej uprawnień.
@@ -0,0 +1,12 @@
Novidades
• Estilo clássico para o widget de agenda.
• Controle de opacidade para o fundo dos widgets.
Correções
• Os números das semanas ficavam um a menos com semanas começando no domingo.
• O widget de mês mostra eventos em qualquer altura.
• Eventos esmaecidos em widgets escuros voltam a ser legíveis.
• Widgets em claro ou escuro seguem as cores do sistema.
Alterações
• Menos permissões.
@@ -0,0 +1,12 @@
Novidades
• Estilo clássico para o widget de agenda.
• Controlo de opacidade para o fundo dos widgets.
Correções
• Os números das semanas ficavam um abaixo com semanas a começar ao domingo.
• O widget de mês mostra eventos em qualquer altura.
• Eventos esbatidos em widgets escuros voltam a ser legíveis.
• Widgets em claro ou escuro seguem as cores do sistema.
Alterações
• Menos permissões.
@@ -0,0 +1,12 @@
Новое
• Классический стиль для виджета повестки.
• Ползунок непрозрачности для фона виджетов.
Исправлено
• Номера недель были на единицу меньше, если неделя начинается с воскресенья.
• Виджет месяца показывает события при любой высоте.
• Приглушённые события в тёмных виджетах снова читаемы.
• Виджеты со светлой или тёмной темой соответствуют цветам системы.
Изменено
• Меньше разрешений.
@@ -0,0 +1,12 @@
Novinky
• Klasický štýl widgetu agendy.
• Posuvník priehľadnosti pozadia widgetov.
Opravené
• Čísla týždňov boli o jedno nižšie, keď týždeň začína nedeľou.
• Widget mesiaca zobrazí udalosti v akejkoľvek výške.
• Stlmené udalosti v tmavých widgetoch sú opäť čitateľné.
• Widgety so svetlým alebo tmavým motívom zodpovedajú farbám systému.
Zmenené
• Menej povolení.
@@ -0,0 +1,12 @@
新功能
• 日程列表小部件新增经典样式。
• 小部件背景新增不透明度滑块。
修复
• 每周从星期日开始时,周数少了一。
• 月份小部件在任何高度都会显示日程。
• 深色小部件中变暗的日程重新清晰可读。
• 设为浅色或深色的小部件与系统颜色一致。
变更
• 减少了所需权限。
@@ -0,0 +1,12 @@
新功能
• 行程列表小工具新增經典樣式。
• 小工具背景新增不透明度滑桿。
修正
• 每週從星期日開始時,週數少了一。
• 月份小工具在任何高度都會顯示行程。
• 深色小工具中變暗的行程重新清晰可讀。
• 設為淺色或深色的小工具與系統顏色一致。
變更
• 減少了所需權限。