Compare commits

..
7 changed files with 177 additions and 106 deletions

No files matched your search

-1
View File
@@ -74,4 +74,3 @@ Gemfile.lock
# Claude Code
/CLAUDE.md
.kotlin/
@@ -1270,7 +1270,7 @@ class AndroidCalendarDataSource @Inject constructor(
form: EventForm,
allDayReminderTimeMinutes: Int,
): Long {
val row = querySeriesRow(eventId)
val row = querySeriesRow(eventId, beginMillis)
// Not a series, so there is no occurrence to single out: the row *is* the
// event, and an exception with nothing to be an exception to would leave
// an orphan holding the edit (the same test deleteOccurrence makes).
@@ -1349,6 +1349,8 @@ class AndroidCalendarDataSource @Inject constructor(
// Reminders, guests and colour come along like any new event, and so does
// a fresh UID — the detached row is a separate event now, and sharing the
// parent's would collide with it in .ics restore dedup.
// Fail before inserting: the EXDATE write below needs a usable length.
row.writeDuration()
val detachedId = insertEvent(form.toDetachedOccurrence(), allDayReminderTimeMinutes)
// Rows touched, not occurrences excluded — 1 whenever the series row still
// exists. It catches the row disappearing under us, not an EXDATE the
@@ -1384,7 +1386,7 @@ class AndroidCalendarDataSource @Inject constructor(
updated: EventForm,
allDayReminderTimeMinutes: Int,
): Long {
val row = querySeriesRow(eventId)
val row = querySeriesRow(eventId, beginMillis)
// From the first occurrence on (or with no rule to split) this is
// just a series update.
if (row.rrule.isNullOrBlank() || beginMillis <= row.dtStartMillis) {
@@ -1392,6 +1394,8 @@ class AndroidCalendarDataSource @Inject constructor(
return eventId
}
// Insert the new series first: if it fails, the original is untouched.
// Fail before inserting: truncating the original needs a usable length.
row.writeDuration()
val newEventId = insertEvent(updated, allDayReminderTimeMinutes)
carrySplitExdate(newEventId, row, beginMillis, original, updated)
truncateSeries(eventId, row, beginMillis)
@@ -1447,7 +1451,7 @@ class AndroidCalendarDataSource @Inject constructor(
}
override fun deleteEventFromOccurrence(eventId: Long, beginMillis: Long) {
val row = querySeriesRow(eventId)
val row = querySeriesRow(eventId, beginMillis)
// From the first occurrence on = the whole series; also the fallback
// when there is no RRULE to truncate.
if (row.rrule.isNullOrBlank() || beginMillis <= row.dtStartMillis) {
@@ -1476,8 +1480,12 @@ class AndroidCalendarDataSource @Inject constructor(
updateEventRow(eventId, values, "truncate series event id=$eventId begin=$beginMillis")
}
/** The series anchor: every time-related column of the Events row. */
private fun querySeriesRow(eventId: Long): SeriesRow = resolver.query(
/**
* The series anchor: every time-related column of the Events row. A recurring
* row with no usable DURATION gets one derived ([seriesDuration]), from the
* expanded occurrence at [occurrenceMillis] when DTEND can't supply it.
*/
private fun querySeriesRow(eventId: Long, occurrenceMillis: Long? = null): SeriesRow = resolver.query(
eventUri(eventId),
arrayOf(
CalendarContract.Events.DTSTART,
@@ -1488,11 +1496,12 @@ class AndroidCalendarDataSource @Inject constructor(
CalendarContract.Events._SYNC_ID,
CalendarContract.Events.EXDATE,
CalendarContract.Events.RDATE,
CalendarContract.Events.DTEND,
),
null, null, null,
)?.use { c ->
if (c.moveToFirst()) {
SeriesRow(
val row = SeriesRow(
dtStartMillis = c.getLong(0),
rrule = c.getString(1),
timezone = c.getString(2),
@@ -1502,11 +1511,27 @@ class AndroidCalendarDataSource @Inject constructor(
exdate = c.getString(6),
rdate = c.getString(7),
)
if (!row.recurs || !row.duration.isNullOrBlank()) return@use row
row.copy(
dtEndMillis = if (c.isNull(8)) null else c.getLong(8),
occurrenceSpanMillis = occurrenceMillis?.let { occurrenceSpan(eventId, it) },
)
} else {
null
}
} ?: throw WriteFailedException("read series row of event id=$eventId")
/** Length of the already-expanded occurrence of [eventId] starting at [beginMillis]. */
private fun occurrenceSpan(eventId: Long, beginMillis: Long): Long? {
return resolver.query(
instancesUri(beginMillis, beginMillis + 1),
arrayOf(CalendarContract.Instances.BEGIN, CalendarContract.Instances.END),
"${CalendarContract.Instances.EVENT_ID} = ? AND ${CalendarContract.Instances.BEGIN} = ?",
arrayOf(eventId.toString(), beginMillis.toString()),
null,
)?.use { c -> if (c.moveToFirst()) c.getLong(1) - c.getLong(0) else null }
}
private data class SeriesRow(
val dtStartMillis: Long,
val rrule: String?,
@@ -1517,6 +1542,9 @@ class AndroidCalendarDataSource @Inject constructor(
val syncId: String? = null,
val exdate: String? = null,
val rdate: String? = null,
/** Only read for a series with no DURATION, to derive one ([writeDuration]). */
val dtEndMillis: Long? = null,
val occurrenceSpanMillis: Long? = null,
) {
/**
* Whether this row expands into more than itself. RDATE counts as much as
@@ -1526,14 +1554,23 @@ class AndroidCalendarDataSource @Inject constructor(
*/
val recurs: Boolean get() = !rrule.isNullOrBlank() || !rdate.isNullOrBlank()
/**
* DURATION for a write that re-expands the series. Refuses rather than
* writing none, which would leave the provider nothing to expand (#502).
*/
fun writeDuration(): String = duration?.takeIf { it.isNotBlank() }
?: seriesDuration(dtStartMillis, dtEndMillis, occurrenceSpanMillis, allDay != 0)
?: throw WriteFailedException("series has no usable length")
/**
* The time/recurrence set a series write carries together: the provider
* re-expands instances only from what the update itself holds.
*/
fun timeColumns(): ContentValues = ContentValues().apply {
put(CalendarContract.Events.DTSTART, dtStartMillis)
putNull(CalendarContract.Events.DTEND)
put(CalendarContract.Events.RRULE, rrule)
put(CalendarContract.Events.DURATION, duration)
put(CalendarContract.Events.DURATION, writeDuration())
put(CalendarContract.Events.EVENT_TIMEZONE, timezone)
put(CalendarContract.Events.ALL_DAY, allDay)
}
@@ -1545,7 +1582,7 @@ class AndroidCalendarDataSource @Inject constructor(
dtStartMillis = dtStartMillis,
rrule = rrule,
rdate = rdate,
duration = duration,
duration = writeDuration(),
timezone = timezone,
allDay = allDay,
)
@@ -1732,7 +1769,7 @@ class AndroidCalendarDataSource @Inject constructor(
}
override fun deleteOccurrence(eventId: Long, beginMillis: Long) {
val row = querySeriesRow(eventId)
val row = querySeriesRow(eventId, beginMillis)
// Not a series, so the row *is* the event: an exclusion would put a
// recurrence set on a one-off, an exception would leave an orphan.
if (!row.recurs) {
@@ -1762,7 +1799,7 @@ class AndroidCalendarDataSource @Inject constructor(
val values = buildOccurrenceCancelValues(
originalInstanceMillis = beginMillis,
dtStartMillis = beginMillis,
duration = row.duration,
duration = row.writeDuration(),
timezone = row.timezone,
allDay = row.allDay,
)
@@ -369,7 +369,8 @@ internal fun buildMovedMasterValues(
/** The recurring copy's DURATION: its own if present, else derived from DTEND. */
private fun MasterEventSnapshot.movedDuration(): String = duration?.takeIf { it.isNotBlank() }
?: rfc2445Duration((dtEndMillis ?: dtStartMillis) - dtStartMillis, isAllDay)
?: seriesDuration(dtStartMillis, dtEndMillis ?: dtStartMillis, occurrenceSpanMillis = null, isAllDay = isAllDay)
?: throw WriteFailedException("move series with no usable length")
/**
* Raw provider snapshot of one exception row of a recurring series (a modified
@@ -454,6 +455,29 @@ internal fun buildOccurrenceExdateValues(
existingExdate, listOf(occurrenceMillis), dtStartMillis, rrule, rdate, duration, timezone, allDay,
)
/**
* DURATION for a series row that has none. Rows from other tools can carry a
* DTEND (sometimes 0) instead; rewriting them without a DURATION leaves the
* provider nothing to expand, and every occurrence vanishes (#502). The span of
* an occurrence the provider actually expanded wins over DTEND; null when
* neither gives a length (a DTEND before DTSTART), so the caller fails
* instead of guessing.
*/
internal fun seriesDuration(
dtStartMillis: Long,
dtEndMillis: Long?,
occurrenceSpanMillis: Long?,
isAllDay: Boolean,
): String? {
val span = occurrenceSpanMillis?.takeIf { it >= 0 }
?: dtEndMillis?.minus(dtStartMillis)?.takeIf { it >= 0 }
?: return null
if (!isAllDay) return rfc2445Duration(span, isAllDay = false)
// Whole days, rounded: a span read across a DST change or zone offset is a few hours off.
val days = ((span + MILLIS_PER_DAY / 2) / MILLIS_PER_DAY).coerceAtLeast(1)
return rfc2445Duration(days * MILLIS_PER_DAY, isAllDay = true)
}
/** [buildOccurrenceExdateValues] excluding every one of [occurrences] in one write. */
internal fun buildOccurrencesExdateValues(
existingExdate: String?,
@@ -469,6 +493,7 @@ internal fun buildOccurrencesExdateValues(
mergedExdate(exdate, millis, allDay != 0, timezone)
},
CalendarContract.Events.DTSTART to dtStartMillis,
CalendarContract.Events.DTEND to null,
CalendarContract.Events.RRULE to rrule,
CalendarContract.Events.RDATE to rdate,
CalendarContract.Events.DURATION to duration,
@@ -2,7 +2,6 @@ package de.jeanlucmakiola.calendula.ui.common
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
@@ -132,8 +131,7 @@ fun FixedTimeReminderEditor(
* Picker for a fixed-time default (#459), full-screen: off, or a reminder at a
* set time edited in place — and, on a per-calendar picker ([inheritedLabel]
* non-null), deferring to the global default, [inherited], which also seeds the
* editor. Applies live; the user leaves via back, or through [footer], which
* follows the options and gets [onDismiss].
* editor. Applies live; the user leaves via back.
*/
@Composable
fun FixedTimeReminderPicker(
@@ -143,7 +141,6 @@ fun FixedTimeReminderPicker(
onDismiss: () -> Unit,
inheritedLabel: String? = null,
inherited: FixedTimeReminder? = null,
footer: @Composable ColumnScope.(dismiss: () -> Unit) -> Unit = {},
) {
var current by rememberSaveable(stateSaver = FixedTimeOverrideSaver) { mutableStateOf(selected) }
var editing by rememberSaveable { mutableStateOf(false) }
@@ -195,7 +192,6 @@ fun FixedTimeReminderPicker(
},
)
}
footer(onDismiss)
}
}
@@ -4,7 +4,6 @@ import de.jeanlucmakiola.floret.identity.collapseExit
import de.jeanlucmakiola.floret.identity.expandEnter
import androidx.compose.foundation.layout.Column
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.EnterExitState
import android.Manifest
import android.content.Context
import android.content.Intent
@@ -20,13 +19,10 @@ import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.relocation.BringIntoViewRequester
import androidx.compose.foundation.relocation.bringIntoViewRequester
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.icons.automirrored.filled.OpenInNew
import androidx.compose.material.icons.outlined.Info
import androidx.compose.material.icons.outlined.NotificationsActive
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
@@ -112,7 +108,6 @@ internal fun NotificationsScreen(
var showFixedDefault by remember { mutableStateOf(false) }
var showDigestDay by remember { mutableStateOf(false) }
var showDigestTime by remember { mutableStateOf(false) }
var revealDigest by rememberSaveable { mutableStateOf(false) }
val scope = rememberCoroutineScope()
val channelStatus by viewModel.channelStatus.collectAsStateWithLifecycle()
val digestBlocked by viewModel.digestBlocked.collectAsStateWithLifecycle()
@@ -198,14 +193,9 @@ internal fun NotificationsScreen(
Spacer(Modifier.height(24.dp))
DailyDigestRows(
reveal = revealDigest,
onRevealed = { revealDigest = false },
digest = state.dailyDigest,
blocked = channelStatus.appBlocked || digestBlocked,
onEnable = {
revealDigest = false
toggleDigest(it)
},
onEnable = toggleDigest,
onPickDay = { showDigestDay = true },
onPickTime = { showDigestTime = true },
onOpenSound = {
@@ -267,29 +257,6 @@ internal fun NotificationsScreen(
selected = state.defaultFixedTimeReminder?.let { FixedTimeOverride.At(it) } ?: FixedTimeOverride.Off,
onSelect = { viewModel.setDefaultFixedTimeReminder((it as? FixedTimeOverride.At)?.reminder) },
onDismiss = { showFixedDefault = false },
footer = { dismiss ->
// For those after one list of the day's events (#459).
if (!state.dailyDigest.enabled) {
Spacer(Modifier.height(24.dp))
GroupedRow(
title = stringResource(R.string.settings_digest_turn_on),
summary = stringResource(R.string.settings_digest_hint),
position = Position.Alone,
leading = {
Icon(
imageVector = Icons.Outlined.NotificationsActive,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
},
onClick = {
revealDigest = true
toggleDigest(true)
dismiss()
},
)
}
},
)
}
if (showDigestDay) {
@@ -361,8 +328,7 @@ internal fun NotificationsScreen(
/**
* The daily summary (#459): its switch, and once on, which day it lists, when,
* and its channel's system settings. With [reveal], the block scrolls into view
* once those rows have expanded, then reports [onRevealed].
* and its channel's system settings.
*/
@Composable
private fun DailyDigestRows(
@@ -372,59 +338,47 @@ private fun DailyDigestRows(
onPickDay: () -> Unit,
onPickTime: () -> Unit,
onOpenSound: () -> Unit,
reveal: Boolean,
onRevealed: () -> Unit,
) {
val requester = remember { BringIntoViewRequester() }
Column(Modifier.bringIntoViewRequester(requester)) {
GroupedSwitchRow(
title = stringResource(R.string.settings_digest),
checked = digest.enabled,
onCheckedChange = onEnable,
summary = if (digest.enabled) {
stringResource(
R.string.settings_digest_summary,
stringResource(digestDayLabel(digest.day)),
settingsTimeOfDay(digest.timeMinutes),
)
} else {
stringResource(R.string.settings_digest_hint)
},
position = if (digest.enabled) Position.Top else Position.Alone,
)
AnimatedVisibility(visible = digest.enabled, enter = expandEnter(), exit = collapseExit()) {
val settled = !transition.isRunning && transition.currentState == EnterExitState.Visible
LaunchedEffect(settled, reveal) {
if (settled && reveal) {
requester.bringIntoView()
onRevealed()
}
}
Column {
GroupedRow(
title = stringResource(R.string.settings_digest_day),
summary = stringResource(digestDayLabel(digest.day)),
position = Position.Middle,
onClick = onPickDay,
)
GroupedRow(
title = stringResource(R.string.settings_digest_time),
summary = settingsTimeOfDay(digest.timeMinutes),
position = Position.Middle,
onClick = onPickTime,
)
GroupedRow(
title = stringResource(R.string.settings_notification_sound),
summary = if (blocked) {
stringResource(R.string.settings_notifications_blocked_hint)
} else {
stringResource(R.string.settings_digest_sound_hint)
},
position = Position.Bottom,
trailing = { ExternalLinkIcon() },
onClick = onOpenSound,
)
}
GroupedSwitchRow(
title = stringResource(R.string.settings_digest),
checked = digest.enabled,
onCheckedChange = onEnable,
summary = if (digest.enabled) {
stringResource(
R.string.settings_digest_summary,
stringResource(digestDayLabel(digest.day)),
settingsTimeOfDay(digest.timeMinutes),
)
} else {
stringResource(R.string.settings_digest_hint)
},
position = if (digest.enabled) Position.Top else Position.Alone,
)
AnimatedVisibility(visible = digest.enabled, enter = expandEnter(), exit = collapseExit()) {
Column {
GroupedRow(
title = stringResource(R.string.settings_digest_day),
summary = stringResource(digestDayLabel(digest.day)),
position = Position.Middle,
onClick = onPickDay,
)
GroupedRow(
title = stringResource(R.string.settings_digest_time),
summary = settingsTimeOfDay(digest.timeMinutes),
position = Position.Middle,
onClick = onPickTime,
)
GroupedRow(
title = stringResource(R.string.settings_notification_sound),
summary = if (blocked) {
stringResource(R.string.settings_notifications_blocked_hint)
} else {
stringResource(R.string.settings_digest_sound_hint)
},
position = Position.Bottom,
trailing = { ExternalLinkIcon() },
onClick = onOpenSound,
)
}
}
}
-1
View File
@@ -808,7 +808,6 @@
<string name="settings_fixed_reminder_hint">Added to new timed events, e.g. the evening before. It follows the event when you move it to another time.</string>
<!-- Daily summary notification (#459) -->
<string name="settings_digest">Daily summary</string>
<string name="settings_digest_turn_on">Turn on daily summary</string>
<string name="settings_digest_hint">One notification listing a day\'s events</string>
<!-- %1$s is settings_digest_day_today/tomorrow, %2$s a clock time. -->
<string name="settings_digest_summary">%1$s at %2$s</string>
@@ -13,6 +13,7 @@ import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.LocalTime
import kotlinx.datetime.UtcOffset
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import java.time.ZoneId
import kotlin.time.Instant
@@ -500,6 +501,58 @@ class EventWriteMapperTest {
.isEqualTo(CalendarContract.Events.STATUS_CANCELED)
}
// --- seriesDuration (#502) ---
@Test
fun `series duration prefers the expanded occurrence over dtend`() {
// DTEND as the end of the whole series must not stretch every occurrence.
assertThat(seriesDuration(1_000_000L, 9_000_000_000L, 3_600_000L, isAllDay = false)).isEqualTo("P3600S")
}
@Test
fun `series duration falls back to dtend when it lies after dtstart`() {
assertThat(seriesDuration(1_000_000L, 8_200_000L, null, isAllDay = false)).isEqualTo("P7200S")
}
@Test
fun `series duration ignores a zero dtend and uses the occurrence span`() {
assertThat(seriesDuration(1_790_852_400_000L, 0L, 7_200_000L, isAllDay = false)).isEqualTo("P7200S")
}
@Test
fun `series duration gives up rather than guessing`() {
assertThat(seriesDuration(1_000L, 0L, null, isAllDay = false)).isNull()
assertThat(seriesDuration(1_000L, null, null, isAllDay = true)).isNull()
}
@Test
fun `all-day series duration rounds to whole days`() {
// 47 h: a two-day occurrence read across a DST change.
assertThat(seriesDuration(0L, null, 47L * 3_600_000L, isAllDay = true)).isEqualTo("P2D")
}
@Test
fun `series duration keeps a zero length the provider already shows`() {
assertThat(seriesDuration(1_000L, 0L, 0L, isAllDay = false)).isEqualTo("P0S")
assertThat(seriesDuration(1_000L, 1_000L, null, isAllDay = true)).isEqualTo("P1D")
}
@Test
fun `exdate drop clears a stray dtend on the series`() {
val values = buildOccurrenceExdateValues(
existingExdate = null,
occurrenceMillis = 1_784_102_400_000L,
dtStartMillis = 1_783_929_600_000L,
rrule = "FREQ=DAILY;COUNT=5",
rdate = null,
duration = "PT1H",
timezone = "Europe/Berlin",
allDay = 0,
)
assertThat(values).containsKey(CalendarContract.Events.DTEND)
assertThat(values[CalendarContract.Events.DTEND]).isNull()
}
// --- buildOccurrenceExdateValues ("delete only this event", no _sync_id) ---
@Test
@@ -1194,6 +1247,14 @@ class EventWriteMapperTest {
description = "",
)
@Test
fun `moved series with a zero dtend and no duration is refused, not copied broken`() {
val snapshot = masterSnapshot(dtEndMillis = 0L, rrule = "FREQ=WEEKLY;BYDAY=TH")
assertThrows<WriteFailedException> {
buildMovedMasterValues(snapshot, targetCalendarId = 9L, uid = "u@calendula")
}
}
@Test
fun `moved one-off carries target calendar, uid and DTEND but no recurrence`() {
val values = buildMovedMasterValues(masterSnapshot(), targetCalendarId = 9L, uid = "u@calendula")