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