Ticking a repeating task moves the series on (#137) (#144)
Beta — Codeberg pre-release / detect (push) Successful in 5s
Beta — Codeberg pre-release / beta (push) Skipped

In Agendula's own storage, ticking off the current occurrence of a repeating task now moves the series on to its next date and keeps a completed copy, as tasks.org and Apple Reminders do.

Before, the series stayed open and the completion was a `RECURRENCE-ID` override with `STATUS:COMPLETED` in the same resource. That's valid iCalendar, but Infomaniak's web view and Apple Reminders ignore it and keep showing the task as open, which is what #137 reports. The reporter hasn't confirmed their storage mode yet. With tasks.org/OpenTasks the provider already moves the series on, so this change is about the built-in CalDAV sync.

How it works (`RoomTasksDataSource`):
- Ticking or cancelling the series' **first open occurrence** moves the master to its next open occurrence. Closed overrides on either side become standalone completed copies (new UID, fresh alarm identities), including the ones 1.3.0 left behind. `COUNT` drops by the occurrences used up (counted before `EXDATE`, shared with `splitSeries`), `EXDATE` values before the new start are dropped, and status and progress are reset. An edited occurrence is converted in place, so its id, edits and own properties survive. Lines inside nested components, such as a `VALARM`'s `UID`, are kept.
- Series with `RDATE`s keep the override model, because moving the anchor onto an `RDATE` would re-align the `RRULE`. So do recurring subtasks, whose copies would otherwise pile up under the parent.
- How the series moved is recorded in two new local tables, `advanced_occurrences` and `advanced_detached` (schema v5, migration and migration test included). They are never part of the synced `VTODO`. A record keeps mapping the occurrence to its copy (pruned after 30 days), so the detail screen and reminders find the copy even after it was edited. Every save path goes through one check: when the only thing that changes on a copy is that it reopens (compared as the editor writes values back), the move is undone. That covers undo, the completed section, the editor, the detail screen and other apps through Agendula's provider. The anchor goes back, `COUNT` regains what it spent, the dropped `EXDATE`s return in the list's own value shape, other edits made since are kept, and a reopened state such as 40% stays on the occurrence. Detached overrides come back as overrides; one deleted since, or given its own parent or subtasks, is excluded instead. A copy that was edited, moved or given subtasks, or whose series moved on, changed its rule or was deleted, reopens as a task of its own.
- If a sync discards the local version of a moved series because the server's is newer, the copies of moves the server never saw are deleted too, and the server's own overrides stand for those occurrences. Moves already uploaded are marked settled and left alone.
- `task(series, anchor)` resolves a moved-past occurrence to its copy, so the detail screen and reminder checks see it as done. The repository then acts on the row it resolved, including the detail screen's subtasks, so deleting or saving from a screen opened before the move can't hit the whole series.
- A stale tick (an old notification or widget row) for an occurrence the series has already moved past does nothing.
- Ticking the last open occurrence closes the series, and reopening any of its occurrences reopens the series.
- Any other occurrence (with earlier ones still open) keeps the override model.

Also fixed here: `AgendulaTaskProviderTest` failed on `release/v1.3.1` whenever Agendula ran on an external provider, because `ProviderWriter` checked the active store first. Read-only tables are now refused as such whichever store is active (one exhaustive `when` per operation), and the two tests that check value errors skip when the provider takes no writes at all.

Tests: `RoomTasksDataSourceTest` covers each case above. There is also a migration test, a `ProviderWriterTest` for reopening through the provider, and `RoomSyncStoreAdvancesTest` (full flavour) for the sync discard. The full on-device suite (223 tests) passes on the emulator, and the unit tests pass for both flavours.

Closes #137

Co-authored-by: Jean-Luc Makiola <business@jeanlucmakiola.de>
Reviewed-on: https://codeberg.org/jlmakiola/agendula/pulls/144
This commit is contained in:
Jean-Luc Makiolaandmakiolaj committed 2026-11-09 18:19:57 +01:00
1 parent 7bcac70cec
commit 68495a936c
18 files changed
+1963 -91

No files matched your search

@@ -89,7 +89,7 @@ object DataProvideModule {
// backed-up `.db` does not. The backup rules carry all three files and
// the app checkpoints on ON_STOP.
.setJournalMode(RoomDatabase.JournalMode.WRITE_AHEAD_LOGGING)
.addMigrations(TasksDatabase.MIGRATION_1_2, TasksDatabase.MIGRATION_2_3, TasksDatabase.MIGRATION_3_4)
.addMigrations(TasksDatabase.MIGRATION_1_2, TasksDatabase.MIGRATION_2_3, TasksDatabase.MIGRATION_3_4, TasksDatabase.MIGRATION_4_5)
.build()
/**
@@ -68,9 +68,10 @@ class TasksRepositoryImpl @Inject constructor(
override fun taskDetail(taskId: Long, occurrenceStart: Instant?): Flow<TaskDetail?> = observing {
dataSource.task(taskId, occurrenceStart)?.let { task ->
val owner = if (task.seriesId == null) resolvedRow(task, taskId) else taskId
TaskDetail(
task = task,
subtasks = SeriesCollapse.visible(dataSource.subtasks(taskId)).filter { it.taskId != taskId },
subtasks = SeriesCollapse.visible(dataSource.subtasks(owner)).filter { it.taskId != owner },
parent = task.parentId?.takeIf { it > 0 }?.let { dataSource.task(it) },
)
}
@@ -201,7 +202,7 @@ class TasksRepositoryImpl @Inject constructor(
// Going through the occurrence forks an override instead, which takes
// the reminders on its own row and leaves the series' alone.
val instance = current?.takeIf { it.isRecurring }?.occurrenceStart
if (instance == null) dataSource.updateTask(taskId, form, reminders)
if (instance == null) dataSource.updateTask(resolvedRow(current, taskId), form, reminders)
else dataSource.updateInstance(taskId, instance, form, reminders)
}
@@ -235,7 +236,7 @@ class TasksRepositoryImpl @Inject constructor(
val current = dataSource.task(taskId, occurrenceStart)
val seriesId = current?.seriesId
val occurrence = current?.occurrenceStart
if (seriesId == null || occurrence == null) return@withContext dataSource.deleteWithSubtasks(taskId)
if (seriesId == null || occurrence == null) return@withContext dataSource.deleteWithSubtasks(resolvedRow(current, taskId))
when (scope) {
RecurringScope.ThisOccurrence ->
// An override row deletes itself into an EXDATE; a generated
@@ -291,6 +292,13 @@ class TasksRepositoryImpl @Inject constructor(
ticks.close()
}
}.flowOn(io)
/**
* The row a read for [taskId] resolved to — a past occurrence the series moved
* past is a task of its own — which is the one a write has to address.
*/
private fun resolvedRow(resolved: Task?, taskId: Long): Long = resolved?.taskId ?: taskId
}
/** Subtask levels a duplicate follows; deeper than any real list, short of a cycle. */
@@ -62,39 +62,33 @@ class ProviderWriter internal constructor(
private var batchWrote = false
/** Inserts one row and returns its published id. */
fun insert(table: ProviderTable, values: ProviderValues): Long = write {
when (table) {
ProviderTable.TASKS -> insertTask(values)
ProviderTable.PROPERTIES -> insertProperty(values)
else -> throw UnsupportedOperationException("${table.path} is read-only")
}
fun insert(table: ProviderTable, values: ProviderValues): Long = when (table) {
ProviderTable.TASKS -> write { insertTask(values) }
ProviderTable.PROPERTIES -> write { insertProperty(values) }
ProviderTable.LISTS, ProviderTable.INSTANCES -> readOnly(table)
}
/** Updates every row [selection] matches and returns how many changed. */
fun update(table: ProviderTable, values: ProviderValues, selection: String?, args: Array<out String>?): Int = write {
when (table) {
ProviderTable.TASKS -> {
val writable = ProviderTaskWriter.writable(table, values, WRITABLE_TASK_COLUMNS)
val matched = ids(table, selection, args)
(if (Tasks.LIST_ID in writable) parentsFirst(matched) else matched).count { updateTask(it, writable) }
}
ProviderTable.INSTANCES -> {
val writable = ProviderTaskWriter.writable(table, values, WRITABLE_TASK_COLUMNS)
instances(selection, args).count { updateInstance(it, writable) }
}
ProviderTable.PROPERTIES -> ids(table, selection, args).count { updateProperty(it, values) }
else -> throw UnsupportedOperationException("${table.path} is read-only")
fun update(table: ProviderTable, values: ProviderValues, selection: String?, args: Array<out String>?): Int = when (table) {
ProviderTable.TASKS -> write {
val writable = ProviderTaskWriter.writable(table, values, WRITABLE_TASK_COLUMNS)
val matched = ids(table, selection, args)
(if (Tasks.LIST_ID in writable) parentsFirst(matched) else matched).count { updateTask(it, writable) }
}
ProviderTable.INSTANCES -> write {
val writable = ProviderTaskWriter.writable(table, values, WRITABLE_TASK_COLUMNS)
instances(selection, args).count { updateInstance(it, writable) }
}
ProviderTable.PROPERTIES -> write { ids(table, selection, args).count { updateProperty(it, values) } }
ProviderTable.LISTS -> readOnly(table)
}
/** Deletes every row [selection] matches and returns how many went. */
fun delete(table: ProviderTable, selection: String?, args: Array<out String>?): Int = write {
when (table) {
ProviderTable.TASKS -> ids(table, selection, args).count { deleteTask(it) }
ProviderTable.INSTANCES -> instances(selection, args).count { deleteInstance(it) }
ProviderTable.PROPERTIES -> ids(table, selection, args).count { deleteProperty(it) }
else -> throw UnsupportedOperationException("${table.path} is read-only")
}
fun delete(table: ProviderTable, selection: String?, args: Array<out String>?): Int = when (table) {
ProviderTable.TASKS -> write { ids(table, selection, args).count { deleteTask(it) } }
ProviderTable.INSTANCES -> write { instances(selection, args).count { deleteInstance(it) } }
ProviderTable.PROPERTIES -> write { ids(table, selection, args).count { deleteProperty(it) } }
ProviderTable.LISTS -> readOnly(table)
}
/** Runs a client's batch in one transaction, re-arming reminders once at the end. */
@@ -113,6 +107,9 @@ class ProviderWriter internal constructor(
}
}
/** Refused as read-only whichever store is active, before the store is even looked at. */
private fun readOnly(table: ProviderTable): Nothing = throw UnsupportedOperationException("${table.path} is read-only")
private fun <T> write(block: () -> T): T = source.locked {
check(resolver.mode() == StorageMode.OWN) {
"Agendula is working on top of an external tasks provider; write to that one instead"
@@ -0,0 +1,120 @@
package de.jeanlucmakiola.agendula.data.tasks.room
import androidx.room.ColumnInfo
import androidx.room.Dao
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.PrimaryKey
import androidx.room.Query
import de.jeanlucmakiola.agendula.domain.TaskStatus
import kotlin.time.Instant
/**
* How a series was moved past one of its occurrences (#137). It maps the
* occurrence to its completed copy for as long as the copy lives, and while
* [undoable] it also holds what reopening the copy needs to move the series
* back: the change, not the old series, so edits made since are kept. Local
* only: never part of a `VTODO`.
*/
@Entity(
tableName = "advanced_occurrences",
foreignKeys = [
ForeignKey(entity = TaskEntity::class, parentColumns = ["id"], childColumns = ["copy_id"], onDelete = ForeignKey.CASCADE),
ForeignKey(entity = TaskEntity::class, parentColumns = ["id"], childColumns = ["master_id"], onDelete = ForeignKey.CASCADE),
],
indices = [Index(value = ["master_id", "anchor"])],
)
data class AdvancedOccurrenceEntity(
/** The completed copy of the occurrence. */
@PrimaryKey @ColumnInfo(name = "copy_id") val copyId: Long,
@ColumnInfo(name = "master_id") val masterId: Long,
@ColumnInfo(name = "anchor") val anchor: Instant,
/** The anchor the series moved to; it is only moved back while it still has it. */
@ColumnInfo(name = "advanced_to") val advancedTo: Instant,
@ColumnInfo(name = "prior_dtstart") val priorDtstart: Instant?,
@ColumnInfo(name = "prior_due") val priorDue: Instant?,
@ColumnInfo(name = "prior_status") val priorStatus: TaskStatus,
@ColumnInfo(name = "prior_percent_complete") val priorPercentComplete: Int?,
@ColumnInfo(name = "prior_completed_at") val priorCompletedAt: Instant?,
/** Occurrences `COUNT` lost to the move. */
@ColumnInfo(name = "spent") val spent: Int,
/** The `RRULE` the move left; once it differs, the series was reshaped and is not moved back. */
@ColumnInfo(name = "rule_after") val ruleAfter: String?,
/** The `EXDATE` occurrences the move dropped, as epoch millis, comma-separated. */
@ColumnInfo(name = "dropped_exdates", defaultValue = "") val droppedExdates: String = "",
/** The copy was an override before, and goes back to being one. */
@ColumnInfo(name = "from_override") val fromOverride: Boolean,
/** Cleared once the copy is edited, moved or reopened on its own: it is then a task of its own. */
@ColumnInfo(name = "undoable", defaultValue = "1") val undoable: Boolean = true,
/** Set once the moved series reached the server, which then holds the move itself. */
@ColumnInfo(name = "settled", defaultValue = "0") val settled: Boolean = false,
) {
val dropped: List<Instant>
get() = droppedExdates.split(',').mapNotNull { it.toLongOrNull()?.let(Instant::fromEpochMilliseconds) }
companion object {
fun encode(instants: List<Instant>) = instants.joinToString(",") { it.toEpochMilliseconds().toString() }
}
}
/** A closed override detached along with an advance; [taskId] is null once that row is gone. */
@Entity(
tableName = "advanced_detached",
foreignKeys = [
ForeignKey(
entity = AdvancedOccurrenceEntity::class,
parentColumns = ["copy_id"],
childColumns = ["copy_id"],
onDelete = ForeignKey.CASCADE,
),
ForeignKey(entity = TaskEntity::class, parentColumns = ["id"], childColumns = ["task_id"], onDelete = ForeignKey.SET_NULL),
],
indices = [Index(value = ["copy_id"]), Index(value = ["task_id"])],
)
data class AdvancedDetachedEntity(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") val id: Long = 0,
@ColumnInfo(name = "copy_id") val copyId: Long,
@ColumnInfo(name = "anchor") val anchor: Instant,
@ColumnInfo(name = "task_id") val taskId: Long?,
)
@Dao
interface AdvancedOccurrenceDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(row: AdvancedOccurrenceEntity)
@Insert
fun insertDetached(rows: List<AdvancedDetachedEntity>)
@Query("SELECT * FROM advanced_occurrences WHERE copy_id = :copyId")
fun forCopy(copyId: Long): AdvancedOccurrenceEntity?
@Query("SELECT * FROM advanced_detached WHERE copy_id = :copyId")
fun detachedFor(copyId: Long): List<AdvancedDetachedEntity>
@Query("SELECT * FROM advanced_occurrences WHERE master_id = :masterId")
fun forMaster(masterId: Long): List<AdvancedOccurrenceEntity>
/** The record for [masterId]'s occurrence within the second starting at [secondStart]. */
@Query(
"SELECT * FROM advanced_occurrences WHERE master_id = :masterId " +
"AND anchor >= :secondStart AND anchor < :secondStart + 1000",
)
fun at(masterId: Long, secondStart: Instant): AdvancedOccurrenceEntity?
@Query("DELETE FROM advanced_occurrences WHERE copy_id = :copyId")
fun delete(copyId: Long)
@Query("UPDATE advanced_occurrences SET undoable = 0 WHERE copy_id = :copyId")
fun keepAsOwnTask(copyId: Long)
@Query("UPDATE advanced_occurrences SET settled = 1 WHERE master_id IN (:masterIds)")
fun settle(masterIds: List<Long>)
/** Records too old to matter: their occurrence is long gone from every list and reminder. */
@Query("DELETE FROM advanced_occurrences WHERE master_id = :masterId AND anchor < :before")
fun pruneBefore(masterId: Long, before: Instant)
}
@@ -4,6 +4,7 @@ import de.jeanlucmakiola.agendula.domain.LocalAccount
import de.jeanlucmakiola.agendula.domain.Task
import de.jeanlucmakiola.agendula.domain.TaskList
import de.jeanlucmakiola.agendula.domain.export.ExportTask
import de.jeanlucmakiola.agendula.domain.isClosed
import de.jeanlucmakiola.agendula.domain.priorityFromICal
import de.jeanlucmakiola.agendula.domain.recurrence.RecurrenceSpec
import kotlin.time.Instant
@@ -100,6 +101,10 @@ object RoomTaskMapper {
val TaskEntity.isRecurring: Boolean
get() = !rrule.isNullOrBlank() || !rdate.isNullOrBlank()
/** Completed or cancelled. */
val TaskEntity.isClosed: Boolean
get() = status.isClosed
/**
* The series anchor: `DTSTART` when present, else `DUE`. A `VTODO` may carry only
* a due date, and RFC 5545 then anchors the recurrence on it — matching how the
@@ -11,8 +11,10 @@ import de.jeanlucmakiola.agendula.domain.TaskForm
import de.jeanlucmakiola.agendula.domain.TaskList
import de.jeanlucmakiola.agendula.domain.TaskStatus
import de.jeanlucmakiola.agendula.domain.export.ExportTask
import de.jeanlucmakiola.agendula.domain.normalizeTags
import de.jeanlucmakiola.agendula.domain.recurrence.ExpansionWindow
import de.jeanlucmakiola.agendula.domain.recurrence.RecurrenceExpander
import de.jeanlucmakiola.agendula.domain.recurrence.RecurrenceSpec
import java.time.ZoneId
import java.util.UUID
import javax.inject.Inject
@@ -28,6 +30,12 @@ private val WINDOW_FORWARD = 730.days
/** Residue lines that describe the old series and must not follow the new one. */
private val SERIES_LINES = listOf("EXDATE", "RDATE", "RRULE", "RECURRENCE-ID", "UID")
/** How long a record keeps mapping a ticked occurrence to its copy. */
private val RECORD_HORIZON = 30.days
/** Only bounds the search: the occurrence count is what stops expansion, so no real gap is cut off. */
private val SERIES_LOOKAHEAD = (366 * 1000).days
/** Enough to count every occurrence before a split point without bounding a real series. */
internal const val SPLIT_COUNT_CEILING = 100_000
@@ -103,6 +111,7 @@ class RoomTasksDataSource @Inject constructor(
private val tasks get() = database.tasks()
private val lists get() = database.taskLists()
private val alarms get() = database.alarms()
private val advanced get() = database.advancedOccurrences()
// --- reads ----------------------------------------------------------------
@@ -132,6 +141,9 @@ class RoomTasksDataSource @Inject constructor(
if (row.task.recurrenceId != null || !row.task.isRecurring) return task(taskId)
return occurrencesOf(row, tasks.overrides(taskId), clock.now())
.firstOrNull { it.occurrenceStart == occurrenceStart }
?: copyAt(row.task, occurrenceStart)?.let { copy ->
tasks.task(copy.id)?.let { RoomTaskMapper.task(it).copy(occurrenceStart = occurrenceStart) }
}
?: task(taskId)
}
@@ -256,7 +268,8 @@ class RoomTasksDataSource @Inject constructor(
// in both (the task query skips non-null `master_id`, and the override
// query finds no master in B) while still uploading as part of A's
// resource.
tasks.update(
saveRow(
current,
if (current.masterId == null) {
TaskFormWriter.withRule(edited, form.rrule)
} else {
@@ -268,6 +281,8 @@ class RoomTasksDataSource @Inject constructor(
/** See [TaskMove]: the rows move, and the old collection is left a tombstone. */
private fun move(current: TaskEntity, edited: TaskEntity) {
// A copy moved elsewhere is a task of its own now.
advanced.keepAsOwnTask(current.id)
val plan = TaskMove.plan(
edited = edited,
previous = current,
@@ -323,11 +338,7 @@ class RoomTasksDataSource @Inject constructor(
return@tx
}
val now = clock.now()
// COUNT counts before EXDATE is applied (RFC 5545 §3.8.5.3).
val spent = RecurrenceExpander.expand(
spec.copy(exdate = null),
ExpansionWindow(from = anchor, until = occurrenceStart, maxOccurrences = SPLIT_COUNT_CEILING),
).size
val spent = spentBefore(spec, occurrenceStart)
val (start, due) = resolvedTimes(master, occurrenceStart)
tasks.update(TaskFormWriter.endedBefore(master, occurrenceStart, now, zone()))
@@ -350,9 +361,7 @@ class RoomTasksDataSource @Inject constructor(
percentComplete = null,
completedAt = null,
// Recurrence lines belong to the old series; everything else carries over.
unknownProperties = master.unknownProperties?.lines()
?.filterNot { line -> SERIES_LINES.any { line.startsWith(it, ignoreCase = true) } }
?.joinToString("\r\n")?.ifBlank { null },
unknownProperties = seriesFreeText(master.unknownProperties),
)
val applied = TaskFormWriter.apply(base, form.copy(percentComplete = null), now, zone())
val delta = applied.dtstart?.let { newStart -> start?.let { newStart - it } }
@@ -411,9 +420,12 @@ class RoomTasksDataSource @Inject constructor(
private inline fun tx(crossinline block: () -> Unit) = database.runInTransaction(Runnable { block() })
private fun seriesMaster(seriesId: Long): TaskEntity {
val row = tasks.entity(seriesId) ?: throw TaskWriteFailedException("series $seriesId")
return row.masterId?.let { tasks.entity(it) } ?: row
private fun seriesMaster(seriesId: Long): TaskEntity = rowAndMaster(seriesId).second
/** [taskId]'s row, and its series' master — the row itself unless it is an override. */
private fun rowAndMaster(taskId: Long): Pair<TaskEntity, TaskEntity> {
val row = tasks.entity(taskId) ?: throw TaskWriteFailedException("series $taskId")
return row to (row.masterId?.let { tasks.entity(it) } ?: row)
}
/** The occurrence's own times: its override's if it has one, else generated. */
@@ -466,56 +478,331 @@ class RoomTasksDataSource @Inject constructor(
writes.onWritten(setOf(current.listId))
}
override fun setCancelled(taskId: Long, cancelled: Boolean) {
/** Reopening the copy a ticked occurrence left behind moves its series back, as in [setCompletedInstance]. */
override fun setCancelled(taskId: Long, cancelled: Boolean) = tx {
val current = tasks.entity(taskId) ?: throw TaskWriteFailedException("cancel task $taskId")
tasks.update(TaskFormWriter.cancelled(current, cancelled, clock.now()))
saveRow(current, TaskFormWriter.cancelled(current, cancelled, clock.now()))
writes.onWritten(setOf(current.listId))
}
override fun setCompleted(taskId: Long, completed: Boolean) {
/** Reopening the copy a ticked occurrence left behind moves its series back, as in [setCompletedInstance]. */
override fun setCompleted(taskId: Long, completed: Boolean) = tx {
val current = tasks.entity(taskId) ?: throw TaskWriteFailedException("complete task $taskId")
tasks.update(TaskFormWriter.completed(current, completed, clock.now()))
saveRow(current, TaskFormWriter.completed(current, completed, clock.now()))
writes.onWritten(setOf(current.listId))
}
/**
* Ticking one occurrence forks a `RECURRENCE-ID` override carrying the
* completion — the same model [updateInstance] writes. Writing the status onto
* the master instead would close the series: the master is what
* [TaskDao.tasks] filters on, so every occurrence, past and future, would
* leave every list at once.
* Ticking a series' first open occurrence moves the series on to its next
* open one and keeps a completed copy, as tasks.org and Apple Reminders do — a
* completed `RECURRENCE-ID` override alone leaves the series showing as open
* in most other clients (#137). Closed overrides between become copies too.
* Reopening the copy while the series is still where that left it moves it
* back. Any other occurrence forks an override carrying the completion, the
* same model [updateInstance] writes. Writing the status onto the master
* instead would close the series.
*/
override fun setCompletedInstance(taskId: Long, occurrenceStart: Instant, completed: Boolean) =
writeInstance(taskId, occurrenceStart, "complete") { TaskFormWriter.completed(it, completed, clock.now()) }
override fun setCompletedInstance(taskId: Long, occurrenceStart: Instant, completed: Boolean) = tx {
closeOccurrence(taskId, occurrenceStart, completed) { TaskFormWriter.completed(it, completed, clock.now()) }
}
/** Same override model as [setCompletedInstance]. */
override fun setCancelledInstance(taskId: Long, occurrenceStart: Instant, cancelled: Boolean) =
writeInstance(taskId, occurrenceStart, "cancel") { TaskFormWriter.cancelled(it, cancelled, clock.now()) }
/** Same model as [setCompletedInstance]. */
override fun setCancelledInstance(taskId: Long, occurrenceStart: Instant, cancelled: Boolean) = tx {
closeOccurrence(taskId, occurrenceStart, cancelled) { TaskFormWriter.cancelled(it, cancelled, clock.now()) }
}
/** Applies [write] to the override for [occurrenceStart], forking one if there is none yet. */
private fun writeInstance(
taskId: Long,
occurrenceStart: Instant,
what: String,
write: (TaskEntity) -> TaskEntity,
) {
val master = tasks.entity(taskId) ?: throw TaskWriteFailedException("$what instance $taskId")
// Not a series master — an override, or a plain task the caller handed an
// anchor for. Either way this row *is* the occurrence.
private fun closeOccurrence(taskId: Long, occurrenceStart: Instant, closing: Boolean, close: (TaskEntity) -> TaskEntity) {
val (row, master) = rowAndMaster(taskId)
if (master.recurrenceSpec() == null) {
tasks.update(write(master))
writes.onWritten(setOf(master.listId))
// A plain task, or the copy a ticked occurrence left: this row is the occurrence.
saveRow(row, close(row))
writes.onWritten(setOf(row.listId))
return
}
val override = if (row.masterId != null) row else tasks.override(master.id, occurrenceStart)
val anchor = override?.recurrenceId ?: occurrenceStart
val seriesStart = master.recurrenceAnchor ?: return
if (anchor < seriesStart && !sameSecond(anchor, seriesStart)) {
// The series has moved past it, so a tick has nothing left to close;
// a reopen goes to the copy that occurrence left.
when {
override != null -> writeInstance(master, override, anchor, close)
!closing -> copyAt(master, anchor)?.let { copy ->
saveRow(copy, close(copy))
writes.onWritten(setOf(copy.listId))
}
}
return
}
if (master.isClosed) {
// A series ends with its last occurrence; reopening any of it reopens the series.
if (!closing) closeSeries(master, override, close) else writeInstance(master, override, anchor, close)
return
}
if (!closing || !advance(master, anchor, override, close)) writeInstance(master, override, anchor, close)
}
tasks.override(taskId, occurrenceStart)?.let {
tasks.update(write(it))
writes.onWritten(setOf(master.listId))
return
/**
* Writes [edited] over [current]. A copy whose only change is that it
* reopens moves its series back instead; any other edit makes it a task of
* its own, and it no longer stands for the series' occurrence.
*/
private fun saveRow(current: TaskEntity, edited: TaskEntity) {
val record = advanced.forCopy(current.id)?.takeIf { it.undoable }
if (record != null) {
val unchanged = sameApartFromState(current, edited)
if (unchanged && current.isClosed && !edited.isClosed && reopenCopy(current, edited, record)) return
if (!unchanged || !edited.isClosed) advanced.keepAsOwnTask(current.id)
}
tasks.update(edited)
}
/**
* Nothing a user sees changed but its state — what saving a reopened copy
* from the editor amounts to. Compared as the editor writes them back:
* trimmed, blank as none, tags normalised.
*/
private fun sameApartFromState(a: TaskEntity, b: TaskEntity): Boolean {
fun text(value: String?) = value?.trim()?.ifEmpty { null }
return text(a.title) == text(b.title) && text(a.description) == text(b.description) &&
text(a.location) == text(b.location) && text(a.url) == text(b.url) &&
a.priority == b.priority && a.dtstart == b.dtstart && a.due == b.due && a.isAllDay == b.isAllDay &&
a.listId == b.listId && a.parentId == b.parentId && a.rrule == b.rrule && a.rdate == b.rdate &&
normalizeTags(a.categories) == normalizeTags(b.categories) && a.color == b.color
}
/** [close] applied to the master — and to [override], its last occurrence — which ends the series. */
private fun closeSeries(master: TaskEntity, override: TaskEntity?, close: (TaskEntity) -> TaskEntity) {
tasks.update(close(master))
override?.let { tasks.update(close(it)) }
writes.onWritten(setOf(master.listId))
}
/**
* Moves [master] past [anchor] when that is its first open occurrence; false
* when it is not, so the caller writes an override. Series with `RDATE`s keep
* the override model (anchoring on one would re-align the `RRULE`), and so do
* recurring subtasks, whose copies would pile up under the parent.
*/
private fun advance(master: TaskEntity, anchor: Instant, override: TaskEntity?, close: (TaskEntity) -> TaskEntity): Boolean {
val rule = master.rrule?.takeIf { it.isNotBlank() } ?: return false
if (!master.rdate.isNullOrBlank() || master.parentId != null) return false
val spec = master.recurrenceSpec() ?: return false
val overrides = tasks.overrides(master.id).associateBy { it.recurrenceId?.epochSeconds }
fun closedAt(at: Instant) = overrides[at.epochSeconds]?.isClosed == true
val leading = expandFrom(spec, maxOccurrences = overrides.values.count { it.isClosed } + 2)
val index = leading.indexOfFirst { sameSecond(it, anchor) }
if (index < 0 || leading.take(index).any { !closedAt(it) }) return false
var nextIndex = index + 1
while (nextIndex < leading.size && closedAt(leading[nextIndex])) nextIndex++
val next = leading.getOrNull(nextIndex) ?: return true.also { closeSeries(master, override, close) }
val now = clock.now()
val zone = master.timezone ?: zone()
val detached = (leading.take(index) + leading.subList(index + 1, nextIndex)).map { at ->
at to detach(overrides.getValue(at.epochSeconds), now)
}
// Expansion drops the anchor's sub-second part; the series keeps it.
val newAnchor = next + (spec.anchor - floorSecond(spec.anchor))
val spent = spentBefore(spec, next)
val (start, due) = occurrenceTimes(master, newAnchor)
val ruleAfter = TaskFormWriter.remainingCount(rule, spent)
tasks.update(
master.copy(
dtstart = start,
due = due,
rrule = ruleAfter,
exdate = TaskFormWriter.valuesFrom(master.exdate, newAnchor, zone),
status = TaskStatus.NEEDS_ACTION,
percentComplete = null,
completedAt = null,
lastModified = now,
isDirty = true,
),
)
val copyId = if (override != null) {
detach(override, now, close)
} else {
val (copyStart, copyDue) = occurrenceTimes(master, anchor)
val id = tasks.insert(close(asCopy(master, now).copy(dtstart = copyStart, due = copyDue)))
alarms.copyToTask(master.id, id, sameResource = false)
id
}
advanced.at(master.id, floorSecond(anchor))?.let { advanced.delete(it.copyId) }
advanced.pruneBefore(master.id, now - RECORD_HORIZON)
advanced.insert(
AdvancedOccurrenceEntity(
copyId = copyId,
masterId = master.id,
anchor = anchor,
advancedTo = newAnchor,
priorDtstart = master.dtstart,
priorDue = master.due,
priorStatus = master.status,
priorPercentComplete = master.percentComplete,
priorCompletedAt = master.completedAt,
spent = spent,
ruleAfter = ruleAfter,
droppedExdates = AdvancedOccurrenceEntity.encode(TaskFormWriter.instantsBefore(master.exdate, newAnchor, zone)),
fromOverride = override != null,
),
)
advanced.insertDetached(detached.map { (at, id) -> AdvancedDetachedEntity(copyId = copyId, anchor = at, taskId = id) })
writes.onWritten(setOf(master.listId))
return true
}
/** Occurrences `COUNT` has spent before [cut]: counted before `EXDATE` (RFC 5545 §3.8.5.3). */
private fun spentBefore(spec: RecurrenceSpec, cut: Instant): Int = RecurrenceExpander.expand(
spec.copy(exdate = null),
ExpansionWindow(from = floorSecond(spec.anchor), until = cut, maxOccurrences = SPLIT_COUNT_CEILING),
).size
/**
* Turns the override [row] into a task of its own, in place so its id keeps
* working: a new UID, unlinked from the series, a resource of its own — and
* so its alarms are fresh copies, not the series' ones.
*/
private fun detach(row: TaskEntity, now: Instant, close: (TaskEntity) -> TaskEntity = { it }): Long {
tasks.update(close(asCopy(row, now).copy(id = row.id)))
refreshAlarms(row.id)
return row.id
}
private fun refreshAlarms(taskId: Long) {
val current = alarms.forTask(taskId)
alarms.deleteForTask(taskId)
current.forEach { alarms.insert(it.freshCopy(taskId)) }
}
/** [source] as a standalone task: no series fields, never uploaded. */
private fun asCopy(source: TaskEntity, now: Instant): TaskEntity = source.copy(
id = 0,
uid = UUID.randomUUID().toString(),
masterId = null,
recurrenceId = null,
href = null,
etag = null,
rrule = null,
rdate = null,
exdate = null,
createdAt = now,
sequence = 0,
isDeleted = false,
isDirty = true,
unknownProperties = seriesFreeText(source.unknownProperties),
)
/**
* Undoes [advance] for the copy [row] while the series still sits where it
* moved it under the same rule, and the copy is still just that — same list,
* nothing filed under it. The anchor goes back, `COUNT` gets back what it
* spent, and the dropped `EXDATE`s return in the list's own shape; any other
* edit made since stays. The occurrence takes [reopened]'s state: as a plain
* occurrence again, or as an override where that state is its own. The
* occurrences detached with it become overrides again, or are excluded where
* their row is gone or has a life of its own. False when it cannot, so the
* caller reopens the copy as a task of its own.
*/
private fun reopenCopy(row: TaskEntity, reopened: TaskEntity, record: AdvancedOccurrenceEntity): Boolean {
val master = tasks.entity(record.masterId)?.takeIf {
!it.isDeleted && !it.isClosed && row.listId == it.listId && it.rrule == record.ruleAfter &&
it.recurrenceAnchor?.let { a -> sameSecond(a, record.advancedTo) } == true
}
if (master == null || tasks.subtasks(row.id).isNotEmpty()) return false
val now = clock.now()
val zone = master.timezone ?: zone()
val synced = lists.entity(master.listId)?.accountId != null
val (start, due) = occurrenceTimes(master, record.priorDtstart ?: record.priorDue ?: record.anchor)
var back = master.copy(
dtstart = start,
due = due,
rrule = master.rrule?.let { TaskFormWriter.remainingCount(it, -record.spent) },
status = if (master.status == TaskStatus.NEEDS_ACTION) record.priorStatus else master.status,
percentComplete = master.percentComplete ?: record.priorPercentComplete,
completedAt = master.completedAt ?: record.priorCompletedAt,
lastModified = now,
isDirty = true,
)
record.dropped.forEach { back = TaskFormWriter.excepting(back, it, now, zone, dirty = synced) }
// A detached row given a parent or subtasks since has a life of its own, and stays out.
fun returns(task: TaskEntity?) = task != null && !task.isDeleted && task.listId == master.listId &&
task.parentId == master.parentId && tasks.subtasks(task.id).isEmpty()
val detached = advanced.detachedFor(row.id).map { it.anchor to it.taskId?.let(tasks::entity) }
detached.forEach { (at, task) -> if (!returns(task)) back = TaskFormWriter.excepting(back, at, now, zone, dirty = synced) }
tasks.update(back)
detached.forEach { (at, task) -> if (returns(task)) toOverride(task!!, back, at, now) }
advanced.delete(row.id)
val plain = reopened.status == TaskStatus.NEEDS_ACTION && reopened.percentComplete == null
if (record.fromOverride || !plain) toOverride(reopened, back, record.anchor, now)
else deleteTask(row.id)
writes.onWritten(setOf(master.listId))
return true
}
/** [row], a detached occurrence, back as [master]'s override for [anchor]. */
private fun toOverride(row: TaskEntity, master: TaskEntity, anchor: Instant, now: Instant) {
val back = row.copy(
uid = master.uid,
masterId = master.id,
recurrenceId = anchor,
href = null,
etag = null,
isDirty = true,
lastModified = now,
unknownProperties = seriesFreeText(row.unknownProperties),
)
if (row.href == null) {
tasks.update(back)
refreshAlarms(row.id)
} else {
// Already uploaded as a resource of its own: that one goes, a fresh override comes.
val id = tasks.insert(back.copy(id = 0))
alarms.copyToTask(row.id, id, sameResource = false)
deleteTask(row.id)
}
}
/** The copy [advance] left for [master]'s occurrence at [anchor], if it is still there. */
private fun copyAt(master: TaskEntity, anchor: Instant): TaskEntity? =
advanced.at(master.id, floorSecond(anchor))?.let { tasks.entity(it.copyId) }?.takeUnless { it.isDeleted }
/** The series' occurrences from its anchor on, at most [maxOccurrences]. */
private fun expandFrom(spec: RecurrenceSpec, maxOccurrences: Int): List<Instant> {
val from = floorSecond(spec.anchor)
return RecurrenceExpander.expand(spec, ExpansionWindow(from = from, until = from + SERIES_LOOKAHEAD, maxOccurrences = maxOccurrences))
}
private fun floorSecond(at: Instant) = Instant.fromEpochSeconds(at.epochSeconds)
/**
* The residue without the series' own lines, as a new resource must not
* carry them. Lines inside a nested component (a `VALARM`'s `UID`) are its
* own and stay.
*/
private fun seriesFreeText(unknown: String?): String? {
var depth = 0
return unknown?.lines()?.filter { line ->
when {
line.startsWith("BEGIN:", ignoreCase = true) -> { depth++; true }
line.startsWith("END:", ignoreCase = true) -> { depth--; true }
else -> depth > 0 || (line.isNotBlank() && SERIES_LINES.none { line.startsWith(it, ignoreCase = true) })
}
}?.joinToString("\r\n")?.ifBlank { null }
}
/** Expansion runs in whole seconds; stored anchors may carry milliseconds. */
private fun sameSecond(a: Instant, b: Instant) = a.epochSeconds == b.epochSeconds
/** Applies [write] to [override], or to a new one forked from [master] for [occurrenceStart]. */
private fun writeInstance(master: TaskEntity, override: TaskEntity?, occurrenceStart: Instant, write: (TaskEntity) -> TaskEntity) {
if (override != null) {
tasks.update(write(override))
} else {
val (start, due) = occurrenceTimes(master, occurrenceStart)
val id = tasks.insert(write(newOverride(master, master.id, occurrenceStart, start, due)))
alarms.copyToTask(master.id, id, sameResource = true)
}
val (start, due) = occurrenceTimes(master, occurrenceStart)
val id = tasks.insert(write(newOverride(master, taskId, occurrenceStart, start, due)))
alarms.copyToTask(taskId, id, sameResource = true)
writes.onWritten(setOf(master.listId))
}
@@ -608,7 +895,7 @@ class RoomTasksDataSource @Inject constructor(
if (lists.exists(edited.listId) == 0) throw TaskWriteFailedException("move task: no list ${edited.listId}")
move(current, edited)
}
else -> tasks.update(edited)
else -> saveRow(current, edited)
}
}
writes.onWritten(setOf(current.listId, edited.listId))
@@ -120,18 +120,25 @@ object TaskFormWriter {
fun valuesBefore(values: String?, cut: Instant, zone: String): String? =
mapValues(values, zone) { it.takeIf { at -> at < cut } }
/** The instants of an `EXDATE`/`RDATE` list before [cut]; values it cannot read are left out. */
fun instantsBefore(values: String?, cut: Instant, zone: String): List<Instant> =
parsed(values, zone).mapNotNull { it.second }.filter { it < cut }
/** The values of an `EXDATE`/`RDATE` list at or after [cut]. */
fun valuesFrom(values: String?, cut: Instant, zone: String): String? =
mapValues(values, zone) { it.takeIf { at -> at >= cut } }
private fun mapValues(values: String?, zone: String, map: (Instant) -> Instant?): String? {
val list = values?.split(',')?.map(String::trim)?.filter(String::isNotEmpty) ?: return values
return list.mapNotNull { raw ->
val at = readValue(raw, zone) ?: return@mapNotNull raw
map(at)?.let { writeValueLike(raw, it, zone) }
if (values == null) return null
return parsed(values, zone).mapNotNull { (raw, at) ->
if (at == null) raw else map(at)?.let { writeValueLike(raw, it, zone) }
}.joinToString(",").ifEmpty { null }
}
/** Each value of an `EXDATE`/`RDATE` list with its instant, or null where it cannot be read. */
private fun parsed(values: String?, zone: String): List<Pair<String, Instant?>> =
values?.split(',')?.map(String::trim)?.filter(String::isNotEmpty)?.map { it to readValue(it, zone) }.orEmpty()
private fun readValue(raw: String, zone: String): Instant? = runCatching {
val z = java.time.ZoneId.of(zone)
val instant = when {
@@ -9,7 +9,7 @@ import java.util.UUID
import kotlin.time.Instant
/**
* Agendula's own task store. Four tables, designed from
* Agendula's own task store. Six tables, designed from
* what the app actually reads and writes plus RFC 5545's `VTODO`.
*
* Schemas are exported to `app/schemas/` and committed, so a future version can
@@ -21,8 +21,10 @@ import kotlin.time.Instant
TaskListEntity::class,
TaskEntity::class,
TaskAlarmEntity::class,
AdvancedOccurrenceEntity::class,
AdvancedDetachedEntity::class,
],
version = 4,
version = 5,
exportSchema = true,
)
@TypeConverters(Converters::class)
@@ -31,6 +33,7 @@ abstract class TasksDatabase : RoomDatabase() {
abstract fun tasks(): TaskDao
abstract fun alarms(): TaskAlarmDao
abstract fun accounts(): AccountDao
abstract fun advancedOccurrences(): AdvancedOccurrenceDao
companion object {
const val NAME = "agendula-tasks.db"
@@ -180,5 +183,26 @@ abstract class TasksDatabase : RoomDatabase() {
db.execSQL("ALTER TABLE accounts ADD COLUMN label TEXT")
}
}
/** v5 remembers how ticking an occurrence moved its series, so reopening it can move it back. */
val MIGRATION_4_5 = object : Migration(4, 5) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(
"CREATE TABLE IF NOT EXISTS `advanced_occurrences` (`copy_id` INTEGER NOT NULL, `master_id` INTEGER NOT NULL, `anchor` INTEGER NOT NULL, `advanced_to` INTEGER NOT NULL, `prior_dtstart` INTEGER, `prior_due` INTEGER, `prior_status` INTEGER NOT NULL, `prior_percent_complete` INTEGER, `prior_completed_at` INTEGER, `spent` INTEGER NOT NULL, `rule_after` TEXT, `dropped_exdates` TEXT NOT NULL DEFAULT '', `from_override` INTEGER NOT NULL, `undoable` INTEGER NOT NULL DEFAULT 1, `settled` INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(`copy_id`), FOREIGN KEY(`copy_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`master_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
)
db.execSQL(
"CREATE INDEX IF NOT EXISTS `index_advanced_occurrences_master_id_anchor` ON `advanced_occurrences` (`master_id`, `anchor`)",
)
db.execSQL(
"CREATE TABLE IF NOT EXISTS `advanced_detached` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `copy_id` INTEGER NOT NULL, `anchor` INTEGER NOT NULL, `task_id` INTEGER, FOREIGN KEY(`copy_id`) REFERENCES `advanced_occurrences`(`copy_id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`task_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
)
db.execSQL(
"CREATE INDEX IF NOT EXISTS `index_advanced_detached_copy_id` ON `advanced_detached` (`copy_id`)",
)
db.execSQL(
"CREATE INDEX IF NOT EXISTS `index_advanced_detached_task_id` ON `advanced_detached` (`task_id`)",
)
}
}
}
}
@@ -37,6 +37,9 @@ data class TaskList(
enum class TaskStatus { NEEDS_ACTION, IN_PROCESS, COMPLETED, CANCELLED }
/** Completed or cancelled. */
val TaskStatus.isClosed: Boolean get() = this == TaskStatus.COMPLETED || this == TaskStatus.CANCELLED
/** iCalendar priority, bucketed for the UI. */
enum class Priority { NONE, LOW, MEDIUM, HIGH }
@@ -111,7 +114,7 @@ data class Task(
val isOccurrence: Boolean get() = seriesId != null && occurrenceStart != null
val isCompleted: Boolean get() = status == TaskStatus.COMPLETED
val isClosed: Boolean get() = status == TaskStatus.COMPLETED || status == TaskStatus.CANCELLED
val isClosed: Boolean get() = status.isClosed
val isSubtask: Boolean get() = parentId != null && parentId > 0
/** The task's own colour if set, else the list colour. */
val effectiveColor: Int get() = taskColor ?: listColor