From e5d9b4965bc538b86ab4fc73618515e2c8ff64b9 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 17:06:11 +0100 Subject: [PATCH 01/16] feat(#325): copy events from one calendar into another --- .../data/calendar/CalendarDataSource.kt | 79 ++++++- .../data/calendar/CalendarRepository.kt | 21 +- .../data/calendar/CalendarRepositoryImpl.kt | 19 ++ .../calendula/data/calendar/Projections.kt | 16 +- .../calendula/domain/ics/CalendarCopy.kt | 119 ++++++++++ .../calendula/ui/calendars/BackupScreen.kt | 37 +++ .../calendula/ui/calendars/BackupUiState.kt | 16 +- .../calendula/ui/calendars/CopyEventsSheet.kt | 221 ++++++++++++++++++ .../ui/calendars/CopyEventsViewModel.kt | 105 +++++++++ app/src/main/res/values/strings.xml | 21 ++ .../calendar/CalendarRepositoryImplTest.kt | 36 +++ .../data/calendar/FakeCalendarDataSource.kt | 6 + .../calendula/domain/ics/CalendarCopyTest.kt | 150 ++++++++++++ .../ui/calendars/BackupUiStateTest.kt | 36 +++ docs/ARCHITECTURE.md | 14 ++ 15 files changed, 882 insertions(+), 14 deletions(-) create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopyTest.kt diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt index fc8c0b75..870e53ba 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt @@ -30,6 +30,9 @@ import de.jeanlucmakiola.calendula.domain.Reminder import de.jeanlucmakiola.calendula.domain.SearchCandidate import de.jeanlucmakiola.calendula.domain.contacts.MANAGED_UID_PREFIX import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType +import de.jeanlucmakiola.calendula.domain.ics.CalendarCopyRows +import de.jeanlucmakiola.calendula.domain.ics.CopyException +import de.jeanlucmakiola.calendula.domain.ics.CopySeries import de.jeanlucmakiola.calendula.domain.ics.IcsEvent import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent import de.jeanlucmakiola.calendula.domain.ics.semanticReminderMinutes @@ -100,6 +103,13 @@ interface CalendarDataSource { */ fun calendarEvents(calendarIds: Set, allDayReminderTimeMinutes: Int): List + /** + * Every event row of [calendarId] for a calendar copy (#325): the + * masters/one-offs [calendarEvents] reads, plus the modified and cancelled + * exception rows it leaves out, each with the keys that link it to its series. + */ + fun calendarCopyRows(calendarId: Long, allDayReminderTimeMinutes: Int): CalendarCopyRows + /** * The non-empty `Events.UID_2445` values present in [calendarId] — used to * dedup an `.ics` import so re-importing a backup doesn't double events. @@ -788,12 +798,60 @@ class AndroidCalendarDataSource @Inject constructor( .associate { it.id to it.displayName } if (names.isEmpty()) return emptyList() - val idList = names.keys.joinToString(",") // Masters + one-offs only: no soft-deleted or exception rows. - val selection = "${CalendarContract.Events.CALENDAR_ID} IN ($idList) AND " + + val selection = "${CalendarContract.Events.CALENDAR_ID} IN (${names.keys.joinToString(",")}) AND " + "${CalendarContract.Events.DELETED} = 0 AND " + "${CalendarContract.Events.ORIGINAL_ID} IS NULL AND " + "${CalendarContract.Events.ORIGINAL_SYNC_ID} IS NULL" + val events = mutableListOf() + forEachExportRow(selection, allDayReminderTimeMinutes) { event -> + events += event(names[getLong(EventExportProjection.IDX_CALENDAR_ID)]) + } + return events + } + + override fun calendarCopyRows(calendarId: Long, allDayReminderTimeMinutes: Int): CalendarCopyRows { + val selection = "${CalendarContract.Events.CALENDAR_ID} = $calendarId AND " + + "${CalendarContract.Events.DELETED} = 0" + val series = mutableListOf() + val exceptions = mutableListOf() + forEachExportRow(selection, allDayReminderTimeMinutes) { event -> + val color = getIntOrNull(EventExportProjection.IDX_EVENT_COLOR) + val originalId = getLongOrNull(EventExportProjection.IDX_ORIGINAL_ID) + val originalSyncId = getString(EventExportProjection.IDX_ORIGINAL_SYNC_ID)?.takeIf { it.isNotEmpty() } + if (originalId == null && originalSyncId == null) { + series += CopySeries( + eventId = getLong(EventExportProjection.IDX_ID), + syncId = getString(EventExportProjection.IDX_SYNC_ID)?.takeIf { it.isNotEmpty() }, + event = event(null), + color = color, + ) + } else { + // An exception without its occurrence time can't name what it replaces. + val originalInstance = getLongOrNull(EventExportProjection.IDX_ORIGINAL_INSTANCE_TIME) + ?: return@forEachExportRow + exceptions += CopyException( + originalId = originalId, + originalSyncId = originalSyncId, + originalInstance = originalInstance.toKotlinInstantFromEpochMillis(), + event = event(null), + color = color, + ) + } + } + return CalendarCopyRows(series, exceptions) + } + + /** + * Hand each Events row matching [selection], oldest first, to [row] with a + * mapper to [IcsEvent] that takes the calendar name to tag it with. + * Reminders are read in one batched pass ahead of the rows. + */ + private fun forEachExportRow( + selection: String, + allDayReminderTimeMinutes: Int, + row: ColumnReader.(event: (calendarName: String?) -> IcsEvent) -> Unit, + ) { val eventIds = resolver.query( CalendarContract.Events.CONTENT_URI, arrayOf(CalendarContract.Events._ID), @@ -802,7 +860,7 @@ class AndroidCalendarDataSource @Inject constructor( null, )?.use { c -> c.mapRows { getLong(0) } }.orEmpty() val reminders = resolver.reminderMinutesByEvent(eventIds, alertsOnly = false) - return resolver.query( + resolver.query( CalendarContract.Events.CONTENT_URI, EventExportProjection.COLUMNS, selection, @@ -811,14 +869,15 @@ class AndroidCalendarDataSource @Inject constructor( )?.use { c -> c.mapRows { val eventId = getLong(EventExportProjection.IDX_ID) - val calendarId = getLong(EventExportProjection.IDX_CALENDAR_ID) - toIcsEvent( - reminderMinutes = reminders[eventId].orEmpty(), - calendarName = names[calendarId], - allDayReminderTimeMinutes = allDayReminderTimeMinutes, - ) + row { calendarName -> + toIcsEvent( + reminderMinutes = reminders[eventId].orEmpty(), + calendarName = calendarName, + allDayReminderTimeMinutes = allDayReminderTimeMinutes, + ) + } } - } ?: emptyList() + } } override fun existingUids(calendarId: Long): Set = resolver.query( diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt index 45f08aa8..fa950bd3 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt @@ -71,8 +71,27 @@ interface CalendarRepository { * Bulk-import parsed `.ics` [events] into [targetCalendarId]. Events whose * UID already exists in the target are skipped (idempotent restore); the * rest are inserted. See [CalendarDataSource.insertImportedEvent]. + * [onProgress] gets the count of events handled so far after each one; a + * cancelled caller stops the import between events. */ - suspend fun importEvents(targetCalendarId: Long, events: List): IcsImportSummary + suspend fun importEvents( + targetCalendarId: Long, + events: List, + onProgress: (done: Int) -> Unit = {}, + ): IcsImportSummary + + /** + * Copy every event of [sourceCalendarId] into [targetCalendarId] (#325), + * exceptions included (see + * [de.jeanlucmakiola.calendula.domain.ics.planCalendarCopy]). The source is only read. Runs + * through [importEvents], so a re-run skips what an earlier one copied. + * [onProgress] gets (done, total) once the source is read and after each event. + */ + suspend fun copyEvents( + sourceCalendarId: Long, + targetCalendarId: Long, + onProgress: (done: Int, total: Int) -> Unit = { _, _ -> }, + ): IcsImportSummary /** Create a new event from a validated form; returns the new `Events._ID`. */ suspend fun createEvent(form: EventForm): Long diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt index 0f9c9bc4..e4c6bea4 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt @@ -14,6 +14,7 @@ import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.domain.SearchCandidate import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent +import de.jeanlucmakiola.calendula.domain.ics.planCalendarCopy import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.Flow @@ -30,6 +31,8 @@ import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.withContext import java.util.concurrent.atomic.AtomicLong import kotlin.time.Instant @@ -250,9 +253,22 @@ class CalendarRepositoryImpl @Inject constructor( override suspend fun exportEvents(calendarIds: Set) = withContext(io) { dataSource.calendarEvents(calendarIds, allDayReminderTimeMinutes()) } + override suspend fun copyEvents( + sourceCalendarId: Long, + targetCalendarId: Long, + onProgress: (done: Int, total: Int) -> Unit, + ): IcsImportSummary { + val events = withContext(io) { + planCalendarCopy(dataSource.calendarCopyRows(sourceCalendarId, allDayReminderTimeMinutes())) + } + onProgress(0, events.size) + return importEvents(targetCalendarId, events) { done -> onProgress(done, events.size) } + } + override suspend fun importEvents( targetCalendarId: Long, events: List, + onProgress: (done: Int) -> Unit, ): IcsImportSummary = write { val existing = dataSource.existingUids(targetCalendarId) // Both are per-calendar, not per-event: looking them up once keeps a @@ -266,6 +282,8 @@ class CalendarRepositoryImpl @Inject constructor( var failed = 0 var notAttempted = 0 for ((index, event) in events.withIndex()) { + currentCoroutineContext().ensureActive() + if (index > 0) onProgress(index) // A known UID means the event is already in this calendar — skip, // keeping a restore idempotent (no overwrite this pass). if (event.uid != null && event.uid in existing) { @@ -296,6 +314,7 @@ class CalendarRepositoryImpl @Inject constructor( Log.w(TAG, "Skipped an unimportable event", e) } } + if (notAttempted == 0) onProgress(events.size) IcsImportSummary( imported = imported, skippedDuplicate = skipped, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/Projections.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/Projections.kt index 5775d1a4..37f4bd7e 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/Projections.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/Projections.kt @@ -156,10 +156,12 @@ internal object EventDetailProjection { * [EventDetailProjection] this reads `UID_2445` (to keep a row's identity across * backups) and `DURATION` (recurring rows carry it instead of DTEND), plus * `EXDATE` so a series exports the occurrences deleted from it. Modified- - * occurrence and cancelled-exception rows are filtered out by the query + * occurrence and cancelled-exception rows are filtered out by the backup query * (`ORIGINAL_ID IS NULL`), so RECURRENCE-ID overrides aren't exported — a * documented v1 limit (import skips them too). EXDATE is unaffected by that - * filter: it lives on the master row, not on an exception of its own. + * filter: it lives on the master row, not on an exception of its own. A + * calendar copy (#325) reads the exception rows too, through the trailing + * colour and series-link columns. */ internal object EventExportProjection { val COLUMNS: Array = arrayOf( @@ -178,6 +180,11 @@ internal object EventExportProjection { CalendarContract.Events.STATUS, CalendarContract.Events.AVAILABILITY, CalendarContract.Events.CALENDAR_ID, + CalendarContract.Events.EVENT_COLOR, + CalendarContract.Events._SYNC_ID, + CalendarContract.Events.ORIGINAL_ID, + CalendarContract.Events.ORIGINAL_SYNC_ID, + CalendarContract.Events.ORIGINAL_INSTANCE_TIME, ) const val IDX_ID = 0 @@ -195,6 +202,11 @@ internal object EventExportProjection { const val IDX_STATUS = 12 const val IDX_AVAILABILITY = 13 const val IDX_CALENDAR_ID = 14 + const val IDX_EVENT_COLOR = 15 + const val IDX_SYNC_ID = 16 + const val IDX_ORIGINAL_ID = 17 + const val IDX_ORIGINAL_SYNC_ID = 18 + const val IDX_ORIGINAL_INSTANCE_TIME = 19 } /** diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt new file mode 100644 index 00000000..bc8facd4 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt @@ -0,0 +1,119 @@ +package de.jeanlucmakiola.calendula.domain.ics + +import de.jeanlucmakiola.calendula.domain.EventStatus +import kotlinx.datetime.TimeZone +import kotlinx.datetime.toLocalDateTime +import kotlin.time.Duration.Companion.days +import kotlin.time.Instant + +/** + * A master or one-off event of the calendar being copied (#325), with the + * provider keys its exception rows point back through. [color] is the event's + * own colour, null when it shows its calendar's. + */ +data class CopySeries( + val eventId: Long, + val syncId: String?, + val event: IcsEvent, + val color: Int? = null, +) + +/** + * An exception row of the calendar being copied: a modified or cancelled + * occurrence of the series named by [originalId] / [originalSyncId], standing in + * for the occurrence that would have started at [originalInstance]. + */ +data class CopyException( + val originalId: Long?, + val originalSyncId: String?, + val originalInstance: Instant, + val event: IcsEvent, + val color: Int? = null, +) { + val isCancelled: Boolean get() = event.status == EventStatus.Cancelled +} + +/** Everything a calendar copy reads from its source: series/one-offs and their exception rows. */ +data class CalendarCopyRows( + val series: List, + val exceptions: List, +) + +/** + * The events a calendar copy inserts into its target, in the shape + * `importEvents` takes. + * + * A copied row has no `_sync_id`, and an exception row only attaches to its + * series through one, so overrides can't be written as exception rows. Every + * exception therefore excludes its occurrence from the copied series (`EXDATE`), + * and a modified one comes along as a standalone event at its own times — what + * Calendula itself writes for "only this event" on such a series. Its UID is + * derived from the series' UID and the occurrence, so a re-run skips it like + * any other event. + * + * Standalone occurrences come first: a run cut short then leaves at worst an + * occurrence missing its series, never a series missing an occurrence. + * Attendees and organizer are not part of either input; the copy is the + * user's own event. + */ +fun planCalendarCopy(rows: CalendarCopyRows): List { + val (series, exceptions) = rows + val byId = series.associateBy { it.eventId } + val bySyncId = series.filter { !it.syncId.isNullOrEmpty() }.associateBy { it.syncId } + val excluded = mutableMapOf>() + val detached = mutableListOf() + for (exception in exceptions) { + val parent = exception.originalId?.let(byId::get) + ?: exception.originalSyncId?.takeIf { it.isNotEmpty() }?.let(bySyncId::get) + if (parent != null) { + // An exception to a one-off overrides nothing a copy could carry. + if (parent.event.recurrenceRule.isNullOrBlank()) continue + excluded.getOrPut(parent.eventId) { mutableListOf() } += + exdateStamp(exception.originalInstance, parent.event.isAllDay) + } + if (exception.isCancelled) continue + val baseUid = parent?.event?.uid ?: exception.event.uid + detached += exception.event + .copy( + uid = "${exception.originalInstance.toEpochMilliseconds()}-$baseUid", + recurrenceRule = null, + exDates = emptyList(), + ) + .toParsedIcsEvent(exception.color) + } + return detached + series.map { s -> + val extra = excluded[s.eventId].orEmpty() + val event = if (extra.isEmpty()) s.event else s.event.copy(exDates = (s.event.exDates + extra).distinct()) + event.toParsedIcsEvent(s.color) + } +} + +/** + * [IcsEvent] read back as if [IcsWriter] had written it and [IcsParser] had read + * it, without the text in between. Unlike that round trip it keeps a one-off's + * own time zone (the writer pins it to UTC) and the event's colour (not part of + * the file format). + */ +fun IcsEvent.toParsedIcsEvent(color: Int? = null): ParsedIcsEvent = ParsedIcsEvent( + uid = uid, + summary = summary, + start = start, + // RFC 5545 §3.6.1: an all-day event lasts at least its one day; zero-length + // it expands into no instance at all. + end = if (isAllDay && end <= start) start + 1.days else end, + isAllDay = isAllDay, + zoneId = zoneId, + recurrenceRule = recurrenceRule?.takeIf { it.isNotBlank() }?.removePrefix("RRULE:"), + location = location, + description = description, + // The writer emits only lead times; a negative one would be an alarm after the start. + reminderMinutes = reminderMinutes.filter { it >= 0 }.distinct(), + status = status, + availability = availability, + color = color, + exDates = if (recurrenceRule.isNullOrBlank()) emptyList() else exDates.filter { it.isNotBlank() }.distinct(), +) + +/** An occurrence as an `EXDATE` entry in the provider's shape: the UTC day for an all-day series, else a UTC stamp. */ +internal fun exdateStamp(occurrence: Instant, isAllDay: Boolean): String = + if (isAllDay) occurrence.toLocalDateTime(TimeZone.UTC).date.toBasic() else occurrence.toUtcBasic() diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt index 0c738b42..a0feb927 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt @@ -13,6 +13,7 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ContentCopy import androidx.compose.material.icons.filled.FileDownload import androidx.compose.material.icons.filled.FileUpload import androidx.compose.material.icons.filled.Schedule @@ -89,8 +90,11 @@ fun BackupScreen( onImport: (Uri) -> Unit, visible: Boolean = true, viewModel: CalendarsViewModel = hiltViewModel(), + copyViewModel: CopyEventsViewModel = hiltViewModel(), ) { val state by viewModel.backupState.collectAsStateWithLifecycle() + val copyRun by copyViewModel.run.collectAsStateWithLifecycle() + var showCopy by rememberSaveable { mutableStateOf(false) } val backupResult by viewModel.backupResult.collectAsStateWithLifecycle() val autoBackup by viewModel.autoBackup.collectAsStateWithLifecycle() @@ -158,6 +162,9 @@ fun BackupScreen( is BackupUiState.Ready -> BackupContent( exportable = s.exportable, canImport = s.canImport, + canCopy = s.canCopy, + copyRun = copyRun, + onCopy = { showCopy = true }, autoBackup = autoBackup, viewModel = viewModel, onRestore = { runCatching { openBackup.launch(RESTORE_MIME_TYPES) } }, @@ -187,6 +194,23 @@ fun BackupScreen( onDismiss = { showExportPicker = false }, ) } + if (showCopy) { + val calendars by copyViewModel.calendars.collectAsStateWithLifecycle() + val selection by copyViewModel.selection.collectAsStateWithLifecycle() + CopyEventsSheet( + calendars = calendars, + selection = selection, + run = copyRun, + onSelectSource = copyViewModel::setSource, + onSelectTarget = copyViewModel::setTarget, + onStart = copyViewModel::start, + onCancel = copyViewModel::cancel, + onDismiss = { + showCopy = false + copyViewModel.clearFinished() + }, + ) + } if (showBackupCalendars) { AutoBackupCalendarPicker( calendars = ready.exportable, @@ -249,6 +273,9 @@ private fun defaultBackupName(): String = "calendula-backup-${LocalDate.now()}.i private fun BackupContent( exportable: List, canImport: Boolean, + canCopy: Boolean, + copyRun: CopyRunState, + onCopy: () -> Unit, autoBackup: AutoBackupUiState, viewModel: CalendarsViewModel, onRestore: () -> Unit, @@ -296,6 +323,16 @@ private fun BackupContent( leading = { LeadingAvatar(Icons.Default.FileUpload) }, onClick = onRestoreClick, ) + if (canCopy) { + GroupedRow( + title = stringResource(R.string.calendars_copy_action), + summary = (copyRun as? CopyRunState.Running)?.let { copyProgressText(it) } + ?: stringResource(R.string.calendars_copy_summary), + position = Position.Middle, + leading = { LeadingAvatar(Icons.Default.ContentCopy) }, + onClick = onCopy, + ) + } GroupedRow( title = stringResource(R.string.calendars_auto_backup), summary = stringResource(R.string.calendars_auto_backup_hint), diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiState.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiState.kt index 13daf24b..c4de4824 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiState.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiState.kt @@ -24,6 +24,8 @@ sealed interface BackupUiState { data class Ready( val exportable: List, val canImport: Boolean, + /** Some calendar can be copied into a different one (#325). */ + val canCopy: Boolean = false, ) : BackupUiState } @@ -50,5 +52,17 @@ fun backupUiState(calendars: List): BackupUiState { calendarListFailure(calendars) ?: FailureReason.NoImportTarget, ) } - return BackupUiState.Ready(exportable = exportable, canImport = canImport) + return BackupUiState.Ready( + exportable = exportable, + canImport = canImport, + canCopy = exportable.any { copyTargets(calendars, it.id).isNotEmpty() }, + ) } + +/** Calendars a copy can read from: any a backup can (#325), synced and read-only ones included. */ +fun copySources(calendars: List): List = + calendars.filter { it.isBackupCandidate } + +/** Calendars a copy from [sourceId] can write into: the import targets, minus the source itself. */ +fun copyTargets(calendars: List, sourceId: Long?): List = + calendars.filter { it.isEventTarget && it.id != sourceId } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt new file mode 100644 index 00000000..a7fbcb25 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt @@ -0,0 +1,221 @@ +package de.jeanlucmakiola.calendula.ui.calendars + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.Button +import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi +import androidx.compose.material3.LinearWavyProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary +import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip +import de.jeanlucmakiola.calendula.ui.common.CalendarPickerGroups +import de.jeanlucmakiola.calendula.ui.common.orUnnamed +import de.jeanlucmakiola.floret.components.FullScreenPicker +import de.jeanlucmakiola.floret.components.GroupedHint +import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.Position + +/** + * Copy every event of one calendar into another (#325): pick the source and the + * target, copy, watch it run. The run lives in [CopyEventsViewModel], so this + * sheet can be closed and reopened mid-copy. + */ +@Composable +fun CopyEventsSheet( + calendars: List, + selection: CopySelection, + run: CopyRunState, + onSelectSource: (Long) -> Unit, + onSelectTarget: (Long) -> Unit, + onStart: () -> Unit, + onCancel: () -> Unit, + onDismiss: () -> Unit, +) { + val sources = copySources(calendars) + val source = sources.firstOrNull { it.id == selection.sourceId } + val targets = copyTargets(calendars, source?.id) + val target = targets.firstOrNull { it.id == selection.targetId } + val running = run is CopyRunState.Running + var picking by rememberSaveable { mutableStateOf(null) } + + FullScreenPicker( + title = stringResource(R.string.calendars_copy_action), + onDismiss = onDismiss, + predictiveBack = true, + ) { + GroupedHint(stringResource(R.string.calendars_copy_hint), style = MaterialTheme.typography.bodySmall) + CopyEndRow( + label = stringResource(R.string.calendars_copy_from), + calendar = source, + position = Position.Top, + onClick = if (running) null else ({ picking = CopyEnd.Source }), + ) + CopyEndRow( + label = stringResource(R.string.calendars_copy_to), + calendar = target, + position = Position.Bottom, + onClick = if (running || source == null) null else ({ picking = CopyEnd.Target }), + ) + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 16.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + when (run) { + is CopyRunState.Running -> CopyProgress(run, onCancel) + is CopyRunState.Done -> CopySummary(run.summary) + CopyRunState.Cancelled -> CopyNote(stringResource(R.string.calendars_copy_cancelled)) + CopyRunState.Failed -> CopyNote( + stringResource(R.string.calendars_copy_failed), + error = true, + ) + CopyRunState.Idle -> Unit + } + if (!running) { + Button( + onClick = onStart, + enabled = source != null && target != null, + modifier = Modifier.fillMaxWidth(), + ) { + Text(stringResource(R.string.calendars_copy_start)) + } + } + } + } + + when (picking) { + CopyEnd.Source -> FullScreenPicker( + title = stringResource(R.string.calendars_copy_from_title), + onDismiss = { picking = null }, + predictiveBack = true, + ) { + CalendarPickerGroups( + calendars = sources, + selectedId = source?.id, + onSelect = { + onSelectSource(it) + picking = null + }, + ) + } + CopyEnd.Target -> FullScreenPicker( + title = stringResource(R.string.calendars_copy_to_title), + onDismiss = { picking = null }, + predictiveBack = true, + ) { + CalendarPickerGroups( + calendars = targets, + selectedId = target?.id, + onSelect = { + onSelectTarget(it) + picking = null + }, + ) + } + null -> Unit + } +} + +private enum class CopyEnd { Source, Target } + +@Composable +private fun CopyEndRow( + label: String, + calendar: CalendarSource?, + position: Position, + onClick: (() -> Unit)?, +) { + GroupedRow( + title = label, + summary = calendar?.displayName?.orUnnamed() ?: stringResource(R.string.calendars_copy_choose), + position = position, + dimmed = onClick == null, + leading = calendar?.let { { CalendarColorChip(it.color) } }, + onClick = onClick, + ) +} + +@OptIn(ExperimentalMaterial3ExpressiveApi::class) +@Composable +private fun CopyProgress(run: CopyRunState.Running, onCancel: () -> Unit) { + val total = run.total + if (total == null || total == 0) { + LinearWavyProgressIndicator(modifier = Modifier.fillMaxWidth()) + } else { + LinearWavyProgressIndicator( + progress = { run.done.toFloat() / total }, + modifier = Modifier.fillMaxWidth(), + ) + } + Text( + text = copyProgressText(run), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + OutlinedButton(onClick = onCancel, modifier = Modifier.fillMaxWidth()) { + Text(stringResource(R.string.dialog_cancel)) + } +} + +/** "Reading events…" until the source is read, then "120 of 2,400 events". */ +@Composable +fun copyProgressText(run: CopyRunState.Running): String { + val total = run.total ?: return stringResource(R.string.calendars_copy_reading) + return pluralStringResource(R.plurals.calendars_copy_progress, total, run.done, total) +} + +@Composable +private fun CopySummary(summary: IcsImportSummary) { + Text( + stringResource(R.string.calendars_copy_done), + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.onSurface, + ) + Row(horizontalArrangement = Arrangement.spacedBy(24.dp)) { + CopyCount(stringResource(R.string.import_done_added_label), summary.imported) + CopyCount(stringResource(R.string.import_done_skipped_label), summary.skippedDuplicate) + if (summary.failed > 0) CopyCount(stringResource(R.string.import_done_failed_label), summary.failed) + } + if (summary.skippedDuplicate > 0) CopyNote(stringResource(R.string.import_done_dedup_note)) + if (summary.failed > 0) CopyNote(stringResource(R.string.import_done_failed_note)) + if (summary.notAttempted > 0) { + CopyNote( + pluralStringResource(R.plurals.calendars_copy_stopped, summary.notAttempted, summary.notAttempted), + error = true, + ) + } +} + +@Composable +private fun CopyCount(label: String, count: Int) { + Column { + Text(count.toString(), style = MaterialTheme.typography.headlineSmall, color = MaterialTheme.colorScheme.onSurface) + Text(label, style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.onSurfaceVariant) + } +} + +@Composable +private fun CopyNote(text: String, error: Boolean = false) { + Text( + text, + style = MaterialTheme.typography.bodyMedium, + color = if (error) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, + ) +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt new file mode 100644 index 00000000..97fb06d2 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt @@ -0,0 +1,105 @@ +package de.jeanlucmakiola.calendula.ui.calendars + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import dagger.hilt.android.lifecycle.HiltViewModel +import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository +import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary +import de.jeanlucmakiola.floret.android.stateWhileSubscribed +import de.jeanlucmakiola.floret.di.IoDispatcher +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.catch +import kotlinx.coroutines.flow.flowOn +import kotlinx.coroutines.launch +import kotlin.coroutines.cancellation.CancellationException +import javax.inject.Inject + +/** + * Copy events from one calendar into another (#325). Lives as long as the + * activity, so a long copy keeps running across rotation and when the Backup + * screen is closed; [cancel] stops it between events. + */ +@HiltViewModel +class CopyEventsViewModel @Inject constructor( + private val repository: CalendarRepository, + @IoDispatcher io: CoroutineDispatcher, +) : ViewModel() { + + val calendars: StateFlow> = + repository.calendars() + .catch { emit(emptyList()) } + .flowOn(io) + .stateWhileSubscribed(scope = viewModelScope, initialValue = emptyList()) + + private val _selection = MutableStateFlow(CopySelection()) + val selection: StateFlow = _selection.asStateFlow() + + private val _run = MutableStateFlow(CopyRunState.Idle) + val run: StateFlow = _run.asStateFlow() + + private var job: Job? = null + + fun setSource(id: Long) { + if (job?.isActive == true) return + _selection.value = _selection.value.withSource(id) + clearFinished() + } + + fun setTarget(id: Long) { + if (job?.isActive == true) return + _selection.value = _selection.value.copy(targetId = id) + clearFinished() + } + + fun start() { + val source = _selection.value.sourceId ?: return + val target = _selection.value.targetId ?: return + if (job?.isActive == true) return + _run.value = CopyRunState.Running(done = 0, total = null) + job = viewModelScope.launch { + try { + val summary = repository.copyEvents(source, target) { done, total -> + _run.value = CopyRunState.Running(done, total) + } + _run.value = CopyRunState.Done(summary) + } catch (e: CancellationException) { + _run.value = CopyRunState.Cancelled + throw e + } catch (e: Exception) { + _run.value = CopyRunState.Failed + } + } + } + + fun cancel() { + job?.cancel() + } + + /** Back to idle once a finished run's outcome has been seen. */ + fun clearFinished() { + if (job?.isActive != true) _run.value = CopyRunState.Idle + } +} + +/** The calendars a copy runs between. */ +data class CopySelection(val sourceId: Long? = null, val targetId: Long? = null) { + /** A target equal to the new source is dropped: a calendar is never copied into itself. */ + fun withSource(id: Long): CopySelection = + CopySelection(sourceId = id, targetId = targetId?.takeIf { it != id }) +} + +sealed interface CopyRunState { + data object Idle : CopyRunState + + /** [total] is null while the source calendar is still being read. */ + data class Running(val done: Int, val total: Int?) : CopyRunState + + data class Done(val summary: IcsImportSummary) : CopyRunState + data object Cancelled : CopyRunState + data object Failed : CopyRunState +} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index eac1f5a3..4a55e627 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -889,6 +889,27 @@ Restore from .ics file Import events from a backup or another calendar app. No calendar can take the imported events yet. + Copy events + Copy one calendar\'s events into another, for example to move off Google. + Copies every event, including repeating ones with the occurrences you changed or deleted. Guests and invitations stay behind, and the original calendar is left as it is. + From + To + Choose a calendar + Copy from + Copy into + Copy + Reading events… + + %1$d of %2$d event + %1$d of %2$d events + + Copy complete + Copy cancelled. Run it again to finish: events that were already copied are skipped. + Couldn\'t copy the events. + + The target calendar stopped accepting events part way through. %d event was never copied. + The target calendar stopped accepting events part way through. %d events were never copied. + Automatic backup Periodically export your calendars to a folder as .ics files. Backup folder diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt index 119cfc65..eff60c52 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt @@ -961,6 +961,42 @@ class CalendarRepositoryImplTest { assertThat(fake.lastCalendarEventsIds).containsExactly(2L) } + @Test + fun `copyEvents reports progress and skips what an earlier run copied`( + @TempDir tempDir: Path, + ) = runTest { + fun icsEvent(uid: String) = de.jeanlucmakiola.calendula.domain.ics.IcsEvent( + uid = uid, + summary = uid, + start = Instant.fromEpochMilliseconds(1_000_000_000L), + end = Instant.fromEpochMilliseconds(1_000_003_600L), + isAllDay = false, + zoneId = "UTC", + ) + val fake = FakeCalendarDataSource().apply { + existingUidsResult = setOf("a") + calendarCopyRowsResult = de.jeanlucmakiola.calendula.domain.ics.CalendarCopyRows( + series = listOf( + de.jeanlucmakiola.calendula.domain.ics.CopySeries(1, null, icsEvent("a")), + de.jeanlucmakiola.calendula.domain.ics.CopySeries(2, null, icsEvent("b")), + ), + exceptions = emptyList(), + ) + } + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) + val progress = mutableListOf>() + + val summary = repo.copyEvents(sourceCalendarId = 1L, targetCalendarId = 3L) { done, total -> + progress += done to total + } + + assertThat(summary.imported).isEqualTo(1) + assertThat(summary.skippedDuplicate).isEqualTo(1) + assertThat(fake.importedEvents.map { it.first.uid to it.second }).containsExactly("b" to 3L) + assertThat(progress.first()).isEqualTo(0 to 2) + assertThat(progress.last()).isEqualTo(2 to 2) + } + private fun parsedEvent(uid: String?, summary: String = "E") = de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent( uid = uid, diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/FakeCalendarDataSource.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/FakeCalendarDataSource.kt index 3921fca1..5ba0bf12 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/FakeCalendarDataSource.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/FakeCalendarDataSource.kt @@ -8,6 +8,7 @@ import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.domain.SearchCandidate import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType +import de.jeanlucmakiola.calendula.domain.ics.CalendarCopyRows import de.jeanlucmakiola.calendula.domain.ics.IcsEvent import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent import java.time.ZoneId @@ -89,6 +90,11 @@ internal class FakeCalendarDataSource : CalendarDataSource { return calendarEventsResult } + var calendarCopyRowsResult: CalendarCopyRows = CalendarCopyRows(emptyList(), emptyList()) + + override fun calendarCopyRows(calendarId: Long, allDayReminderTimeMinutes: Int): CalendarCopyRows = + calendarCopyRowsResult + override fun existingUids(calendarId: Long): Set = existingUidsResult /** (event, targetCalendarId) pairs passed to [insertImportedEvent]. */ diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopyTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopyTest.kt new file mode 100644 index 00000000..c1036b10 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopyTest.kt @@ -0,0 +1,150 @@ +package de.jeanlucmakiola.calendula.domain.ics + +import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.domain.EventStatus +import org.junit.jupiter.api.Test +import kotlin.time.Instant + +/** What a calendar copy (#325) inserts for a source calendar's rows. */ +class CalendarCopyTest { + + private val start = Instant.parse("2026-01-05T09:00:00Z") + private val week = 7 * 24 * 3_600_000L + + private fun event( + uid: String, + rrule: String? = null, + allDay: Boolean = false, + at: Instant = start, + status: EventStatus = EventStatus.Confirmed, + exDates: List = emptyList(), + reminders: List = emptyList(), + ) = IcsEvent( + uid = uid, + summary = uid, + start = at, + end = Instant.fromEpochMilliseconds(at.toEpochMilliseconds() + 3_600_000L), + isAllDay = allDay, + zoneId = "Europe/Berlin", + recurrenceRule = rrule, + exDates = exDates, + reminderMinutes = reminders, + status = status, + ) + + private fun occurrence(n: Int) = Instant.fromEpochMilliseconds(start.toEpochMilliseconds() + n * week) + + @Test + fun `a plain event copies as itself, keeping its zone and colour`() { + val plan = planCalendarCopy( + CalendarCopyRows( + series = listOf(CopySeries(1, null, event("a", reminders = listOf(10, -5, 10)), color = 0xFF112233.toInt())), + exceptions = emptyList(), + ), + ) + + val copied = plan.single() + assertThat(copied.uid).isEqualTo("a") + assertThat(copied.zoneId).isEqualTo("Europe/Berlin") + assertThat(copied.color).isEqualTo(0xFF112233.toInt()) + assertThat(copied.reminderMinutes).containsExactly(10) + } + + @Test + fun `a cancelled occurrence becomes an EXDATE on the series`() { + val plan = planCalendarCopy( + CalendarCopyRows( + series = listOf(CopySeries(1, "sync-1", event("s", rrule = "FREQ=WEEKLY", exDates = listOf("20260112T080000Z")))), + exceptions = listOf( + CopyException( + originalId = null, + originalSyncId = "sync-1", + originalInstance = occurrence(2), + event = event("s", at = occurrence(2), status = EventStatus.Cancelled), + ), + ), + ), + ) + + val series = plan.single() + assertThat(series.exDates).containsExactly("20260112T080000Z", "20260119T090000Z").inOrder() + } + + @Test + fun `a modified occurrence is excluded from the series and copied on its own, first`() { + val moved = Instant.fromEpochMilliseconds(occurrence(1).toEpochMilliseconds() + 3_600_000L) + val plan = planCalendarCopy( + CalendarCopyRows( + series = listOf(CopySeries(1, null, event("s", rrule = "FREQ=WEEKLY"))), + exceptions = listOf( + CopyException( + originalId = 1, + originalSyncId = null, + originalInstance = occurrence(1), + event = event("s", rrule = "FREQ=WEEKLY", at = moved), + ), + ), + ), + ) + + assertThat(plan).hasSize(2) + val detached = plan[0] + assertThat(detached.uid).isEqualTo("${occurrence(1).toEpochMilliseconds()}-s") + assertThat(detached.recurrenceRule).isNull() + assertThat(detached.start).isEqualTo(moved) + assertThat(plan[1].exDates).containsExactly("20260112T090000Z") + } + + @Test + fun `an all-day series excludes the occurrence by its day`() { + val day = Instant.parse("2026-01-05T00:00:00Z") + val plan = planCalendarCopy( + CalendarCopyRows( + series = listOf(CopySeries(1, null, event("s", rrule = "FREQ=DAILY", allDay = true, at = day))), + exceptions = listOf( + CopyException( + originalId = 1, + originalSyncId = null, + originalInstance = Instant.parse("2026-01-07T00:00:00Z"), + event = event("s", allDay = true, status = EventStatus.Cancelled), + ), + ), + ), + ) + + assertThat(plan.single().exDates).containsExactly("20260107") + } + + @Test + fun `an orphaned modified occurrence still copies, an orphaned cancellation does not`() { + val plan = planCalendarCopy( + CalendarCopyRows( + series = emptyList(), + exceptions = listOf( + CopyException(5, null, occurrence(1), event("x")), + CopyException(5, null, occurrence(2), event("y", status = EventStatus.Cancelled)), + ), + ), + ) + + assertThat(plan.map { it.summary }).containsExactly("x") + } + + @Test + fun `the plan is stable, so a re-run dedups every event`() { + val rows = CalendarCopyRows( + series = listOf(CopySeries(1, null, event("s", rrule = "FREQ=WEEKLY"))), + exceptions = listOf(CopyException(1, null, occurrence(1), event("s"))), + ) + + assertThat(planCalendarCopy(rows).map { it.uid }).isEqualTo(planCalendarCopy(rows).map { it.uid }) + } + + @Test + fun `a zero-length all-day event lasts its day`() { + val day = Instant.parse("2026-01-05T00:00:00Z") + val parsed = event("a", allDay = true, at = day).copy(end = day).toParsedIcsEvent() + + assertThat(parsed.end).isEqualTo(Instant.parse("2026-01-06T00:00:00Z")) + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiStateTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiStateTest.kt index 196125ca..99106a76 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiStateTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiStateTest.kt @@ -97,4 +97,40 @@ class BackupUiStateTest { assertThat(state.exportable.map { it.id }).containsExactly(1L, 2L) assertThat(state.canImport).isTrue() } + + @Test + fun `a read-only calendar can be copied into a writable one`() { + val readOnly = cal(1, writable = false) + val local = cal(2, local = true) + + val state = ready(backupUiState(listOf(readOnly, local))) + + assertThat(state.canCopy).isTrue() + assertThat(copySources(listOf(readOnly, local)).map { it.id }).containsExactly(1L, 2L) + assertThat(copyTargets(listOf(readOnly, local), 1L).map { it.id }).containsExactly(2L) + } + + @Test + fun `a single writable calendar has nothing to copy into`() { + val only = cal(1, local = true) + + assertThat(ready(backupUiState(listOf(only))).canCopy).isFalse() + assertThat(copyTargets(listOf(only), 1L)).isEmpty() + } + + @Test + fun `a copy never targets a managed or switched-off calendar`() { + val source = cal(1) + val calendars = listOf(source, cal(2, managed = true), cal(3, visible = false)) + + assertThat(copyTargets(calendars, source.id)).isEmpty() + } + + @Test + fun `choosing the target as source drops it`() { + assertThat(CopySelection(sourceId = 1, targetId = 2).withSource(2)) + .isEqualTo(CopySelection(sourceId = 2, targetId = null)) + assertThat(CopySelection(sourceId = 1, targetId = 2).withSource(3)) + .isEqualTo(CopySelection(sourceId = 3, targetId = 2)) + } } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 5214f44b..9a11451d 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -495,6 +495,20 @@ on whether an all-day exclusion is `yyyyMMdd` or a padded midnight stamp, so `exportExDates` drops the time part on the way out. Without this, an in-app backup→restore resurrected every occurrence the user had deleted. +**Copying a calendar reads its exceptions too.** Backup & restore → Copy events +(#325) reads every row of the source through `calendarCopyRows` — masters, +one-offs *and* the exception rows the backup query leaves out — and +`planCalendarCopy` turns them into the `ParsedIcsEvent`s that the normal +`importEvents` inserts, so the UID dedup makes a re-run skip what landed before. +The copy has no `_sync_id`, and an exception row only attaches through one, so +overrides are written the way Calendula writes "only this event" on such a +series: each exception adds its occurrence to the series' `EXDATE`, and a +modified one becomes a standalone event with a UID derived from the series UID +and the occurrence. The rows skip the `.ics` text: the writer pins a timed +one-off to UTC and carries no colour, the direct mapping keeps both. Attendees +and organizer are never read. The backup keeps excluding exceptions; a restore +could not place a `RECURRENCE-ID` either. + That re-encode is sampled where the reminder will actually *fire*, not at `DTSTART` (`importedAllDayReminderDate`). An imported series' `DTSTART` is only an anchor and is routinely ancient — Fossify writes a year-less contact birthday at From 46882d154ea550b5fd250b89cbe7bd857b44b4ed Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 17:16:13 +0100 Subject: [PATCH 02/16] fix(#325): review round 1 - visibility and RDATE copied, cancel only stops a copy, sources need a target --- .../data/calendar/CalendarDataSource.kt | 9 ++-- .../data/calendar/CalendarRepository.kt | 4 +- .../data/calendar/CalendarRepositoryImpl.kt | 14 +++-- .../data/calendar/EventWriteMapper.kt | 10 ++-- .../data/calendar/IcsExportMapper.kt | 6 ++- .../calendula/data/calendar/Projections.kt | 6 ++- .../calendula/domain/ics/CalendarCopy.kt | 42 ++++++++------- .../calendula/domain/ics/IcsEvent.kt | 9 ++++ .../calendula/domain/ics/IcsParser.kt | 4 ++ .../calendula/ui/calendars/BackupScreen.kt | 9 +++- .../calendula/ui/calendars/BackupUiState.kt | 14 +++-- .../calendula/ui/calendars/CopyEventsSheet.kt | 6 +-- .../ui/calendars/CopyEventsViewModel.kt | 54 +++++++++++++------ .../data/calendar/ImportedEventValuesTest.kt | 18 +++++++ .../calendula/domain/ics/CalendarCopyTest.kt | 39 +++++++++++++- .../ui/calendars/BackupUiStateTest.kt | 10 +++- docs/ARCHITECTURE.md | 6 ++- 17 files changed, 200 insertions(+), 60 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt index 870e53ba..85147d3f 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt @@ -867,10 +867,11 @@ class AndroidCalendarDataSource @Inject constructor( null, CalendarContract.Events.DTSTART + " ASC", )?.use { c -> - c.mapRows { - val eventId = getLong(EventExportProjection.IDX_ID) - row { calendarName -> - toIcsEvent( + val reader = CursorColumnReader(c) + while (c.moveToNext()) { + val eventId = reader.getLong(EventExportProjection.IDX_ID) + reader.row { calendarName -> + reader.toIcsEvent( reminderMinutes = reminders[eventId].orEmpty(), calendarName = calendarName, allDayReminderTimeMinutes = allDayReminderTimeMinutes, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt index fa950bd3..47a1fd52 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt @@ -71,8 +71,8 @@ interface CalendarRepository { * Bulk-import parsed `.ics` [events] into [targetCalendarId]. Events whose * UID already exists in the target are skipped (idempotent restore); the * rest are inserted. See [CalendarDataSource.insertImportedEvent]. - * [onProgress] gets the count of events handled so far after each one; a - * cancelled caller stops the import between events. + * [onProgress] gets the count of events handled so far after each one, and + * may throw to stop the import between events. */ suspend fun importEvents( targetCalendarId: Long, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt index e4c6bea4..367046f7 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt @@ -259,10 +259,19 @@ class CalendarRepositoryImpl @Inject constructor( onProgress: (done: Int, total: Int) -> Unit, ): IcsImportSummary { val events = withContext(io) { - planCalendarCopy(dataSource.calendarCopyRows(sourceCalendarId, allDayReminderTimeMinutes())) + planCalendarCopy( + dataSource.calendarCopyRows(sourceCalendarId, allDayReminderTimeMinutes()), + ::formatExdateStamp, + ) } onProgress(0, events.size) - return importEvents(targetCalendarId, events) { done -> onProgress(done, events.size) } + // Checked between events, so cancelling stops the copy; a plain import + // keeps running to the end of its file. + val context = currentCoroutineContext() + return importEvents(targetCalendarId, events) { done -> + context.ensureActive() + onProgress(done, events.size) + } } override suspend fun importEvents( @@ -282,7 +291,6 @@ class CalendarRepositoryImpl @Inject constructor( var failed = 0 var notAttempted = 0 for ((index, event) in events.withIndex()) { - currentCoroutineContext().ensureActive() if (index > 0) onProgress(index) // A known UID means the event is already in this calendar — skip, // keeping a restore idempotent (no overwrite this pass). diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapper.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapper.kt index 1317e9c6..3a093585 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapper.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapper.kt @@ -684,7 +684,7 @@ private const val TZID_PREFIX = "TZID=" * are UTC: the provider stores an all-day DTSTART at UTC midnight, so its date * reads off the UTC calendar day. */ -private fun formatExdateStamp(occurrenceMillis: Long, isAllDay: Boolean): String = +internal fun formatExdateStamp(occurrenceMillis: Long, isAllDay: Boolean): String = formatExdateStamp( local = Instant.ofEpochMilli(occurrenceMillis).atZone(ZoneOffset.UTC).toLocalDateTime(), isAllDay = isAllDay, @@ -851,10 +851,11 @@ internal fun buildImportedEventValues( put(CalendarContract.Events.TITLE, event.summary.trim()) put(CalendarContract.Events.ALL_DAY, if (event.isAllDay) 1 else 0) put(CalendarContract.Events.DTSTART, startMillis) - if (event.recurrenceRule == null) { + if (event.recurrenceRule == null && event.recurrenceDates == null) { put(CalendarContract.Events.DTEND, endMillis) } else { - put(CalendarContract.Events.RRULE, event.recurrenceRule) + event.recurrenceRule?.let { put(CalendarContract.Events.RRULE, it) } + event.recurrenceDates?.let { put(CalendarContract.Events.RDATE, it) } put( CalendarContract.Events.DURATION, importDuration(startMillis, endMillis, event.isAllDay), @@ -866,6 +867,9 @@ internal fun buildImportedEventValues( // timed rows keep the event's own zone. put(CalendarContract.Events.EVENT_TIMEZONE, if (event.isAllDay) "UTC" else event.zoneId) put(CalendarContract.Events.AVAILABILITY, event.availability.toProviderValue()) + if (event.accessLevel != AccessLevel.Default) { + put(CalendarContract.Events.ACCESS_LEVEL, event.accessLevel.toProviderValue()) + } put(CalendarContract.Events.STATUS, event.status.forNewEvent().toProviderStatus()) event.location?.trim()?.takeIf { it.isNotEmpty() } ?.let { put(CalendarContract.Events.EVENT_LOCATION, it) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapper.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapper.kt index 1657e5b4..311ce964 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapper.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapper.kt @@ -1,6 +1,7 @@ package de.jeanlucmakiola.calendula.data.calendar import de.jeanlucmakiola.floret.time.toKotlinInstantFromEpochMillis +import de.jeanlucmakiola.calendula.domain.AccessLevel import de.jeanlucmakiola.calendula.domain.ics.IcsEvent import de.jeanlucmakiola.calendula.domain.ics.deriveIcsUid import java.time.ZoneId @@ -27,6 +28,7 @@ internal fun ColumnReader.toIcsEvent( val eventId = getLong(EventExportProjection.IDX_ID) val dtStart = getLong(EventExportProjection.IDX_DTSTART) val rrule = getString(EventExportProjection.IDX_RRULE)?.takeIf { it.isNotBlank() } + val rdate = getString(EventExportProjection.IDX_RDATE)?.takeIf { it.isNotBlank() } val isAllDay = getInt(EventExportProjection.IDX_ALL_DAY) != 0 // Unclamped: the writer renders DTEND as stored. @@ -41,7 +43,7 @@ internal fun ColumnReader.toIcsEvent( zoneId = getString(EventExportProjection.IDX_EVENT_TIMEZONE)?.takeIf { it.isNotBlank() } ?: "UTC", recurrenceRule = rrule, - exDates = if (rrule == null) { + exDates = if (rrule == null && rdate == null) { emptyList() } else { exportExDates( @@ -63,6 +65,8 @@ internal fun ColumnReader.toIcsEvent( status = eventStatus(EventExportProjection.IDX_STATUS), availability = mapAvailability(getInt(EventExportProjection.IDX_AVAILABILITY)), calendarName = calendarName, + recurrenceDates = rdate, + accessLevel = getIntOrNull(EventExportProjection.IDX_ACCESS_LEVEL)?.let(::mapAccessLevel) ?: AccessLevel.Default, ) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/Projections.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/Projections.kt index 37f4bd7e..a312bcf5 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/Projections.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/Projections.kt @@ -161,7 +161,7 @@ internal object EventDetailProjection { * documented v1 limit (import skips them too). EXDATE is unaffected by that * filter: it lives on the master row, not on an exception of its own. A * calendar copy (#325) reads the exception rows too, through the trailing - * colour and series-link columns. + * colour, series-link, RDATE and access-level columns. */ internal object EventExportProjection { val COLUMNS: Array = arrayOf( @@ -185,6 +185,8 @@ internal object EventExportProjection { CalendarContract.Events.ORIGINAL_ID, CalendarContract.Events.ORIGINAL_SYNC_ID, CalendarContract.Events.ORIGINAL_INSTANCE_TIME, + CalendarContract.Events.RDATE, + CalendarContract.Events.ACCESS_LEVEL, ) const val IDX_ID = 0 @@ -207,6 +209,8 @@ internal object EventExportProjection { const val IDX_ORIGINAL_ID = 17 const val IDX_ORIGINAL_SYNC_ID = 18 const val IDX_ORIGINAL_INSTANCE_TIME = 19 + const val IDX_RDATE = 20 + const val IDX_ACCESS_LEVEL = 21 } /** diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt index bc8facd4..2aa89741 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt @@ -1,8 +1,6 @@ package de.jeanlucmakiola.calendula.domain.ics import de.jeanlucmakiola.calendula.domain.EventStatus -import kotlinx.datetime.TimeZone -import kotlinx.datetime.toLocalDateTime import kotlin.time.Duration.Companion.days import kotlin.time.Instant @@ -52,24 +50,34 @@ data class CalendarCopyRows( * any other event. * * Standalone occurrences come first: a run cut short then leaves at worst an - * occurrence missing its series, never a series missing an occurrence. - * Attendees and organizer are not part of either input; the copy is the - * user's own event. + * occurrence missing its series, never a series missing an occurrence. A UID + * that comes up twice is planned once, as a re-run would dedup it anyway. + * Attendees and organizer are not part of either input. + * + * Idempotent per snapshot only: a series already in the target is skipped + * whole, so an occurrence changed in the source after an earlier run arrives + * as a standalone event next to the copied series' original one. + * + * [exdateStamp] formats an occurrence as an `EXDATE` entry in the provider's + * shape, the same one Calendula's own exclusions use. */ -fun planCalendarCopy(rows: CalendarCopyRows): List { +fun planCalendarCopy( + rows: CalendarCopyRows, + exdateStamp: (occurrenceMillis: Long, isAllDay: Boolean) -> String, +): List { val (series, exceptions) = rows val byId = series.associateBy { it.eventId } - val bySyncId = series.filter { !it.syncId.isNullOrEmpty() }.associateBy { it.syncId } + val bySyncId = series.filter { it.syncId != null }.associateBy { it.syncId } val excluded = mutableMapOf>() val detached = mutableListOf() for (exception in exceptions) { val parent = exception.originalId?.let(byId::get) - ?: exception.originalSyncId?.takeIf { it.isNotEmpty() }?.let(bySyncId::get) + ?: exception.originalSyncId?.let(bySyncId::get) if (parent != null) { // An exception to a one-off overrides nothing a copy could carry. - if (parent.event.recurrenceRule.isNullOrBlank()) continue + if (!parent.event.recurs) continue excluded.getOrPut(parent.eventId) { mutableListOf() } += - exdateStamp(exception.originalInstance, parent.event.isAllDay) + exdateStamp(exception.originalInstance.toEpochMilliseconds(), parent.event.isAllDay) } if (exception.isCancelled) continue val baseUid = parent?.event?.uid ?: exception.event.uid @@ -77,15 +85,15 @@ fun planCalendarCopy(rows: CalendarCopyRows): List { .copy( uid = "${exception.originalInstance.toEpochMilliseconds()}-$baseUid", recurrenceRule = null, - exDates = emptyList(), + recurrenceDates = null, ) .toParsedIcsEvent(exception.color) } - return detached + series.map { s -> + return (detached + series.map { s -> val extra = excluded[s.eventId].orEmpty() val event = if (extra.isEmpty()) s.event else s.event.copy(exDates = (s.event.exDates + extra).distinct()) event.toParsedIcsEvent(s.color) - } + }).distinctBy { it.uid } } /** @@ -104,16 +112,14 @@ fun IcsEvent.toParsedIcsEvent(color: Int? = null): ParsedIcsEvent = ParsedIcsEve isAllDay = isAllDay, zoneId = zoneId, recurrenceRule = recurrenceRule?.takeIf { it.isNotBlank() }?.removePrefix("RRULE:"), + recurrenceDates = recurrenceDates?.takeIf { it.isNotBlank() }, location = location, description = description, // The writer emits only lead times; a negative one would be an alarm after the start. reminderMinutes = reminderMinutes.filter { it >= 0 }.distinct(), status = status, availability = availability, + accessLevel = accessLevel, color = color, - exDates = if (recurrenceRule.isNullOrBlank()) emptyList() else exDates.filter { it.isNotBlank() }.distinct(), + exDates = if (recurs) exDates.filter { it.isNotBlank() }.distinct() else emptyList(), ) - -/** An occurrence as an `EXDATE` entry in the provider's shape: the UTC day for an all-day series, else a UTC stamp. */ -internal fun exdateStamp(occurrence: Instant, isAllDay: Boolean): String = - if (isAllDay) occurrence.toLocalDateTime(TimeZone.UTC).date.toBasic() else occurrence.toUtcBasic() diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsEvent.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsEvent.kt index 19da17bb..d3ab50ad 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsEvent.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsEvent.kt @@ -1,5 +1,6 @@ package de.jeanlucmakiola.calendula.domain.ics +import de.jeanlucmakiola.calendula.domain.AccessLevel import de.jeanlucmakiola.calendula.domain.Availability import de.jeanlucmakiola.calendula.domain.EventStatus import kotlin.time.Instant @@ -36,8 +37,16 @@ data class IcsEvent( val availability: Availability = Availability.Busy, /** Source calendar name, emitted as `X-CALENDULA-CALENDAR` so a combined backup can fan back out. */ val calendarName: String? = null, + /** The provider's raw `RDATE`; carried by a calendar copy, not written to a file. */ + val recurrenceDates: String? = null, + /** Carried by a calendar copy, not written to a file. */ + val accessLevel: AccessLevel = AccessLevel.Default, ) +/** Whether this is a series: by rule, or by listed dates alone. */ +val IcsEvent.recurs: Boolean + get() = !recurrenceRule.isNullOrBlank() || !recurrenceDates.isNullOrBlank() + /** * The UID to export for a provider event. A row that already carries a UID * (`Events.UID_2445`) keeps it; otherwise we synthesise a **stable** one from diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsParser.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsParser.kt index 75d40206..6ce1c19e 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsParser.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsParser.kt @@ -1,5 +1,6 @@ package de.jeanlucmakiola.calendula.domain.ics +import de.jeanlucmakiola.calendula.domain.AccessLevel import de.jeanlucmakiola.calendula.domain.Availability import de.jeanlucmakiola.calendula.domain.EventStatus import de.jeanlucmakiola.calendula.domain.zoneOrNull @@ -45,6 +46,9 @@ data class ParsedIcsEvent( val exDates: List = emptyList(), /** True when this came from a `VTODO` rather than a `VEVENT`. */ val isTask: Boolean = false, + /** The provider's raw `RDATE`, only set by a calendar copy. */ + val recurrenceDates: String? = null, + val accessLevel: AccessLevel = AccessLevel.Default, ) /** diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt index a0feb927..62413fc1 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt @@ -326,8 +326,13 @@ private fun BackupContent( if (canCopy) { GroupedRow( title = stringResource(R.string.calendars_copy_action), - summary = (copyRun as? CopyRunState.Running)?.let { copyProgressText(it) } - ?: stringResource(R.string.calendars_copy_summary), + summary = when (copyRun) { + is CopyRunState.Running -> copyProgressText(copyRun) + is CopyRunState.Done -> stringResource(R.string.calendars_copy_done) + CopyRunState.Cancelled -> stringResource(R.string.calendars_copy_cancelled) + CopyRunState.Failed -> stringResource(R.string.calendars_copy_failed) + CopyRunState.Idle -> stringResource(R.string.calendars_copy_summary) + }, position = Position.Middle, leading = { LeadingAvatar(Icons.Default.ContentCopy) }, onClick = onCopy, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiState.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiState.kt index c4de4824..f34c1619 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiState.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiState.kt @@ -55,13 +55,19 @@ fun backupUiState(calendars: List): BackupUiState { return BackupUiState.Ready( exportable = exportable, canImport = canImport, - canCopy = exportable.any { copyTargets(calendars, it.id).isNotEmpty() }, + canCopy = copySources(calendars).isNotEmpty(), ) } -/** Calendars a copy can read from: any a backup can (#325), synced and read-only ones included. */ -fun copySources(calendars: List): List = - calendars.filter { it.isBackupCandidate } +/** + * Calendars a copy can read from: any a backup can (#325), synced and read-only + * ones included, as long as some other calendar can take their events. + */ +fun copySources(calendars: List): List { + val targets = calendars.filter { it.isEventTarget } + if (targets.isEmpty()) return emptyList() + return calendars.filter { source -> source.isBackupCandidate && targets.any { it.id != source.id } } +} /** Calendars a copy from [sourceId] can write into: the import targets, minus the source itself. */ fun copyTargets(calendars: List, sourceId: Long?): List = diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt index a7fbcb25..e452009a 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt @@ -38,7 +38,7 @@ import de.jeanlucmakiola.floret.components.Position */ @Composable fun CopyEventsSheet( - calendars: List, + calendars: List?, selection: CopySelection, run: CopyRunState, onSelectSource: (Long) -> Unit, @@ -47,9 +47,9 @@ fun CopyEventsSheet( onCancel: () -> Unit, onDismiss: () -> Unit, ) { - val sources = copySources(calendars) + val sources = calendars?.let(::copySources).orEmpty() val source = sources.firstOrNull { it.id == selection.sourceId } - val targets = copyTargets(calendars, source?.id) + val targets = calendars?.let { copyTargets(it, source?.id) }.orEmpty() val target = targets.firstOrNull { it.id == selection.targetId } val running = run is CopyRunState.Running var picking by rememberSaveable { mutableStateOf(null) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt index 97fb06d2..cd84b87a 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt @@ -1,5 +1,6 @@ package de.jeanlucmakiola.calendula.ui.calendars +import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel @@ -13,53 +14,71 @@ import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.catch +import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.flowOn +import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlin.coroutines.cancellation.CancellationException import javax.inject.Inject /** - * Copy events from one calendar into another (#325). Lives as long as the - * activity, so a long copy keeps running across rotation and when the Backup - * screen is closed; [cancel] stops it between events. + * Copy events from one calendar into another (#325). Scoped to the activity, so + * a copy keeps running across rotation and while the Backup screen is closed; + * finishing the activity or losing the process stops it like [cancel] does, + * and a re-run picks up where it ended. */ @HiltViewModel class CopyEventsViewModel @Inject constructor( private val repository: CalendarRepository, + private val savedState: SavedStateHandle, @IoDispatcher io: CoroutineDispatcher, ) : ViewModel() { - val calendars: StateFlow> = + /** Null until the first read. */ + val calendars: StateFlow?> = repository.calendars() .catch { emit(emptyList()) } .flowOn(io) - .stateWhileSubscribed(scope = viewModelScope, initialValue = emptyList()) + .stateWhileSubscribed(scope = viewModelScope, initialValue = null) - private val _selection = MutableStateFlow(CopySelection()) - val selection: StateFlow = _selection.asStateFlow() + val selection: StateFlow = combine( + savedState.getStateFlow(KEY_SOURCE, null), + savedState.getStateFlow(KEY_TARGET, null), + ) { source, target -> CopySelection(source, target) } + .stateIn(viewModelScope, SharingStarted.Eagerly, CopySelection()) private val _run = MutableStateFlow(CopyRunState.Idle) val run: StateFlow = _run.asStateFlow() private var job: Job? = null + private val busy: Boolean get() = job?.isCompleted == false + + private fun current() = CopySelection(savedState[KEY_SOURCE], savedState[KEY_TARGET]) + + private fun select(selection: CopySelection) { + savedState[KEY_SOURCE] = selection.sourceId + savedState[KEY_TARGET] = selection.targetId + } + fun setSource(id: Long) { - if (job?.isActive == true) return - _selection.value = _selection.value.withSource(id) + if (busy) return + select(current().withSource(id)) clearFinished() } fun setTarget(id: Long) { - if (job?.isActive == true) return - _selection.value = _selection.value.copy(targetId = id) + if (busy) return + select(current().copy(targetId = id)) clearFinished() } fun start() { - val source = _selection.value.sourceId ?: return - val target = _selection.value.targetId ?: return - if (job?.isActive == true) return + val source = current().sourceId ?: return + val target = current().targetId ?: return + if (busy) return _run.value = CopyRunState.Running(done = 0, total = null) job = viewModelScope.launch { try { @@ -82,7 +101,12 @@ class CopyEventsViewModel @Inject constructor( /** Back to idle once a finished run's outcome has been seen. */ fun clearFinished() { - if (job?.isActive != true) _run.value = CopyRunState.Idle + if (!busy) _run.value = CopyRunState.Idle + } + + private companion object { + const val KEY_SOURCE = "copy_source" + const val KEY_TARGET = "copy_target" } } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/ImportedEventValuesTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/ImportedEventValuesTest.kt index e84e6580..83fd6f98 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/ImportedEventValuesTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/ImportedEventValuesTest.kt @@ -2,6 +2,7 @@ package de.jeanlucmakiola.calendula.data.calendar import android.provider.CalendarContract import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.domain.AccessLevel import de.jeanlucmakiola.calendula.domain.EventColorOption import de.jeanlucmakiola.calendula.domain.EventStatus import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent @@ -123,4 +124,21 @@ class ImportedEventValuesTest { assertThat(v[CalendarContract.Events.DURATION]).isEqualTo("P900S") assertThat(v[CalendarContract.Events.ALL_DAY]).isEqualTo(0) } + + @Test + fun `a copied RDATE-only series recurs by its dates`() { + val v = values(allDay().copy(recurrenceDates = "20260820", exDates = listOf("20260820"))) + assertThat(v).doesNotContainKey(CalendarContract.Events.DTEND) + assertThat(v).doesNotContainKey(CalendarContract.Events.RRULE) + assertThat(v[CalendarContract.Events.RDATE]).isEqualTo("20260820") + assertThat(v[CalendarContract.Events.EXDATE]).isEqualTo("20260820") + assertThat(v[CalendarContract.Events.DURATION]).isEqualTo("P1D") + } + + @Test + fun `a private event stays private, a default one leaves the calendar's say`() { + assertThat(values(allDay().copy(accessLevel = AccessLevel.Private))[CalendarContract.Events.ACCESS_LEVEL]) + .isEqualTo(CalendarContract.Events.ACCESS_PRIVATE) + assertThat(values(allDay())).doesNotContainKey(CalendarContract.Events.ACCESS_LEVEL) + } } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopyTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopyTest.kt index c1036b10..32bd0af1 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopyTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopyTest.kt @@ -1,6 +1,7 @@ package de.jeanlucmakiola.calendula.domain.ics import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.data.calendar.formatExdateStamp import de.jeanlucmakiola.calendula.domain.EventStatus import org.junit.jupiter.api.Test import kotlin.time.Instant @@ -41,6 +42,7 @@ class CalendarCopyTest { series = listOf(CopySeries(1, null, event("a", reminders = listOf(10, -5, 10)), color = 0xFF112233.toInt())), exceptions = emptyList(), ), + ::formatExdateStamp, ) val copied = plan.single() @@ -64,6 +66,7 @@ class CalendarCopyTest { ), ), ), + ::formatExdateStamp, ) val series = plan.single() @@ -85,6 +88,7 @@ class CalendarCopyTest { ), ), ), + ::formatExdateStamp, ) assertThat(plan).hasSize(2) @@ -110,6 +114,7 @@ class CalendarCopyTest { ), ), ), + ::formatExdateStamp, ) assertThat(plan.single().exDates).containsExactly("20260107") @@ -125,6 +130,7 @@ class CalendarCopyTest { CopyException(5, null, occurrence(2), event("y", status = EventStatus.Cancelled)), ), ), + ::formatExdateStamp, ) assertThat(plan.map { it.summary }).containsExactly("x") @@ -137,7 +143,7 @@ class CalendarCopyTest { exceptions = listOf(CopyException(1, null, occurrence(1), event("s"))), ) - assertThat(planCalendarCopy(rows).map { it.uid }).isEqualTo(planCalendarCopy(rows).map { it.uid }) + assertThat(planCalendarCopy(rows, ::formatExdateStamp).map { it.uid }).isEqualTo(planCalendarCopy(rows, ::formatExdateStamp).map { it.uid }) } @Test @@ -147,4 +153,35 @@ class CalendarCopyTest { assertThat(parsed.end).isEqualTo(Instant.parse("2026-01-06T00:00:00Z")) } + + @Test + fun `an RDATE-only series keeps its dates and takes its exceptions`() { + val plan = planCalendarCopy( + CalendarCopyRows( + series = listOf(CopySeries(1, null, event("s").copy(recurrenceDates = "20260112T090000Z"))), + exceptions = listOf(CopyException(1, null, occurrence(1), event("s", status = EventStatus.Cancelled))), + ), + ::formatExdateStamp, + ) + + val series = plan.single() + assertThat(series.recurrenceDates).isEqualTo("20260112T090000Z") + assertThat(series.exDates).containsExactly("20260112T090000Z") + } + + @Test + fun `a UID that comes up twice is planned once`() { + val plan = planCalendarCopy( + CalendarCopyRows( + series = listOf(CopySeries(1, null, event("s", rrule = "FREQ=WEEKLY"))), + exceptions = listOf( + CopyException(1, null, occurrence(1), event("x")), + CopyException(1, null, occurrence(1), event("y")), + ), + ), + ::formatExdateStamp, + ) + + assertThat(plan.map { it.summary }).containsExactly("x", "s").inOrder() + } } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiStateTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiStateTest.kt index 99106a76..c2e8f031 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiStateTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiStateTest.kt @@ -106,7 +106,7 @@ class BackupUiStateTest { val state = ready(backupUiState(listOf(readOnly, local))) assertThat(state.canCopy).isTrue() - assertThat(copySources(listOf(readOnly, local)).map { it.id }).containsExactly(1L, 2L) + assertThat(copySources(listOf(readOnly, local)).map { it.id }).containsExactly(1L) assertThat(copyTargets(listOf(readOnly, local), 1L).map { it.id }).containsExactly(2L) } @@ -118,6 +118,14 @@ class BackupUiStateTest { assertThat(copyTargets(listOf(only), 1L)).isEmpty() } + @Test + fun `the only writable calendar is not offered as a source`() { + val local = cal(1, local = true) + val holidays = cal(2, writable = false) + + assertThat(copySources(listOf(local, holidays)).map { it.id }).containsExactly(2L) + } + @Test fun `a copy never targets a managed or switched-off calendar`() { val source = cal(1) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 9a11451d..8324ce7f 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -505,8 +505,10 @@ overrides are written the way Calendula writes "only this event" on such a series: each exception adds its occurrence to the series' `EXDATE`, and a modified one becomes a standalone event with a UID derived from the series UID and the occurrence. The rows skip the `.ics` text: the writer pins a timed -one-off to UTC and carries no colour, the direct mapping keeps both. Attendees -and organizer are never read. The backup keeps excluding exceptions; a restore +one-off to UTC and carries no colour, visibility or `RDATE`; the direct mapping +keeps them. Attendees and organizer are never read. A re-run is idempotent per +snapshot: a series already in the target is skipped whole, so an occurrence +changed in the source since lands beside it rather than replacing it. The backup keeps excluding exceptions; a restore could not place a `RECURRENCE-ID` either. That re-encode is sampled where the reminder will actually *fire*, not at From 026970501e6a6c015738b18cc4759a0221a5c99a Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 17:24:29 +0100 Subject: [PATCH 03/16] fix(#325): review round 2 - cancelled and orphaned rows left out, re-runs add no duplicate overrides, stopped copies say so --- .../data/calendar/CalendarDataSource.kt | 5 ++- .../data/calendar/CalendarRepository.kt | 5 ++- .../data/calendar/CalendarRepositoryImpl.kt | 9 ++-- .../calendula/domain/ics/CalendarCopy.kt | 37 ++++++++-------- .../calendula/ui/calendars/BackupScreen.kt | 4 +- .../calendula/ui/calendars/CopyEventsSheet.kt | 21 ++++++++-- .../ui/calendars/CopyEventsViewModel.kt | 8 +++- app/src/main/res/values/strings.xml | 2 + .../calendula/domain/ics/CalendarCopyTest.kt | 42 +++++++++++++++++-- docs/ARCHITECTURE.md | 6 ++- 10 files changed, 103 insertions(+), 36 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt index 85147d3f..8b49062e 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt @@ -815,8 +815,11 @@ class AndroidCalendarDataSource @Inject constructor( "${CalendarContract.Events.DELETED} = 0" val series = mutableListOf() val exceptions = mutableListOf() + // Some adapters stamp the calendar's colour onto every row; that is no + // colour of the event's own and would pin it in the target. + val calendarColor = calendars().firstOrNull { it.id == calendarId }?.color forEachExportRow(selection, allDayReminderTimeMinutes) { event -> - val color = getIntOrNull(EventExportProjection.IDX_EVENT_COLOR) + val color = getIntOrNull(EventExportProjection.IDX_EVENT_COLOR)?.takeIf { it != calendarColor } val originalId = getLongOrNull(EventExportProjection.IDX_ORIGINAL_ID) val originalSyncId = getString(EventExportProjection.IDX_ORIGINAL_SYNC_ID)?.takeIf { it.isNotEmpty() } if (originalId == null && originalSyncId == null) { diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt index 47a1fd52..b65c376b 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt @@ -71,8 +71,9 @@ interface CalendarRepository { * Bulk-import parsed `.ics` [events] into [targetCalendarId]. Events whose * UID already exists in the target are skipped (idempotent restore); the * rest are inserted. See [CalendarDataSource.insertImportedEvent]. - * [onProgress] gets the count of events handled so far after each one, and - * may throw to stop the import between events. + * [onProgress] gets the count of events handled so far before each event + * after the first and once more when all were handled; it may throw to stop + * the import between events. */ suspend fun importEvents( targetCalendarId: Long, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt index 367046f7..57c77d4a 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt @@ -260,16 +260,17 @@ class CalendarRepositoryImpl @Inject constructor( ): IcsImportSummary { val events = withContext(io) { planCalendarCopy( - dataSource.calendarCopyRows(sourceCalendarId, allDayReminderTimeMinutes()), - ::formatExdateStamp, + rows = dataSource.calendarCopyRows(sourceCalendarId, allDayReminderTimeMinutes()), + targetUids = dataSource.existingUids(targetCalendarId), + exdateStamp = ::formatExdateStamp, ) } onProgress(0, events.size) // Checked between events, so cancelling stops the copy; a plain import - // keeps running to the end of its file. + // keeps running to the end of its file. A finished run stays finished. val context = currentCoroutineContext() return importEvents(targetCalendarId, events) { done -> - context.ensureActive() + if (done < events.size) context.ensureActive() onProgress(done, events.size) } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt index 2aa89741..afbdcc91 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt @@ -50,50 +50,51 @@ data class CalendarCopyRows( * any other event. * * Standalone occurrences come first: a run cut short then leaves at worst an - * occurrence missing its series, never a series missing an occurrence. A UID - * that comes up twice is planned once, as a re-run would dedup it anyway. - * Attendees and organizer are not part of either input. + * occurrence missing its series, never a series missing an occurrence. + * Cancelled events, and exceptions whose series isn't among the rows, are left + * out; the source doesn't show them either. Attendees and organizer are not + * part of either input. * - * Idempotent per snapshot only: a series already in the target is skipped - * whole, so an occurrence changed in the source after an earlier run arrives - * as a standalone event next to the copied series' original one. + * Idempotent per snapshot: a series whose UID is in [targetUids] is skipped + * whole, its overrides included, so a re-run never puts a changed occurrence + * next to the copied series' original one; it keeps the earlier copy instead. * * [exdateStamp] formats an occurrence as an `EXDATE` entry in the provider's * shape, the same one Calendula's own exclusions use. */ fun planCalendarCopy( rows: CalendarCopyRows, + targetUids: Set, exdateStamp: (occurrenceMillis: Long, isAllDay: Boolean) -> String, ): List { - val (series, exceptions) = rows + val series = rows.series.filterNot { it.event.status == EventStatus.Cancelled } val byId = series.associateBy { it.eventId } val bySyncId = series.filter { it.syncId != null }.associateBy { it.syncId } val excluded = mutableMapOf>() val detached = mutableListOf() - for (exception in exceptions) { + for (exception in rows.exceptions) { val parent = exception.originalId?.let(byId::get) ?: exception.originalSyncId?.let(bySyncId::get) - if (parent != null) { - // An exception to a one-off overrides nothing a copy could carry. - if (!parent.event.recurs) continue - excluded.getOrPut(parent.eventId) { mutableListOf() } += - exdateStamp(exception.originalInstance.toEpochMilliseconds(), parent.event.isAllDay) - } + ?: continue + // An exception to a one-off overrides nothing a copy could carry. + if (!parent.event.recurs || parent.event.uid in targetUids) continue + excluded.getOrPut(parent.eventId) { mutableListOf() } += + exdateStamp(exception.originalInstance.toEpochMilliseconds(), parent.event.isAllDay) if (exception.isCancelled) continue - val baseUid = parent?.event?.uid ?: exception.event.uid detached += exception.event .copy( - uid = "${exception.originalInstance.toEpochMilliseconds()}-$baseUid", + uid = "${exception.originalInstance.toEpochMilliseconds()}-${parent.event.uid}", recurrenceRule = null, recurrenceDates = null, ) .toParsedIcsEvent(exception.color) } - return (detached + series.map { s -> + // Two exception rows for one occurrence would derive the same UID. + return detached.distinctBy { it.uid } + series.map { s -> val extra = excluded[s.eventId].orEmpty() val event = if (extra.isEmpty()) s.event else s.event.copy(exDates = (s.event.exDates + extra).distinct()) event.toParsedIcsEvent(s.color) - }).distinctBy { it.uid } + } } /** diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt index 62413fc1..03f4c77a 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt @@ -328,7 +328,9 @@ private fun BackupContent( title = stringResource(R.string.calendars_copy_action), summary = when (copyRun) { is CopyRunState.Running -> copyProgressText(copyRun) - is CopyRunState.Done -> stringResource(R.string.calendars_copy_done) + is CopyRunState.Done -> stringResource( + if (copyRun.stopped) R.string.calendars_copy_stopped_title else R.string.calendars_copy_done, + ) CopyRunState.Cancelled -> stringResource(R.string.calendars_copy_cancelled) CopyRunState.Failed -> stringResource(R.string.calendars_copy_failed) CopyRunState.Idle -> stringResource(R.string.calendars_copy_summary) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt index e452009a..68a659cd 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt @@ -1,11 +1,13 @@ package de.jeanlucmakiola.calendula.ui.calendars import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.LinearWavyProgressIndicator import androidx.compose.material3.MaterialTheme @@ -16,13 +18,13 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.domain.CalendarSource -import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip import de.jeanlucmakiola.calendula.ui.common.CalendarPickerGroups import de.jeanlucmakiola.calendula.ui.common.orUnnamed @@ -60,6 +62,16 @@ fun CopyEventsSheet( predictiveBack = true, ) { GroupedHint(stringResource(R.string.calendars_copy_hint), style = MaterialTheme.typography.bodySmall) + if (calendars == null) { + Box(Modifier.fillMaxWidth().padding(32.dp), contentAlignment = Alignment.Center) { + CircularProgressIndicator() + } + return@FullScreenPicker + } + if (sources.isEmpty() && !running) { + GroupedHint(stringResource(R.string.calendars_copy_none)) + return@FullScreenPicker + } CopyEndRow( label = stringResource(R.string.calendars_copy_from), calendar = source, @@ -80,7 +92,7 @@ fun CopyEventsSheet( ) { when (run) { is CopyRunState.Running -> CopyProgress(run, onCancel) - is CopyRunState.Done -> CopySummary(run.summary) + is CopyRunState.Done -> CopySummary(run) CopyRunState.Cancelled -> CopyNote(stringResource(R.string.calendars_copy_cancelled)) CopyRunState.Failed -> CopyNote( stringResource(R.string.calendars_copy_failed), @@ -182,9 +194,10 @@ fun copyProgressText(run: CopyRunState.Running): String { } @Composable -private fun CopySummary(summary: IcsImportSummary) { +private fun CopySummary(run: CopyRunState.Done) { + val summary = run.summary Text( - stringResource(R.string.calendars_copy_done), + stringResource(if (run.stopped) R.string.calendars_copy_stopped_title else R.string.calendars_copy_done), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onSurface, ) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt index cd84b87a..2e0bfb79 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt @@ -1,5 +1,6 @@ package de.jeanlucmakiola.calendula.ui.calendars +import android.util.Log import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope @@ -90,6 +91,7 @@ class CopyEventsViewModel @Inject constructor( _run.value = CopyRunState.Cancelled throw e } catch (e: Exception) { + Log.w(TAG, "Copy events failed", e) _run.value = CopyRunState.Failed } } @@ -107,6 +109,7 @@ class CopyEventsViewModel @Inject constructor( private companion object { const val KEY_SOURCE = "copy_source" const val KEY_TARGET = "copy_target" + const val TAG = "CopyEvents" } } @@ -123,7 +126,10 @@ sealed interface CopyRunState { /** [total] is null while the source calendar is still being read. */ data class Running(val done: Int, val total: Int?) : CopyRunState - data class Done(val summary: IcsImportSummary) : CopyRunState + data class Done(val summary: IcsImportSummary) : CopyRunState { + /** The target stopped taking events part way, so some were never tried. */ + val stopped: Boolean get() = summary.notAttempted > 0 + } data object Cancelled : CopyRunState data object Failed : CopyRunState } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 4a55e627..c40971b5 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -904,6 +904,8 @@ %1$d of %2$d events Copy complete + Copy stopped + No calendar can be copied into another one right now. Copy cancelled. Run it again to finish: events that were already copied are skipped. Couldn\'t copy the events. diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopyTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopyTest.kt index 32bd0af1..0bc88399 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopyTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopyTest.kt @@ -42,6 +42,7 @@ class CalendarCopyTest { series = listOf(CopySeries(1, null, event("a", reminders = listOf(10, -5, 10)), color = 0xFF112233.toInt())), exceptions = emptyList(), ), + emptySet(), ::formatExdateStamp, ) @@ -66,6 +67,7 @@ class CalendarCopyTest { ), ), ), + emptySet(), ::formatExdateStamp, ) @@ -88,6 +90,7 @@ class CalendarCopyTest { ), ), ), + emptySet(), ::formatExdateStamp, ) @@ -114,6 +117,7 @@ class CalendarCopyTest { ), ), ), + emptySet(), ::formatExdateStamp, ) @@ -121,7 +125,7 @@ class CalendarCopyTest { } @Test - fun `an orphaned modified occurrence still copies, an orphaned cancellation does not`() { + fun `exceptions without their series are left out`() { val plan = planCalendarCopy( CalendarCopyRows( series = emptyList(), @@ -130,10 +134,40 @@ class CalendarCopyTest { CopyException(5, null, occurrence(2), event("y", status = EventStatus.Cancelled)), ), ), + emptySet(), ::formatExdateStamp, ) - assertThat(plan.map { it.summary }).containsExactly("x") + assertThat(plan).isEmpty() + } + + @Test + fun `a cancelled series is left out with its exceptions`() { + val plan = planCalendarCopy( + CalendarCopyRows( + series = listOf(CopySeries(1, null, event("s", rrule = "FREQ=WEEKLY", status = EventStatus.Cancelled))), + exceptions = listOf(CopyException(1, null, occurrence(1), event("x"))), + ), + emptySet(), + ::formatExdateStamp, + ) + + assertThat(plan).isEmpty() + } + + @Test + fun `a series already in the target brings no overrides along`() { + val plan = planCalendarCopy( + CalendarCopyRows( + series = listOf(CopySeries(1, null, event("s", rrule = "FREQ=WEEKLY"))), + exceptions = listOf(CopyException(1, null, occurrence(1), event("x"))), + ), + setOf("s"), + ::formatExdateStamp, + ) + + assertThat(plan.map { it.uid }).containsExactly("s") + assertThat(plan.single().exDates).isEmpty() } @Test @@ -143,7 +177,7 @@ class CalendarCopyTest { exceptions = listOf(CopyException(1, null, occurrence(1), event("s"))), ) - assertThat(planCalendarCopy(rows, ::formatExdateStamp).map { it.uid }).isEqualTo(planCalendarCopy(rows, ::formatExdateStamp).map { it.uid }) + assertThat(planCalendarCopy(rows, emptySet(), ::formatExdateStamp).map { it.uid }).isEqualTo(planCalendarCopy(rows, emptySet(), ::formatExdateStamp).map { it.uid }) } @Test @@ -161,6 +195,7 @@ class CalendarCopyTest { series = listOf(CopySeries(1, null, event("s").copy(recurrenceDates = "20260112T090000Z"))), exceptions = listOf(CopyException(1, null, occurrence(1), event("s", status = EventStatus.Cancelled))), ), + emptySet(), ::formatExdateStamp, ) @@ -179,6 +214,7 @@ class CalendarCopyTest { CopyException(1, null, occurrence(1), event("y")), ), ), + emptySet(), ::formatExdateStamp, ) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 8324ce7f..8bc0fb8a 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -507,8 +507,10 @@ modified one becomes a standalone event with a UID derived from the series UID and the occurrence. The rows skip the `.ics` text: the writer pins a timed one-off to UTC and carries no colour, visibility or `RDATE`; the direct mapping keeps them. Attendees and organizer are never read. A re-run is idempotent per -snapshot: a series already in the target is skipped whole, so an occurrence -changed in the source since lands beside it rather than replacing it. The backup keeps excluding exceptions; a restore +snapshot: a series already in the target is skipped with its overrides, so a +re-run keeps the earlier copy of an occurrence changed since rather than adding +a second one beside it. Cancelled events and exceptions whose series is gone are +left out, as the source doesn't show them either. The backup keeps excluding exceptions; a restore could not place a `RECURRENCE-ID` either. That re-encode is sampled where the reminder will actually *fire*, not at From 3f4bf65b1a631865f24b9fb6cd0a99dadd64d441 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 17:32:57 +0100 Subject: [PATCH 04/16] fix(#325): review round 3 - sheet failure state, unlinkable exceptions treated as the backup does, one-row colour lookup --- .../data/calendar/CalendarDataSource.kt | 14 ++++++++--- .../data/calendar/CalendarRepositoryImpl.kt | 4 ++-- .../calendula/ui/calendars/CopyEventsSheet.kt | 24 +++++++++++++------ .../ui/calendars/CopyEventsViewModel.kt | 21 +++++++++------- 4 files changed, 42 insertions(+), 21 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt index 8b49062e..ba0dadb2 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt @@ -817,11 +817,19 @@ class AndroidCalendarDataSource @Inject constructor( val exceptions = mutableListOf() // Some adapters stamp the calendar's colour onto every row; that is no // colour of the event's own and would pin it in the target. - val calendarColor = calendars().firstOrNull { it.id == calendarId }?.color + val calendarColor = resolver.query( + ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI, calendarId), + arrayOf(CalendarContract.Calendars.CALENDAR_COLOR), + null, + null, + null, + )?.use { c -> if (c.moveToFirst() && !c.isNull(0)) c.getInt(0) else null } forEachExportRow(selection, allDayReminderTimeMinutes) { event -> val color = getIntOrNull(EventExportProjection.IDX_EVENT_COLOR)?.takeIf { it != calendarColor } val originalId = getLongOrNull(EventExportProjection.IDX_ORIGINAL_ID) - val originalSyncId = getString(EventExportProjection.IDX_ORIGINAL_SYNC_ID)?.takeIf { it.isNotEmpty() } + val originalSyncId = getString(EventExportProjection.IDX_ORIGINAL_SYNC_ID) + // The same test the backup query makes: an empty ORIGINAL_SYNC_ID + // still marks an exception, one that can't be linked. if (originalId == null && originalSyncId == null) { series += CopySeries( eventId = getLong(EventExportProjection.IDX_ID), @@ -835,7 +843,7 @@ class AndroidCalendarDataSource @Inject constructor( ?: return@forEachExportRow exceptions += CopyException( originalId = originalId, - originalSyncId = originalSyncId, + originalSyncId = originalSyncId.takeIf { !it.isNullOrEmpty() }, originalInstance = originalInstance.toKotlinInstantFromEpochMillis(), event = event(null), color = color, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt index 57c77d4a..10fee83b 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt @@ -267,10 +267,10 @@ class CalendarRepositoryImpl @Inject constructor( } onProgress(0, events.size) // Checked between events, so cancelling stops the copy; a plain import - // keeps running to the end of its file. A finished run stays finished. + // keeps running to the end of its file. val context = currentCoroutineContext() return importEvents(targetCalendarId, events) { done -> - if (done < events.size) context.ensureActive() + context.ensureActive() onProgress(done, events.size) } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt index 68a659cd..f99c419d 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt @@ -25,6 +25,8 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.domain.FailureReason +import de.jeanlucmakiola.calendula.ui.common.CalendarFailure import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip import de.jeanlucmakiola.calendula.ui.common.CalendarPickerGroups import de.jeanlucmakiola.calendula.ui.common.orUnnamed @@ -40,7 +42,7 @@ import de.jeanlucmakiola.floret.components.Position */ @Composable fun CopyEventsSheet( - calendars: List?, + calendars: CopyCalendars, selection: CopySelection, run: CopyRunState, onSelectSource: (Long) -> Unit, @@ -49,9 +51,10 @@ fun CopyEventsSheet( onCancel: () -> Unit, onDismiss: () -> Unit, ) { - val sources = calendars?.let(::copySources).orEmpty() + val list = (calendars as? CopyCalendars.Ready)?.calendars.orEmpty() + val sources = copySources(list) val source = sources.firstOrNull { it.id == selection.sourceId } - val targets = calendars?.let { copyTargets(it, source?.id) }.orEmpty() + val targets = copyTargets(list, source?.id) val target = targets.firstOrNull { it.id == selection.targetId } val running = run is CopyRunState.Running var picking by rememberSaveable { mutableStateOf(null) } @@ -62,11 +65,18 @@ fun CopyEventsSheet( predictiveBack = true, ) { GroupedHint(stringResource(R.string.calendars_copy_hint), style = MaterialTheme.typography.bodySmall) - if (calendars == null) { - Box(Modifier.fillMaxWidth().padding(32.dp), contentAlignment = Alignment.Center) { - CircularProgressIndicator() + when (calendars) { + CopyCalendars.Loading -> { + Box(Modifier.fillMaxWidth().padding(32.dp), contentAlignment = Alignment.Center) { + CircularProgressIndicator() + } + return@FullScreenPicker } - return@FullScreenPicker + CopyCalendars.Failure -> { + CalendarFailure(reason = FailureReason.ProviderUnavailable, onRetry = onDismiss) + return@FullScreenPicker + } + is CopyCalendars.Ready -> Unit } if (sources.isEmpty() && !running) { GroupedHint(stringResource(R.string.calendars_copy_none)) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt index 2e0bfb79..32bcbd34 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt @@ -9,8 +9,6 @@ import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary import de.jeanlucmakiola.floret.android.stateWhileSubscribed -import de.jeanlucmakiola.floret.di.IoDispatcher -import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow @@ -18,7 +16,7 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.combine -import kotlinx.coroutines.flow.flowOn +import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlin.coroutines.cancellation.CancellationException @@ -34,15 +32,13 @@ import javax.inject.Inject class CopyEventsViewModel @Inject constructor( private val repository: CalendarRepository, private val savedState: SavedStateHandle, - @IoDispatcher io: CoroutineDispatcher, ) : ViewModel() { - /** Null until the first read. */ - val calendars: StateFlow?> = + val calendars: StateFlow = repository.calendars() - .catch { emit(emptyList()) } - .flowOn(io) - .stateWhileSubscribed(scope = viewModelScope, initialValue = null) + .map, CopyCalendars> { CopyCalendars.Ready(it) } + .catch { emit(CopyCalendars.Failure) } + .stateWhileSubscribed(scope = viewModelScope, initialValue = CopyCalendars.Loading) val selection: StateFlow = combine( savedState.getStateFlow(KEY_SOURCE, null), @@ -120,6 +116,13 @@ data class CopySelection(val sourceId: Long? = null, val targetId: Long? = null) CopySelection(sourceId = id, targetId = targetId?.takeIf { it != id }) } +/** The calendar list the copy sheet picks from. */ +sealed interface CopyCalendars { + data object Loading : CopyCalendars + data object Failure : CopyCalendars + data class Ready(val calendars: List) : CopyCalendars +} + sealed interface CopyRunState { data object Idle : CopyRunState From 3ed56b859692a500727a6cdf173e7cbd54689015 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Sat, 14 Nov 2026 01:15:46 +0100 Subject: [PATCH 05/16] fix(#147, #325): backups keep moved and deleted occurrences of synced series --- .../data/calendar/CalendarDataSource.kt | 96 +++----- .../data/calendar/CalendarRepository.kt | 9 +- .../data/calendar/CalendarRepositoryImpl.kt | 23 +- .../calendula/data/calendar/Projections.kt | 13 +- .../calendula/domain/ics/CalendarCopy.kt | 100 +------- .../calendula/domain/ics/CalendarRows.kt | 88 +++++++ .../calendula/domain/ics/IcsEvent.kt | 7 + .../calendula/domain/ics/IcsParser.kt | 9 + .../calendula/domain/ics/IcsWriter.kt | 2 + .../calendar/CalendarRepositoryImplTest.kt | 67 +++++- .../data/calendar/FakeCalendarDataSource.kt | 22 +- .../calendula/domain/ics/CalendarCopyTest.kt | 223 ------------------ .../calendula/domain/ics/CalendarRowsTest.kt | 188 +++++++++++++++ docs/ARCHITECTURE.md | 60 +++-- 14 files changed, 466 insertions(+), 441 deletions(-) create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt delete mode 100644 app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopyTest.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt index ba0dadb2..5de0f22f 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt @@ -30,9 +30,9 @@ import de.jeanlucmakiola.calendula.domain.Reminder import de.jeanlucmakiola.calendula.domain.SearchCandidate import de.jeanlucmakiola.calendula.domain.contacts.MANAGED_UID_PREFIX import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType -import de.jeanlucmakiola.calendula.domain.ics.CalendarCopyRows -import de.jeanlucmakiola.calendula.domain.ics.CopyException -import de.jeanlucmakiola.calendula.domain.ics.CopySeries +import de.jeanlucmakiola.calendula.domain.ics.CalendarRows +import de.jeanlucmakiola.calendula.domain.ics.OverrideRow +import de.jeanlucmakiola.calendula.domain.ics.MasterRow import de.jeanlucmakiola.calendula.domain.ics.IcsEvent import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent import de.jeanlucmakiola.calendula.domain.ics.semanticReminderMinutes @@ -93,22 +93,15 @@ interface CalendarDataSource { fun publishedEventColors(calendarId: Long): List /** - * Every master/one-off event of [calendarIds], whatever kind of calendar - * they are (local, synced, read-only), mapped to [IcsEvent]s. A plain read: - * which calendars may be read for what is the caller's call. Modified- - * occurrence and cancelled-exception rows are excluded (see - * [EventExportProjection]). [allDayReminderTimeMinutes]: needed to write - * all-day reminders as whole-day lead times rather than raw provider + * Every event row of [calendarIds], whatever kind of calendar they are + * (local, synced, read-only): the masters/one-offs and the modified and + * cancelled exception rows, each with the keys that link it to its series + * and tagged with its calendar's name. A plain read: which calendars may be + * read for what is the caller's call. [allDayReminderTimeMinutes]: needed to + * write all-day reminders as whole-day lead times rather than raw provider * offsets (see [toIcsEvent]). */ - fun calendarEvents(calendarIds: Set, allDayReminderTimeMinutes: Int): List - - /** - * Every event row of [calendarId] for a calendar copy (#325): the - * masters/one-offs [calendarEvents] reads, plus the modified and cancelled - * exception rows it leaves out, each with the keys that link it to its series. - */ - fun calendarCopyRows(calendarId: Long, allDayReminderTimeMinutes: Int): CalendarCopyRows + fun calendarRows(calendarIds: Set, allDayReminderTimeMinutes: Int): CalendarRows /** * The non-empty `Events.UID_2445` values present in [calendarId] — used to @@ -786,71 +779,48 @@ class AndroidCalendarDataSource @Inject constructor( ?: emptyList() } - override fun calendarEvents( - calendarIds: Set, - allDayReminderTimeMinutes: Int, - ): List { - if (calendarIds.isEmpty()) return emptyList() - // Id → display name for the X-CALENDULA-CALENDAR tag a restore uses to - // fan back out; an id that no longer exists drops out here. - val names = calendars() - .filter { it.id in calendarIds } - .associate { it.id to it.displayName } - if (names.isEmpty()) return emptyList() + override fun calendarRows(calendarIds: Set, allDayReminderTimeMinutes: Int): CalendarRows { + if (calendarIds.isEmpty()) return CalendarRows(emptyList(), emptyList()) + // The name tags each event for a combined backup's restore to fan back + // out; an id that no longer exists drops out here. + val calendars = calendars().filter { it.id in calendarIds }.associateBy { it.id } + if (calendars.isEmpty()) return CalendarRows(emptyList(), emptyList()) - // Masters + one-offs only: no soft-deleted or exception rows. - val selection = "${CalendarContract.Events.CALENDAR_ID} IN (${names.keys.joinToString(",")}) AND " + - "${CalendarContract.Events.DELETED} = 0 AND " + - "${CalendarContract.Events.ORIGINAL_ID} IS NULL AND " + - "${CalendarContract.Events.ORIGINAL_SYNC_ID} IS NULL" - val events = mutableListOf() - forEachExportRow(selection, allDayReminderTimeMinutes) { event -> - events += event(names[getLong(EventExportProjection.IDX_CALENDAR_ID)]) - } - return events - } - - override fun calendarCopyRows(calendarId: Long, allDayReminderTimeMinutes: Int): CalendarCopyRows { - val selection = "${CalendarContract.Events.CALENDAR_ID} = $calendarId AND " + + val selection = "${CalendarContract.Events.CALENDAR_ID} IN (${calendars.keys.joinToString(",")}) AND " + "${CalendarContract.Events.DELETED} = 0" - val series = mutableListOf() - val exceptions = mutableListOf() - // Some adapters stamp the calendar's colour onto every row; that is no - // colour of the event's own and would pin it in the target. - val calendarColor = resolver.query( - ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI, calendarId), - arrayOf(CalendarContract.Calendars.CALENDAR_COLOR), - null, - null, - null, - )?.use { c -> if (c.moveToFirst() && !c.isNull(0)) c.getInt(0) else null } + val series = mutableListOf() + val overrides = mutableListOf() forEachExportRow(selection, allDayReminderTimeMinutes) { event -> - val color = getIntOrNull(EventExportProjection.IDX_EVENT_COLOR)?.takeIf { it != calendarColor } + val calendarId = getLong(EventExportProjection.IDX_CALENDAR_ID) + val calendar = calendars[calendarId] + // Some adapters stamp the calendar's colour onto every row; that is no + // colour of the event's own and would pin it in a copy. + val color = getIntOrNull(EventExportProjection.IDX_EVENT_COLOR)?.takeIf { it != calendar?.color } + val mapped = event(calendar?.displayName).copy(color = color) val originalId = getLongOrNull(EventExportProjection.IDX_ORIGINAL_ID) val originalSyncId = getString(EventExportProjection.IDX_ORIGINAL_SYNC_ID) - // The same test the backup query makes: an empty ORIGINAL_SYNC_ID - // still marks an exception, one that can't be linked. + // An empty ORIGINAL_SYNC_ID still marks an exception, one that can't be linked. if (originalId == null && originalSyncId == null) { - series += CopySeries( + series += MasterRow( eventId = getLong(EventExportProjection.IDX_ID), + calendarId = calendarId, syncId = getString(EventExportProjection.IDX_SYNC_ID)?.takeIf { it.isNotEmpty() }, - event = event(null), - color = color, + event = mapped, ) } else { // An exception without its occurrence time can't name what it replaces. val originalInstance = getLongOrNull(EventExportProjection.IDX_ORIGINAL_INSTANCE_TIME) ?: return@forEachExportRow - exceptions += CopyException( + overrides += OverrideRow( + calendarId = calendarId, originalId = originalId, originalSyncId = originalSyncId.takeIf { !it.isNullOrEmpty() }, originalInstance = originalInstance.toKotlinInstantFromEpochMillis(), - event = event(null), - color = color, + event = mapped, ) } } - return CalendarCopyRows(series, exceptions) + return CalendarRows(series, overrides) } /** diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt index b65c376b..850832bc 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepository.kt @@ -62,15 +62,18 @@ interface CalendarRepository { /** * Every event of [calendarIds], ready to serialise into an `.ics` backup - * (see [CalendarDataSource.calendarEvents]). Any calendar can be read, - * synced and read-only ones included (#147). + * (see [CalendarDataSource.calendarRows]). Any calendar can be read, + * synced and read-only ones included (#147). Exception rows come out + * flattened ([de.jeanlucmakiola.calendula.domain.ics.flattenOverrides]), + * so a restore keeps moved and deleted occurrences of a series. */ suspend fun exportEvents(calendarIds: Set): List /** * Bulk-import parsed `.ics` [events] into [targetCalendarId]. Events whose * UID already exists in the target are skipped (idempotent restore); the - * rest are inserted. See [CalendarDataSource.insertImportedEvent]. + * rest are inserted, as is a standalone occurrence whose series is already + * there ([ParsedIcsEvent.overrideOf]). See [CalendarDataSource.insertImportedEvent]. * [onProgress] gets the count of events handled so far before each event * after the first and once more when all were handled; it may throw to stop * the import between events. diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt index 10fee83b..f2f7190c 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt @@ -14,6 +14,7 @@ import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.domain.SearchCandidate import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent +import de.jeanlucmakiola.calendula.domain.ics.flattenOverrides import de.jeanlucmakiola.calendula.domain.ics.planCalendarCopy import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.channels.BufferOverflow @@ -250,8 +251,9 @@ class CalendarRepositoryImpl @Inject constructor( } } - override suspend fun exportEvents(calendarIds: Set) = - withContext(io) { dataSource.calendarEvents(calendarIds, allDayReminderTimeMinutes()) } + override suspend fun exportEvents(calendarIds: Set) = withContext(io) { + flattenOverrides(dataSource.calendarRows(calendarIds, allDayReminderTimeMinutes()), ::formatExdateStamp) + } override suspend fun copyEvents( sourceCalendarId: Long, @@ -260,9 +262,8 @@ class CalendarRepositoryImpl @Inject constructor( ): IcsImportSummary { val events = withContext(io) { planCalendarCopy( - rows = dataSource.calendarCopyRows(sourceCalendarId, allDayReminderTimeMinutes()), - targetUids = dataSource.existingUids(targetCalendarId), - exdateStamp = ::formatExdateStamp, + dataSource.calendarRows(setOf(sourceCalendarId), allDayReminderTimeMinutes()), + ::formatExdateStamp, ) } onProgress(0, events.size) @@ -295,7 +296,7 @@ class CalendarRepositoryImpl @Inject constructor( if (index > 0) onProgress(index) // A known UID means the event is already in this calendar — skip, // keeping a restore idempotent (no overwrite this pass). - if (event.uid != null && event.uid in existing) { + if (event.isAlreadyIn(existing)) { skipped++ continue } @@ -311,7 +312,7 @@ class CalendarRepositoryImpl @Inject constructor( // A known UID would have been skipped whatever happened, so it is // no part of what a retry still has to import. val remaining = events.drop(index) - val duplicates = remaining.count { it.uid?.let { uid -> uid in existing } == true } + val duplicates = remaining.count { it.isAlreadyIn(existing) } skipped += duplicates notAttempted = remaining.size - duplicates break @@ -404,3 +405,11 @@ class CalendarRepositoryImpl @Inject constructor( private fun Flow.reQuery(block: suspend () -> T): Flow = flow { collect { emit(block()) } } + +/** + * Whether [existing] UIDs already hold this event: its own UID, or — for a + * standalone occurrence of a backed-up or copied series — the series, which + * there carries the override itself. + */ +private fun ParsedIcsEvent.isAlreadyIn(existing: Set): Boolean = + (uid != null && uid in existing) || (overrideOf != null && overrideOf in existing) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/Projections.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/Projections.kt index a312bcf5..0d092e04 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/Projections.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/Projections.kt @@ -152,16 +152,13 @@ internal object EventDetailProjection { } /** - * Master/one-off Events rows for a whole-calendar backup. Unlike + * Every Events row of a whole-calendar backup or copy. Unlike * [EventDetailProjection] this reads `UID_2445` (to keep a row's identity across * backups) and `DURATION` (recurring rows carry it instead of DTEND), plus - * `EXDATE` so a series exports the occurrences deleted from it. Modified- - * occurrence and cancelled-exception rows are filtered out by the backup query - * (`ORIGINAL_ID IS NULL`), so RECURRENCE-ID overrides aren't exported — a - * documented v1 limit (import skips them too). EXDATE is unaffected by that - * filter: it lives on the master row, not on an exception of its own. A - * calendar copy (#325) reads the exception rows too, through the trailing - * colour, series-link, RDATE and access-level columns. + * `EXDATE` so a series exports the occurrences deleted from it. Exception rows + * are read too and told apart by their series-link columns; see + * [de.jeanlucmakiola.calendula.domain.ics.flattenOverrides] for how they are + * written out. */ internal object EventExportProjection { val COLUMNS: Array = arrayOf( diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt index afbdcc91..2531c5f0 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt @@ -2,99 +2,24 @@ package de.jeanlucmakiola.calendula.domain.ics import de.jeanlucmakiola.calendula.domain.EventStatus import kotlin.time.Duration.Companion.days -import kotlin.time.Instant /** - * A master or one-off event of the calendar being copied (#325), with the - * provider keys its exception rows point back through. [color] is the event's - * own colour, null when it shows its calendar's. - */ -data class CopySeries( - val eventId: Long, - val syncId: String?, - val event: IcsEvent, - val color: Int? = null, -) - -/** - * An exception row of the calendar being copied: a modified or cancelled - * occurrence of the series named by [originalId] / [originalSyncId], standing in - * for the occurrence that would have started at [originalInstance]. - */ -data class CopyException( - val originalId: Long?, - val originalSyncId: String?, - val originalInstance: Instant, - val event: IcsEvent, - val color: Int? = null, -) { - val isCancelled: Boolean get() = event.status == EventStatus.Cancelled -} - -/** Everything a calendar copy reads from its source: series/one-offs and their exception rows. */ -data class CalendarCopyRows( - val series: List, - val exceptions: List, -) - -/** - * The events a calendar copy inserts into its target, in the shape - * `importEvents` takes. + * The events a calendar copy (#325) inserts into its target, in the shape + * `importEvents` takes: the source's rows flattened as [flattenOverrides] does + * for a backup, minus cancelled series and one-offs, which would arrive live + * (an insert can't be cancelled). Attendees and organizer are never read. * - * A copied row has no `_sync_id`, and an exception row only attaches to its - * series through one, so overrides can't be written as exception rows. Every - * exception therefore excludes its occurrence from the copied series (`EXDATE`), - * and a modified one comes along as a standalone event at its own times — what - * Calendula itself writes for "only this event" on such a series. Its UID is - * derived from the series' UID and the occurrence, so a re-run skips it like - * any other event. - * - * Standalone occurrences come first: a run cut short then leaves at worst an - * occurrence missing its series, never a series missing an occurrence. - * Cancelled events, and exceptions whose series isn't among the rows, are left - * out; the source doesn't show them either. Attendees and organizer are not - * part of either input. - * - * Idempotent per snapshot: a series whose UID is in [targetUids] is skipped - * whole, its overrides included, so a re-run never puts a changed occurrence - * next to the copied series' original one; it keeps the earlier copy instead. - * - * [exdateStamp] formats an occurrence as an `EXDATE` entry in the provider's - * shape, the same one Calendula's own exclusions use. + * Idempotent per snapshot: `importEvents` skips a UID the target already holds, + * and an [IcsEvent.overrideOf] occurrence whose series it holds, so a re-run + * keeps the earlier copy of an occurrence changed since rather than adding a + * second one beside it. */ fun planCalendarCopy( - rows: CalendarCopyRows, - targetUids: Set, + rows: CalendarRows, exdateStamp: (occurrenceMillis: Long, isAllDay: Boolean) -> String, ): List { - val series = rows.series.filterNot { it.event.status == EventStatus.Cancelled } - val byId = series.associateBy { it.eventId } - val bySyncId = series.filter { it.syncId != null }.associateBy { it.syncId } - val excluded = mutableMapOf>() - val detached = mutableListOf() - for (exception in rows.exceptions) { - val parent = exception.originalId?.let(byId::get) - ?: exception.originalSyncId?.let(bySyncId::get) - ?: continue - // An exception to a one-off overrides nothing a copy could carry. - if (!parent.event.recurs || parent.event.uid in targetUids) continue - excluded.getOrPut(parent.eventId) { mutableListOf() } += - exdateStamp(exception.originalInstance.toEpochMilliseconds(), parent.event.isAllDay) - if (exception.isCancelled) continue - detached += exception.event - .copy( - uid = "${exception.originalInstance.toEpochMilliseconds()}-${parent.event.uid}", - recurrenceRule = null, - recurrenceDates = null, - ) - .toParsedIcsEvent(exception.color) - } - // Two exception rows for one occurrence would derive the same UID. - return detached.distinctBy { it.uid } + series.map { s -> - val extra = excluded[s.eventId].orEmpty() - val event = if (extra.isEmpty()) s.event else s.event.copy(exDates = (s.event.exDates + extra).distinct()) - event.toParsedIcsEvent(s.color) - } + val live = rows.copy(series = rows.series.filterNot { it.event.status == EventStatus.Cancelled }) + return flattenOverrides(live, exdateStamp).map { it.toParsedIcsEvent() } } /** @@ -103,7 +28,7 @@ fun planCalendarCopy( * own time zone (the writer pins it to UTC) and the event's colour (not part of * the file format). */ -fun IcsEvent.toParsedIcsEvent(color: Int? = null): ParsedIcsEvent = ParsedIcsEvent( +fun IcsEvent.toParsedIcsEvent(): ParsedIcsEvent = ParsedIcsEvent( uid = uid, summary = summary, start = start, @@ -122,5 +47,6 @@ fun IcsEvent.toParsedIcsEvent(color: Int? = null): ParsedIcsEvent = ParsedIcsEve availability = availability, accessLevel = accessLevel, color = color, + overrideOf = overrideOf, exDates = if (recurs) exDates.filter { it.isNotBlank() }.distinct() else emptyList(), ) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt new file mode 100644 index 00000000..85963527 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt @@ -0,0 +1,88 @@ +package de.jeanlucmakiola.calendula.domain.ics + +import de.jeanlucmakiola.calendula.domain.EventStatus +import kotlin.time.Instant + +/** + * A master or one-off Events row of a calendar being backed up or copied, with + * the provider keys its exception rows point back through. + */ +data class MasterRow( + val eventId: Long, + val calendarId: Long, + val syncId: String?, + val event: IcsEvent, +) + +/** + * An exception row: a modified or cancelled occurrence of the series named by + * [originalId] / [originalSyncId] in [calendarId], standing in for the + * occurrence that would have started at [originalInstance]. + */ +data class OverrideRow( + val calendarId: Long, + val originalId: Long?, + val originalSyncId: String?, + val originalInstance: Instant, + val event: IcsEvent, +) { + val isCancelled: Boolean get() = event.status == EventStatus.Cancelled +} + +/** Every event row a backup or copy reads: series/one-offs and their exception rows. */ +data class CalendarRows( + val series: List, + val overrides: List, +) + +/** + * [rows] as plain events with no exception rows left, the shape both a backup + * file and a copied calendar need: neither can hold an exception row, since one + * only attaches to its series through a `_sync_id` (and an `.ics` restore skips + * `RECURRENCE-ID` overrides). + * + * Every override excludes its occurrence from the series (`EXDATE`), and a + * modified one comes along as a standalone event at its own times, marked + * [IcsEvent.overrideOf] its series — what Calendula itself writes for "only this + * event" on an unsynced series. Its UID is derived from the series' UID and the + * occurrence, so it is the same on every run. Overrides whose series isn't + * among the rows are left out; the provider doesn't show them either. + * + * Standalone occurrences come first, so an import cut short leaves at worst an + * occurrence missing its series, never a series missing an occurrence. + * + * [exdateStamp] formats an occurrence as an `EXDATE` entry in the provider's + * shape, the same one Calendula's own exclusions use. + */ +fun flattenOverrides( + rows: CalendarRows, + exdateStamp: (occurrenceMillis: Long, isAllDay: Boolean) -> String, +): List { + val byId = rows.series.associateBy { it.eventId } + // Sync ids are only unique within an account, so the link is per calendar. + val bySyncId = rows.series.filter { it.syncId != null }.associateBy { it.calendarId to it.syncId } + val excluded = mutableMapOf>() + val detached = mutableListOf() + for (override in rows.overrides) { + val parent = override.originalId?.let(byId::get)?.takeIf { it.calendarId == override.calendarId } + ?: override.originalSyncId?.let { bySyncId[override.calendarId to it] } + ?: continue + // An exception to a one-off overrides nothing a plain event could carry. + if (!parent.event.recurs) continue + val occurrence = override.originalInstance.toEpochMilliseconds() + excluded.getOrPut(parent.eventId) { mutableListOf() } += exdateStamp(occurrence, parent.event.isAllDay) + if (override.isCancelled) continue + detached += override.event.copy( + uid = "$occurrence-${parent.event.uid}", + recurrenceRule = null, + recurrenceDates = null, + exDates = emptyList(), + overrideOf = parent.event.uid, + ) + } + // Two exception rows for one occurrence would derive the same UID. + return detached.distinctBy { it.uid } + rows.series.map { s -> + val extra = excluded[s.eventId].orEmpty() + if (extra.isEmpty()) s.event else s.event.copy(exDates = (s.event.exDates + extra).distinct()) + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsEvent.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsEvent.kt index d3ab50ad..a24f8673 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsEvent.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsEvent.kt @@ -41,6 +41,13 @@ data class IcsEvent( val recurrenceDates: String? = null, /** Carried by a calendar copy, not written to a file. */ val accessLevel: AccessLevel = AccessLevel.Default, + /** The event's own colour, null when it shows its calendar's; carried by a calendar copy, not written to a file. */ + val color: Int? = null, + /** + * For a modified occurrence written out on its own ([flattenOverrides]): the + * UID of the series it replaces an occurrence of, as `X-CALENDULA-OVERRIDE-OF`. + */ + val overrideOf: String? = null, ) /** Whether this is a series: by rule, or by listed dates alone. */ diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsParser.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsParser.kt index 6ce1c19e..0a48e44f 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsParser.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsParser.kt @@ -46,6 +46,12 @@ data class ParsedIcsEvent( val exDates: List = emptyList(), /** True when this came from a `VTODO` rather than a `VEVENT`. */ val isTask: Boolean = false, + /** + * The UID of the series this standalone occurrence replaces one occurrence + * of (`X-CALENDULA-OVERRIDE-OF`). An import skips it where that series + * already is, since the series there carries its own override. + */ + val overrideOf: String? = null, /** The provider's raw `RDATE`, only set by a calendar copy. */ val recurrenceDates: String? = null, val accessLevel: AccessLevel = AccessLevel.Default, @@ -217,6 +223,7 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault val reminders = mutableListOf() val exDateLines = mutableListOf() var skipAsOverride = false + var overrideOf: String? = null var i = 0 while (i < body.size) { @@ -245,6 +252,7 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault else Availability.Busy "RECURRENCE-ID" -> skipAsOverride = true "ATTENDEE" -> warnings.add(IcsParseWarning.AttendeesIgnored) + "X-CALENDULA-OVERRIDE-OF" -> overrideOf = unescapeText(line.value).trim().ifEmpty { null } "X-CALENDULA-CALENDAR" -> calendarName = unescapeText(line.value).trim().ifEmpty { calendarName } // Fossify names the source calendar per event; it never writes @@ -304,6 +312,7 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault normalizeExDates(exDateLines, start) }, isTask = isTask, + overrideOf = overrideOf, ) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsWriter.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsWriter.kt index 250e2df5..833c0c22 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsWriter.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsWriter.kt @@ -56,6 +56,8 @@ class IcsWriter(private val prodId: String = ICS_PROD_ID) { add("TRANSP:${transpValue(event.availability)}") event.calendarName?.takeIf { it.isNotBlank() } ?.let { add("X-CALENDULA-CALENDAR:${escapeText(it)}") } + event.overrideOf?.takeIf { it.isNotBlank() } + ?.let { add("X-CALENDULA-OVERRIDE-OF:${escapeText(it)}") } event.reminderMinutes.filter { it >= 0 }.distinct().forEach { minutes -> appendAlarm(minutes, event.summary) } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt index eff60c52..53fb8c87 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt @@ -8,6 +8,13 @@ import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.domain.FormTime import de.jeanlucmakiola.calendula.domain.SearchCandidate +import de.jeanlucmakiola.calendula.domain.EventStatus +import de.jeanlucmakiola.calendula.domain.ics.CalendarRows +import de.jeanlucmakiola.calendula.domain.ics.IcsEvent +import de.jeanlucmakiola.calendula.domain.ics.IcsParser +import de.jeanlucmakiola.calendula.domain.ics.IcsWriter +import de.jeanlucmakiola.calendula.domain.ics.OverrideRow +import de.jeanlucmakiola.calendula.domain.ics.MasterRow import de.jeanlucmakiola.calendula.testEvent import de.jeanlucmakiola.calendula.testPrefs import de.jeanlucmakiola.calendula.testRepository @@ -946,7 +953,7 @@ class CalendarRepositoryImplTest { repo.exportEvents(calendarIds = setOf(1L, 4L)) - assertThat(fake.lastCalendarEventsIds).containsExactly(1L, 4L) + assertThat(fake.lastCalendarRowsIds).containsExactly(1L, 4L) } @Test @@ -958,14 +965,14 @@ class CalendarRepositoryImplTest { repo.exportEvents(calendarIds = setOf(2L)) - assertThat(fake.lastCalendarEventsIds).containsExactly(2L) + assertThat(fake.lastCalendarRowsIds).containsExactly(2L) } @Test fun `copyEvents reports progress and skips what an earlier run copied`( @TempDir tempDir: Path, ) = runTest { - fun icsEvent(uid: String) = de.jeanlucmakiola.calendula.domain.ics.IcsEvent( + fun icsEvent(uid: String) = IcsEvent( uid = uid, summary = uid, start = Instant.fromEpochMilliseconds(1_000_000_000L), @@ -975,12 +982,9 @@ class CalendarRepositoryImplTest { ) val fake = FakeCalendarDataSource().apply { existingUidsResult = setOf("a") - calendarCopyRowsResult = de.jeanlucmakiola.calendula.domain.ics.CalendarCopyRows( - series = listOf( - de.jeanlucmakiola.calendula.domain.ics.CopySeries(1, null, icsEvent("a")), - de.jeanlucmakiola.calendula.domain.ics.CopySeries(2, null, icsEvent("b")), - ), - exceptions = emptyList(), + calendarRowsResult = CalendarRows( + series = listOf(MasterRow(1, 1, null, icsEvent("a")), MasterRow(2, 1, null, icsEvent("b"))), + overrides = emptyList(), ) } val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) @@ -997,6 +1001,51 @@ class CalendarRepositoryImplTest { assertThat(progress.last()).isEqualTo(2 to 2) } + @Test + fun `a backup restores a series' moved and deleted occurrences, and skips them where the series is`( + @TempDir tempDir: Path, + ) = runTest { + val start = Instant.parse("2026-01-05T09:00:00Z") + fun at(week: Int) = Instant.fromEpochMilliseconds(start.toEpochMilliseconds() + week * 7 * 86_400_000L) + fun event(at: Instant, status: EventStatus = EventStatus.Confirmed, rrule: String? = null) = IcsEvent( + uid = "s@x", + summary = "Standup", + start = at, + end = Instant.fromEpochMilliseconds(at.toEpochMilliseconds() + 3_600_000L), + isAllDay = false, + zoneId = "Europe/Berlin", + recurrenceRule = rrule, + status = status, + ) + val moved = Instant.fromEpochMilliseconds(at(1).toEpochMilliseconds() + 3_600_000L) + val source = FakeCalendarDataSource().apply { + calendarRowsResult = CalendarRows( + series = listOf(MasterRow(1, 1, "sync-1", event(start, rrule = "FREQ=WEEKLY"))), + overrides = listOf( + OverrideRow(1, null, "sync-1", at(1), event(moved)), + OverrideRow(1, null, "sync-1", at(2), event(at(2), EventStatus.Cancelled)), + ), + ) + } + val file = IcsWriter().writeCalendar( + testRepository(source, tempDir.resolve("a"), Dispatchers.Unconfined).exportEvents(setOf(1L)), + start, + ) + val parsed = IcsParser().parse(file).events + + val empty = FakeCalendarDataSource() + testRepository(empty, tempDir.resolve("b"), Dispatchers.Unconfined).importEvents(3L, parsed) + val (detached, series) = empty.importedEvents.map { it.first } + assertThat(detached.start).isEqualTo(moved) + assertThat(detached.recurrenceRule).isNull() + assertThat(series.exDates).containsExactly("20260112T090000Z", "20260119T090000Z") + + val original = FakeCalendarDataSource().apply { existingUidsResult = setOf("s@x") } + val summary = testRepository(original, tempDir.resolve("c"), Dispatchers.Unconfined).importEvents(3L, parsed) + assertThat(original.importedEvents).isEmpty() + assertThat(summary.skippedDuplicate).isEqualTo(2) + } + private fun parsedEvent(uid: String?, summary: String = "E") = de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent( uid = uid, diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/FakeCalendarDataSource.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/FakeCalendarDataSource.kt index 5ba0bf12..794dcb03 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/FakeCalendarDataSource.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/FakeCalendarDataSource.kt @@ -8,7 +8,7 @@ import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.EventInstance import de.jeanlucmakiola.calendula.domain.SearchCandidate import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType -import de.jeanlucmakiola.calendula.domain.ics.CalendarCopyRows +import de.jeanlucmakiola.calendula.domain.ics.CalendarRows import de.jeanlucmakiola.calendula.domain.ics.IcsEvent import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent import java.time.ZoneId @@ -24,9 +24,9 @@ internal class FakeCalendarDataSource : CalendarDataSource { var searchResult: (String) -> List = { _ -> emptyList() } var eventDetailResult: (Long) -> EventDetail? = { null } var publishedEventColorsResult: (Long) -> List = { emptyList() } - var calendarEventsResult: List = emptyList() - /** The [calendarIds] the last [calendarEvents] call received. */ - var lastCalendarEventsIds: Set? = null + var calendarRowsResult: CalendarRows = CalendarRows(emptyList(), emptyList()) + /** The [calendarIds] the last [calendarRows] call received. */ + var lastCalendarRowsIds: Set? = null /** UIDs the target calendar already holds, for import dedup. */ var existingUidsResult: Set = emptySet() /** Set to make the next write call throw. */ @@ -82,19 +82,11 @@ internal class FakeCalendarDataSource : CalendarDataSource { eventDetailResult(eventId) override fun publishedEventColors(calendarId: Long): List = publishedEventColorsResult(calendarId) - override fun calendarEvents( - calendarIds: Set, - allDayReminderTimeMinutes: Int, - ): List { - lastCalendarEventsIds = calendarIds - return calendarEventsResult + override fun calendarRows(calendarIds: Set, allDayReminderTimeMinutes: Int): CalendarRows { + lastCalendarRowsIds = calendarIds + return calendarRowsResult } - var calendarCopyRowsResult: CalendarCopyRows = CalendarCopyRows(emptyList(), emptyList()) - - override fun calendarCopyRows(calendarId: Long, allDayReminderTimeMinutes: Int): CalendarCopyRows = - calendarCopyRowsResult - override fun existingUids(calendarId: Long): Set = existingUidsResult /** (event, targetCalendarId) pairs passed to [insertImportedEvent]. */ diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopyTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopyTest.kt deleted file mode 100644 index 0bc88399..00000000 --- a/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopyTest.kt +++ /dev/null @@ -1,223 +0,0 @@ -package de.jeanlucmakiola.calendula.domain.ics - -import com.google.common.truth.Truth.assertThat -import de.jeanlucmakiola.calendula.data.calendar.formatExdateStamp -import de.jeanlucmakiola.calendula.domain.EventStatus -import org.junit.jupiter.api.Test -import kotlin.time.Instant - -/** What a calendar copy (#325) inserts for a source calendar's rows. */ -class CalendarCopyTest { - - private val start = Instant.parse("2026-01-05T09:00:00Z") - private val week = 7 * 24 * 3_600_000L - - private fun event( - uid: String, - rrule: String? = null, - allDay: Boolean = false, - at: Instant = start, - status: EventStatus = EventStatus.Confirmed, - exDates: List = emptyList(), - reminders: List = emptyList(), - ) = IcsEvent( - uid = uid, - summary = uid, - start = at, - end = Instant.fromEpochMilliseconds(at.toEpochMilliseconds() + 3_600_000L), - isAllDay = allDay, - zoneId = "Europe/Berlin", - recurrenceRule = rrule, - exDates = exDates, - reminderMinutes = reminders, - status = status, - ) - - private fun occurrence(n: Int) = Instant.fromEpochMilliseconds(start.toEpochMilliseconds() + n * week) - - @Test - fun `a plain event copies as itself, keeping its zone and colour`() { - val plan = planCalendarCopy( - CalendarCopyRows( - series = listOf(CopySeries(1, null, event("a", reminders = listOf(10, -5, 10)), color = 0xFF112233.toInt())), - exceptions = emptyList(), - ), - emptySet(), - ::formatExdateStamp, - ) - - val copied = plan.single() - assertThat(copied.uid).isEqualTo("a") - assertThat(copied.zoneId).isEqualTo("Europe/Berlin") - assertThat(copied.color).isEqualTo(0xFF112233.toInt()) - assertThat(copied.reminderMinutes).containsExactly(10) - } - - @Test - fun `a cancelled occurrence becomes an EXDATE on the series`() { - val plan = planCalendarCopy( - CalendarCopyRows( - series = listOf(CopySeries(1, "sync-1", event("s", rrule = "FREQ=WEEKLY", exDates = listOf("20260112T080000Z")))), - exceptions = listOf( - CopyException( - originalId = null, - originalSyncId = "sync-1", - originalInstance = occurrence(2), - event = event("s", at = occurrence(2), status = EventStatus.Cancelled), - ), - ), - ), - emptySet(), - ::formatExdateStamp, - ) - - val series = plan.single() - assertThat(series.exDates).containsExactly("20260112T080000Z", "20260119T090000Z").inOrder() - } - - @Test - fun `a modified occurrence is excluded from the series and copied on its own, first`() { - val moved = Instant.fromEpochMilliseconds(occurrence(1).toEpochMilliseconds() + 3_600_000L) - val plan = planCalendarCopy( - CalendarCopyRows( - series = listOf(CopySeries(1, null, event("s", rrule = "FREQ=WEEKLY"))), - exceptions = listOf( - CopyException( - originalId = 1, - originalSyncId = null, - originalInstance = occurrence(1), - event = event("s", rrule = "FREQ=WEEKLY", at = moved), - ), - ), - ), - emptySet(), - ::formatExdateStamp, - ) - - assertThat(plan).hasSize(2) - val detached = plan[0] - assertThat(detached.uid).isEqualTo("${occurrence(1).toEpochMilliseconds()}-s") - assertThat(detached.recurrenceRule).isNull() - assertThat(detached.start).isEqualTo(moved) - assertThat(plan[1].exDates).containsExactly("20260112T090000Z") - } - - @Test - fun `an all-day series excludes the occurrence by its day`() { - val day = Instant.parse("2026-01-05T00:00:00Z") - val plan = planCalendarCopy( - CalendarCopyRows( - series = listOf(CopySeries(1, null, event("s", rrule = "FREQ=DAILY", allDay = true, at = day))), - exceptions = listOf( - CopyException( - originalId = 1, - originalSyncId = null, - originalInstance = Instant.parse("2026-01-07T00:00:00Z"), - event = event("s", allDay = true, status = EventStatus.Cancelled), - ), - ), - ), - emptySet(), - ::formatExdateStamp, - ) - - assertThat(plan.single().exDates).containsExactly("20260107") - } - - @Test - fun `exceptions without their series are left out`() { - val plan = planCalendarCopy( - CalendarCopyRows( - series = emptyList(), - exceptions = listOf( - CopyException(5, null, occurrence(1), event("x")), - CopyException(5, null, occurrence(2), event("y", status = EventStatus.Cancelled)), - ), - ), - emptySet(), - ::formatExdateStamp, - ) - - assertThat(plan).isEmpty() - } - - @Test - fun `a cancelled series is left out with its exceptions`() { - val plan = planCalendarCopy( - CalendarCopyRows( - series = listOf(CopySeries(1, null, event("s", rrule = "FREQ=WEEKLY", status = EventStatus.Cancelled))), - exceptions = listOf(CopyException(1, null, occurrence(1), event("x"))), - ), - emptySet(), - ::formatExdateStamp, - ) - - assertThat(plan).isEmpty() - } - - @Test - fun `a series already in the target brings no overrides along`() { - val plan = planCalendarCopy( - CalendarCopyRows( - series = listOf(CopySeries(1, null, event("s", rrule = "FREQ=WEEKLY"))), - exceptions = listOf(CopyException(1, null, occurrence(1), event("x"))), - ), - setOf("s"), - ::formatExdateStamp, - ) - - assertThat(plan.map { it.uid }).containsExactly("s") - assertThat(plan.single().exDates).isEmpty() - } - - @Test - fun `the plan is stable, so a re-run dedups every event`() { - val rows = CalendarCopyRows( - series = listOf(CopySeries(1, null, event("s", rrule = "FREQ=WEEKLY"))), - exceptions = listOf(CopyException(1, null, occurrence(1), event("s"))), - ) - - assertThat(planCalendarCopy(rows, emptySet(), ::formatExdateStamp).map { it.uid }).isEqualTo(planCalendarCopy(rows, emptySet(), ::formatExdateStamp).map { it.uid }) - } - - @Test - fun `a zero-length all-day event lasts its day`() { - val day = Instant.parse("2026-01-05T00:00:00Z") - val parsed = event("a", allDay = true, at = day).copy(end = day).toParsedIcsEvent() - - assertThat(parsed.end).isEqualTo(Instant.parse("2026-01-06T00:00:00Z")) - } - - @Test - fun `an RDATE-only series keeps its dates and takes its exceptions`() { - val plan = planCalendarCopy( - CalendarCopyRows( - series = listOf(CopySeries(1, null, event("s").copy(recurrenceDates = "20260112T090000Z"))), - exceptions = listOf(CopyException(1, null, occurrence(1), event("s", status = EventStatus.Cancelled))), - ), - emptySet(), - ::formatExdateStamp, - ) - - val series = plan.single() - assertThat(series.recurrenceDates).isEqualTo("20260112T090000Z") - assertThat(series.exDates).containsExactly("20260112T090000Z") - } - - @Test - fun `a UID that comes up twice is planned once`() { - val plan = planCalendarCopy( - CalendarCopyRows( - series = listOf(CopySeries(1, null, event("s", rrule = "FREQ=WEEKLY"))), - exceptions = listOf( - CopyException(1, null, occurrence(1), event("x")), - CopyException(1, null, occurrence(1), event("y")), - ), - ), - emptySet(), - ::formatExdateStamp, - ) - - assertThat(plan.map { it.summary }).containsExactly("x", "s").inOrder() - } -} diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt new file mode 100644 index 00000000..172baedd --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt @@ -0,0 +1,188 @@ +package de.jeanlucmakiola.calendula.domain.ics + +import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.calendula.data.calendar.formatExdateStamp +import de.jeanlucmakiola.calendula.domain.EventStatus +import org.junit.jupiter.api.Test +import kotlin.time.Instant + +/** How a calendar's exception rows are written out for a backup (#147) or a copy (#325). */ +class CalendarRowsTest { + + private val start = Instant.parse("2026-01-05T09:00:00Z") + private val week = 7 * 24 * 3_600_000L + + private fun event( + uid: String, + rrule: String? = null, + allDay: Boolean = false, + at: Instant = start, + status: EventStatus = EventStatus.Confirmed, + exDates: List = emptyList(), + reminders: List = emptyList(), + color: Int? = null, + ) = IcsEvent( + uid = uid, + summary = uid, + start = at, + end = Instant.fromEpochMilliseconds(at.toEpochMilliseconds() + 3_600_000L), + isAllDay = allDay, + zoneId = "Europe/Berlin", + recurrenceRule = rrule, + exDates = exDates, + reminderMinutes = reminders, + status = status, + color = color, + calendarName = "Work", + ) + + private fun occurrence(n: Int) = Instant.fromEpochMilliseconds(start.toEpochMilliseconds() + n * week) + + private fun series(uid: String, rrule: String? = "FREQ=WEEKLY", id: Long = 1, calendar: Long = 1, syncId: String? = null, status: EventStatus = EventStatus.Confirmed) = + MasterRow(id, calendar, syncId, event(uid, rrule = rrule, status = status)) + + private fun flatten(series: List, overrides: List) = + flattenOverrides(CalendarRows(series, overrides), ::formatExdateStamp) + + @Test + fun `a cancelled occurrence becomes an EXDATE on the series`() { + val flat = flatten( + listOf(MasterRow(1, 1, "sync-1", event("s", rrule = "FREQ=WEEKLY", exDates = listOf("20260112T080000Z")))), + listOf(OverrideRow(1, null, "sync-1", occurrence(2), event("s", at = occurrence(2), status = EventStatus.Cancelled))), + ) + + assertThat(flat.single().exDates).containsExactly("20260112T080000Z", "20260119T090000Z").inOrder() + } + + @Test + fun `a modified occurrence is excluded from the series and written on its own, first`() { + val moved = Instant.fromEpochMilliseconds(occurrence(1).toEpochMilliseconds() + 3_600_000L) + val flat = flatten( + listOf(series("s")), + listOf(OverrideRow(1, 1, null, occurrence(1), event("s", rrule = "FREQ=WEEKLY", at = moved))), + ) + + assertThat(flat).hasSize(2) + val detached = flat[0] + assertThat(detached.uid).isEqualTo("${occurrence(1).toEpochMilliseconds()}-s") + assertThat(detached.overrideOf).isEqualTo("s") + assertThat(detached.recurrenceRule).isNull() + assertThat(detached.start).isEqualTo(moved) + assertThat(detached.calendarName).isEqualTo("Work") + assertThat(flat[1].exDates).containsExactly("20260112T090000Z") + } + + @Test + fun `an all-day series excludes the occurrence by its day`() { + val day = Instant.parse("2026-01-05T00:00:00Z") + val flat = flatten( + listOf(MasterRow(1, 1, null, event("s", rrule = "FREQ=DAILY", allDay = true, at = day))), + listOf(OverrideRow(1, 1, null, Instant.parse("2026-01-07T00:00:00Z"), event("s", allDay = true, status = EventStatus.Cancelled))), + ) + + assertThat(flat.single().exDates).containsExactly("20260107") + } + + @Test + fun `exceptions without their series are left out`() { + val flat = flatten( + emptyList(), + listOf( + OverrideRow(1, 5, null, occurrence(1), event("x")), + OverrideRow(1, 5, null, occurrence(2), event("y", status = EventStatus.Cancelled)), + ), + ) + + assertThat(flat).isEmpty() + } + + @Test + fun `a sync id links an exception only within its own calendar`() { + val flat = flatten( + listOf(series("a", calendar = 1, syncId = "same"), series("b", id = 2, calendar = 2, syncId = "same")), + listOf(OverrideRow(2, null, "same", occurrence(1), event("x", status = EventStatus.Cancelled))), + ) + + assertThat(flat.first { it.uid == "a" }.exDates).isEmpty() + assertThat(flat.first { it.uid == "b" }.exDates).containsExactly("20260112T090000Z") + } + + @Test + fun `an exception to a one-off is ignored`() { + val flat = flatten( + listOf(series("o", rrule = null)), + listOf(OverrideRow(1, 1, null, occurrence(0), event("x"))), + ) + + assertThat(flat.map { it.uid }).containsExactly("o") + } + + @Test + fun `an RDATE-only series keeps its dates and takes its exceptions`() { + val flat = flatten( + listOf(MasterRow(1, 1, null, event("s").copy(recurrenceDates = "20260112T090000Z"))), + listOf(OverrideRow(1, 1, null, occurrence(1), event("s", status = EventStatus.Cancelled))), + ) + + assertThat(flat.single().recurrenceDates).isEqualTo("20260112T090000Z") + assertThat(flat.single().exDates).containsExactly("20260112T090000Z") + } + + @Test + fun `two exception rows for one occurrence are written once`() { + val flat = flatten( + listOf(series("s")), + listOf(OverrideRow(1, 1, null, occurrence(1), event("x")), OverrideRow(1, 1, null, occurrence(1), event("y"))), + ) + + assertThat(flat.map { it.summary }).containsExactly("x", "s").inOrder() + } + + @Test + fun `the output is stable, so a re-run dedups every event`() { + val rows = CalendarRows(listOf(series("s")), listOf(OverrideRow(1, 1, null, occurrence(1), event("x")))) + + assertThat(flattenOverrides(rows, ::formatExdateStamp).map { it.uid }) + .isEqualTo(flattenOverrides(rows, ::formatExdateStamp).map { it.uid }) + } + + @Test + fun `a backup keeps a cancelled series, a copy leaves it out with its exceptions`() { + val rows = CalendarRows( + listOf(series("s", status = EventStatus.Cancelled)), + listOf(OverrideRow(1, 1, null, occurrence(1), event("x"))), + ) + + assertThat(flattenOverrides(rows, ::formatExdateStamp).map { it.uid }).contains("s") + assertThat(planCalendarCopy(rows, ::formatExdateStamp)).isEmpty() + } + + @Test + fun `a copy keeps the zone, colour and override link`() { + val rows = CalendarRows( + listOf(MasterRow(1, 1, null, event("s", rrule = "FREQ=WEEKLY", reminders = listOf(10, -5, 10), color = 0xFF112233.toInt()))), + listOf(OverrideRow(1, 1, null, occurrence(1), event("x"))), + ) + + val (detached, copied) = planCalendarCopy(rows, ::formatExdateStamp) + assertThat(detached.overrideOf).isEqualTo("s") + assertThat(copied.zoneId).isEqualTo("Europe/Berlin") + assertThat(copied.color).isEqualTo(0xFF112233.toInt()) + assertThat(copied.reminderMinutes).containsExactly(10) + } + + @Test + fun `a zero-length all-day event lasts its day`() { + val day = Instant.parse("2026-01-05T00:00:00Z") + val parsed = event("a", allDay = true, at = day).copy(end = day).toParsedIcsEvent() + + assertThat(parsed.end).isEqualTo(Instant.parse("2026-01-06T00:00:00Z")) + } + + @Test + fun `the override link survives the file`() { + val text = IcsWriter().writeCalendar(listOf(event("d").copy(overrideOf = "s;1")), start) + + assertThat(IcsParser().parse(text).events.single().overrideOf).isEqualTo("s;1") + } +} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 8bc0fb8a..b13f037b 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -485,33 +485,41 @@ of the backup keeps its last one. The pre-#411 fixed `calendula-backup.ics` is the combined series' stable copy for the install that wrote it, and an install that already had a folder stays on the combined layout. -**A backup carries the series' deleted occurrences.** `EXDATE` lives on the -master row, so the export query's `ORIGINAL_ID IS NULL` filter — which does drop -`RECURRENCE-ID` overrides — never hid it; it simply wasn't read. It is now part -of `EventExportProjection`, and `IcsWriter` marks an all-day series' exclusions -`VALUE=DATE`, because RFC 5545 ties `EXDATE`'s value type to `DTSTART`'s and a -bare day code without it reads as a malformed DATE-TIME. Sync adapters disagree -on whether an all-day exclusion is `yyyyMMdd` or a padded midnight stamp, so -`exportExDates` drops the time part on the way out. Without this, an in-app -backup→restore resurrected every occurrence the user had deleted. +**A backup carries the series' deleted and moved occurrences.** `EXDATE` lives on +the master row and is part of `EventExportProjection`; `IcsWriter` marks an +all-day series' exclusions `VALUE=DATE`, because RFC 5545 ties `EXDATE`'s value +type to `DTSTART`'s and a bare day code without it reads as a malformed +DATE-TIME. Sync adapters disagree on whether an all-day exclusion is `yyyyMMdd` +or a padded midnight stamp, so `exportExDates` drops the time part on the way +out. -**Copying a calendar reads its exceptions too.** Backup & restore → Copy events -(#325) reads every row of the source through `calendarCopyRows` — masters, -one-offs *and* the exception rows the backup query leaves out — and -`planCalendarCopy` turns them into the `ParsedIcsEvent`s that the normal -`importEvents` inserts, so the UID dedup makes a re-run skip what landed before. -The copy has no `_sync_id`, and an exception row only attaches through one, so -overrides are written the way Calendula writes "only this event" on such a -series: each exception adds its occurrence to the series' `EXDATE`, and a -modified one becomes a standalone event with a UID derived from the series UID -and the occurrence. The rows skip the `.ics` text: the writer pins a timed -one-off to UTC and carries no colour, visibility or `RDATE`; the direct mapping -keeps them. Attendees and organizer are never read. A re-run is idempotent per -snapshot: a series already in the target is skipped with its overrides, so a -re-run keeps the earlier copy of an occurrence changed since rather than adding -a second one beside it. Cancelled events and exceptions whose series is gone are -left out, as the source doesn't show them either. The backup keeps excluding exceptions; a restore -could not place a `RECURRENCE-ID` either. +A synced calendar records a deleted or moved occurrence as an *exception row* +(`ORIGINAL_ID` / `ORIGINAL_SYNC_ID` = the series, `ORIGINAL_INSTANCE_TIME` = the +occurrence) instead, and neither a backup file nor a copied calendar can hold +one: an `.ics` restore skips `RECURRENCE-ID` overrides, and an inserted row has +no `_sync_id` for an exception to attach through. `CalendarDataSource.calendarRows` +therefore reads every row, exceptions included, and `flattenOverrides` — the one +place this mapping lives, shared by the backup (`exportEvents`) and Copy events +(#325, `planCalendarCopy`) — writes them the way Calendula writes "only this +event" on an unsynced series: every exception adds its occurrence to the +series' `EXDATE`, and a modified one becomes a standalone event at its own +times. Its UID is derived from the series UID and the occurrence, so it is the +same in every backup, and it carries the series UID as `X-CALENDULA-OVERRIDE-OF`. +`importEvents` skips such an occurrence wherever its series already is — that +series there has the override itself — so restoring into the calendar a backup +came from adds nothing twice, while a restore into an empty one gets both. +Exceptions whose series isn't among the rows are left out, and sync ids link +only within their own calendar. Backups made before this carry no exceptions +and restore exactly as before. + +**Copying a calendar.** Backup & restore → Copy events (#325) runs the source's +flattened rows straight into `importEvents`, so the UID dedup makes a re-run skip +what landed before. It skips the `.ics` text: the writer pins a timed one-off to +UTC and carries no colour, visibility or `RDATE`; the direct mapping keeps them. +Attendees and organizer are never read, and cancelled events are left out (an +insert can't be cancelled; it would arrive live). A re-run is idempotent per +snapshot: a series already in the target keeps its overrides, so an occurrence +changed since keeps its earlier copy rather than gaining a second one. That re-encode is sampled where the reminder will actually *fire*, not at `DTSTART` (`importedAllDayReminderDate`). An imported series' `DTSTART` is only an From d5079f0618df903fc97b625bb1935b34bbc294cd Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Sat, 14 Nov 2026 01:23:45 +0100 Subject: [PATCH 06/16] fix(#147, #325): review round 1 - overrides per calendar, RDATE-only series in files, chosen colours kept, copy row stays while running --- .../data/calendar/CalendarDataSource.kt | 7 ++-- .../data/calendar/CalendarRepositoryImpl.kt | 6 +++- .../calendula/data/calendar/Projections.kt | 2 ++ .../calendula/domain/ics/CalendarRows.kt | 28 +++++++++------ .../calendula/ui/calendars/BackupScreen.kt | 3 +- .../calendula/ui/calendars/CopyEventsSheet.kt | 4 ++- .../ui/calendars/CopyEventsViewModel.kt | 5 ++- .../calendula/domain/ics/CalendarRowsTest.kt | 35 +++++++++++++++++++ docs/ARCHITECTURE.md | 6 ++-- 9 files changed, 78 insertions(+), 18 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt index 5de0f22f..5ee27e55 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt @@ -794,8 +794,11 @@ class AndroidCalendarDataSource @Inject constructor( val calendarId = getLong(EventExportProjection.IDX_CALENDAR_ID) val calendar = calendars[calendarId] // Some adapters stamp the calendar's colour onto every row; that is no - // colour of the event's own and would pin it in a copy. - val color = getIntOrNull(EventExportProjection.IDX_EVENT_COLOR)?.takeIf { it != calendar?.color } + // colour of the event's own and would pin it in a copy. A palette key + // means it was chosen. + val color = getIntOrNull(EventExportProjection.IDX_EVENT_COLOR)?.takeIf { + it != calendar?.color || !getString(EventExportProjection.IDX_EVENT_COLOR_KEY).isNullOrEmpty() + } val mapped = event(calendar?.displayName).copy(color = color) val originalId = getLongOrNull(EventExportProjection.IDX_ORIGINAL_ID) val originalSyncId = getString(EventExportProjection.IDX_ORIGINAL_SYNC_ID) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt index f2f7190c..3945c5f6 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt @@ -252,7 +252,11 @@ class CalendarRepositoryImpl @Inject constructor( } override suspend fun exportEvents(calendarIds: Set) = withContext(io) { - flattenOverrides(dataSource.calendarRows(calendarIds, allDayReminderTimeMinutes()), ::formatExdateStamp) + flattenOverrides( + rows = dataSource.calendarRows(calendarIds, allDayReminderTimeMinutes()), + exdateStamp = ::formatExdateStamp, + keepsRecurrenceDates = false, + ) } override suspend fun copyEvents( diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/Projections.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/Projections.kt index 0d092e04..6931d31d 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/Projections.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/Projections.kt @@ -184,6 +184,7 @@ internal object EventExportProjection { CalendarContract.Events.ORIGINAL_INSTANCE_TIME, CalendarContract.Events.RDATE, CalendarContract.Events.ACCESS_LEVEL, + CalendarContract.Events.EVENT_COLOR_KEY, ) const val IDX_ID = 0 @@ -208,6 +209,7 @@ internal object EventExportProjection { const val IDX_ORIGINAL_INSTANCE_TIME = 19 const val IDX_RDATE = 20 const val IDX_ACCESS_LEVEL = 21 + const val IDX_EVENT_COLOR_KEY = 22 } /** diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt index 85963527..91ec0035 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt @@ -52,27 +52,33 @@ data class CalendarRows( * occurrence missing its series, never a series missing an occurrence. * * [exdateStamp] formats an occurrence as an `EXDATE` entry in the provider's - * shape, the same one Calendula's own exclusions use. + * shape, the same one Calendula's own exclusions use. [keepsRecurrenceDates] is + * false where the output can't carry `RDATE` (an `.ics` file): a series that + * repeats by listed dates alone then reads as the one-off it will be written as, + * and its overrides are left alone rather than excluded from nothing. A + * cancelled series' modified occurrences aren't brought back to life either. */ fun flattenOverrides( rows: CalendarRows, exdateStamp: (occurrenceMillis: Long, isAllDay: Boolean) -> String, + keepsRecurrenceDates: Boolean = true, ): List { val byId = rows.series.associateBy { it.eventId } // Sync ids are only unique within an account, so the link is per calendar. val bySyncId = rows.series.filter { it.syncId != null }.associateBy { it.calendarId to it.syncId } val excluded = mutableMapOf>() - val detached = mutableListOf() + val detached = mutableListOf>() for (override in rows.overrides) { val parent = override.originalId?.let(byId::get)?.takeIf { it.calendarId == override.calendarId } ?: override.originalSyncId?.let { bySyncId[override.calendarId to it] } ?: continue // An exception to a one-off overrides nothing a plain event could carry. - if (!parent.event.recurs) continue + val recurs = if (keepsRecurrenceDates) parent.event.recurs else !parent.event.recurrenceRule.isNullOrBlank() + if (!recurs) continue val occurrence = override.originalInstance.toEpochMilliseconds() excluded.getOrPut(parent.eventId) { mutableListOf() } += exdateStamp(occurrence, parent.event.isAllDay) - if (override.isCancelled) continue - detached += override.event.copy( + if (override.isCancelled || parent.event.status == EventStatus.Cancelled) continue + detached += override.calendarId to override.event.copy( uid = "$occurrence-${parent.event.uid}", recurrenceRule = null, recurrenceDates = null, @@ -80,9 +86,11 @@ fun flattenOverrides( overrideOf = parent.event.uid, ) } - // Two exception rows for one occurrence would derive the same UID. - return detached.distinctBy { it.uid } + rows.series.map { s -> - val extra = excluded[s.eventId].orEmpty() - if (extra.isEmpty()) s.event else s.event.copy(exDates = (s.event.exDates + extra).distinct()) - } + // Two exception rows for one occurrence would derive the same UID; the same + // series in two calendars legitimately does. + return detached.distinctBy { (calendarId, event) -> calendarId to event.uid }.map { it.second } + + rows.series.map { s -> + val extra = excluded[s.eventId].orEmpty() + if (extra.isEmpty()) s.event else s.event.copy(exDates = (s.event.exDates + extra).distinct()) + } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt index 03f4c77a..4e68c341 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt @@ -323,7 +323,8 @@ private fun BackupContent( leading = { LeadingAvatar(Icons.Default.FileUpload) }, onClick = onRestoreClick, ) - if (canCopy) { + // A running or finished copy keeps its row, the way back to its sheet. + if (canCopy || copyRun != CopyRunState.Idle) { GroupedRow( title = stringResource(R.string.calendars_copy_action), summary = when (copyRun) { diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt index f99c419d..c17629d6 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt @@ -213,7 +213,9 @@ private fun CopySummary(run: CopyRunState.Done) { ) Row(horizontalArrangement = Arrangement.spacedBy(24.dp)) { CopyCount(stringResource(R.string.import_done_added_label), summary.imported) - CopyCount(stringResource(R.string.import_done_skipped_label), summary.skippedDuplicate) + if (summary.skippedDuplicate > 0) { + CopyCount(stringResource(R.string.import_done_skipped_label), summary.skippedDuplicate) + } if (summary.failed > 0) CopyCount(stringResource(R.string.import_done_failed_label), summary.failed) } if (summary.skippedDuplicate > 0) CopyNote(stringResource(R.string.import_done_dedup_note)) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt index 32bcbd34..602df3b8 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt @@ -80,7 +80,10 @@ class CopyEventsViewModel @Inject constructor( job = viewModelScope.launch { try { val summary = repository.copyEvents(source, target) { done, total -> - _run.value = CopyRunState.Running(done, total) + // About every half percent: thousands of inserts needn't mean thousands of frames. + if (done == 0 || done == total || done % (total / 200).coerceAtLeast(1) == 0) { + _run.value = CopyRunState.Running(done, total) + } } _run.value = CopyRunState.Done(summary) } catch (e: CancellationException) { diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt index 172baedd..1c0fe9f7 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt @@ -185,4 +185,39 @@ class CalendarRowsTest { assertThat(IcsParser().parse(text).events.single().overrideOf).isEqualTo("s;1") } + + @Test + fun `a file can't carry RDATE, so an RDATE-only series keeps its overrides out of it`() { + val rows = CalendarRows( + listOf(MasterRow(1, 1, null, event("s").copy(recurrenceDates = "20260112T090000Z"))), + listOf(OverrideRow(1, 1, null, occurrence(1), event("x"))), + ) + + val flat = flattenOverrides(rows, ::formatExdateStamp, keepsRecurrenceDates = false) + assertThat(flat.map { it.uid }).containsExactly("s") + assertThat(flat.single().exDates).isEmpty() + } + + @Test + fun `a cancelled series' moved occurrence isn't brought back`() { + val flat = flatten( + listOf(series("s", status = EventStatus.Cancelled)), + listOf(OverrideRow(1, 1, null, occurrence(1), event("x"))), + ) + + assertThat(flat.map { it.uid }).containsExactly("s") + } + + @Test + fun `the same series in two calendars keeps each calendar's moved occurrence`() { + val flat = flatten( + listOf(series("s", id = 1, calendar = 1), series("s", id = 2, calendar = 2)), + listOf( + OverrideRow(1, 1, null, occurrence(1), event("x")), + OverrideRow(2, 2, null, occurrence(1), event("x")), + ), + ) + + assertThat(flat.count { it.overrideOf == "s" }).isEqualTo(2) + } } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index b13f037b..9a5972a9 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -508,8 +508,10 @@ same in every backup, and it carries the series UID as `X-CALENDULA-OVERRIDE-OF` `importEvents` skips such an occurrence wherever its series already is — that series there has the override itself — so restoring into the calendar a backup came from adds nothing twice, while a restore into an empty one gets both. -Exceptions whose series isn't among the rows are left out, and sync ids link -only within their own calendar. Backups made before this carry no exceptions +Exceptions whose series isn't among the rows are left out, a cancelled +series' moved occurrences stay cancelled, and sync ids link only within their +own calendar. A file can't carry `RDATE`, so a backup treats a series that +repeats by listed dates alone as the one-off it writes it as. Backups made before this carry no exceptions and restore exactly as before. **Copying a calendar.** Backup & restore → Copy events (#325) runs the source's From 0a36a6d28746619369d3d9e990dd06f9be0997fe Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Sat, 14 Nov 2026 01:32:21 +0100 Subject: [PATCH 07/16] fix(#147, #325): review round 2 - empty sync-id masters kept, series held when its occurrence fails, declined invites not copied --- .../data/calendar/CalendarDataSource.kt | 17 +++++---- .../data/calendar/CalendarRepositoryImpl.kt | 19 ++++++---- .../calendula/data/calendar/Projections.kt | 2 ++ .../calendula/domain/ics/CalendarCopy.kt | 4 +-- .../calendula/domain/ics/CalendarRows.kt | 13 +++---- .../ui/calendars/CalendarsViewModel.kt | 2 +- .../calendula/ui/calendars/CopyEventsSheet.kt | 20 +++++------ .../ui/calendars/CopyEventsViewModel.kt | 1 - .../calendar/CalendarRepositoryImplTest.kt | 35 +++++++++++++++++++ .../calendula/domain/ics/CalendarRowsTest.kt | 19 ++++------ docs/ARCHITECTURE.md | 9 +++-- 11 files changed, 88 insertions(+), 53 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt index 5ee27e55..cbc82e53 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt @@ -793,31 +793,30 @@ class AndroidCalendarDataSource @Inject constructor( forEachExportRow(selection, allDayReminderTimeMinutes) { event -> val calendarId = getLong(EventExportProjection.IDX_CALENDAR_ID) val calendar = calendars[calendarId] - // Some adapters stamp the calendar's colour onto every row; that is no - // colour of the event's own and would pin it in a copy. A palette key - // means it was chosen. + // An adapter may stamp the calendar colour on every row; a palette key means it was chosen. val color = getIntOrNull(EventExportProjection.IDX_EVENT_COLOR)?.takeIf { it != calendar?.color || !getString(EventExportProjection.IDX_EVENT_COLOR_KEY).isNullOrEmpty() } val mapped = event(calendar?.displayName).copy(color = color) val originalId = getLongOrNull(EventExportProjection.IDX_ORIGINAL_ID) - val originalSyncId = getString(EventExportProjection.IDX_ORIGINAL_SYNC_ID) - // An empty ORIGINAL_SYNC_ID still marks an exception, one that can't be linked. - if (originalId == null && originalSyncId == null) { + val originalSyncId = getString(EventExportProjection.IDX_ORIGINAL_SYNC_ID)?.takeIf { it.isNotEmpty() } + val originalInstance = getLongOrNull(EventExportProjection.IDX_ORIGINAL_INSTANCE_TIME) + if (originalId == null && originalSyncId == null && originalInstance == null) { series += MasterRow( eventId = getLong(EventExportProjection.IDX_ID), calendarId = calendarId, syncId = getString(EventExportProjection.IDX_SYNC_ID)?.takeIf { it.isNotEmpty() }, event = mapped, + declined = getIntOrNull(EventExportProjection.IDX_SELF_ATTENDEE_STATUS) == + CalendarContract.Attendees.ATTENDEE_STATUS_DECLINED, ) } else { // An exception without its occurrence time can't name what it replaces. - val originalInstance = getLongOrNull(EventExportProjection.IDX_ORIGINAL_INSTANCE_TIME) - ?: return@forEachExportRow + if (originalInstance == null) return@forEachExportRow overrides += OverrideRow( calendarId = calendarId, originalId = originalId, - originalSyncId = originalSyncId.takeIf { !it.isNullOrEmpty() }, + originalSyncId = originalSyncId, originalInstance = originalInstance.toKotlinInstantFromEpochMillis(), event = mapped, ) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt index 3945c5f6..9d85a350 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt @@ -252,10 +252,11 @@ class CalendarRepositoryImpl @Inject constructor( } override suspend fun exportEvents(calendarIds: Set) = withContext(io) { + // A file can't carry RDATE: such a series is written as the one-off it reads as. + val rows = dataSource.calendarRows(calendarIds, allDayReminderTimeMinutes()) flattenOverrides( - rows = dataSource.calendarRows(calendarIds, allDayReminderTimeMinutes()), - exdateStamp = ::formatExdateStamp, - keepsRecurrenceDates = false, + rows.copy(series = rows.series.map { it.copy(event = it.event.copy(recurrenceDates = null)) }), + ::formatExdateStamp, ) } @@ -271,11 +272,9 @@ class CalendarRepositoryImpl @Inject constructor( ) } onProgress(0, events.size) - // Checked between events, so cancelling stops the copy; a plain import - // keeps running to the end of its file. val context = currentCoroutineContext() return importEvents(targetCalendarId, events) { done -> - context.ensureActive() + if (done < events.size) context.ensureActive() onProgress(done, events.size) } } @@ -296,6 +295,9 @@ class CalendarRepositoryImpl @Inject constructor( var skipped = 0 var failed = 0 var notAttempted = 0 + // Series whose standalone occurrence didn't land: inserted, they would + // exclude it for good, since a re-run skips it next to its series. + val held = mutableSetOf() for ((index, event) in events.withIndex()) { if (index > 0) onProgress(index) // A known UID means the event is already in this calendar — skip, @@ -304,6 +306,10 @@ class CalendarRepositoryImpl @Inject constructor( skipped++ continue } + if (event.uid != null && event.uid in held) { + failed++ + continue + } try { dataSource.insertImportedEvent(event, targetCalendarId, allDayMinutes, palette) imported++ @@ -325,6 +331,7 @@ class CalendarRepositoryImpl @Inject constructor( // rest of the file — foreign exports do carry rows it rejects // outright (a malformed RRULE throws straight out of insert). failed++ + event.overrideOf?.let(held::add) Log.w(TAG, "Skipped an unimportable event", e) } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/Projections.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/Projections.kt index 6931d31d..eeed00d7 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/Projections.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/Projections.kt @@ -185,6 +185,7 @@ internal object EventExportProjection { CalendarContract.Events.RDATE, CalendarContract.Events.ACCESS_LEVEL, CalendarContract.Events.EVENT_COLOR_KEY, + CalendarContract.Events.SELF_ATTENDEE_STATUS, ) const val IDX_ID = 0 @@ -210,6 +211,7 @@ internal object EventExportProjection { const val IDX_RDATE = 20 const val IDX_ACCESS_LEVEL = 21 const val IDX_EVENT_COLOR_KEY = 22 + const val IDX_SELF_ATTENDEE_STATUS = 23 } /** diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt index 2531c5f0..a03c260c 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt @@ -7,7 +7,7 @@ import kotlin.time.Duration.Companion.days * The events a calendar copy (#325) inserts into its target, in the shape * `importEvents` takes: the source's rows flattened as [flattenOverrides] does * for a backup, minus cancelled series and one-offs, which would arrive live - * (an insert can't be cancelled). Attendees and organizer are never read. + * (an insert can't be cancelled), and declined invitations. Attendees and organizer are never read. * * Idempotent per snapshot: `importEvents` skips a UID the target already holds, * and an [IcsEvent.overrideOf] occurrence whose series it holds, so a re-run @@ -18,7 +18,7 @@ fun planCalendarCopy( rows: CalendarRows, exdateStamp: (occurrenceMillis: Long, isAllDay: Boolean) -> String, ): List { - val live = rows.copy(series = rows.series.filterNot { it.event.status == EventStatus.Cancelled }) + val live = rows.copy(series = rows.series.filterNot { it.event.status == EventStatus.Cancelled || it.declined }) return flattenOverrides(live, exdateStamp).map { it.toParsedIcsEvent() } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt index 91ec0035..fa5d4810 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt @@ -12,6 +12,8 @@ data class MasterRow( val calendarId: Long, val syncId: String?, val event: IcsEvent, + /** The user declined this invitation. */ + val declined: Boolean = false, ) /** @@ -52,16 +54,12 @@ data class CalendarRows( * occurrence missing its series, never a series missing an occurrence. * * [exdateStamp] formats an occurrence as an `EXDATE` entry in the provider's - * shape, the same one Calendula's own exclusions use. [keepsRecurrenceDates] is - * false where the output can't carry `RDATE` (an `.ics` file): a series that - * repeats by listed dates alone then reads as the one-off it will be written as, - * and its overrides are left alone rather than excluded from nothing. A - * cancelled series' modified occurrences aren't brought back to life either. + * shape, the same one Calendula's own exclusions use. A cancelled series' + * modified occurrences stay cancelled. */ fun flattenOverrides( rows: CalendarRows, exdateStamp: (occurrenceMillis: Long, isAllDay: Boolean) -> String, - keepsRecurrenceDates: Boolean = true, ): List { val byId = rows.series.associateBy { it.eventId } // Sync ids are only unique within an account, so the link is per calendar. @@ -73,8 +71,7 @@ fun flattenOverrides( ?: override.originalSyncId?.let { bySyncId[override.calendarId to it] } ?: continue // An exception to a one-off overrides nothing a plain event could carry. - val recurs = if (keepsRecurrenceDates) parent.event.recurs else !parent.event.recurrenceRule.isNullOrBlank() - if (!recurs) continue + if (!parent.event.recurs) continue val occurrence = override.originalInstance.toEpochMilliseconds() excluded.getOrPut(parent.eventId) { mutableListOf() } += exdateStamp(occurrence, parent.event.isAllDay) if (override.isCancelled || parent.event.status == EventStatus.Cancelled) continue diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt index 5ebad9b6..172269ed 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt @@ -143,7 +143,7 @@ class CalendarsViewModel @Inject constructor( uri = uri, content = IcsWriter().writeCalendar(events, Clock.System.now(), name), ) - events.size + events.count { it.overrideOf == null } } BackupResult.Success(count) } catch (e: CancellationException) { diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt index c17629d6..3f41aaea 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt @@ -6,13 +6,13 @@ import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding -import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.LinearWavyProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -63,6 +63,13 @@ fun CopyEventsSheet( title = stringResource(R.string.calendars_copy_action), onDismiss = onDismiss, predictiveBack = true, + actions = { + if (!running) { + TextButton(onClick = onStart, enabled = source != null && target != null) { + Text(stringResource(R.string.calendars_copy_start)) + } + } + }, ) { GroupedHint(stringResource(R.string.calendars_copy_hint), style = MaterialTheme.typography.bodySmall) when (calendars) { @@ -78,7 +85,7 @@ fun CopyEventsSheet( } is CopyCalendars.Ready -> Unit } - if (sources.isEmpty() && !running) { + if (sources.isEmpty() && run == CopyRunState.Idle) { GroupedHint(stringResource(R.string.calendars_copy_none)) return@FullScreenPicker } @@ -110,15 +117,6 @@ fun CopyEventsSheet( ) CopyRunState.Idle -> Unit } - if (!running) { - Button( - onClick = onStart, - enabled = source != null && target != null, - modifier = Modifier.fillMaxWidth(), - ) { - Text(stringResource(R.string.calendars_copy_start)) - } - } } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt index 602df3b8..6144c9c0 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt @@ -80,7 +80,6 @@ class CopyEventsViewModel @Inject constructor( job = viewModelScope.launch { try { val summary = repository.copyEvents(source, target) { done, total -> - // About every half percent: thousands of inserts needn't mean thousands of frames. if (done == 0 || done == total || done % (total / 200).coerceAtLeast(1) == 0) { _run.value = CopyRunState.Running(done, total) } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt index 53fb8c87..6f81698a 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt @@ -1046,6 +1046,41 @@ class CalendarRepositoryImplTest { assertThat(summary.skippedDuplicate).isEqualTo(2) } + @Test + fun `a series waits for a standalone occurrence that didn't land`( + @TempDir tempDir: Path, + ) = runTest { + val fake = FakeCalendarDataSource().apply { failingImportSummaries += "moved" } + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) + + val summary = repo.importEvents( + 3L, + listOf(parsedEvent("1-s", summary = "moved").copy(overrideOf = "s"), parsedEvent("s"), parsedEvent("t")), + ) + + assertThat(fake.importedEvents.map { it.first.uid }).containsExactly("t") + assertThat(summary.failed).isEqualTo(2) + } + + @Test + fun `a backup writes an RDATE-only series as the one-off a file can hold`( + @TempDir tempDir: Path, + ) = runTest { + val start = Instant.parse("2026-01-05T09:00:00Z") + val event = IcsEvent("s", "S", start, Instant.parse("2026-01-05T10:00:00Z"), false, "UTC", recurrenceDates = "20260112T090000Z") + val fake = FakeCalendarDataSource().apply { + calendarRowsResult = CalendarRows( + listOf(MasterRow(1, 1, null, event)), + listOf(OverrideRow(1, 1, null, start, event.copy(recurrenceDates = null))), + ) + } + + val exported = testRepository(fake, tempDir, Dispatchers.Unconfined).exportEvents(setOf(1L)) + + assertThat(exported.map { it.uid }).containsExactly("s") + assertThat(exported.single().recurrenceDates).isNull() + } + private fun parsedEvent(uid: String?, summary: String = "E") = de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent( uid = uid, diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt index 1c0fe9f7..11dab970 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt @@ -186,18 +186,6 @@ class CalendarRowsTest { assertThat(IcsParser().parse(text).events.single().overrideOf).isEqualTo("s;1") } - @Test - fun `a file can't carry RDATE, so an RDATE-only series keeps its overrides out of it`() { - val rows = CalendarRows( - listOf(MasterRow(1, 1, null, event("s").copy(recurrenceDates = "20260112T090000Z"))), - listOf(OverrideRow(1, 1, null, occurrence(1), event("x"))), - ) - - val flat = flattenOverrides(rows, ::formatExdateStamp, keepsRecurrenceDates = false) - assertThat(flat.map { it.uid }).containsExactly("s") - assertThat(flat.single().exDates).isEmpty() - } - @Test fun `a cancelled series' moved occurrence isn't brought back`() { val flat = flatten( @@ -220,4 +208,11 @@ class CalendarRowsTest { assertThat(flat.count { it.overrideOf == "s" }).isEqualTo(2) } + + @Test + fun `a copy leaves declined invitations out`() { + val rows = CalendarRows(listOf(series("d").copy(declined = true), series("k", id = 2)), emptyList()) + + assertThat(planCalendarCopy(rows, ::formatExdateStamp).map { it.uid }).containsExactly("k") + } } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 9a5972a9..f5a319ba 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -507,7 +507,10 @@ times. Its UID is derived from the series UID and the occurrence, so it is the same in every backup, and it carries the series UID as `X-CALENDULA-OVERRIDE-OF`. `importEvents` skips such an occurrence wherever its series already is — that series there has the override itself — so restoring into the calendar a backup -came from adds nothing twice, while a restore into an empty one gets both. +came from adds nothing twice, while a restore into an empty one gets both. If +the standalone occurrence fails to insert, its series is held back too (counted +as not added), since inserted with the occurrence excluded it would make every +re-run skip the occurrence for good. Exceptions whose series isn't among the rows are left out, a cancelled series' moved occurrences stay cancelled, and sync ids link only within their own calendar. A file can't carry `RDATE`, so a backup treats a series that @@ -518,8 +521,8 @@ and restore exactly as before. flattened rows straight into `importEvents`, so the UID dedup makes a re-run skip what landed before. It skips the `.ics` text: the writer pins a timed one-off to UTC and carries no colour, visibility or `RDATE`; the direct mapping keeps them. -Attendees and organizer are never read, and cancelled events are left out (an -insert can't be cancelled; it would arrive live). A re-run is idempotent per +Attendees and organizer are never read, and cancelled events and declined +invitations are left out (an insert can't be cancelled; it would arrive live). A re-run is idempotent per snapshot: a series already in the target keeps its overrides, so an occurrence changed since keeps its earlier copy rather than gaining a second one. From 10208a332ebfeac0d688dd3d27f7b01de7490a36 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Sat, 14 Nov 2026 01:41:31 +0100 Subject: [PATCH 08/16] fix(#147, #325): review round 3 - a failed moved occurrence stays at its old time, declined occurrences not copied, unlinked rows kept --- .../data/calendar/CalendarDataSource.kt | 13 ++++--- .../data/calendar/CalendarRepositoryImpl.kt | 23 ++++++----- .../calendula/domain/ics/CalendarCopy.kt | 11 +++++- .../calendula/domain/ics/CalendarRows.kt | 3 ++ .../calendula/domain/ics/IcsEvent.kt | 2 + .../calendula/domain/ics/IcsParser.kt | 5 +++ .../calendula/domain/ics/IcsWriter.kt | 1 + .../calendula/ui/calendars/BackupScreen.kt | 38 ++++++++++--------- .../calendula/ui/calendars/BackupUiState.kt | 3 +- .../calendula/ui/calendars/CopyEventsSheet.kt | 5 ++- app/src/main/res/values/strings.xml | 2 +- .../calendar/CalendarRepositoryImplTest.kt | 12 ++++-- .../calendula/domain/ics/CalendarRowsTest.kt | 18 ++++++++- docs/ARCHITECTURE.md | 10 ++--- 14 files changed, 98 insertions(+), 48 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt index cbc82e53..6ee39d62 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt @@ -798,27 +798,30 @@ class AndroidCalendarDataSource @Inject constructor( it != calendar?.color || !getString(EventExportProjection.IDX_EVENT_COLOR_KEY).isNullOrEmpty() } val mapped = event(calendar?.displayName).copy(color = color) + val declined = getIntOrNull(EventExportProjection.IDX_SELF_ATTENDEE_STATUS) == + CalendarContract.Attendees.ATTENDEE_STATUS_DECLINED val originalId = getLongOrNull(EventExportProjection.IDX_ORIGINAL_ID) val originalSyncId = getString(EventExportProjection.IDX_ORIGINAL_SYNC_ID)?.takeIf { it.isNotEmpty() } - val originalInstance = getLongOrNull(EventExportProjection.IDX_ORIGINAL_INSTANCE_TIME) - if (originalId == null && originalSyncId == null && originalInstance == null) { + // Without a link the provider shows the row as an event of its own. + if (originalId == null && originalSyncId == null) { series += MasterRow( eventId = getLong(EventExportProjection.IDX_ID), calendarId = calendarId, syncId = getString(EventExportProjection.IDX_SYNC_ID)?.takeIf { it.isNotEmpty() }, event = mapped, - declined = getIntOrNull(EventExportProjection.IDX_SELF_ATTENDEE_STATUS) == - CalendarContract.Attendees.ATTENDEE_STATUS_DECLINED, + declined = declined, ) } else { // An exception without its occurrence time can't name what it replaces. - if (originalInstance == null) return@forEachExportRow + val originalInstance = getLongOrNull(EventExportProjection.IDX_ORIGINAL_INSTANCE_TIME) + ?: return@forEachExportRow overrides += OverrideRow( calendarId = calendarId, originalId = originalId, originalSyncId = originalSyncId, originalInstance = originalInstance.toKotlinInstantFromEpochMillis(), event = mapped, + declined = declined, ) } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt index 9d85a350..d2aac8a9 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt @@ -295,9 +295,9 @@ class CalendarRepositoryImpl @Inject constructor( var skipped = 0 var failed = 0 var notAttempted = 0 - // Series whose standalone occurrence didn't land: inserted, they would - // exclude it for good, since a re-run skips it next to its series. - val held = mutableSetOf() + // Occurrences whose standalone copy didn't land, by series UID: the series + // keeps them instead of excluding them for good. + val unexcluded = mutableMapOf>() for ((index, event) in events.withIndex()) { if (index > 0) onProgress(index) // A known UID means the event is already in this calendar — skip, @@ -306,12 +306,8 @@ class CalendarRepositoryImpl @Inject constructor( skipped++ continue } - if (event.uid != null && event.uid in held) { - failed++ - continue - } try { - dataSource.insertImportedEvent(event, targetCalendarId, allDayMinutes, palette) + dataSource.insertImportedEvent(event.keeping(unexcluded), targetCalendarId, allDayMinutes, palette) imported++ } catch (e: CancellationException) { throw e @@ -331,7 +327,9 @@ class CalendarRepositoryImpl @Inject constructor( // rest of the file — foreign exports do carry rows it rejects // outright (a malformed RRULE throws straight out of insert). failed++ - event.overrideOf?.let(held::add) + if (event.overrideOf != null && event.overrideAt != null) { + unexcluded.getOrPut(event.overrideOf) { mutableListOf() } += event.overrideAt + } Log.w(TAG, "Skipped an unimportable event", e) } } @@ -424,3 +422,10 @@ private fun Flow.reQuery(block: suspend () -> T): Flow = flow { */ private fun ParsedIcsEvent.isAlreadyIn(existing: Set): Boolean = (uid != null && uid in existing) || (overrideOf != null && overrideOf in existing) + +/** This series without the exclusions of [unexcluded] occurrences whose standalone copy failed. */ +private fun ParsedIcsEvent.keeping(unexcluded: Map>): ParsedIcsEvent { + val kept = uid?.let(unexcluded::get) ?: return this + val stamps = kept.map { formatExdateStamp(it.toEpochMilliseconds(), isAllDay) }.toSet() + return copy(exDates = exDates.filterNot { it in stamps }) +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt index a03c260c..502e90d8 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt @@ -7,7 +7,7 @@ import kotlin.time.Duration.Companion.days * The events a calendar copy (#325) inserts into its target, in the shape * `importEvents` takes: the source's rows flattened as [flattenOverrides] does * for a backup, minus cancelled series and one-offs, which would arrive live - * (an insert can't be cancelled), and declined invitations. Attendees and organizer are never read. + * (an insert can't be cancelled), and declined invitations and occurrences. Attendees and organizer are never read. * * Idempotent per snapshot: `importEvents` skips a UID the target already holds, * and an [IcsEvent.overrideOf] occurrence whose series it holds, so a re-run @@ -18,7 +18,13 @@ fun planCalendarCopy( rows: CalendarRows, exdateStamp: (occurrenceMillis: Long, isAllDay: Boolean) -> String, ): List { - val live = rows.copy(series = rows.series.filterNot { it.event.status == EventStatus.Cancelled || it.declined }) + val live = CalendarRows( + series = rows.series.filterNot { it.event.status == EventStatus.Cancelled || it.declined }, + // A declined occurrence is as good as deleted here. + overrides = rows.overrides.map { + if (it.declined) it.copy(event = it.event.copy(status = EventStatus.Cancelled)) else it + }, + ) return flattenOverrides(live, exdateStamp).map { it.toParsedIcsEvent() } } @@ -48,5 +54,6 @@ fun IcsEvent.toParsedIcsEvent(): ParsedIcsEvent = ParsedIcsEvent( accessLevel = accessLevel, color = color, overrideOf = overrideOf, + overrideAt = overrideAt, exDates = if (recurs) exDates.filter { it.isNotBlank() }.distinct() else emptyList(), ) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt index fa5d4810..56ab2cbb 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt @@ -27,6 +27,8 @@ data class OverrideRow( val originalSyncId: String?, val originalInstance: Instant, val event: IcsEvent, + /** The user declined this occurrence. */ + val declined: Boolean = false, ) { val isCancelled: Boolean get() = event.status == EventStatus.Cancelled } @@ -81,6 +83,7 @@ fun flattenOverrides( recurrenceDates = null, exDates = emptyList(), overrideOf = parent.event.uid, + overrideAt = override.originalInstance, ) } // Two exception rows for one occurrence would derive the same UID; the same diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsEvent.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsEvent.kt index a24f8673..9cb23a55 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsEvent.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsEvent.kt @@ -48,6 +48,8 @@ data class IcsEvent( * UID of the series it replaces an occurrence of, as `X-CALENDULA-OVERRIDE-OF`. */ val overrideOf: String? = null, + /** The occurrence of [overrideOf] this event replaces, as `X-CALENDULA-OVERRIDE-AT`. */ + val overrideAt: Instant? = null, ) /** Whether this is a series: by rule, or by listed dates alone. */ diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsParser.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsParser.kt index 0a48e44f..b4e15bcf 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsParser.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsParser.kt @@ -52,6 +52,8 @@ data class ParsedIcsEvent( * already is, since the series there carries its own override. */ val overrideOf: String? = null, + /** The occurrence of [overrideOf] this event replaces (`X-CALENDULA-OVERRIDE-AT`). */ + val overrideAt: Instant? = null, /** The provider's raw `RDATE`, only set by a calendar copy. */ val recurrenceDates: String? = null, val accessLevel: AccessLevel = AccessLevel.Default, @@ -224,6 +226,7 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault val exDateLines = mutableListOf() var skipAsOverride = false var overrideOf: String? = null + var overrideAt: Instant? = null var i = 0 while (i < body.size) { @@ -253,6 +256,7 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault "RECURRENCE-ID" -> skipAsOverride = true "ATTENDEE" -> warnings.add(IcsParseWarning.AttendeesIgnored) "X-CALENDULA-OVERRIDE-OF" -> overrideOf = unescapeText(line.value).trim().ifEmpty { null } + "X-CALENDULA-OVERRIDE-AT" -> overrideAt = parseBasicDateTime(line.value.trim())?.toInstant(TimeZone.UTC) "X-CALENDULA-CALENDAR" -> calendarName = unescapeText(line.value).trim().ifEmpty { calendarName } // Fossify names the source calendar per event; it never writes @@ -313,6 +317,7 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault }, isTask = isTask, overrideOf = overrideOf, + overrideAt = overrideAt, ) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsWriter.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsWriter.kt index 833c0c22..a0a039be 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsWriter.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsWriter.kt @@ -58,6 +58,7 @@ class IcsWriter(private val prodId: String = ICS_PROD_ID) { ?.let { add("X-CALENDULA-CALENDAR:${escapeText(it)}") } event.overrideOf?.takeIf { it.isNotBlank() } ?.let { add("X-CALENDULA-OVERRIDE-OF:${escapeText(it)}") } + event.overrideAt?.let { add("X-CALENDULA-OVERRIDE-AT:${it.toUtcBasic()}") } event.reminderMinutes.filter { it >= 0 }.distinct().forEach { minutes -> appendAlarm(minutes, event.summary) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt index 4e68c341..3aad783d 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt @@ -305,6 +305,7 @@ private fun BackupContent( leading = { LeadingAvatar(Icons.Default.FileUpload) }, onClick = onRestoreClick, ) + if (copyRun != CopyRunState.Idle) CopyEventsRow(copyRun, Position.Alone, onCopy) return } @@ -324,23 +325,7 @@ private fun BackupContent( onClick = onRestoreClick, ) // A running or finished copy keeps its row, the way back to its sheet. - if (canCopy || copyRun != CopyRunState.Idle) { - GroupedRow( - title = stringResource(R.string.calendars_copy_action), - summary = when (copyRun) { - is CopyRunState.Running -> copyProgressText(copyRun) - is CopyRunState.Done -> stringResource( - if (copyRun.stopped) R.string.calendars_copy_stopped_title else R.string.calendars_copy_done, - ) - CopyRunState.Cancelled -> stringResource(R.string.calendars_copy_cancelled) - CopyRunState.Failed -> stringResource(R.string.calendars_copy_failed) - CopyRunState.Idle -> stringResource(R.string.calendars_copy_summary) - }, - position = Position.Middle, - leading = { LeadingAvatar(Icons.Default.ContentCopy) }, - onClick = onCopy, - ) - } + if (canCopy || copyRun != CopyRunState.Idle) CopyEventsRow(copyRun, Position.Middle, onCopy) GroupedRow( title = stringResource(R.string.calendars_auto_backup), summary = stringResource(R.string.calendars_auto_backup_hint), @@ -406,6 +391,25 @@ private fun BackupContent( } } +@Composable +private fun CopyEventsRow(copyRun: CopyRunState, position: Position, onClick: () -> Unit) { + GroupedRow( + title = stringResource(R.string.calendars_copy_action), + summary = when (copyRun) { + is CopyRunState.Running -> copyProgressText(copyRun) + is CopyRunState.Done -> stringResource( + if (copyRun.stopped) R.string.calendars_copy_stopped_title else R.string.calendars_copy_done, + ) + CopyRunState.Cancelled -> stringResource(R.string.calendars_copy_cancelled) + CopyRunState.Failed -> stringResource(R.string.calendars_copy_failed) + CopyRunState.Idle -> stringResource(R.string.calendars_copy_summary) + }, + position = position, + leading = { LeadingAvatar(Icons.Default.ContentCopy) }, + onClick = onClick, + ) +} + /** * Choose which calendars to include in a one-time `.ics` export. Starts on the * calendars a backup covers by default, or on all of them when none is; the Export action opens the SAF save dialog and hands back diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiState.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiState.kt index f34c1619..55a70958 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiState.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupUiState.kt @@ -65,8 +65,9 @@ fun backupUiState(calendars: List): BackupUiState { */ fun copySources(calendars: List): List { val targets = calendars.filter { it.isEventTarget } + val onlyTarget = targets.singleOrNull()?.id if (targets.isEmpty()) return emptyList() - return calendars.filter { source -> source.isBackupCandidate && targets.any { it.id != source.id } } + return calendars.filter { it.isBackupCandidate && it.id != onlyTarget } } /** Calendars a copy from [sourceId] can write into: the import targets, minus the source itself. */ diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt index 3f41aaea..71e6450e 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt @@ -16,6 +16,7 @@ import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment @@ -52,9 +53,9 @@ fun CopyEventsSheet( onDismiss: () -> Unit, ) { val list = (calendars as? CopyCalendars.Ready)?.calendars.orEmpty() - val sources = copySources(list) + val sources = remember(list) { copySources(list) } val source = sources.firstOrNull { it.id == selection.sourceId } - val targets = copyTargets(list, source?.id) + val targets = remember(list, source?.id) { copyTargets(list, source?.id) } val target = targets.firstOrNull { it.id == selection.targetId } val running = run is CopyRunState.Running var picking by rememberSaveable { mutableStateOf(null) } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index c40971b5..9c8cf4a8 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -891,7 +891,7 @@ No calendar can take the imported events yet. Copy events Copy one calendar\'s events into another, for example to move off Google. - Copies every event, including repeating ones with the occurrences you changed or deleted. Guests and invitations stay behind, and the original calendar is left as it is. + Copies your events, including repeating ones with the occurrences you changed or deleted. Cancelled events and invitations you declined are left out, guests stay behind, and the original calendar is left as it is. From To Choose a calendar diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt index 6f81698a..0dd24eb1 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt @@ -1047,19 +1047,23 @@ class CalendarRepositoryImplTest { } @Test - fun `a series waits for a standalone occurrence that didn't land`( + fun `a series keeps an occurrence whose standalone copy didn't land`( @TempDir tempDir: Path, ) = runTest { val fake = FakeCalendarDataSource().apply { failingImportSummaries += "moved" } val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) + val at = Instant.parse("2026-01-12T09:00:00Z") val summary = repo.importEvents( 3L, - listOf(parsedEvent("1-s", summary = "moved").copy(overrideOf = "s"), parsedEvent("s"), parsedEvent("t")), + listOf( + parsedEvent("1-s", summary = "moved").copy(overrideOf = "s", overrideAt = at), + parsedEvent("s").copy(recurrenceRule = "FREQ=WEEKLY", exDates = listOf("20260112T090000Z", "20260119T090000Z")), + ), ) - assertThat(fake.importedEvents.map { it.first.uid }).containsExactly("t") - assertThat(summary.failed).isEqualTo(2) + assertThat(summary.failed).isEqualTo(1) + assertThat(fake.importedEvents.single().first.exDates).containsExactly("20260119T090000Z") } @Test diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt index 11dab970..d6fb3d40 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt @@ -181,9 +181,11 @@ class CalendarRowsTest { @Test fun `the override link survives the file`() { - val text = IcsWriter().writeCalendar(listOf(event("d").copy(overrideOf = "s;1")), start) + val text = IcsWriter().writeCalendar(listOf(event("d").copy(overrideOf = "s;1", overrideAt = occurrence(1))), start) - assertThat(IcsParser().parse(text).events.single().overrideOf).isEqualTo("s;1") + val parsed = IcsParser().parse(text).events.single() + assertThat(parsed.overrideOf).isEqualTo("s;1") + assertThat(parsed.overrideAt).isEqualTo(occurrence(1)) } @Test @@ -215,4 +217,16 @@ class CalendarRowsTest { assertThat(planCalendarCopy(rows, ::formatExdateStamp).map { it.uid }).containsExactly("k") } + + @Test + fun `a copy treats a declined occurrence as deleted`() { + val rows = CalendarRows( + listOf(series("s")), + listOf(OverrideRow(1, 1, null, occurrence(1), event("x"), declined = true)), + ) + + val plan = planCalendarCopy(rows, ::formatExdateStamp) + assertThat(plan.map { it.uid }).containsExactly("s") + assertThat(plan.single().exDates).containsExactly("20260112T090000Z") + } } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index f5a319ba..da369688 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -507,10 +507,10 @@ times. Its UID is derived from the series UID and the occurrence, so it is the same in every backup, and it carries the series UID as `X-CALENDULA-OVERRIDE-OF`. `importEvents` skips such an occurrence wherever its series already is — that series there has the override itself — so restoring into the calendar a backup -came from adds nothing twice, while a restore into an empty one gets both. If -the standalone occurrence fails to insert, its series is held back too (counted -as not added), since inserted with the occurrence excluded it would make every -re-run skip the occurrence for good. +came from adds nothing twice, while a restore into an empty one gets both. The +standalone event also names its occurrence (`X-CALENDULA-OVERRIDE-AT`); if it +fails to insert, the series is inserted without that exclusion, so the +occurrence stays at its original time rather than vanishing for good. Exceptions whose series isn't among the rows are left out, a cancelled series' moved occurrences stay cancelled, and sync ids link only within their own calendar. A file can't carry `RDATE`, so a backup treats a series that @@ -522,7 +522,7 @@ flattened rows straight into `importEvents`, so the UID dedup makes a re-run ski what landed before. It skips the `.ics` text: the writer pins a timed one-off to UTC and carries no colour, visibility or `RDATE`; the direct mapping keeps them. Attendees and organizer are never read, and cancelled events and declined -invitations are left out (an insert can't be cancelled; it would arrive live). A re-run is idempotent per +invitations are left out (a declined occurrence counts as deleted) (an insert can't be cancelled; it would arrive live). A re-run is idempotent per snapshot: a series already in the target keeps its overrides, so an occurrence changed since keeps its earlier copy rather than gaining a second one. From 041f8ec2f79d17a34d17b729b8f14e5616824f30 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Sat, 14 Nov 2026 01:50:22 +0100 Subject: [PATCH 09/16] fix(#147, #325): review round 4 - standalone occurrences imported first in any file order, copy sheet independent of the list state --- .../data/calendar/CalendarRepositoryImpl.kt | 6 ++- .../calendula/ui/calendars/BackupScreen.kt | 39 ++++++++++--------- .../ui/calendars/CalendarsViewModel.kt | 2 +- .../calendar/CalendarRepositoryImplTest.kt | 12 ++++++ docs/ARCHITECTURE.md | 4 +- 5 files changed, 40 insertions(+), 23 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt index d2aac8a9..18fc7098 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt @@ -298,7 +298,9 @@ class CalendarRepositoryImpl @Inject constructor( // Occurrences whose standalone copy didn't land, by series UID: the series // keeps them instead of excluding them for good. val unexcluded = mutableMapOf>() - for ((index, event) in events.withIndex()) { + // Standalone occurrences ahead of the series they were cut from, however the file is ordered. + val ordered = events.sortedBy { it.overrideOf == null } + for ((index, event) in ordered.withIndex()) { if (index > 0) onProgress(index) // A known UID means the event is already in this calendar — skip, // keeping a restore idempotent (no overwrite this pass). @@ -317,7 +319,7 @@ class CalendarRepositoryImpl @Inject constructor( Log.w(TAG, "Import stopped: the calendar is no longer writable", e) // A known UID would have been skipped whatever happened, so it is // no part of what a retry still has to import. - val remaining = events.drop(index) + val remaining = ordered.drop(index) val duplicates = remaining.count { it.isAlreadyIn(existing) } skipped += duplicates notAttempted = remaining.size - duplicates diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt index 3aad783d..adf6b33e 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt @@ -184,6 +184,24 @@ fun BackupScreen( } } + // Not gated on Ready: a running copy keeps its progress and Cancel whatever the list does. + if (showCopy) { + val calendars by copyViewModel.calendars.collectAsStateWithLifecycle() + val selection by copyViewModel.selection.collectAsStateWithLifecycle() + CopyEventsSheet( + calendars = calendars, + selection = selection, + run = copyRun, + onSelectSource = copyViewModel::setSource, + onSelectTarget = copyViewModel::setTarget, + onStart = copyViewModel::start, + onCancel = copyViewModel::cancel, + onDismiss = { + showCopy = false + copyViewModel.clearFinished() + }, + ) + } // Gated on Ready rather than resetting the flag when the state leaves it: // flipping it here would be a write during composition. (state as? BackupUiState.Ready)?.let { ready -> @@ -194,23 +212,6 @@ fun BackupScreen( onDismiss = { showExportPicker = false }, ) } - if (showCopy) { - val calendars by copyViewModel.calendars.collectAsStateWithLifecycle() - val selection by copyViewModel.selection.collectAsStateWithLifecycle() - CopyEventsSheet( - calendars = calendars, - selection = selection, - run = copyRun, - onSelectSource = copyViewModel::setSource, - onSelectTarget = copyViewModel::setTarget, - onStart = copyViewModel::start, - onCancel = copyViewModel::cancel, - onDismiss = { - showCopy = false - copyViewModel.clearFinished() - }, - ) - } if (showBackupCalendars) { AutoBackupCalendarPicker( calendars = ready.exportable, @@ -301,11 +302,11 @@ private fun BackupContent( GroupedHint(restoreSummary, style = MaterialTheme.typography.bodySmall) GroupedRow( title = stringResource(R.string.calendars_restore_action), - position = Position.Alone, + position = if (copyRun != CopyRunState.Idle) Position.Top else Position.Alone, leading = { LeadingAvatar(Icons.Default.FileUpload) }, onClick = onRestoreClick, ) - if (copyRun != CopyRunState.Idle) CopyEventsRow(copyRun, Position.Alone, onCopy) + if (copyRun != CopyRunState.Idle) CopyEventsRow(copyRun, Position.Bottom, onCopy) return } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt index 172269ed..5ebad9b6 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CalendarsViewModel.kt @@ -143,7 +143,7 @@ class CalendarsViewModel @Inject constructor( uri = uri, content = IcsWriter().writeCalendar(events, Clock.System.now(), name), ) - events.count { it.overrideOf == null } + events.size } BackupResult.Success(count) } catch (e: CancellationException) { diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt index 0dd24eb1..12e25bc2 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt @@ -1066,6 +1066,18 @@ class CalendarRepositoryImplTest { assertThat(fake.importedEvents.single().first.exDates).containsExactly("20260119T090000Z") } + @Test + fun `a standalone occurrence listed after its series still goes first`( + @TempDir tempDir: Path, + ) = runTest { + val fake = FakeCalendarDataSource() + val repo = testRepository(fake, tempDir, Dispatchers.Unconfined) + + repo.importEvents(3L, listOf(parsedEvent("s"), parsedEvent("1-s").copy(overrideOf = "s"))) + + assertThat(fake.importedEvents.map { it.first.uid }).containsExactly("1-s", "s").inOrder() + } + @Test fun `a backup writes an RDATE-only series as the one-off a file can hold`( @TempDir tempDir: Path, diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index da369688..0fe0e456 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -510,7 +510,9 @@ series there has the override itself — so restoring into the calendar a backup came from adds nothing twice, while a restore into an empty one gets both. The standalone event also names its occurrence (`X-CALENDULA-OVERRIDE-AT`); if it fails to insert, the series is inserted without that exclusion, so the -occurrence stays at its original time rather than vanishing for good. +occurrence stays at its original time rather than vanishing for good. The +import inserts every such event ahead of the series, whatever order the file +lists them in. Exceptions whose series isn't among the rows are left out, a cancelled series' moved occurrences stay cancelled, and sync ids link only within their own calendar. A file can't carry `RDATE`, so a backup treats a series that From 30af150197b3a75cba466d9bca02bd3da2142871 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Sat, 14 Nov 2026 02:51:25 +0100 Subject: [PATCH 10/16] feat(#515): write RDATE into .ics backups and read it back --- .../data/calendar/CalendarRepositoryImpl.kt | 7 +-- .../data/calendar/EventWriteMapper.kt | 5 ++- .../data/calendar/IcsExportMapper.kt | 35 +++++++++++---- .../calendula/domain/ics/CalendarCopy.kt | 2 +- .../calendula/domain/ics/CalendarRows.kt | 2 +- .../calendula/domain/ics/IcsEvent.kt | 6 +-- .../calendula/domain/ics/IcsParser.kt | 15 +++++-- .../calendula/domain/ics/IcsWriter.kt | 13 +++++- .../calendar/CalendarRepositoryImplTest.kt | 15 ++++--- .../data/calendar/IcsExportMapperTest.kt | 12 +++++ .../data/calendar/ImportedEventValuesTest.kt | 2 +- .../calendula/domain/ics/CalendarRowsTest.kt | 45 ++++++++++++++++++- docs/ARCHITECTURE.md | 20 ++++++--- 13 files changed, 139 insertions(+), 40 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt index 18fc7098..fcaef6fc 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImpl.kt @@ -252,12 +252,7 @@ class CalendarRepositoryImpl @Inject constructor( } override suspend fun exportEvents(calendarIds: Set) = withContext(io) { - // A file can't carry RDATE: such a series is written as the one-off it reads as. - val rows = dataSource.calendarRows(calendarIds, allDayReminderTimeMinutes()) - flattenOverrides( - rows.copy(series = rows.series.map { it.copy(event = it.event.copy(recurrenceDates = null)) }), - ::formatExdateStamp, - ) + flattenOverrides(dataSource.calendarRows(calendarIds, allDayReminderTimeMinutes()), ::formatExdateStamp) } override suspend fun copyEvents( diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapper.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapper.kt index 3a093585..328b1215 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapper.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/EventWriteMapper.kt @@ -851,11 +851,12 @@ internal fun buildImportedEventValues( put(CalendarContract.Events.TITLE, event.summary.trim()) put(CalendarContract.Events.ALL_DAY, if (event.isAllDay) 1 else 0) put(CalendarContract.Events.DTSTART, startMillis) - if (event.recurrenceRule == null && event.recurrenceDates == null) { + if (event.recurrenceRule == null && event.recurrenceDates.isEmpty()) { put(CalendarContract.Events.DTEND, endMillis) } else { event.recurrenceRule?.let { put(CalendarContract.Events.RRULE, it) } - event.recurrenceDates?.let { put(CalendarContract.Events.RDATE, it) } + event.recurrenceDates.takeIf { it.isNotEmpty() } + ?.let { put(CalendarContract.Events.RDATE, it.joinToString(",")) } put( CalendarContract.Events.DURATION, importDuration(startMillis, endMillis, event.isAllDay), diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapper.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapper.kt index 311ce964..ff56ba3c 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapper.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapper.kt @@ -28,8 +28,9 @@ internal fun ColumnReader.toIcsEvent( val eventId = getLong(EventExportProjection.IDX_ID) val dtStart = getLong(EventExportProjection.IDX_DTSTART) val rrule = getString(EventExportProjection.IDX_RRULE)?.takeIf { it.isNotBlank() } - val rdate = getString(EventExportProjection.IDX_RDATE)?.takeIf { it.isNotBlank() } val isAllDay = getInt(EventExportProjection.IDX_ALL_DAY) != 0 + val timezone = getString(EventExportProjection.IDX_EVENT_TIMEZONE) + val rdates = exportRecurrenceDates(getString(EventExportProjection.IDX_RDATE), isAllDay, timezone) // Unclamped: the writer renders DTEND as stored. val end = endMillis(dtStart, EventExportProjection.IDX_DTEND, EventExportProjection.IDX_DURATION) @@ -43,14 +44,10 @@ internal fun ColumnReader.toIcsEvent( zoneId = getString(EventExportProjection.IDX_EVENT_TIMEZONE)?.takeIf { it.isNotBlank() } ?: "UTC", recurrenceRule = rrule, - exDates = if (rrule == null && rdate == null) { + exDates = if (rrule == null && rdates.isEmpty()) { emptyList() } else { - exportExDates( - getString(EventExportProjection.IDX_EXDATE), - isAllDay, - getString(EventExportProjection.IDX_EVENT_TIMEZONE), - ) + exportExDates(getString(EventExportProjection.IDX_EXDATE), isAllDay, timezone) }, location = getString(EventExportProjection.IDX_LOCATION), description = getString(EventExportProjection.IDX_DESCRIPTION), @@ -65,7 +62,7 @@ internal fun ColumnReader.toIcsEvent( status = eventStatus(EventExportProjection.IDX_STATUS), availability = mapAvailability(getInt(EventExportProjection.IDX_AVAILABILITY)), calendarName = calendarName, - recurrenceDates = rdate, + recurrenceDates = rdates, accessLevel = getIntOrNull(EventExportProjection.IDX_ACCESS_LEVEL)?.let(::mapAccessLevel) ?: AccessLevel.Default, ) } @@ -111,3 +108,25 @@ internal fun exportExDates( } .distinct() } + +/** + * The row's `RDATE` in the same shape [exportExDates] gives `EXDATE` — the list + * shares its `;` form. A `PERIOD` entry (`start/end`) keeps only its + * start: the occurrence then runs the series' own length. Anything that still + * isn't a date or a UTC stamp is dropped, since a file can't name it. + */ +internal fun exportRecurrenceDates( + rdate: String?, + isAllDay: Boolean, + eventTimezone: String? = null, +): List { + if (rdate.isNullOrBlank()) return emptyList() + // The zone prefix may hold a '/' of its own (Europe/Berlin), so only the stamps lose their period end. + val stamps = rdate.withoutExdateParameters() + val prefix = rdate.dropLast(stamps.length) + val starts = prefix + stamps.split(',').joinToString(",") { it.substringBefore('/') } + return exportExDates(starts, isAllDay, eventTimezone).filter { RECURRENCE_DATE.matches(it) } +} + +private val RECURRENCE_DATE = Regex("""\d{8}(T\d{6}Z)?""") + diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt index 502e90d8..36dfb060 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt @@ -44,7 +44,7 @@ fun IcsEvent.toParsedIcsEvent(): ParsedIcsEvent = ParsedIcsEvent( isAllDay = isAllDay, zoneId = zoneId, recurrenceRule = recurrenceRule?.takeIf { it.isNotBlank() }?.removePrefix("RRULE:"), - recurrenceDates = recurrenceDates?.takeIf { it.isNotBlank() }, + recurrenceDates = recurrenceDates.filter { it.isNotBlank() }.distinct(), location = location, description = description, // The writer emits only lead times; a negative one would be an alarm after the start. diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt index 56ab2cbb..a5b9bcc0 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt @@ -80,7 +80,7 @@ fun flattenOverrides( detached += override.calendarId to override.event.copy( uid = "$occurrence-${parent.event.uid}", recurrenceRule = null, - recurrenceDates = null, + recurrenceDates = emptyList(), exDates = emptyList(), overrideOf = parent.event.uid, overrideAt = override.originalInstance, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsEvent.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsEvent.kt index 9cb23a55..bf708821 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsEvent.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsEvent.kt @@ -37,8 +37,8 @@ data class IcsEvent( val availability: Availability = Availability.Busy, /** Source calendar name, emitted as `X-CALENDULA-CALENDAR` so a combined backup can fan back out. */ val calendarName: String? = null, - /** The provider's raw `RDATE`; carried by a calendar copy, not written to a file. */ - val recurrenceDates: String? = null, + /** Extra occurrences (`RDATE`), in the same shape as [exDates]. */ + val recurrenceDates: List = emptyList(), /** Carried by a calendar copy, not written to a file. */ val accessLevel: AccessLevel = AccessLevel.Default, /** The event's own colour, null when it shows its calendar's; carried by a calendar copy, not written to a file. */ @@ -54,7 +54,7 @@ data class IcsEvent( /** Whether this is a series: by rule, or by listed dates alone. */ val IcsEvent.recurs: Boolean - get() = !recurrenceRule.isNullOrBlank() || !recurrenceDates.isNullOrBlank() + get() = !recurrenceRule.isNullOrBlank() || recurrenceDates.isNotEmpty() /** * The UID to export for a provider event. A row that already carries a UID diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsParser.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsParser.kt index b4e15bcf..757e2290 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsParser.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsParser.kt @@ -54,8 +54,8 @@ data class ParsedIcsEvent( val overrideOf: String? = null, /** The occurrence of [overrideOf] this event replaces (`X-CALENDULA-OVERRIDE-AT`). */ val overrideAt: Instant? = null, - /** The provider's raw `RDATE`, only set by a calendar copy. */ - val recurrenceDates: String? = null, + /** Extra occurrences (`RDATE`), in the same shape as [exDates]. */ + val recurrenceDates: List = emptyList(), val accessLevel: AccessLevel = AccessLevel.Default, ) @@ -224,6 +224,7 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault var calendarColor: Int? = null val reminders = mutableListOf() val exDateLines = mutableListOf() + val rDateLines = mutableListOf() var skipAsOverride = false var overrideOf: String? = null var overrideAt: Instant? = null @@ -247,6 +248,7 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault "DURATION" -> duration = line.value.trim() "RRULE" -> rrule = line.value.trim().ifEmpty { null } "EXDATE" -> exDateLines.add(line) + "RDATE" -> rDateLines.add(line) "LOCATION" -> location = unescapeText(line.value).ifEmpty { null } "DESCRIPTION" -> description = unescapeText(line.value).ifEmpty { null } "STATUS" -> status = mapIcsStatus(line.value) @@ -295,6 +297,7 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault val recurrence = sanitizeRrule(rrule) if (recurrence.repaired) warnings.add(IcsParseWarning.RecurrenceRuleRepaired) val end = resolveEnd(start, dtEnd, duration) + val recurrenceDates = normalizeExDates(rDateLines, start) return ParsedIcsEvent( uid = uid, summary = summary, @@ -310,11 +313,12 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault availability = availability, calendarName = calendarName ?: category, color = eventColor ?: calendarColor, - exDates = if (recurrence.rule == null) { + exDates = if (recurrence.rule == null && recurrenceDates.isEmpty()) { emptyList() } else { normalizeExDates(exDateLines, start) }, + recurrenceDates = recurrenceDates, isTask = isTask, overrideOf = overrideOf, overrideAt = overrideAt, @@ -352,13 +356,16 @@ class IcsParser(private val deviceZone: TimeZone = TimeZone.currentSystemDefault * still means the day it spells out; resolving it to an instant first and * reading *that* back in UTC would roll a midnight east of UTC onto the day * before and exclude an occurrence that doesn't exist. + * + * `RDATE` shares the value form and is read here too. */ private fun normalizeExDates(lines: List, start: IcsDateTime): List { if (lines.isEmpty()) return emptyList() val startZone = zoneOrNull(start.zoneId) ?: deviceZone val startTime = start.instant.toLocalDateTime(startZone).time return lines - .flatMap { line -> line.value.split(',').map { line to it.trim() } } + // An RDATE PERIOD (`start/end`) counts by its start. + .flatMap { line -> line.value.split(',').map { line to it.trim().substringBefore('/') } } .mapNotNull { (line, token) -> when { token.isEmpty() -> null diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsWriter.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsWriter.kt index a0a039be..f3deed61 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsWriter.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsWriter.kt @@ -47,6 +47,7 @@ class IcsWriter(private val prodId: String = ICS_PROD_ID) { appendTimes(event) event.recurrenceRule?.takeIf { it.isNotBlank() } ?.let { add("RRULE:${it.removePrefix("RRULE:")}") } + appendRecurrenceDates(event) appendExDates(event) event.location?.takeIf { it.isNotBlank() } ?.let { add("LOCATION:${escapeText(it)}") } @@ -71,7 +72,7 @@ class IcsWriter(private val prodId: String = ICS_PROD_ID) { add("DTEND;VALUE=DATE:${event.end.toLocalDateTime(TimeZone.UTC).date.toBasic()}") } // Recurring: anchor to wall-clock in the event's own zone. - event.recurrenceRule?.isNotBlank() == true -> { + event.recurs -> { val zone = zoneOrNull(event.zoneId) if (zone != null) { add("DTSTART;TZID=${event.zoneId}:${event.start.toLocalDateTime(zone).toBasic()}") @@ -94,8 +95,16 @@ class IcsWriter(private val prodId: String = ICS_PROD_ID) { * it the bare day codes read as an invalid DATE-TIME. Only written for a * recurring event: an exclusion names an occurrence, and a one-off has none. */ + /** Extra occurrences: the same UTC stamps / `VALUE=DATE` days as [appendExDates]. */ + private fun MutableList.appendRecurrenceDates(event: IcsEvent) { + val stamps = event.recurrenceDates.filter { it.isNotBlank() }.distinct() + if (stamps.isEmpty()) return + val prefix = if (event.isAllDay) "RDATE;VALUE=DATE:" else "RDATE:" + add(prefix + stamps.joinToString(",")) + } + private fun MutableList.appendExDates(event: IcsEvent) { - if (event.recurrenceRule.isNullOrBlank()) return + if (!event.recurs) return val stamps = event.exDates.filter { it.isNotBlank() }.distinct() if (stamps.isEmpty()) return val prefix = if (event.isAllDay) "EXDATE;VALUE=DATE:" else "EXDATE:" diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt index 12e25bc2..a951a2a4 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/CalendarRepositoryImplTest.kt @@ -1079,22 +1079,27 @@ class CalendarRepositoryImplTest { } @Test - fun `a backup writes an RDATE-only series as the one-off a file can hold`( + fun `a backup keeps an RDATE-only series and its exceptions`( @TempDir tempDir: Path, ) = runTest { val start = Instant.parse("2026-01-05T09:00:00Z") - val event = IcsEvent("s", "S", start, Instant.parse("2026-01-05T10:00:00Z"), false, "UTC", recurrenceDates = "20260112T090000Z") + val other = Instant.parse("2026-01-12T09:00:00Z") + val event = IcsEvent( + "s", "S", start, Instant.parse("2026-01-05T10:00:00Z"), false, "UTC", + recurrenceDates = listOf("20260112T090000Z", "20260119T090000Z"), + ) val fake = FakeCalendarDataSource().apply { calendarRowsResult = CalendarRows( listOf(MasterRow(1, 1, null, event)), - listOf(OverrideRow(1, 1, null, start, event.copy(recurrenceDates = null))), + listOf(OverrideRow(1, 1, null, other, event.copy(recurrenceDates = emptyList(), status = EventStatus.Cancelled))), ) } val exported = testRepository(fake, tempDir, Dispatchers.Unconfined).exportEvents(setOf(1L)) + val restored = IcsParser().parse(IcsWriter().writeCalendar(exported, start)).events.single() - assertThat(exported.map { it.uid }).containsExactly("s") - assertThat(exported.single().recurrenceDates).isNull() + assertThat(restored.recurrenceDates).containsExactly("20260112T090000Z", "20260119T090000Z") + assertThat(restored.exDates).containsExactly("20260112T090000Z") } private fun parsedEvent(uid: String?, summary: String = "E") = diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapperTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapperTest.kt index 6045ef4d..fbd18068 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapperTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapperTest.kt @@ -294,4 +294,16 @@ class IcsExportMapperTest { assertThat(event.exDates).isEmpty() } + + @Test + fun `a zoned RDATE list is written as UTC stamps, a period by its start`() { + assertThat(exportRecurrenceDates("Europe/Berlin;20260110T100000,20260111T100000/PT1H", isAllDay = false)) + .containsExactly("20260110T090000Z", "20260111T090000Z").inOrder() + } + + @Test + fun `an all-day RDATE keeps its days, junk is dropped`() { + assertThat(exportRecurrenceDates("20260110T000000Z,20260111,garbage", isAllDay = true)) + .containsExactly("20260110", "20260111").inOrder() + } } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/ImportedEventValuesTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/ImportedEventValuesTest.kt index 83fd6f98..49b39cf8 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/ImportedEventValuesTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/ImportedEventValuesTest.kt @@ -127,7 +127,7 @@ class ImportedEventValuesTest { @Test fun `a copied RDATE-only series recurs by its dates`() { - val v = values(allDay().copy(recurrenceDates = "20260820", exDates = listOf("20260820"))) + val v = values(allDay().copy(recurrenceDates = listOf("20260820"), exDates = listOf("20260820"))) assertThat(v).doesNotContainKey(CalendarContract.Events.DTEND) assertThat(v).doesNotContainKey(CalendarContract.Events.RRULE) assertThat(v[CalendarContract.Events.RDATE]).isEqualTo("20260820") diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt index d6fb3d40..5064de0a 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt @@ -120,11 +120,11 @@ class CalendarRowsTest { @Test fun `an RDATE-only series keeps its dates and takes its exceptions`() { val flat = flatten( - listOf(MasterRow(1, 1, null, event("s").copy(recurrenceDates = "20260112T090000Z"))), + listOf(MasterRow(1, 1, null, event("s").copy(recurrenceDates = listOf("20260112T090000Z")))), listOf(OverrideRow(1, 1, null, occurrence(1), event("s", status = EventStatus.Cancelled))), ) - assertThat(flat.single().recurrenceDates).isEqualTo("20260112T090000Z") + assertThat(flat.single().recurrenceDates).containsExactly("20260112T090000Z") assertThat(flat.single().exDates).containsExactly("20260112T090000Z") } @@ -229,4 +229,45 @@ class CalendarRowsTest { assertThat(plan.map { it.uid }).containsExactly("s") assertThat(plan.single().exDates).containsExactly("20260112T090000Z") } + + @Test + fun `RDATE and its exclusions survive the file`() { + val timed = event("t").copy( + recurrenceDates = listOf("20260112T090000Z", "20260120T090000Z"), + exDates = listOf("20260112T090000Z"), + ) + val day = Instant.parse("2026-01-05T00:00:00Z") + val allDay = event("a", allDay = true, at = day).copy( + end = Instant.parse("2026-01-06T00:00:00Z"), + recurrenceDates = listOf("20260110"), + exDates = listOf("20260110"), + ) + val text = IcsWriter().writeCalendar(listOf(timed, allDay), start) + + assertThat(text).contains("RDATE;VALUE=DATE:20260110") + assertThat(text).contains("DTSTART;TZID=Europe/Berlin:20260105T100000") + val (t, a) = IcsParser().parse(text).events + assertThat(t.recurrenceDates).containsExactly("20260112T090000Z", "20260120T090000Z") + assertThat(t.exDates).containsExactly("20260112T090000Z") + assertThat(a.recurrenceDates).containsExactly("20260110") + assertThat(a.exDates).containsExactly("20260110") + } + + @Test + fun `a foreign RDATE is read in its own zone, a period by its start`() { + val text = """ + BEGIN:VCALENDAR + BEGIN:VEVENT + UID:f + DTSTART;TZID=Europe/Berlin:20260105T100000 + DTEND;TZID=Europe/Berlin:20260105T110000 + RDATE;TZID=America/New_York:20260110T090000 + RDATE;VALUE=PERIOD:20260111T090000Z/PT1H + END:VEVENT + END:VCALENDAR + """.trimIndent().replace("\n", "\r\n") + + assertThat(IcsParser().parse(text).events.single().recurrenceDates) + .containsExactly("20260110T140000Z", "20260111T090000Z") + } } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 0fe0e456..bced3eec 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -515,16 +515,26 @@ import inserts every such event ahead of the series, whatever order the file lists them in. Exceptions whose series isn't among the rows are left out, a cancelled series' moved occurrences stay cancelled, and sync ids link only within their -own calendar. A file can't carry `RDATE`, so a backup treats a series that -repeats by listed dates alone as the one-off it writes it as. Backups made before this carry no exceptions -and restore exactly as before. +own calendar. Backups made before this carry no exceptions and restore exactly +as before. + +**`RDATE` travels like `EXDATE` (#515).** A series can repeat by listed dates +alone. The provider stores `RDATE` in the same `;` form as +`EXDATE`, so `exportRecurrenceDates` resolves it the same way to UTC stamps (or +bare days for an all-day series); a `PERIOD` entry keeps its start. `IcsWriter` +writes it as `RDATE:` / `RDATE;VALUE=DATE:`, anchors such a series to its zone +like an RRULE series, and writes its `EXDATE` too; `IcsParser` reads `RDATE` +through the same normalisation as `EXDATE`, so a foreign `TZID` or floating +value lands on the right instant. Older backups wrote such a series as a single +event and still restore as one. **Copying a calendar.** Backup & restore → Copy events (#325) runs the source's flattened rows straight into `importEvents`, so the UID dedup makes a re-run skip what landed before. It skips the `.ics` text: the writer pins a timed one-off to -UTC and carries no colour, visibility or `RDATE`; the direct mapping keeps them. +UTC and carries no colour or visibility; the direct mapping keeps them. Attendees and organizer are never read, and cancelled events and declined -invitations are left out (a declined occurrence counts as deleted) (an insert can't be cancelled; it would arrive live). A re-run is idempotent per +invitations are left out (an insert can't be cancelled; it would arrive live, and +a declined occurrence counts as deleted). A re-run is idempotent per snapshot: a series already in the target keeps its overrides, so an occurrence changed since keeps its earlier copy rather than gaining a second one. From 028d8d0e1e659b2ee92bdc19e7ebd29d6f10a796 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Sat, 14 Nov 2026 03:01:37 +0100 Subject: [PATCH 11/16] fix(#515, #325): review round 1 - multi-line RDATE, accepted occurrences of declined series copied, partial copies say so --- .../calendula/data/calendar/IcsExportMapper.kt | 15 ++++++++------- .../calendula/domain/ics/CalendarCopy.kt | 8 ++++++-- .../calendula/domain/ics/IcsWriter.kt | 12 ++++++------ .../calendula/ui/calendars/BackupScreen.kt | 6 +++++- .../calendula/ui/calendars/CopyEventsSheet.kt | 5 +++-- app/src/main/res/values/strings.xml | 1 + .../data/calendar/IcsExportMapperTest.kt | 6 ++++++ .../calendula/domain/ics/CalendarRowsTest.kt | 10 +++++++--- docs/ARCHITECTURE.md | 3 ++- 9 files changed, 44 insertions(+), 22 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapper.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapper.kt index ff56ba3c..8b08590c 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapper.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapper.kt @@ -41,8 +41,7 @@ internal fun ColumnReader.toIcsEvent( start = dtStart.toKotlinInstantFromEpochMillis(), end = end.toKotlinInstantFromEpochMillis(), isAllDay = isAllDay, - zoneId = getString(EventExportProjection.IDX_EVENT_TIMEZONE)?.takeIf { it.isNotBlank() } - ?: "UTC", + zoneId = timezone?.takeIf { it.isNotBlank() } ?: "UTC", recurrenceRule = rrule, exDates = if (rrule == null && rdates.isEmpty()) { emptyList() @@ -121,11 +120,13 @@ internal fun exportRecurrenceDates( eventTimezone: String? = null, ): List { if (rdate.isNullOrBlank()) return emptyList() - // The zone prefix may hold a '/' of its own (Europe/Berlin), so only the stamps lose their period end. - val stamps = rdate.withoutExdateParameters() - val prefix = rdate.dropLast(stamps.length) - val starts = prefix + stamps.split(',').joinToString(",") { it.substringBefore('/') } - return exportExDates(starts, isAllDay, eventTimezone).filter { RECURRENCE_DATE.matches(it) } + // Several RDATE properties are stored one per line, each with its own zone prefix. + return rdate.lines().filter { it.isNotBlank() }.flatMap { line -> + // The zone prefix may hold a '/' of its own (Europe/Berlin), so only the stamps lose their period end. + val stamps = line.withoutExdateParameters() + val starts = line.dropLast(stamps.length) + stamps.split(',').joinToString(",") { it.substringBefore('/') } + exportExDates(starts, isAllDay, eventTimezone) + }.filter { RECURRENCE_DATE.matches(it) }.distinct() } private val RECURRENCE_DATE = Regex("""\d{8}(T\d{6}Z)?""") diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt index 36dfb060..98abc64b 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt @@ -19,13 +19,17 @@ fun planCalendarCopy( exdateStamp: (occurrenceMillis: Long, isAllDay: Boolean) -> String, ): List { val live = CalendarRows( - series = rows.series.filterNot { it.event.status == EventStatus.Cancelled || it.declined }, + series = rows.series.filterNot { it.event.status == EventStatus.Cancelled }, // A declined occurrence is as good as deleted here. overrides = rows.overrides.map { if (it.declined) it.copy(event = it.event.copy(status = EventStatus.Cancelled)) else it }, ) - return flattenOverrides(live, exdateStamp).map { it.toParsedIcsEvent() } + // A declined series still hands its accepted occurrences on before it goes. + val declined = rows.series.filter { it.declined }.map { it.event.uid }.toSet() + return flattenOverrides(live, exdateStamp) + .filterNot { it.overrideOf == null && it.uid in declined } + .map { it.toParsedIcsEvent() } } /** diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsWriter.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsWriter.kt index f3deed61..1cf5e806 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsWriter.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/IcsWriter.kt @@ -89,12 +89,6 @@ class IcsWriter(private val prodId: String = ICS_PROD_ID) { } } - /** - * The series' deleted occurrences. RFC 5545 ties `EXDATE`'s value type to - * `DTSTART`'s, so an all-day series needs the explicit `VALUE=DATE` — without - * it the bare day codes read as an invalid DATE-TIME. Only written for a - * recurring event: an exclusion names an occurrence, and a one-off has none. - */ /** Extra occurrences: the same UTC stamps / `VALUE=DATE` days as [appendExDates]. */ private fun MutableList.appendRecurrenceDates(event: IcsEvent) { val stamps = event.recurrenceDates.filter { it.isNotBlank() }.distinct() @@ -103,6 +97,12 @@ class IcsWriter(private val prodId: String = ICS_PROD_ID) { add(prefix + stamps.joinToString(",")) } + /** + * The series' deleted occurrences. RFC 5545 ties `EXDATE`'s value type to + * `DTSTART`'s, so an all-day series needs the explicit `VALUE=DATE` — without + * it the bare day codes read as an invalid DATE-TIME. Only written for a + * recurring event: an exclusion names an occurrence, and a one-off has none. + */ private fun MutableList.appendExDates(event: IcsEvent) { if (!event.recurs) return val stamps = event.exDates.filter { it.isNotBlank() }.distinct() diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt index adf6b33e..b4382b14 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt @@ -399,7 +399,11 @@ private fun CopyEventsRow(copyRun: CopyRunState, position: Position, onClick: () summary = when (copyRun) { is CopyRunState.Running -> copyProgressText(copyRun) is CopyRunState.Done -> stringResource( - if (copyRun.stopped) R.string.calendars_copy_stopped_title else R.string.calendars_copy_done, + when { + copyRun.stopped -> R.string.calendars_copy_stopped_title + copyRun.summary.failed > 0 -> R.string.calendars_copy_partial + else -> R.string.calendars_copy_done + }, ) CopyRunState.Cancelled -> stringResource(R.string.calendars_copy_cancelled) CopyRunState.Failed -> stringResource(R.string.calendars_copy_failed) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt index 71e6450e..720f8ffb 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt @@ -53,11 +53,12 @@ fun CopyEventsSheet( onDismiss: () -> Unit, ) { val list = (calendars as? CopyCalendars.Ready)?.calendars.orEmpty() + val running = run is CopyRunState.Running val sources = remember(list) { copySources(list) } - val source = sources.firstOrNull { it.id == selection.sourceId } + // A running copy keeps showing its source even if it stopped qualifying meanwhile. + val source = (if (running) list else sources).firstOrNull { it.id == selection.sourceId } val targets = remember(list, source?.id) { copyTargets(list, source?.id) } val target = targets.firstOrNull { it.id == selection.targetId } - val running = run is CopyRunState.Running var picking by rememberSaveable { mutableStateOf(null) } FullScreenPicker( diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 9c8cf4a8..791612c5 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -905,6 +905,7 @@ Copy complete Copy stopped + Copy finished, some events couldn\'t be added No calendar can be copied into another one right now. Copy cancelled. Run it again to finish: events that were already copied are skipped. Couldn\'t copy the events. diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapperTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapperTest.kt index fbd18068..01a2fc6d 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapperTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapperTest.kt @@ -306,4 +306,10 @@ class IcsExportMapperTest { assertThat(exportRecurrenceDates("20260110T000000Z,20260111,garbage", isAllDay = true)) .containsExactly("20260110", "20260111").inOrder() } + + @Test + fun `an RDATE stored over several lines keeps every line's dates`() { + assertThat(exportRecurrenceDates("Europe/Berlin;20260110T100000\nAmerica/New_York;20260112T090000", isAllDay = false)) + .containsExactly("20260110T090000Z", "20260112T140000Z").inOrder() + } } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt index 5064de0a..8f7c9e68 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt @@ -212,10 +212,14 @@ class CalendarRowsTest { } @Test - fun `a copy leaves declined invitations out`() { - val rows = CalendarRows(listOf(series("d").copy(declined = true), series("k", id = 2)), emptyList()) + fun `a copy leaves declined invitations out but keeps an occurrence accepted on its own`() { + val rows = CalendarRows( + listOf(series("d").copy(declined = true), series("k", id = 2)), + listOf(OverrideRow(1, 1, null, occurrence(1), event("accepted"))), + ) - assertThat(planCalendarCopy(rows, ::formatExdateStamp).map { it.uid }).containsExactly("k") + val plan = planCalendarCopy(rows, ::formatExdateStamp) + assertThat(plan.map { it.summary }).containsExactly("accepted", "k") } @Test diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index bced3eec..cc6ff22e 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -521,7 +521,8 @@ as before. **`RDATE` travels like `EXDATE` (#515).** A series can repeat by listed dates alone. The provider stores `RDATE` in the same `;` form as `EXDATE`, so `exportRecurrenceDates` resolves it the same way to UTC stamps (or -bare days for an all-day series); a `PERIOD` entry keeps its start. `IcsWriter` +bare days for an all-day series), line by line where several `RDATE`s were +stored; a `PERIOD` entry keeps its start. `IcsWriter` writes it as `RDATE:` / `RDATE;VALUE=DATE:`, anchors such a series to its zone like an RRULE series, and writes its `EXDATE` too; `IcsParser` reads `RDATE` through the same normalisation as `EXDATE`, so a foreign `TZID` or floating From 05887d2ed0d8345f66484c6ff1f303f6de6c130a Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Sat, 14 Nov 2026 03:12:43 +0100 Subject: [PATCH 12/16] fix(#515, #325): review round 2 - multi-line and unreadable EXDATE handled, imports all or nothing per event, running copy survives list failures --- .../data/calendar/CalendarDataSource.kt | 29 ++++++++++++------- .../data/calendar/IcsExportMapper.kt | 24 ++++++++------- .../calendula/domain/ics/CalendarRows.kt | 5 ++-- .../calendula/ui/calendars/BackupScreen.kt | 8 +---- .../calendula/ui/calendars/CopyEventsSheet.kt | 5 ++-- .../ui/calendars/CopyEventsViewModel.kt | 10 +++++++ .../data/calendar/IcsExportMapperTest.kt | 6 ++++ 7 files changed, 55 insertions(+), 32 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt index 6ee39d62..021575e9 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt @@ -913,18 +913,25 @@ class AndroidCalendarDataSource @Inject constructor( } else { null } - event.semanticReminderMinutes().forEach { minutes -> - val providerMinutes = if (reminderDate != null) { - toProviderAllDayMinutes( - semanticMinutes = minutes, - startDate = reminderDate, - zone = zone, - timeOfDayMinutes = allDayReminderTimeMinutes, - ) - } else { - minutes + // All or nothing: a row whose reminders failed would count as not added + // and still be there. + try { + event.semanticReminderMinutes().forEach { minutes -> + val providerMinutes = if (reminderDate != null) { + toProviderAllDayMinutes( + semanticMinutes = minutes, + startDate = reminderDate, + zone = zone, + timeOfDayMinutes = allDayReminderTimeMinutes, + ) + } else { + minutes + } + insertReminderRow(eventId, providerMinutes) } - insertReminderRow(eventId, providerMinutes) + } catch (t: Throwable) { + runCatching { resolver.delete(eventUri(eventId), null, null) } + throw t } return eventId } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapper.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapper.kt index 8b08590c..e12f23b2 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapper.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapper.kt @@ -96,15 +96,19 @@ internal fun exportExDates( eventTimezone: String? = null, ): List { if (exdate.isNullOrBlank()) return emptyList() - val zone = exdateListZone(exdate, eventTimezone) - return exdateStamps(exdate) - .map { stamp -> + // Several properties are stored one per line, each with its own zone prefix. + return exdate.lines().filter { it.isNotBlank() }.flatMap { line -> + val zone = exdateListZone(line, eventTimezone) + exdateStamps(line).map { stamp -> if (isAllDay) { stamp.substringBefore('T') } else { canonicalExdateStamp(stamp, isAllDay = false, listZone = zone) ?: stamp } } + } + // A bare day on a timed series stays: a restore reads it at the series' time of day. + .filter { EXPORTED_STAMP.matches(it) } .distinct() } @@ -120,14 +124,14 @@ internal fun exportRecurrenceDates( eventTimezone: String? = null, ): List { if (rdate.isNullOrBlank()) return emptyList() - // Several RDATE properties are stored one per line, each with its own zone prefix. - return rdate.lines().filter { it.isNotBlank() }.flatMap { line -> - // The zone prefix may hold a '/' of its own (Europe/Berlin), so only the stamps lose their period end. + // The zone prefix may hold a '/' of its own (Europe/Berlin), so only the stamps lose their period end. + val starts = rdate.lines().joinToString("\n") { line -> val stamps = line.withoutExdateParameters() - val starts = line.dropLast(stamps.length) + stamps.split(',').joinToString(",") { it.substringBefore('/') } - exportExDates(starts, isAllDay, eventTimezone) - }.filter { RECURRENCE_DATE.matches(it) }.distinct() + line.dropLast(stamps.length) + stamps.split(',').joinToString(",") { it.substringBefore('/') } + } + return exportExDates(starts, isAllDay, eventTimezone) } -private val RECURRENCE_DATE = Regex("""\d{8}(T\d{6}Z)?""") +/** What a file and a provider both read back: a day, or a UTC stamp. */ +private val EXPORTED_STAMP = Regex("""\d{8}(T\d{6}Z)?""") diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt index a5b9bcc0..276d3156 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt @@ -52,8 +52,9 @@ data class CalendarRows( * occurrence, so it is the same on every run. Overrides whose series isn't * among the rows are left out; the provider doesn't show them either. * - * Standalone occurrences come first, so an import cut short leaves at worst an - * occurrence missing its series, never a series missing an occurrence. + * Standalone occurrences come first; `importEvents` enforces that order for + * any file, so an import cut short leaves at worst an occurrence missing its + * series, never a series missing an occurrence. * * [exdateStamp] formats an occurrence as an `EXDATE` entry in the provider's * shape, the same one Calendula's own exclusions use. A cancelled series' diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt index b4382b14..4dd5401a 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt @@ -398,13 +398,7 @@ private fun CopyEventsRow(copyRun: CopyRunState, position: Position, onClick: () title = stringResource(R.string.calendars_copy_action), summary = when (copyRun) { is CopyRunState.Running -> copyProgressText(copyRun) - is CopyRunState.Done -> stringResource( - when { - copyRun.stopped -> R.string.calendars_copy_stopped_title - copyRun.summary.failed > 0 -> R.string.calendars_copy_partial - else -> R.string.calendars_copy_done - }, - ) + is CopyRunState.Done -> stringResource(copyRun.titleRes) CopyRunState.Cancelled -> stringResource(R.string.calendars_copy_cancelled) CopyRunState.Failed -> stringResource(R.string.calendars_copy_failed) CopyRunState.Idle -> stringResource(R.string.calendars_copy_summary) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt index 720f8ffb..818bd4db 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt @@ -74,7 +74,8 @@ fun CopyEventsSheet( }, ) { GroupedHint(stringResource(R.string.calendars_copy_hint), style = MaterialTheme.typography.bodySmall) - when (calendars) { + // A copy under way keeps its progress and Cancel whatever the list does. + if (run == CopyRunState.Idle) when (calendars) { CopyCalendars.Loading -> { Box(Modifier.fillMaxWidth().padding(32.dp), contentAlignment = Alignment.Center) { CircularProgressIndicator() @@ -207,7 +208,7 @@ fun copyProgressText(run: CopyRunState.Running): String { private fun CopySummary(run: CopyRunState.Done) { val summary = run.summary Text( - stringResource(if (run.stopped) R.string.calendars_copy_stopped_title else R.string.calendars_copy_done), + stringResource(run.titleRes), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onSurface, ) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt index 6144c9c0..f07df8b7 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt @@ -1,10 +1,12 @@ package de.jeanlucmakiola.calendula.ui.calendars import android.util.Log +import androidx.annotation.StringRes import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel +import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary @@ -134,6 +136,14 @@ sealed interface CopyRunState { data class Done(val summary: IcsImportSummary) : CopyRunState { /** The target stopped taking events part way, so some were never tried. */ val stopped: Boolean get() = summary.notAttempted > 0 + + /** How the run ended, the same words on the row and in the sheet. */ + @get:StringRes + val titleRes: Int get() = when { + stopped -> R.string.calendars_copy_stopped_title + summary.failed > 0 -> R.string.calendars_copy_partial + else -> R.string.calendars_copy_done + } } data object Cancelled : CopyRunState data object Failed : CopyRunState diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapperTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapperTest.kt index 01a2fc6d..3aad6fcb 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapperTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapperTest.kt @@ -312,4 +312,10 @@ class IcsExportMapperTest { assertThat(exportRecurrenceDates("Europe/Berlin;20260110T100000\nAmerica/New_York;20260112T090000", isAllDay = false)) .containsExactly("20260110T090000Z", "20260112T140000Z").inOrder() } + + @Test + fun `an EXDATE stored over several lines keeps every line, unreadable stamps go`() { + assertThat(exportExDates("Europe/Berlin;20260110T100000\nEurope/Berlin;20260117T100000,junk", isAllDay = false)) + .containsExactly("20260110T090000Z", "20260117T090000Z").inOrder() + } } From 1e83000696de8517040b0adca8168e8e58dc9bcc Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Sat, 14 Nov 2026 03:22:45 +0100 Subject: [PATCH 13/16] fix(#515, #325): review round 3 - bare-day EXDATE/RDATE on timed series resolved when read, unaccepted occurrences of declined series not copied --- .../data/calendar/CalendarDataSource.kt | 6 ++-- .../data/calendar/IcsExportMapper.kt | 36 ++++++++++++------- .../calendula/domain/ics/CalendarCopy.kt | 16 +++++++-- .../calendula/domain/ics/CalendarRows.kt | 2 ++ .../data/calendar/IcsExportMapperTest.kt | 11 ++++++ .../calendula/domain/ics/CalendarRowsTest.kt | 5 ++- docs/ARCHITECTURE.md | 7 ++-- 7 files changed, 63 insertions(+), 20 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt index 021575e9..65e202f7 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/CalendarDataSource.kt @@ -798,8 +798,8 @@ class AndroidCalendarDataSource @Inject constructor( it != calendar?.color || !getString(EventExportProjection.IDX_EVENT_COLOR_KEY).isNullOrEmpty() } val mapped = event(calendar?.displayName).copy(color = color) - val declined = getIntOrNull(EventExportProjection.IDX_SELF_ATTENDEE_STATUS) == - CalendarContract.Attendees.ATTENDEE_STATUS_DECLINED + val selfStatus = getIntOrNull(EventExportProjection.IDX_SELF_ATTENDEE_STATUS) + val declined = selfStatus == CalendarContract.Attendees.ATTENDEE_STATUS_DECLINED val originalId = getLongOrNull(EventExportProjection.IDX_ORIGINAL_ID) val originalSyncId = getString(EventExportProjection.IDX_ORIGINAL_SYNC_ID)?.takeIf { it.isNotEmpty() } // Without a link the provider shows the row as an event of its own. @@ -822,6 +822,8 @@ class AndroidCalendarDataSource @Inject constructor( originalInstance = originalInstance.toKotlinInstantFromEpochMillis(), event = mapped, declined = declined, + accepted = selfStatus == CalendarContract.Attendees.ATTENDEE_STATUS_ACCEPTED || + selfStatus == CalendarContract.Attendees.ATTENDEE_STATUS_TENTATIVE, ) } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapper.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapper.kt index e12f23b2..4dec9b9a 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapper.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapper.kt @@ -4,7 +4,10 @@ import de.jeanlucmakiola.floret.time.toKotlinInstantFromEpochMillis import de.jeanlucmakiola.calendula.domain.AccessLevel import de.jeanlucmakiola.calendula.domain.ics.IcsEvent import de.jeanlucmakiola.calendula.domain.ics.deriveIcsUid +import java.time.Instant +import java.time.LocalDate import java.time.ZoneId +import java.time.format.DateTimeFormatter /** * Map one Events row (read through [EventExportProjection]) into an [IcsEvent] @@ -30,7 +33,7 @@ internal fun ColumnReader.toIcsEvent( val rrule = getString(EventExportProjection.IDX_RRULE)?.takeIf { it.isNotBlank() } val isAllDay = getInt(EventExportProjection.IDX_ALL_DAY) != 0 val timezone = getString(EventExportProjection.IDX_EVENT_TIMEZONE) - val rdates = exportRecurrenceDates(getString(EventExportProjection.IDX_RDATE), isAllDay, timezone) + val rdates = exportRecurrenceDates(getString(EventExportProjection.IDX_RDATE), isAllDay, timezone, dtStart) // Unclamped: the writer renders DTEND as stored. val end = endMillis(dtStart, EventExportProjection.IDX_DTEND, EventExportProjection.IDX_DURATION) @@ -46,7 +49,7 @@ internal fun ColumnReader.toIcsEvent( exDates = if (rrule == null && rdates.isEmpty()) { emptyList() } else { - exportExDates(getString(EventExportProjection.IDX_EXDATE), isAllDay, timezone) + exportExDates(getString(EventExportProjection.IDX_EXDATE), isAllDay, timezone, dtStart) }, location = getString(EventExportProjection.IDX_LOCATION), description = getString(EventExportProjection.IDX_DESCRIPTION), @@ -94,21 +97,22 @@ internal fun exportExDates( exdate: String?, isAllDay: Boolean, eventTimezone: String? = null, + seriesStartMillis: Long? = null, ): List { if (exdate.isNullOrBlank()) return emptyList() // Several properties are stored one per line, each with its own zone prefix. return exdate.lines().filter { it.isNotBlank() }.flatMap { line -> val zone = exdateListZone(line, eventTimezone) - exdateStamps(line).map { stamp -> - if (isAllDay) { - stamp.substringBefore('T') - } else { - canonicalExdateStamp(stamp, isAllDay = false, listZone = zone) ?: stamp + exdateStamps(line).mapNotNull { stamp -> + when { + isAllDay -> stamp.substringBefore('T') + // A bare day on a timed series means the occurrence at the series' time of day. + seriesStartMillis != null && BARE_DAY.matches(stamp) -> atSeriesTime(stamp, seriesStartMillis, zone) + else -> canonicalExdateStamp(stamp, isAllDay = false, listZone = zone) ?: stamp } } } - // A bare day on a timed series stays: a restore reads it at the series' time of day. - .filter { EXPORTED_STAMP.matches(it) } + .filter { (if (isAllDay) BARE_DAY else UTC_STAMP).matches(it) } .distinct() } @@ -122,6 +126,7 @@ internal fun exportRecurrenceDates( rdate: String?, isAllDay: Boolean, eventTimezone: String? = null, + seriesStartMillis: Long? = null, ): List { if (rdate.isNullOrBlank()) return emptyList() // The zone prefix may hold a '/' of its own (Europe/Berlin), so only the stamps lose their period end. @@ -129,9 +134,16 @@ internal fun exportRecurrenceDates( val stamps = line.withoutExdateParameters() line.dropLast(stamps.length) + stamps.split(',').joinToString(",") { it.substringBefore('/') } } - return exportExDates(starts, isAllDay, eventTimezone) + return exportExDates(starts, isAllDay, eventTimezone, seriesStartMillis) } -/** What a file and a provider both read back: a day, or a UTC stamp. */ -private val EXPORTED_STAMP = Regex("""\d{8}(T\d{6}Z)?""") +/** [day] (`yyyyMMdd`) at the wall-clock time the series starts at in [zone], as a UTC stamp. */ +private fun atSeriesTime(day: String, seriesStartMillis: Long, zone: ZoneId): String? { + val date = runCatching { LocalDate.parse(day, DateTimeFormatter.BASIC_ISO_DATE) }.getOrNull() ?: return null + val time = Instant.ofEpochMilli(seriesStartMillis).atZone(zone).toLocalTime() + return formatExdateStamp(date.atTime(time).atZone(zone).toInstant().toEpochMilli(), isAllDay = false) +} + +private val BARE_DAY = Regex("""\d{8}""") +private val UTC_STAMP = Regex("""\d{8}T\d{6}Z""") diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt index 98abc64b..2f4883a2 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt @@ -18,15 +18,25 @@ fun planCalendarCopy( rows: CalendarRows, exdateStamp: (occurrenceMillis: Long, isAllDay: Boolean) -> String, ): List { + val declinedSeries = rows.series.filter { it.declined } + val declinedIds = declinedSeries.map { it.eventId }.toSet() + val declinedSyncIds = declinedSeries.filter { it.syncId != null }.map { it.calendarId to it.syncId }.toSet() + fun OverrideRow.ofDeclinedSeries() = + originalId in declinedIds || (originalSyncId != null && (calendarId to originalSyncId) in declinedSyncIds) val live = CalendarRows( series = rows.series.filterNot { it.event.status == EventStatus.Cancelled }, - // A declined occurrence is as good as deleted here. + // A declined occurrence is as good as deleted here, and so is one of a + // declined series the user didn't accept on its own. overrides = rows.overrides.map { - if (it.declined) it.copy(event = it.event.copy(status = EventStatus.Cancelled)) else it + if (it.declined || (it.ofDeclinedSeries() && !it.accepted)) { + it.copy(event = it.event.copy(status = EventStatus.Cancelled)) + } else { + it + } }, ) // A declined series still hands its accepted occurrences on before it goes. - val declined = rows.series.filter { it.declined }.map { it.event.uid }.toSet() + val declined = declinedSeries.map { it.event.uid }.toSet() return flattenOverrides(live, exdateStamp) .filterNot { it.overrideOf == null && it.uid in declined } .map { it.toParsedIcsEvent() } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt index 276d3156..2258e6ce 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRows.kt @@ -29,6 +29,8 @@ data class OverrideRow( val event: IcsEvent, /** The user declined this occurrence. */ val declined: Boolean = false, + /** The user accepted (or tentatively accepted) this occurrence on its own. */ + val accepted: Boolean = false, ) { val isCancelled: Boolean get() = event.status == EventStatus.Cancelled } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapperTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapperTest.kt index 3aad6fcb..a6096aa3 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapperTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/calendar/IcsExportMapperTest.kt @@ -318,4 +318,15 @@ class IcsExportMapperTest { assertThat(exportExDates("Europe/Berlin;20260110T100000\nEurope/Berlin;20260117T100000,junk", isAllDay = false)) .containsExactly("20260110T090000Z", "20260117T090000Z").inOrder() } + + @Test + fun `a bare day on a timed series is read at the series' time of day`() { + val tenBerlin = java.time.ZonedDateTime.of(2026, 1, 5, 10, 0, 0, 0, java.time.ZoneId.of("Europe/Berlin")) + .toInstant().toEpochMilli() + + assertThat(exportExDates("20260112", isAllDay = false, "Europe/Berlin", tenBerlin)) + .containsExactly("20260112T090000Z") + assertThat(exportRecurrenceDates("20260712", isAllDay = false, "Europe/Berlin", tenBerlin)) + .containsExactly("20260712T080000Z") + } } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt index 8f7c9e68..dba00cf0 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt @@ -215,7 +215,10 @@ class CalendarRowsTest { fun `a copy leaves declined invitations out but keeps an occurrence accepted on its own`() { val rows = CalendarRows( listOf(series("d").copy(declined = true), series("k", id = 2)), - listOf(OverrideRow(1, 1, null, occurrence(1), event("accepted"))), + listOf( + OverrideRow(1, 1, null, occurrence(1), event("accepted"), accepted = true), + OverrideRow(1, 1, null, occurrence(2), event("moved by the organizer")), + ), ) val plan = planCalendarCopy(rows, ::formatExdateStamp) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index cc6ff22e..9c649bac 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -522,7 +522,9 @@ as before. alone. The provider stores `RDATE` in the same `;` form as `EXDATE`, so `exportRecurrenceDates` resolves it the same way to UTC stamps (or bare days for an all-day series), line by line where several `RDATE`s were -stored; a `PERIOD` entry keeps its start. `IcsWriter` +stored; a `PERIOD` entry keeps its start, and a bare day on a timed series +becomes the occurrence at the series' time of day, so the copy (which never +goes through the parser) and a file get the same stamps. `IcsWriter` writes it as `RDATE:` / `RDATE;VALUE=DATE:`, anchors such a series to its zone like an RRULE series, and writes its `EXDATE` too; `IcsParser` reads `RDATE` through the same normalisation as `EXDATE`, so a foreign `TZID` or floating @@ -535,7 +537,8 @@ what landed before. It skips the `.ics` text: the writer pins a timed one-off to UTC and carries no colour or visibility; the direct mapping keeps them. Attendees and organizer are never read, and cancelled events and declined invitations are left out (an insert can't be cancelled; it would arrive live, and -a declined occurrence counts as deleted). A re-run is idempotent per +a declined occurrence counts as deleted, as does one of a declined series the +user didn't accept on its own). A re-run is idempotent per snapshot: a series already in the target keeps its overrides, so an occurrence changed since keeps its earlier copy rather than gaining a second one. From 8e99c46f3e301e4ac00d487f5263f1cf4be54043 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Sat, 14 Nov 2026 03:31:47 +0100 Subject: [PATCH 14/16] fix(#515, #325): review round 4 - declined rows dropped by row, not by UID --- .../de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt | 7 ++++--- .../calendula/domain/ics/CalendarRowsTest.kt | 7 +++++++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt index 2f4883a2..13046a57 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/ics/CalendarCopy.kt @@ -36,9 +36,10 @@ fun planCalendarCopy( }, ) // A declined series still hands its accepted occurrences on before it goes. - val declined = declinedSeries.map { it.event.uid }.toSet() - return flattenOverrides(live, exdateStamp) - .filterNot { it.overrideOf == null && it.uid in declined } + // The flattened series follow the standalone occurrences, one per row in order. + val flat = flattenOverrides(live, exdateStamp) + val standalone = flat.size - live.series.size + return flat.filterIndexed { i, _ -> i < standalone || live.series[i - standalone].eventId !in declinedIds } .map { it.toParsedIcsEvent() } } diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt index dba00cf0..4c763dbc 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/ics/CalendarRowsTest.kt @@ -277,4 +277,11 @@ class CalendarRowsTest { assertThat(IcsParser().parse(text).events.single().recurrenceDates) .containsExactly("20260110T140000Z", "20260111T090000Z") } + + @Test + fun `a declined row takes no other row with its UID along`() { + val rows = CalendarRows(listOf(series("u").copy(declined = true), series("u", id = 2)), emptyList()) + + assertThat(planCalendarCopy(rows, ::formatExdateStamp)).hasSize(1) + } } From ec060056ddaab56ef8c839fb8e0be35c4e0206ef Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Mon, 16 Nov 2026 20:01:01 +0100 Subject: [PATCH 15/16] fix(#325): copy events as a full-screen two-step flow with a route card --- .../calendula/ui/calendars/BackupScreen.kt | 3 +- .../ui/calendars/CopyEventsScreen.kt | 376 ++++++++++++++++++ .../calendula/ui/calendars/CopyEventsSheet.kt | 247 ------------ .../ui/calendars/CopyEventsViewModel.kt | 4 +- .../calendula/ui/common/ResultSummary.kt | 135 +++++++ .../calendula/ui/imports/ImportScreen.kt | 192 +-------- app/src/main/res/values/strings.xml | 3 +- floret-kit | 2 +- 8 files changed, 536 insertions(+), 426 deletions(-) create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsScreen.kt delete mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/ui/common/ResultSummary.kt diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt index 4dd5401a..67f31445 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/BackupScreen.kt @@ -188,7 +188,7 @@ fun BackupScreen( if (showCopy) { val calendars by copyViewModel.calendars.collectAsStateWithLifecycle() val selection by copyViewModel.selection.collectAsStateWithLifecycle() - CopyEventsSheet( + CopyEventsScreen( calendars = calendars, selection = selection, run = copyRun, @@ -196,6 +196,7 @@ fun BackupScreen( onSelectTarget = copyViewModel::setTarget, onStart = copyViewModel::start, onCancel = copyViewModel::cancel, + onClearFinished = copyViewModel::clearFinished, onDismiss = { showCopy = false copyViewModel.clearFinished() diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsScreen.kt new file mode 100644 index 00000000..e5e7ee21 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsScreen.kt @@ -0,0 +1,376 @@ +package de.jeanlucmakiola.calendula.ui.calendars + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.outlined.Info +import androidx.compose.material.icons.rounded.ArrowDownward +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi +import androidx.compose.material3.Icon +import androidx.compose.material3.LinearWavyProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.domain.FailureReason +import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip +import de.jeanlucmakiola.calendula.ui.common.CalendarFailure +import de.jeanlucmakiola.calendula.ui.common.CalendarPickerGroups +import de.jeanlucmakiola.calendula.ui.common.ImportSummaryStats +import de.jeanlucmakiola.calendula.ui.common.ResultBadge +import de.jeanlucmakiola.calendula.ui.common.ResultMessage +import de.jeanlucmakiola.calendula.ui.common.importSummaryNotes +import de.jeanlucmakiola.floret.components.ResultBadge as FloretResultBadge +import de.jeanlucmakiola.calendula.ui.common.orUnnamed +import de.jeanlucmakiola.floret.components.FullScreenPicker +import de.jeanlucmakiola.floret.components.GroupedHint +import de.jeanlucmakiola.floret.components.GroupedListInset +import de.jeanlucmakiola.floret.components.IconInfoCard + +/** + * Copy every event of one calendar into another (#325), in the import flow's + * steps: pick the source, pick the target and copy, watch it run, see the result. + * The run lives in [CopyEventsViewModel], so the screen can be closed and + * reopened mid-copy. + */ +@Composable +fun CopyEventsScreen( + calendars: CopyCalendars, + selection: CopySelection, + run: CopyRunState, + onSelectSource: (Long) -> Unit, + onSelectTarget: (Long) -> Unit, + onStart: () -> Unit, + onCancel: () -> Unit, + onClearFinished: () -> Unit, + onDismiss: () -> Unit, +) { + val list = (calendars as? CopyCalendars.Ready)?.calendars.orEmpty() + val sources = remember(list) { copySources(list) } + val source = sources.firstOrNull { it.id == selection.sourceId } + val targets = remember(list, source?.id) { copyTargets(list, source?.id) } + val target = targets.firstOrNull { it.id == selection.targetId } + var step by rememberSaveable { mutableStateOf(CopyStep.Source) } + val idle = run == CopyRunState.Idle + // The run's ends, held once seen so a calendar gone or a list reloading mid-run doesn't blank them. + val runSource = rememberLastSeen(selection.sourceId, list) + val runTarget = rememberLastSeen(selection.targetId, list) + // A source that stopped qualifying sends the target step back to the start. + // Keyed on the chosen id too: right after a pick the selection may not have arrived yet. + LaunchedEffect(step, selection.sourceId, source, calendars) { + val gone = selection.sourceId != null && source == null && calendars is CopyCalendars.Ready + if (step == CopyStep.Target && gone) step = CopyStep.Source + } + + FullScreenPicker( + title = stringResource( + when { + !idle -> R.string.calendars_copy_action + step == CopyStep.Source -> R.string.calendars_copy_from_title + else -> R.string.calendars_copy_to_title + }, + ), + onDismiss = { if (idle && step == CopyStep.Target) step = CopyStep.Source else onDismiss() }, + // The target step's back only steps back, so it mustn't preview closing the screen. + predictiveBack = !(idle && step == CopyStep.Target), + scrollable = idle, + actions = { + if (idle && step == CopyStep.Target) { + Button( + onClick = onStart, + enabled = source != null && target != null, + modifier = Modifier.padding(end = 12.dp), + ) { + Text(stringResource(R.string.calendars_copy_start)) + } + } + }, + ) { + if (!idle) { + val copyMore = { + onClearFinished() + step = CopyStep.Source + } + CopyRun( + run = run, + source = runSource, + target = runTarget, + onCancel = onCancel, + // A retry only where the picker would still offer both ends; otherwise pick again. + onRetry = if (source != null && target != null) onStart else copyMore, + onCopyMore = copyMore, + onClose = onDismiss, + ) + return@FullScreenPicker + } + when (calendars) { + CopyCalendars.Loading -> { + Box(Modifier.fillMaxWidth().padding(32.dp), contentAlignment = Alignment.Center) { + CircularProgressIndicator() + } + return@FullScreenPicker + } + CopyCalendars.Failure -> { + CalendarFailure(reason = FailureReason.ProviderUnavailable, onRetry = onDismiss) + return@FullScreenPicker + } + is CopyCalendars.Ready -> Unit + } + if (sources.isEmpty()) { + GroupedHint(stringResource(R.string.calendars_copy_none)) + return@FullScreenPicker + } + when (step) { + CopyStep.Source -> { + IconInfoCard( + icon = Icons.Outlined.Info, + iconContentDescription = null, + modifier = Modifier.padding(horizontal = GroupedListInset), + ) { + Text(stringResource(R.string.calendars_copy_hint), style = MaterialTheme.typography.bodyMedium) + } + Spacer(Modifier.height(16.dp)) + CalendarPickerGroups( + calendars = sources, + selectedId = source?.id, + onSelect = { + onSelectSource(it) + step = CopyStep.Target + }, + ) + } + CopyStep.Target -> { + CopyRouteCard(source, target, Modifier.padding(horizontal = GroupedListInset)) + Spacer(Modifier.height(16.dp)) + CalendarPickerGroups( + calendars = targets, + selectedId = target?.id, + onSelect = onSelectTarget, + ) + } + } + } +} + +private enum class CopyStep { Source, Target } + +/** Progress while the copy runs, then its outcome; both under the route it took. */ +@Composable +private fun ColumnScope.CopyRun( + run: CopyRunState, + source: CalendarSource?, + target: CalendarSource?, + onCancel: () -> Unit, + onRetry: () -> Unit, + onCopyMore: () -> Unit, + onClose: () -> Unit, +) { + // Centred where it fits, scrolling where it doesn't (landscape, large fonts). + BoxWithConstraints(Modifier.fillMaxWidth().weight(1f)) { + Column( + Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .heightIn(min = maxHeight) + .padding(horizontal = GroupedListInset) + .padding(top = 8.dp, bottom = 24.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.SpaceBetween, + ) { + CopyRouteCard(source, target, pickable = false) + Column(Modifier.fillMaxWidth().padding(vertical = 24.dp), horizontalAlignment = Alignment.CenterHorizontally) { + when (run) { + is CopyRunState.Running -> CopyProgress(run) + is CopyRunState.Done -> CopyDone(run) + CopyRunState.Cancelled -> { + FloretResultBadge( + Icons.Default.Close, + MaterialTheme.colorScheme.secondaryContainer, + MaterialTheme.colorScheme.onSecondaryContainer, + ) + ResultMessage(stringResource(R.string.calendars_copy_cancelled)) + } + CopyRunState.Failed -> { + ResultBadge(error = true) + ResultMessage(stringResource(R.string.calendars_copy_failed)) + } + CopyRunState.Idle -> Unit + } + } + when (run) { + is CopyRunState.Running -> OutlinedButton(onClick = onCancel, modifier = Modifier.fillMaxWidth()) { + Text(stringResource(R.string.dialog_cancel)) + } + is CopyRunState.Done -> CopyEndButtons(stringResource(R.string.calendars_copy_more), onCopyMore, onClose) + CopyRunState.Cancelled, CopyRunState.Failed -> + CopyEndButtons(stringResource(R.string.state_retry), onRetry, onClose) + CopyRunState.Idle -> Unit + } + } + } +} + +/** The calendar with [id] in [list], or the last one seen under that id while it is missing. */ +@Composable +private fun rememberLastSeen(id: Long?, list: List): CalendarSource? { + val held = remember(id) { mutableStateOf(null) } + list.firstOrNull { it.id == id }?.let { held.value = it } + return held.value +} + +@OptIn(ExperimentalMaterial3ExpressiveApi::class) +@Composable +private fun CopyProgress(run: CopyRunState.Running) { + val total = run.total + if (total == null || total == 0) { + LinearWavyProgressIndicator(modifier = Modifier.fillMaxWidth()) + } else { + LinearWavyProgressIndicator(progress = { run.done.toFloat() / total }, modifier = Modifier.fillMaxWidth()) + } + Spacer(Modifier.height(16.dp)) + Text( + text = copyProgressText(run), + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) +} + +/** "Reading events…" until the source is read, then "120 of 2,400 events". */ +@Composable +fun copyProgressText(run: CopyRunState.Running): String { + val total = run.total ?: return stringResource(R.string.calendars_copy_reading) + return pluralStringResource(R.plurals.calendars_copy_progress, total, run.done, total) +} + +@Composable +private fun CopyDone(run: CopyRunState.Done) { + val summary = run.summary + // As on the import: only a run the target cut short reads as an error. + ResultBadge(error = run.stopped) + ResultMessage( + title = stringResource(run.titleRes), + notes = importSummaryNotes( + summary, + stoppedNote = if (run.stopped) { + pluralStringResource(R.plurals.calendars_copy_stopped, summary.notAttempted, summary.notAttempted) + } else { + null + }, + ), + ) + Spacer(Modifier.height(24.dp)) + ImportSummaryStats(summary) +} + +/** The way on ([secondary], e.g. Copy more) above the way out (Close). */ +@Composable +private fun CopyEndButtons(secondary: String, onSecondary: () -> Unit, onClose: () -> Unit) { + Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedButton(onClick = onSecondary, modifier = Modifier.fillMaxWidth()) { Text(secondary) } + Button(onClick = onClose, modifier = Modifier.fillMaxWidth()) { Text(stringResource(R.string.import_close)) } + } +} + +/** + * Where the events come from and go to, with an arrow between. A missing end + * reads "Choose a calendar" while [pickable], or as unnamed on the run screens. + */ +@Composable +private fun CopyRouteCard( + source: CalendarSource?, + target: CalendarSource?, + modifier: Modifier = Modifier, + pickable: Boolean = true, +) { + Surface( + modifier = modifier.fillMaxWidth(), + shape = RoundedCornerShape(24.dp), + color = MaterialTheme.colorScheme.surfaceContainerHigh, + ) { + Column(Modifier.padding(16.dp)) { + CopyRouteEnd(stringResource(R.string.calendars_copy_from), source, pickable) + Box(Modifier.width(40.dp).padding(vertical = 4.dp), contentAlignment = Alignment.Center) { + Surface(shape = CircleShape, color = MaterialTheme.colorScheme.primaryContainer) { + Icon( + Icons.Rounded.ArrowDownward, + contentDescription = null, + tint = MaterialTheme.colorScheme.onPrimaryContainer, + modifier = Modifier.padding(6.dp).size(20.dp), + ) + } + } + CopyRouteEnd(stringResource(R.string.calendars_copy_to), target, pickable) + } + } +} + +@Composable +private fun CopyRouteEnd(label: String, calendar: CalendarSource?, pickable: Boolean) { + Row(verticalAlignment = Alignment.CenterVertically) { + if (calendar != null) { + CalendarColorChip(calendar.color) + } else { + Surface( + modifier = Modifier.size(40.dp), + shape = CircleShape, + color = MaterialTheme.colorScheme.surfaceContainerHigh, + border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant), + ) {} + } + Spacer(Modifier.width(16.dp)) + Column { + Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text( + calendar?.displayName?.orUnnamed() + ?: if (pickable) stringResource(R.string.calendars_copy_choose) else "".orUnnamed(), + style = MaterialTheme.typography.titleMedium, + color = if (calendar != null) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (calendar != null) { + Text( + if (calendar.isLocal) stringResource(R.string.calendars_local_header) else calendar.accountName, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt deleted file mode 100644 index 818bd4db..00000000 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsSheet.kt +++ /dev/null @@ -1,247 +0,0 @@ -package de.jeanlucmakiola.calendula.ui.calendars - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi -import androidx.compose.material3.LinearWavyProgressIndicator -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedButton -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.res.pluralStringResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.unit.dp -import de.jeanlucmakiola.calendula.R -import de.jeanlucmakiola.calendula.domain.CalendarSource -import de.jeanlucmakiola.calendula.domain.FailureReason -import de.jeanlucmakiola.calendula.ui.common.CalendarFailure -import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip -import de.jeanlucmakiola.calendula.ui.common.CalendarPickerGroups -import de.jeanlucmakiola.calendula.ui.common.orUnnamed -import de.jeanlucmakiola.floret.components.FullScreenPicker -import de.jeanlucmakiola.floret.components.GroupedHint -import de.jeanlucmakiola.floret.components.GroupedRow -import de.jeanlucmakiola.floret.components.Position - -/** - * Copy every event of one calendar into another (#325): pick the source and the - * target, copy, watch it run. The run lives in [CopyEventsViewModel], so this - * sheet can be closed and reopened mid-copy. - */ -@Composable -fun CopyEventsSheet( - calendars: CopyCalendars, - selection: CopySelection, - run: CopyRunState, - onSelectSource: (Long) -> Unit, - onSelectTarget: (Long) -> Unit, - onStart: () -> Unit, - onCancel: () -> Unit, - onDismiss: () -> Unit, -) { - val list = (calendars as? CopyCalendars.Ready)?.calendars.orEmpty() - val running = run is CopyRunState.Running - val sources = remember(list) { copySources(list) } - // A running copy keeps showing its source even if it stopped qualifying meanwhile. - val source = (if (running) list else sources).firstOrNull { it.id == selection.sourceId } - val targets = remember(list, source?.id) { copyTargets(list, source?.id) } - val target = targets.firstOrNull { it.id == selection.targetId } - var picking by rememberSaveable { mutableStateOf(null) } - - FullScreenPicker( - title = stringResource(R.string.calendars_copy_action), - onDismiss = onDismiss, - predictiveBack = true, - actions = { - if (!running) { - TextButton(onClick = onStart, enabled = source != null && target != null) { - Text(stringResource(R.string.calendars_copy_start)) - } - } - }, - ) { - GroupedHint(stringResource(R.string.calendars_copy_hint), style = MaterialTheme.typography.bodySmall) - // A copy under way keeps its progress and Cancel whatever the list does. - if (run == CopyRunState.Idle) when (calendars) { - CopyCalendars.Loading -> { - Box(Modifier.fillMaxWidth().padding(32.dp), contentAlignment = Alignment.Center) { - CircularProgressIndicator() - } - return@FullScreenPicker - } - CopyCalendars.Failure -> { - CalendarFailure(reason = FailureReason.ProviderUnavailable, onRetry = onDismiss) - return@FullScreenPicker - } - is CopyCalendars.Ready -> Unit - } - if (sources.isEmpty() && run == CopyRunState.Idle) { - GroupedHint(stringResource(R.string.calendars_copy_none)) - return@FullScreenPicker - } - CopyEndRow( - label = stringResource(R.string.calendars_copy_from), - calendar = source, - position = Position.Top, - onClick = if (running) null else ({ picking = CopyEnd.Source }), - ) - CopyEndRow( - label = stringResource(R.string.calendars_copy_to), - calendar = target, - position = Position.Bottom, - onClick = if (running || source == null) null else ({ picking = CopyEnd.Target }), - ) - Column( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 16.dp), - verticalArrangement = Arrangement.spacedBy(12.dp), - ) { - when (run) { - is CopyRunState.Running -> CopyProgress(run, onCancel) - is CopyRunState.Done -> CopySummary(run) - CopyRunState.Cancelled -> CopyNote(stringResource(R.string.calendars_copy_cancelled)) - CopyRunState.Failed -> CopyNote( - stringResource(R.string.calendars_copy_failed), - error = true, - ) - CopyRunState.Idle -> Unit - } - } - } - - when (picking) { - CopyEnd.Source -> FullScreenPicker( - title = stringResource(R.string.calendars_copy_from_title), - onDismiss = { picking = null }, - predictiveBack = true, - ) { - CalendarPickerGroups( - calendars = sources, - selectedId = source?.id, - onSelect = { - onSelectSource(it) - picking = null - }, - ) - } - CopyEnd.Target -> FullScreenPicker( - title = stringResource(R.string.calendars_copy_to_title), - onDismiss = { picking = null }, - predictiveBack = true, - ) { - CalendarPickerGroups( - calendars = targets, - selectedId = target?.id, - onSelect = { - onSelectTarget(it) - picking = null - }, - ) - } - null -> Unit - } -} - -private enum class CopyEnd { Source, Target } - -@Composable -private fun CopyEndRow( - label: String, - calendar: CalendarSource?, - position: Position, - onClick: (() -> Unit)?, -) { - GroupedRow( - title = label, - summary = calendar?.displayName?.orUnnamed() ?: stringResource(R.string.calendars_copy_choose), - position = position, - dimmed = onClick == null, - leading = calendar?.let { { CalendarColorChip(it.color) } }, - onClick = onClick, - ) -} - -@OptIn(ExperimentalMaterial3ExpressiveApi::class) -@Composable -private fun CopyProgress(run: CopyRunState.Running, onCancel: () -> Unit) { - val total = run.total - if (total == null || total == 0) { - LinearWavyProgressIndicator(modifier = Modifier.fillMaxWidth()) - } else { - LinearWavyProgressIndicator( - progress = { run.done.toFloat() / total }, - modifier = Modifier.fillMaxWidth(), - ) - } - Text( - text = copyProgressText(run), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - OutlinedButton(onClick = onCancel, modifier = Modifier.fillMaxWidth()) { - Text(stringResource(R.string.dialog_cancel)) - } -} - -/** "Reading events…" until the source is read, then "120 of 2,400 events". */ -@Composable -fun copyProgressText(run: CopyRunState.Running): String { - val total = run.total ?: return stringResource(R.string.calendars_copy_reading) - return pluralStringResource(R.plurals.calendars_copy_progress, total, run.done, total) -} - -@Composable -private fun CopySummary(run: CopyRunState.Done) { - val summary = run.summary - Text( - stringResource(run.titleRes), - style = MaterialTheme.typography.titleMedium, - color = MaterialTheme.colorScheme.onSurface, - ) - Row(horizontalArrangement = Arrangement.spacedBy(24.dp)) { - CopyCount(stringResource(R.string.import_done_added_label), summary.imported) - if (summary.skippedDuplicate > 0) { - CopyCount(stringResource(R.string.import_done_skipped_label), summary.skippedDuplicate) - } - if (summary.failed > 0) CopyCount(stringResource(R.string.import_done_failed_label), summary.failed) - } - if (summary.skippedDuplicate > 0) CopyNote(stringResource(R.string.import_done_dedup_note)) - if (summary.failed > 0) CopyNote(stringResource(R.string.import_done_failed_note)) - if (summary.notAttempted > 0) { - CopyNote( - pluralStringResource(R.plurals.calendars_copy_stopped, summary.notAttempted, summary.notAttempted), - error = true, - ) - } -} - -@Composable -private fun CopyCount(label: String, count: Int) { - Column { - Text(count.toString(), style = MaterialTheme.typography.headlineSmall, color = MaterialTheme.colorScheme.onSurface) - Text(label, style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.onSurfaceVariant) - } -} - -@Composable -private fun CopyNote(text: String, error: Boolean = false) { - Text( - text, - style = MaterialTheme.typography.bodyMedium, - color = if (error) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, - ) -} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt index f07df8b7..d94fe9c4 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsViewModel.kt @@ -120,7 +120,7 @@ data class CopySelection(val sourceId: Long? = null, val targetId: Long? = null) CopySelection(sourceId = id, targetId = targetId?.takeIf { it != id }) } -/** The calendar list the copy sheet picks from. */ +/** The calendar list the copy screen picks from. */ sealed interface CopyCalendars { data object Loading : CopyCalendars data object Failure : CopyCalendars @@ -137,7 +137,7 @@ sealed interface CopyRunState { /** The target stopped taking events part way, so some were never tried. */ val stopped: Boolean get() = summary.notAttempted > 0 - /** How the run ended, the same words on the row and in the sheet. */ + /** How the run ended, the same words on the row and on the result screen. */ @get:StringRes val titleRes: Int get() = when { stopped -> R.string.calendars_copy_stopped_title diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/ResultSummary.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/ResultSummary.kt new file mode 100644 index 00000000..0c9d5375 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/common/ResultSummary.kt @@ -0,0 +1,135 @@ +package de.jeanlucmakiola.calendula.ui.common + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.height +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.PriorityHigh +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary +import de.jeanlucmakiola.floret.components.ResultBadge as FloretResultBadge + +/** floret's [FloretResultBadge] as a check on success, or an exclamation mark in the error colours. */ +@Composable +fun ResultBadge(error: Boolean) { + val scheme = MaterialTheme.colorScheme + if (error) { + FloretResultBadge(Icons.Default.PriorityHigh, scheme.errorContainer, scheme.onErrorContainer) + } else { + FloretResultBadge(Icons.Default.Check, scheme.primaryContainer, scheme.onPrimaryContainer) + } +} + +/** A result screen's headline under its badge, then its notes; an error note takes the error colour. */ +@Composable +fun ResultMessage(title: String, notes: List = emptyList()) { + Spacer(Modifier.height(24.dp)) + Text( + title, + style = MaterialTheme.typography.headlineSmall, + color = MaterialTheme.colorScheme.onSurface, + textAlign = TextAlign.Center, + ) + notes.forEach { note -> + Spacer(Modifier.height(8.dp)) + Text( + note.text, + style = MaterialTheme.typography.bodyMedium, + color = if (note.error) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + ) + } +} + +data class ResultNote(val text: String, val error: Boolean = false) + +/** The notes an import summary carries: failures, skipped duplicates, then [stoppedNote] when part was never tried. */ +@Composable +fun importSummaryNotes(summary: IcsImportSummary, stoppedNote: String?): List = buildList { + if (summary.failed > 0) add(ResultNote(stringResource(R.string.import_done_failed_note))) + if (summary.skippedDuplicate > 0) add(ResultNote(stringResource(R.string.import_done_dedup_note))) + if (stoppedNote != null) add(ResultNote(stoppedNote, error = true)) +} + +/** Added / skipped / failed as big-number tiles, the latter two only when non-zero. */ +@Composable +fun ImportSummaryStats(summary: IcsImportSummary, modifier: Modifier = Modifier) { + Row(modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) { + ResultStatCard( + count = summary.imported, + label = stringResource(R.string.import_done_added_label), + contentDescription = pluralStringResource(R.plurals.import_done_imported, summary.imported, summary.imported), + container = MaterialTheme.colorScheme.secondaryContainer, + onContainer = MaterialTheme.colorScheme.onSecondaryContainer, + ) + if (summary.skippedDuplicate > 0) { + ResultStatCard( + count = summary.skippedDuplicate, + label = stringResource(R.string.import_done_skipped_label), + contentDescription = pluralStringResource( + R.plurals.import_done_skipped, + summary.skippedDuplicate, + summary.skippedDuplicate, + ), + container = MaterialTheme.colorScheme.surfaceContainerHighest, + onContainer = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + if (summary.failed > 0) { + ResultStatCard( + count = summary.failed, + label = stringResource(R.string.import_done_failed_label), + contentDescription = pluralStringResource(R.plurals.import_done_failed, summary.failed, summary.failed), + container = MaterialTheme.colorScheme.errorContainer, + onContainer = MaterialTheme.colorScheme.onErrorContainer, + ) + } + } +} + +/** A big-number tonal tile summarising one outcome. */ +@Composable +private fun RowScope.ResultStatCard( + count: Int, + label: String, + contentDescription: String, + container: Color, + onContainer: Color, +) { + Surface( + modifier = Modifier + .weight(1f) + .clearAndSetSemantics { this.contentDescription = contentDescription }, + shape = RoundedCornerShape(24.dp), + color = container, + ) { + Column( + Modifier.padding(vertical = 20.dp, horizontal = 12.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + Text(count.toString(), style = MaterialTheme.typography.displaySmall, color = onContainer) + Text(label, style = MaterialTheme.typography.labelLarge, color = onContainer.copy(alpha = 0.85f)) + } + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/imports/ImportScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/imports/ImportScreen.kt index 9fd95c6c..242e24b2 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/imports/ImportScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/imports/ImportScreen.kt @@ -1,15 +1,9 @@ package de.jeanlucmakiola.calendula.ui.imports import android.net.Uri -import androidx.compose.animation.core.Animatable -import androidx.compose.animation.core.Spring -import androidx.compose.animation.core.spring -import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth @@ -17,13 +11,9 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Check import androidx.compose.material.icons.filled.Close -import androidx.compose.material.icons.filled.PriorityHigh import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api @@ -31,25 +21,17 @@ import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold -import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.graphicsLayer -import androidx.compose.ui.semantics.clearAndSetSemantics -import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp @@ -59,6 +41,10 @@ import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.ics.IcsParseWarning import de.jeanlucmakiola.calendula.ui.common.CalendarPickerGroups +import de.jeanlucmakiola.calendula.ui.common.ImportSummaryStats +import de.jeanlucmakiola.calendula.ui.common.ResultBadge +import de.jeanlucmakiola.calendula.ui.common.ResultMessage +import de.jeanlucmakiola.calendula.ui.common.importSummaryNotes import de.jeanlucmakiola.floret.identity.predictiveBack /** @@ -211,18 +197,6 @@ private fun ManyContent( @Composable private fun DoneContent(state: ImportUiState.Done, onClose: () -> Unit) { - // A little expressive pop on the success badge — springs in on first show. - val badgeScale = remember { Animatable(0.7f) } - LaunchedEffect(Unit) { - badgeScale.animateTo( - targetValue = 1f, - animationSpec = spring( - dampingRatio = Spring.DampingRatioMediumBouncy, - stiffness = Spring.StiffnessLow, - ), - ) - } - // Part of the file never reached the calendar, so the screen doesn't get to // read as a plain success. val stopped = state.summary.notAttempted > 0 @@ -232,118 +206,23 @@ private fun DoneContent(state: ImportUiState.Done, onClose: () -> Unit) { horizontalAlignment = Alignment.CenterHorizontally, ) { Spacer(Modifier.weight(1f)) - Box( - Modifier - .size(112.dp) - .graphicsLayer { - scaleX = badgeScale.value - scaleY = badgeScale.value - } - .clip(CircleShape) - .background( - if (stopped) { - MaterialTheme.colorScheme.errorContainer - } else { - MaterialTheme.colorScheme.primaryContainer - }, - ), - contentAlignment = Alignment.Center, - ) { - Icon( - if (stopped) Icons.Default.PriorityHigh else Icons.Default.Check, - contentDescription = null, - tint = if (stopped) { - MaterialTheme.colorScheme.onErrorContainer - } else { - MaterialTheme.colorScheme.onPrimaryContainer - }, - modifier = Modifier.size(56.dp), - ) - } - Spacer(Modifier.height(24.dp)) - Text( - stringResource( + ResultBadge(error = stopped) + ResultMessage( + title = stringResource( if (stopped) R.string.import_done_stopped_title else R.string.import_done_title, ), - style = MaterialTheme.typography.headlineSmall, - color = MaterialTheme.colorScheme.onSurface, + // The counts cover the part of the file that was tried, so say how much never was. + notes = importSummaryNotes( + state.summary, + stoppedNote = if (stopped) { + pluralStringResource(R.plurals.import_done_stopped, state.summary.notAttempted, state.summary.notAttempted) + } else { + null + }, + ), ) - if (state.summary.failed > 0) { - Spacer(Modifier.height(8.dp)) - Text( - stringResource(R.string.import_done_failed_note), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center, - ) - } - if (state.summary.skippedDuplicate > 0) { - Spacer(Modifier.height(8.dp)) - Text( - stringResource(R.string.import_done_dedup_note), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center, - ) - } - // The one note that isn't about individual events: the counts below cover - // the part of the file that was tried, so say how much never was. - if (stopped) { - Spacer(Modifier.height(8.dp)) - Text( - pluralStringResource( - R.plurals.import_done_stopped, - state.summary.notAttempted, - state.summary.notAttempted, - ), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.error, - textAlign = TextAlign.Center, - ) - } Spacer(Modifier.height(24.dp)) - Row( - Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - ImportStatCard( - count = state.summary.imported, - label = stringResource(R.string.import_done_added_label), - contentDescription = pluralStringResource( - R.plurals.import_done_imported, - state.summary.imported, - state.summary.imported, - ), - container = MaterialTheme.colorScheme.secondaryContainer, - onContainer = MaterialTheme.colorScheme.onSecondaryContainer, - ) - if (state.summary.skippedDuplicate > 0) { - ImportStatCard( - count = state.summary.skippedDuplicate, - label = stringResource(R.string.import_done_skipped_label), - contentDescription = pluralStringResource( - R.plurals.import_done_skipped, - state.summary.skippedDuplicate, - state.summary.skippedDuplicate, - ), - container = MaterialTheme.colorScheme.surfaceContainerHighest, - onContainer = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - if (state.summary.failed > 0) { - ImportStatCard( - count = state.summary.failed, - label = stringResource(R.string.import_done_failed_label), - contentDescription = pluralStringResource( - R.plurals.import_done_failed, - state.summary.failed, - state.summary.failed, - ), - container = MaterialTheme.colorScheme.errorContainer, - onContainer = MaterialTheme.colorScheme.onErrorContainer, - ) - } - } + ImportSummaryStats(state.summary) Spacer(Modifier.weight(1f)) Button( onClick = onClose, @@ -354,41 +233,6 @@ private fun DoneContent(state: ImportUiState.Done, onClose: () -> Unit) { } } -/** A big-number tonal tile summarising one import outcome (added / skipped / failed). */ -@Composable -private fun RowScope.ImportStatCard( - count: Int, - label: String, - contentDescription: String, - container: Color, - onContainer: Color, -) { - Surface( - modifier = Modifier - .weight(1f) - .clearAndSetSemantics { this.contentDescription = contentDescription }, - shape = RoundedCornerShape(24.dp), - color = container, - ) { - Column( - Modifier.padding(vertical = 20.dp, horizontal = 12.dp), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(2.dp), - ) { - Text( - count.toString(), - style = MaterialTheme.typography.displaySmall, - color = onContainer, - ) - Text( - label, - style = MaterialTheme.typography.labelLarge, - color = onContainer.copy(alpha = 0.85f), - ) - } - } -} - @Composable private fun WarningText(warning: IcsParseWarning) { val text = when (warning) { diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 791612c5..a699fe13 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -891,13 +891,14 @@ No calendar can take the imported events yet. Copy events Copy one calendar\'s events into another, for example to move off Google. - Copies your events, including repeating ones with the occurrences you changed or deleted. Cancelled events and invitations you declined are left out, guests stay behind, and the original calendar is left as it is. + The original calendar stays as it is. Guests and invitations you declined are left out. From To Choose a calendar Copy from Copy into Copy + Copy more Reading events… %1$d of %2$d event diff --git a/floret-kit b/floret-kit index 389cc029..f5b51922 160000 --- a/floret-kit +++ b/floret-kit @@ -1 +1 @@ -Subproject commit 389cc0298f341e293dee15f27dada3d72123b5f9 +Subproject commit f5b51922cf5ec2dc6eff2c70e08fbfec870eb138 From 2c3e90951553b22ec5ac5e275bc5ef97a00ece2c Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Mon, 16 Nov 2026 20:11:01 +0100 Subject: [PATCH 16/16] fix(#325): end-of-flow buttons as the app's primary + text button pair --- .../ui/calendars/CopyEventsScreen.kt | 28 +++++++++++++------ .../calendula/ui/imports/ImportScreen.kt | 9 +++--- 2 files changed, 23 insertions(+), 14 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsScreen.kt index e5e7ee21..546059ca 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/calendars/CopyEventsScreen.kt @@ -28,7 +28,7 @@ import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.Icon import androidx.compose.material3.LinearWavyProgressIndicator import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.TextButton import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable @@ -54,6 +54,7 @@ import de.jeanlucmakiola.calendula.ui.common.ImportSummaryStats import de.jeanlucmakiola.calendula.ui.common.ResultBadge import de.jeanlucmakiola.calendula.ui.common.ResultMessage import de.jeanlucmakiola.calendula.ui.common.importSummaryNotes +import de.jeanlucmakiola.floret.components.OnboardingPrimaryButton import de.jeanlucmakiola.floret.components.ResultBadge as FloretResultBadge import de.jeanlucmakiola.calendula.ui.common.orUnnamed import de.jeanlucmakiola.floret.components.FullScreenPicker @@ -232,12 +233,21 @@ private fun ColumnScope.CopyRun( } } when (run) { - is CopyRunState.Running -> OutlinedButton(onClick = onCancel, modifier = Modifier.fillMaxWidth()) { + is CopyRunState.Running -> TextButton(onClick = onCancel, modifier = Modifier.fillMaxWidth()) { Text(stringResource(R.string.dialog_cancel)) } - is CopyRunState.Done -> CopyEndButtons(stringResource(R.string.calendars_copy_more), onCopyMore, onClose) - CopyRunState.Cancelled, CopyRunState.Failed -> - CopyEndButtons(stringResource(R.string.state_retry), onRetry, onClose) + is CopyRunState.Done -> CopyEndButtons( + primary = stringResource(R.string.import_close), + onPrimary = onClose, + secondary = stringResource(R.string.calendars_copy_more), + onSecondary = onCopyMore, + ) + CopyRunState.Cancelled, CopyRunState.Failed -> CopyEndButtons( + primary = stringResource(R.string.state_retry), + onPrimary = onRetry, + secondary = stringResource(R.string.import_close), + onSecondary = onClose, + ) CopyRunState.Idle -> Unit } } @@ -298,10 +308,10 @@ private fun CopyDone(run: CopyRunState.Done) { /** The way on ([secondary], e.g. Copy more) above the way out (Close). */ @Composable -private fun CopyEndButtons(secondary: String, onSecondary: () -> Unit, onClose: () -> Unit) { - Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) { - OutlinedButton(onClick = onSecondary, modifier = Modifier.fillMaxWidth()) { Text(secondary) } - Button(onClick = onClose, modifier = Modifier.fillMaxWidth()) { Text(stringResource(R.string.import_close)) } +private fun CopyEndButtons(primary: String, onPrimary: () -> Unit, secondary: String, onSecondary: () -> Unit) { + Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) { + OnboardingPrimaryButton(text = primary, onClick = onPrimary) + TextButton(onClick = onSecondary, modifier = Modifier.fillMaxWidth()) { Text(secondary) } } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/imports/ImportScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/imports/ImportScreen.kt index 242e24b2..3a957985 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/imports/ImportScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/imports/ImportScreen.kt @@ -37,6 +37,7 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle +import de.jeanlucmakiola.floret.components.OnboardingPrimaryButton import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.domain.EventForm import de.jeanlucmakiola.calendula.domain.ics.IcsParseWarning @@ -224,12 +225,10 @@ private fun DoneContent(state: ImportUiState.Done, onClose: () -> Unit) { Spacer(Modifier.height(24.dp)) ImportSummaryStats(state.summary) Spacer(Modifier.weight(1f)) - Button( + OnboardingPrimaryButton( + text = stringResource(R.string.import_close), onClick = onClose, - modifier = Modifier.fillMaxWidth(), - ) { - Text(stringResource(R.string.import_close)) - } + ) } }