Keep sub-task resets apart from tick copies, scope copy markers (#160)

This commit is contained in:
makiolaj committed 2026-11-12 16:40:39 +01:00
1 parent 6f4ae7e2ec
commit b3189f04b2
10 files changed
+426 -207

No files matched your search

@@ -792,13 +792,37 @@ class RoomTasksDataSourceTest {
val at = now
val id = source.insertTask(form(title = "Routine"))
makeRecurring(id, at)
val routineUid = db.tasks().entity(id)!!.uid
val copy = source.insertTask(form(title = "Daily part").copy(parentId = id))
val elsewhere = source.insertTask(form(title = "Moved here").copy(parentId = id))
source.setCompleted(copy, completed = true)
db.tasks().update(db.tasks().entity(copy)!!.copy(unknownProperties = "X-AGENDULA-TICK-COPY:1"))
source.setCompleted(elsewhere, completed = true)
db.tasks().update(db.tasks().entity(copy)!!.copy(unknownProperties = "X-AGENDULA-TICK-COPY:$routineUid"))
db.tasks().update(db.tasks().entity(elsewhere)!!.copy(unknownProperties = "X-AGENDULA-TICK-COPY:another-parent"))
source.setCompletedInstance(id, at, completed = true)
assertThat(db.tasks().entity(copy)!!.status).isEqualTo(TaskStatus.COMPLETED)
// Its marker names a parent it no longer sits under: an ordinary sub-task here.
assertThat(db.tasks().entity(elsewhere)!!.status).isEqualTo(TaskStatus.NEEDS_ACTION)
}
@Test
fun aLegacyResetRecordRestoresTheStateAndLeavesTheDates() {
val at = now
val id = source.insertTask(form(title = "Routine"))
makeRecurring(id, at)
val step = source.insertTask(form(title = "Step", due = at + 1.days).copy(parentId = id))
source.setCompleted(step, completed = true)
source.setCompletedInstance(id, at, completed = true)
val record = db.advancedOccurrences().forMaster(id).single()
db.advancedOccurrences().insert(record.copy(resetSubtasks = "$step,COMPLETED,100,"))
val movedDue = db.tasks().entity(step)!!.due
source.setCompletedInstance(id, at, completed = false)
assertThat(db.tasks().entity(step)!!.status).isEqualTo(TaskStatus.COMPLETED)
assertThat(db.tasks().entity(step)!!.due).isEqualTo(movedDue)
}
@Test
@@ -31,7 +31,6 @@ 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.time.ZoneOffset
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.time.Instant
@@ -330,18 +329,7 @@ class AndroidTasksDataSource @Inject constructor(
arrayOf(Tasks.RRULE, Tasks.RDATE, Tasks.EXDATE, Tasks.DTSTART, Tasks.DUE, Tasks.IS_ALLDAY, Tasks.TZ),
null, null, null,
)?.use { c ->
if (!c.moveToFirst()) return@use null
val r = CursorColumnReader(c)
val anchor = r.getLong(Tasks.DTSTART) ?: r.getLong(Tasks.DUE) ?: return@use null
val rule = TaskMapper.seriesRule(r)
RecurrenceSpec(
rrule = rule?.rrule,
rdate = rule?.rdate,
exdate = r.getString(Tasks.EXDATE),
anchor = Instant.fromEpochMilliseconds(anchor),
isAllDay = r.getBoolean(Tasks.IS_ALLDAY),
timeZone = r.getString(Tasks.TZ),
)
if (c.moveToFirst()) TaskMapper.seriesSpec(CursorColumnReader(c)) else null
}
/** End the master's rule before [occurrenceStart], and drop the exceptions past it. */
@@ -739,8 +727,7 @@ class AndroidTasksDataSource @Inject constructor(
* into a task of its own, remembers that copy, so the occurrence can still be
* read and reopened, and how the series moved, so reopening can move it back.
* When the series moved on, its sub-tasks start over for the next occurrence,
* and the tick remembers how they were (#160). Without a copy there is no
* tick to remember them in, so they are left as they are.
* and [resets] remembers how they were (#160), with or without a copy.
*/
private fun rememberingCopy(taskId: Long, occurrenceStart: Instant, closing: Boolean, write: () -> Int): Int {
if (!closing) return write()
@@ -754,22 +741,14 @@ class AndroidTasksDataSource @Inject constructor(
.onFailure { Log.w(TAG, "Reading the series after the tick failed", it) }
.getOrNull()?.takeIf { it != before }
}
if (before != null && after != null && SubtaskReset.movedOn(before, after)) {
runCatching { resetSubtasks(authority, taskId, before, after) }
.onFailure { Log.w(TAG, "Resetting the sub-tasks failed", it) }
}
runCatching {
val copy = detachedSince(authority, lastId)
val resets = SubtaskReset.resetsOnTick(copy, before, after)
copy?.let {
markCopy(authority, copy)
val reset = if (resets && before != null && after != null) {
runCatching { resetSubtasks(authority, taskId, SubtaskReset.shiftOf(before, after)) }
.onFailure { Log.w(TAG, "Resetting the sub-tasks failed", it) }
.getOrNull()
} else {
null
}
val tick = Tick(
copy, taskId.takeIf { after != null }, before.takeIf { after != null }, after, System.currentTimeMillis(),
reset = reset?.let(SubtaskReset::encode),
)
detachedSince(authority, lastId)?.let { copy ->
markCopy(authority, copy, taskId)
val tick = Tick(copy, taskId.takeIf { after != null }, before.takeIf { after != null }, after, System.currentTimeMillis())
ticks.put(ticks.key(authority, taskId, occurrenceStart), tick)
}
}.onFailure { Log.w(TAG, "Looking up the detached copy failed", it) }
@@ -777,52 +756,81 @@ class AndroidTasksDataSource @Inject constructor(
}
}
/** Marks [copyId] as a tick's copy where DAVx5 keeps and uploads unknown properties, so other installs know it too. */
private fun markCopy(authority: String, copyId: Long) {
val values = mapOf(
Properties.TASK_ID to copyId,
Properties.MIMETYPE to SubtaskReset.UNKNOWN_PROPERTY_MIMETYPE,
Properties.DATA0 to SubtaskReset.COPY_MARKER_JSON,
)
runCatching { resolver.insert(TasksContract.propertiesUri(authority), values.toContentValues()) }
.onFailure { Log.w(TAG, "Marking the ticked copy failed", it) }
/**
* Marks [copyId], left by ticking the recurring sub-task [seriesId], with the
* UID of the parent it sits under, where DAVx5 keeps and uploads unknown
* properties, so other installs know it too. A top-level series' copy sits
* under nothing a reset walks, so it is left unmarked.
*/
private fun markCopy(authority: String, copyId: Long, seriesId: Long) {
runCatching {
val parentId = resolver.query(taskUri(authority, seriesId), arrayOf(Tasks.PARENT_ID), null, null, null)
?.use { c -> if (c.moveToFirst() && !c.isNull(0)) c.getLong(0) else null } ?: return
val parentUid = uidOf(authority, parentId) ?: return
val values = mapOf(
Properties.TASK_ID to copyId,
Properties.MIMETYPE to SubtaskReset.UNKNOWN_PROPERTY_MIMETYPE,
Properties.DATA0 to SubtaskReset.copyMarkerJson(parentUid),
)
resolver.insert(TasksContract.propertiesUri(authority), values.toContentValues())
}.onFailure { Log.w(TAG, "Marking the ticked copy failed", it) }
}
/** The rows carrying Agendula's copy marker. */
private fun markedCopies(authority: String): Set<Long> = runCatching {
resolver.query(
private fun uidOf(authority: String, taskId: Long): String? =
resolver.query(taskUri(authority, taskId), arrayOf(Tasks.UID), null, null, null)
?.use { c -> if (c.moveToFirst()) c.getString(0) else null }
/** The parent UID each of [taskIds] carries a copy marker for. */
private fun markerParents(authority: String, taskIds: List<Long>): Map<Long, String> = runCatching {
queryByIds(
TasksContract.propertiesUri(authority),
arrayOf(Properties.TASK_ID, Properties.DATA0),
"${Properties.MIMETYPE} = ? AND ${Properties.DATA0} LIKE ?",
arrayOf(SubtaskReset.UNKNOWN_PROPERTY_MIMETYPE, "%${SubtaskReset.COPY_MARKER}%"),
null,
)?.use { c ->
val r = CursorColumnReader(c)
buildSet { while (c.moveToNext()) if (SubtaskReset.isCopyMarker(r.getString(Properties.DATA0))) r.getLong(Properties.TASK_ID)?.let(::add) }
}.orEmpty()
}.onFailure { Log.w(TAG, "Reading the copy markers failed", it) }.getOrDefault(emptySet())
Properties.TASK_ID,
taskIds,
filter = "${Properties.MIMETYPE} = ?",
filterArgs = listOf(SubtaskReset.UNKNOWN_PROPERTY_MIMETYPE),
) { r ->
val id = r.getLong(Properties.TASK_ID) ?: return@queryByIds null
SubtaskReset.markerParentFromJson(r.getString(Properties.DATA0))?.let { id to it }
}.toMap()
}.onFailure { Log.w(TAG, "Reading the copy markers failed", it) }.getOrDefault(emptyMap())
/** Resets what [SubtaskReset] picks under [parentId], dated ones moved by [shift]. */
private fun resetSubtasks(authority: String, parentId: Long, shift: SeriesShift?): List<ResetSubtask> {
val copies = ticks.copies(authority) + markedCopies(authority)
val reset = SubtaskReset.toReset(parentId, shift) { id ->
childRows(authority, id, SUBTASK_STATE) { r ->
val rowId = r.getLong(Tasks.ID) ?: return@childRows null
val allDay = r.getBoolean(Tasks.IS_ALLDAY)
SubtaskReset.providerNode(
rowId, r.getString(Tasks.RRULE), r.getString(Tasks.RDATE), copies, subtaskState(r),
SubtaskDates(r.getLong(Tasks.DTSTART), r.getLong(Tasks.DUE)), allDay, zoneOf(allDay, r.getString(Tasks.TZ)),
)
/**
* Resets what [SubtaskReset] picks under the series [seriesId], dated ones
* moved as the series moved from [before] to [after], and records it in
* [resets] first, under the anchor the series moved to.
*/
private fun resetSubtasks(authority: String, seriesId: Long, before: Map<String, Any?>, after: Map<String, Any?>) {
val copies = ticks.copies(authority)
val uids = HashMap<Long, String?>().apply { put(seriesId, uidOf(authority, seriesId)) }
val reset = SubtaskReset.toReset(seriesId, SubtaskReset.shiftOf(before, after)) { id ->
val rows = childRows(authority, id, SUBTASK_STATE) { r ->
r.getLong(Tasks.ID)?.let { rowId ->
uids[rowId] = r.getString(Tasks.UID)
// Read now: the cursor is closed by the time the markers are in.
val rrule = r.getString(Tasks.RRULE)
val rdate = r.getString(Tasks.RDATE)
val state = subtaskState(r)
val dates = SubtaskDates(r.getLong(Tasks.DTSTART), r.getLong(Tasks.DUE))
val allDay = r.getBoolean(Tasks.IS_ALLDAY)
val tz = r.getString(Tasks.TZ)
rowId to { markerParent: String? ->
SubtaskReset.providerNode(
rowId, rrule, rdate, copies, markerParent = markerParent, parentUid = uids[id],
state = state, dates = dates, isAllDay = allDay, timeZone = tz,
)
}
}
}
val markers = markerParents(authority, rows.map { it.first })
rows.map { (rowId, node) -> node(markers[rowId]) }
}
val ops = reset.map { subtaskOp(authority, it.id, SubtaskState.FRESH, it.dates.takeIf { _ -> it.dates != it.priorDates }) }
if (ops.isNotEmpty()) resolver.applyBatch(authority, ArrayList(ops))
return reset
if (reset.isEmpty()) return
SubtaskReset.anchor(after)?.let { resets.put(authority, seriesId, it, SubtaskReset.encode(reset), System.currentTimeMillis()) }
val ops = reset.map { subtaskOp(authority, it.id, SubtaskState.FRESH, it.dates?.takeIf { d -> d != it.priorDates }) }
resolver.applyBatch(authority, ArrayList(ops))
}
private fun zoneOf(allDay: Boolean, tz: String?): ZoneId =
if (allDay) ZoneOffset.UTC else tz?.let { runCatching { ZoneId.of(it) }.getOrNull() } ?: ZoneId.systemDefault()
private fun subtaskState(r: ColumnReader) =
SubtaskState(statusFromInt(r.getInt(Tasks.STATUS)), r.getInt(Tasks.PERCENT_COMPLETE), r.getLong(Tasks.COMPLETED))
@@ -850,10 +858,14 @@ class AndroidTasksDataSource @Inject constructor(
Tasks.ID,
entries.map { it.id },
filter = "${Tasks.DELETED} IS NULL OR ${Tasks.DELETED} = 0",
) { r -> r.getLong(Tasks.ID)?.let { it to (subtaskState(r) to SubtaskDates(r.getLong(Tasks.DTSTART), r.getLong(Tasks.DUE))) } }.toMap()
return SubtaskReset.toRestore(entries, current::get).map {
subtaskOp(authority, it.id, it.prior, it.priorDates.takeIf { _ -> it.priorDates != it.dates })
}
) { r ->
r.getLong(Tasks.ID)?.let {
it to SubtaskNow(subtaskState(r), SubtaskDates(r.getLong(Tasks.DTSTART), r.getLong(Tasks.DUE)), r.getBoolean(Tasks.IS_ALLDAY))
}
}.toMap()
val outcome = SubtaskReset.toRestore(entries, current::get)
if (outcome.changed.isNotEmpty()) Log.i(TAG, "Sub-tasks ${outcome.changed} changed since the reset and keep their state")
return outcome.restore.map { subtaskOp(authority, it.id, it.prior, it.priorDates?.takeIf { d -> d != it.dates }) }
}
/** Walks [parentId]'s direct sub-task rows, overrides left out, with [read] on each. */
@@ -878,8 +890,9 @@ class AndroidTasksDataSource @Inject constructor(
* Undoes the tick that left [taskId]'s occurrence at [occurrenceStart] — or,
* with no occurrence, the tick that left the copy [taskId]: the series goes
* back where it was and the copy goes, as long as the series is still where
* the tick moved it and the copy has nothing filed under it. False when it
* cannot, so the caller reopens the copy as a task of its own.
* the tick moved it and the copy has nothing filed under it. The sub-tasks
* the tick reset get their state back from [resets]. False when it cannot,
* so the caller reopens the copy as a task of its own.
*/
private fun movedBack(taskId: Long, occurrenceStart: Instant?): Boolean = runCatching {
val authority = authority()
@@ -897,9 +910,14 @@ class AndroidTasksDataSource @Inject constructor(
ContentProviderOperation.newUpdate(taskUri(authority, series)).withValues(restore.toContentValues()).build(),
ContentProviderOperation.newDelete(taskUri(authority, tick.copyId)).build(),
)
runCatching { ops += subtaskRestore(authority, tick.reset) }.onFailure { Log.w(TAG, "Reading the reset sub-tasks failed", it) }
val anchor = SubtaskReset.anchor(after)
anchor?.let { at ->
runCatching { ops += subtaskRestore(authority, resets.get(authority, series, at)) }
.onFailure { Log.w(TAG, "Reading the reset sub-tasks failed", it) }
}
resolver.applyBatch(authority, ops)
ticks.remove(key)
anchor?.let { resets.remove(authority, series, it) }
true
}.onFailure { Log.w(TAG, "Moving the series back failed", it) }.getOrDefault(false)
@@ -939,6 +957,8 @@ class AndroidTasksDataSource @Inject constructor(
known = { context.getSharedPreferences(KNOWN_COPIES, Context.MODE_PRIVATE) },
)
private val resets = TickResets { context.getSharedPreferences(TICK_RESETS, Context.MODE_PRIVATE) }
/** The copy a tick left for [taskId]'s occurrence at [occurrenceStart], if one was remembered. */
private fun tickedCopy(taskId: Long, occurrenceStart: Instant): Long? =
ticks.get(ticks.key(authority(), taskId, occurrenceStart))?.copyId
@@ -1049,10 +1069,13 @@ private const val TICKED_COPIES = "provider_ticked_copies"
/** Every copy a tick on this install left, kept past [TickedCopies.HORIZON_MS] alongside the marker on the row. */
private const val KNOWN_COPIES = "provider_known_copies"
/** The sub-tasks each tick reset, kept apart from its copy. */
private const val TICK_RESETS = "provider_tick_resets"
/** What resetting a sub-task reads: whether it recurs, its progress and its dates. */
private val SUBTASK_STATE = arrayOf(
Tasks.ID, Tasks.ORIGINAL_INSTANCE_ID, Tasks.RRULE, Tasks.RDATE, Tasks.STATUS, Tasks.PERCENT_COMPLETE, Tasks.COMPLETED,
Tasks.DTSTART, Tasks.DUE, Tasks.IS_ALLDAY, Tasks.TZ,
Tasks.DTSTART, Tasks.DUE, Tasks.IS_ALLDAY, Tasks.TZ, Tasks.UID,
)
/** What a tick changes on a series, and an undo changes back; with what its rule is read in. */
@@ -6,14 +6,18 @@ import de.jeanlucmakiola.agendula.domain.isClosed
import de.jeanlucmakiola.agendula.domain.recurrence.ExpansionWindow
import de.jeanlucmakiola.agendula.domain.recurrence.RecurrenceExpander
import de.jeanlucmakiola.agendula.domain.recurrence.RecurrenceSpec
import de.jeanlucmakiola.agendula.domain.recurrence.dateZone
import de.jeanlucmakiola.agendula.domain.statusFromInt
import java.time.Duration
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.ZoneOffset
import java.time.temporal.ChronoUnit
import kotlin.time.Duration.Companion.days
import kotlin.time.Instant
private const val MILLIS_PER_SECOND = 1000L
private const val MILLIS_PER_DAY = 24L * 60 * 60 * 1000
/** A sub-task's progress, which a routine's next occurrence starts without. */
internal data class SubtaskState(val status: TaskStatus, val percent: Int?, val completedAt: Long?) {
/** Open with nothing done yet: what a reset leaves. */
@@ -28,6 +32,12 @@ internal data class SubtaskState(val status: TaskStatus, val percent: Int?, val
internal data class SubtaskDates(val start: Long?, val due: Long?) {
val isEmpty: Boolean get() = start == null && due == null
/** The same dates as a store keeps them: to the second, or for an all-day task to the day. */
fun sameAs(other: SubtaskDates, isAllDay: Boolean): Boolean {
fun unit(at: Long?) = at?.let { Math.floorDiv(it, if (isAllDay) MILLIS_PER_DAY else MILLIS_PER_SECOND) }
return unit(start) == unit(other.start) && unit(due) == unit(other.due)
}
companion object {
val NONE = SubtaskDates(null, null)
}
@@ -35,7 +45,7 @@ internal data class SubtaskDates(val start: Long?, val due: Long?) {
/**
* A sub-task as [SubtaskReset] sees it; [recurring] also covers a copy a tick of
* a recurring one left. [zone] is the one its dates are read in.
* a recurring one left. Its dates are read in [dateZone] of [isAllDay] and [timeZone].
*/
internal class SubtaskNode(
val id: Long,
@@ -43,29 +53,42 @@ internal class SubtaskNode(
val state: SubtaskState,
val dates: SubtaskDates = SubtaskDates.NONE,
val isAllDay: Boolean = false,
val zone: ZoneId = ZoneOffset.UTC,
)
/** A sub-task [SubtaskReset] reset: its state and dates before, and the dates the reset gave it. */
internal data class ResetSubtask(
val id: Long,
val prior: SubtaskState,
val priorDates: SubtaskDates = SubtaskDates.NONE,
val dates: SubtaskDates = priorDates,
val timeZone: String? = null,
)
/**
* How far a series moved, as wall-clock time in [seriesZone], so a sub-task
* keeps its place relative to the routine across a DST change.
* A sub-task [SubtaskReset] reset: its state and dates before, and the dates the
* reset gave it. A record from before dates were kept has neither, and its dates
* are neither compared nor restored.
*/
internal class SeriesShift(from: Long, to: Long, seriesZone: ZoneId) {
private val delta = Duration.between(local(from, seriesZone), local(to, seriesZone))
internal data class ResetSubtask(
val id: Long,
val prior: SubtaskState,
val priorDates: SubtaskDates? = SubtaskDates.NONE,
val dates: SubtaskDates? = priorDates,
)
/** [at] moved along; an all-day date by whole days. */
fun apply(at: Long, isAllDay: Boolean, zone: ZoneId): Long {
val z = if (isAllDay) ZoneOffset.UTC else zone
val by = if (isAllDay) Duration.ofDays(delta.toDays()) else delta
return local(at, z).plus(by).atZone(z).toInstant().toEpochMilli()
/** A reset sub-task as it is now, for [SubtaskReset.toRestore]. */
internal class SubtaskNow(val state: SubtaskState, val dates: SubtaskDates, val isAllDay: Boolean)
/** What moving a series back does with its reset sub-tasks: who gets their state back, and who changed since. */
internal class SubtaskRestore(val restore: List<ResetSubtask>, val changed: List<Long>)
/**
* How far a series moved in [seriesZone]: wall-clock time for a timed sub-task,
* so it keeps its place relative to the routine across a DST change, and the
* change of calendar date for an all-day one. [floating] reads a sub-task with
* no zone of its own.
*/
internal class SeriesShift(from: Long, to: Long, seriesZone: ZoneId, private val floating: ZoneId = ZoneId.systemDefault()) {
private val delta = Duration.between(local(from, seriesZone), local(to, seriesZone))
private val days = ChronoUnit.DAYS.between(local(from, seriesZone).toLocalDate(), local(to, seriesZone).toLocalDate())
/** [at] moved along. */
fun apply(at: Long, isAllDay: Boolean, timeZone: String? = null): Long {
val zone = dateZone(isAllDay, timeZone, floating)
val moved = if (isAllDay) local(at, zone).plusDays(days) else local(at, zone).plus(delta)
return moved.atZone(zone).toInstant().toEpochMilli()
}
private fun local(at: Long, zone: ZoneId) = LocalDateTime.ofInstant(java.time.Instant.ofEpochMilli(at), zone)
@@ -82,24 +105,36 @@ internal object SubtaskReset {
/** Only bounds the search for a next occurrence. */
private val LOOKAHEAD = (366 * 1000).days
/** The `X-` property Agendula puts on the copy a provider tick left, so any device knows it for one. */
/**
* The `X-` property Agendula puts on the copy a provider tick of a recurring
* sub-task left, valued with the UID of the parent it sits under, so any
* device knows it for one while it stays there.
*/
const val COPY_MARKER = "X-AGENDULA-TICK-COPY"
/** The marker as DAVx5 stores an unknown property: a JSON array of name and value. */
const val COPY_MARKER_JSON = "[\"$COPY_MARKER\",\"1\"]"
/** The provider `properties` mimetype DAVx5 keeps unknown properties under, and round-trips. */
const val UNKNOWN_PROPERTY_MIMETYPE = "vnd.android.cursor.item/vnd.ical4android.unknown-property"
/** Whether an unknown-property row's JSON is the copy marker. */
fun isCopyMarker(json: String?): Boolean =
json?.trim()?.startsWith("[\"$COPY_MARKER\"", ignoreCase = true) == true
private val MARKER_JSON = Regex("""^\s*\[\s*"$COPY_MARKER"\s*,\s*"((?:[^"\\]|\\.)*)"""", RegexOption.IGNORE_CASE)
/** Whether a stored residue carries the copy marker, as a copy synced in from a provider install does. */
fun hasCopyMarker(residue: String?): Boolean = residue?.lines()?.any {
/** The marker for a copy under the parent [parentUid], as DAVx5 stores an unknown property: a JSON array of name and value. */
fun copyMarkerJson(parentUid: String): String =
"[\"$COPY_MARKER\",\"${parentUid.replace("\\", "\\\\").replace("\"", "\\\"")}\"]"
/** The parent UID an unknown-property row's JSON marks its task a copy under, or null when it is no marker. */
fun markerParentFromJson(json: String?): String? =
json?.let(MARKER_JSON::find)?.groupValues?.get(1)?.replace(Regex("""\\(.)"""), "$1")
/** The parent UID a stored residue's marker names, as a copy synced in from a provider install carries it. */
fun markerParentFromResidue(residue: String?): String? = residue?.lines()?.firstNotNullOfOrNull {
val line = it.trim()
line.startsWith(COPY_MARKER, ignoreCase = true) && line.getOrNull(COPY_MARKER.length).let { c -> c == ':' || c == ';' }
} == true
val next = line.getOrNull(COPY_MARKER.length)
if (!line.startsWith(COPY_MARKER, ignoreCase = true) || (next != ':' && next != ';')) return@firstNotNullOfOrNull null
line.substringAfter(':').replace(Regex("""\\([\\;,])"""), "$1")
}
/** Whether a marker naming [markerParent] makes a task under [parentUid] a copy: only under the parent it came from. */
fun isCopyOf(markerParent: String?, parentUid: String?): Boolean = markerParent != null && markerParent == parentUid
/**
* The sub-tasks under [parentId], all the way down, to reset: started ones,
@@ -115,8 +150,8 @@ internal object SubtaskReset {
val moves = shift != null && !it.dates.isEmpty
if (it.state.status != TaskStatus.CANCELLED && (!it.state.isFresh || moves)) {
val dates = if (shift == null) it.dates else SubtaskDates(
it.dates.start?.let { at -> shift.apply(at, it.isAllDay, it.zone) },
it.dates.due?.let { at -> shift.apply(at, it.isAllDay, it.zone) },
it.dates.start?.let { at -> shift.apply(at, it.isAllDay, it.timeZone) },
it.dates.due?.let { at -> shift.apply(at, it.isAllDay, it.timeZone) },
)
reset += ResetSubtask(it.id, it.state, it.dates, dates)
}
@@ -129,28 +164,47 @@ internal object SubtaskReset {
/**
* A provider row as a node. Nothing the provider sets on a detached copy marks
* it as one, so a copy is known by Agendula's marker or by the [copies] ticks
* on this install left: it belongs to a recurring sub-task and counts as recurring.
* it as one, so a copy is known by the [copies] ticks on this install left, or
* by a [markerParent] naming the [parentUid] it sits under: it belongs to a
* recurring sub-task and counts as recurring.
*/
fun providerNode(
id: Long,
rrule: String?,
rdate: String?,
copies: Set<Long>,
markerParent: String? = null,
parentUid: String? = null,
state: SubtaskState,
dates: SubtaskDates = SubtaskDates.NONE,
isAllDay: Boolean = false,
zone: ZoneId = ZoneOffset.UTC,
) = SubtaskNode(id, !rrule.isNullOrBlank() || !rdate.isNullOrBlank() || id in copies, state, dates, isAllDay, zone)
timeZone: String? = null,
) = SubtaskNode(
id,
!rrule.isNullOrBlank() || !rdate.isNullOrBlank() || id in copies || isCopyOf(markerParent, parentUid),
state, dates, isAllDay, timeZone,
)
/** The reset sub-tasks still as the reset left them, so moving back may restore them. */
fun toRestore(reset: List<ResetSubtask>, current: (Long) -> Pair<SubtaskState, SubtaskDates>?): List<ResetSubtask> =
reset.filter { entry -> current(entry.id)?.let { (state, dates) -> state.isFresh && dates == entry.dates } == true }
/**
* The reset sub-tasks still as the reset left them, so moving back may
* restore them, and the ones changed since, which keep the user's state.
* A deleted one is neither.
*/
fun toRestore(reset: List<ResetSubtask>, current: (Long) -> SubtaskNow?): SubtaskRestore {
val restore = mutableListOf<ResetSubtask>()
val changed = mutableListOf<Long>()
reset.forEach { entry ->
val now = current(entry.id) ?: return@forEach
val unchanged = now.state.isFresh && (entry.dates == null || now.dates.sameAs(entry.dates, now.isAllDay))
if (unchanged) restore += entry else changed += entry.id
}
return SubtaskRestore(restore, changed)
}
fun encode(reset: List<ResetSubtask>): String = reset.joinToString(";") {
listOf(
it.id, it.prior.status.name, it.prior.percent, it.prior.completedAt,
it.priorDates.start, it.priorDates.due, it.dates.start, it.dates.due,
it.priorDates?.start, it.priorDates?.due, it.dates?.start, it.dates?.due,
).joinToString(",") { value -> value?.toString().orEmpty() }
}
@@ -159,36 +213,24 @@ internal object SubtaskReset {
if (parts.size != 4 && parts.size != 8) return@mapNotNull null
val id = parts[0].toLongOrNull() ?: return@mapNotNull null
val status = TaskStatus.entries.firstOrNull { it.name == parts[1] } ?: return@mapNotNull null
val prior = SubtaskDates(parts.getOrNull(4)?.toLongOrNull(), parts.getOrNull(5)?.toLongOrNull())
val dates = if (parts.size == 8) SubtaskDates(parts[6].toLongOrNull(), parts[7].toLongOrNull()) else prior
ResetSubtask(id, SubtaskState(status, parts[2].toIntOrNull(), parts[3].toLongOrNull()), prior, dates)
}
/** A provider series' rule set from its columns, or null when it does not recur. */
fun specOf(state: Map<String, Any?>): RecurrenceSpec? {
val rrule = (state[Tasks.RRULE] as? String)?.ifBlank { null }
val rdate = (state[Tasks.RDATE] as? String)?.ifBlank { null }
if (rrule == null && rdate == null) return null
val anchor = anchor(state) ?: return null
return RecurrenceSpec(
rrule = rrule,
rdate = rdate,
exdate = state[Tasks.EXDATE] as? String,
anchor = Instant.fromEpochMilliseconds(anchor),
isAllDay = isAllDay(state),
timeZone = state[Tasks.TZ] as? String,
val state = SubtaskState(status, parts[2].toIntOrNull(), parts[3].toLongOrNull())
if (parts.size == 4) return@mapNotNull ResetSubtask(id, state, priorDates = null, dates = null)
ResetSubtask(
id, state,
SubtaskDates(parts[4].toLongOrNull(), parts[5].toLongOrNull()),
SubtaskDates(parts[6].toLongOrNull(), parts[7].toLongOrNull()),
)
}
fun isAllDay(state: Map<String, Any?>): Boolean = (state[Tasks.IS_ALLDAY] as? Number)?.toInt()?.let { it != 0 } == true
/** A provider series' rule set from its columns. */
fun specOf(state: Map<String, Any?>): RecurrenceSpec? = TaskMapper.seriesSpec(MapColumnReader(state))
/** How the series moved from [before] to [after], read in the zone its rule is expanded in. */
fun shiftOf(before: Map<String, Any?>, after: Map<String, Any?>, floating: ZoneId = ZoneId.systemDefault()): SeriesShift? {
val from = anchor(before) ?: return null
val to = anchor(after) ?: return null
val zone = if (isAllDay(after)) ZoneOffset.UTC
else (after[Tasks.TZ] as? String)?.let { runCatching { ZoneId.of(it) }.getOrNull() } ?: floating
return SeriesShift(from, to, zone)
val reader = MapColumnReader(after)
return SeriesShift(from, to, dateZone(reader.getBoolean(Tasks.IS_ALLDAY), reader.getString(Tasks.TZ), floating), floating)
}
/**
@@ -204,6 +246,7 @@ internal object SubtaskReset {
if (now <= was) return false
if (statusFromInt((after[Tasks.STATUS] as? Number)?.toInt()).isClosed) return false
val spec = next ?: return false
if (spec.rrule == null && spec.rdate == null) return false
val parts = spec.rrule?.split(';')?.map { it.trim() }?.filter { it.isNotEmpty() }
val count = parts?.firstOrNull { it.startsWith("COUNT=", ignoreCase = true) }?.substringAfter('=')?.toIntOrNull()
if (count != null && count <= 0) return false
@@ -217,14 +260,7 @@ internal object SubtaskReset {
return RecurrenceExpander.expand(probe, ExpansionWindow(from = from, until = from + LOOKAHEAD, maxOccurrences = 1)).isNotEmpty()
}
/**
* Whether a provider tick resets the sub-tasks: the series moved on, and the
* provider left a [copy] whose tick can record what the reset changed. With
* no copy there is nothing to undo through, so they are left as they are.
*/
fun resetsOnTick(copy: Long?, before: Map<String, Any?>?, after: Map<String, Any?>?): Boolean =
copy != null && movedOn(before, after)
private fun anchor(state: Map<String, Any?>): Long? =
/** The anchor a series' columns put it at: its start, or else its due date. */
fun anchor(state: Map<String, Any?>): Long? =
(state[Tasks.DTSTART] as? Number)?.toLong() ?: (state[Tasks.DUE] as? Number)?.toLong()
}
@@ -8,6 +8,7 @@ import de.jeanlucmakiola.agendula.domain.TaskList
import de.jeanlucmakiola.agendula.domain.export.ExportTask
import de.jeanlucmakiola.agendula.domain.priorityFromICal
import de.jeanlucmakiola.agendula.domain.statusFromInt
import de.jeanlucmakiola.agendula.domain.recurrence.RecurrenceSpec
import kotlin.time.Instant
/** Maps a provider row (via [ColumnReader]) to a domain model. Pure + testable. */
@@ -77,6 +78,20 @@ object TaskMapper {
return if (rrule == null && rdate == null) null else SeriesRule(rrule, rdate)
}
/** The rule set of a `tasks` row, anchored on its start or else its due date; null without either date. */
fun seriesSpec(r: ColumnReader): RecurrenceSpec? {
val rule = seriesRule(r)
val anchor = r.getLong(Tasks.DTSTART) ?: r.getLong(Tasks.DUE) ?: return null
return RecurrenceSpec(
rrule = rule?.rrule,
rdate = rule?.rdate,
exdate = r.getString(Tasks.EXDATE),
anchor = Instant.fromEpochMilliseconds(anchor),
isAllDay = r.getBoolean(Tasks.IS_ALLDAY),
timeZone = r.getString(Tasks.TZ),
)
}
/**
* The occurrence's `RECURRENCE-ID` anchor.
*
@@ -0,0 +1,42 @@
package de.jeanlucmakiola.agendula.data.tasks
import android.content.SharedPreferences
/**
* The sub-tasks a provider tick reset, as [SubtaskReset.encode] writes them,
* kept for [TickedCopies.HORIZON_MS] under the series and the anchor the tick
* moved it to: whether or not the provider left a copy that [TickedCopies]
* could record, moving the series back from there finds them.
*/
internal class TickResets(private val prefs: () -> SharedPreferences) {
fun put(authority: String, seriesId: Long, anchor: Long, reset: String, at: Long) {
val stale = expire(prefs().all, at)
prefs().edit().apply {
stale.forEach(::remove)
putString(key(authority, seriesId, anchor), encode(at, reset))
}.apply()
}
fun get(authority: String, seriesId: Long, anchor: Long): String? =
prefs().getString(key(authority, seriesId, anchor), null)?.let(::decode)
fun remove(authority: String, seriesId: Long, anchor: Long) {
prefs().edit().remove(key(authority, seriesId, anchor)).apply()
}
companion object {
fun key(authority: String, seriesId: Long, anchor: Long) = "$authority|$seriesId|$anchor"
fun encode(at: Long, reset: String) = "$at|$reset"
/** The reset an entry holds, or null when it is not one. */
fun decode(raw: String): String? = raw.substringBefore('|', "").toLongOrNull()?.let { raw.substringAfter('|') }
/** The keys of [entries] past the horizon at [now], unreadable ones included. */
fun expire(entries: Map<String, *>, now: Long): Set<String> = entries.filter { (_, value) ->
val at = (value as? String)?.substringBefore('|', "")?.toLongOrNull() ?: 0L
now - at > TickedCopies.HORIZON_MS
}.keys
}
}
@@ -5,9 +5,9 @@ import org.json.JSONObject
import kotlin.time.Instant
/**
* What ticking a provider occurrence left: the copy the provider detached, the
* series' columns before and after the tick, so an undo can move it back, and
* the sub-tasks it reset, as [SubtaskReset.encode] writes them.
* What ticking a provider occurrence left: the copy the provider detached, and
* the series' columns before and after the tick, so an undo can move it back.
* The sub-tasks it reset are kept apart, in [TickResets].
*/
internal class Tick(
val copyId: Long,
@@ -15,7 +15,6 @@ internal class Tick(
val before: Map<String, Any?>?,
val after: Map<String, Any?>?,
val at: Long,
val reset: String? = null,
)
/**
@@ -77,7 +76,6 @@ internal class TickedCopies(private val prefs: () -> SharedPreferences, private
tick.seriesId?.let { put("series", it) }
tick.before?.let { put("before", columns(it)) }
tick.after?.let { put("after", columns(it)) }
tick.reset?.let { put("reset", it) }
}.toString()
private fun columns(values: Map<String, Any?>) = JSONObject().apply {
@@ -92,7 +90,6 @@ internal class TickedCopies(private val prefs: () -> SharedPreferences, private
before = json.optJSONObject("before")?.let(::values),
after = json.optJSONObject("after")?.let(::values),
at = json.getLong("at"),
reset = if (json.has("reset")) json.getString("reset") else null,
)
}.getOrNull()
@@ -1,10 +1,12 @@
package de.jeanlucmakiola.agendula.data.tasks.room
import android.util.Log
import androidx.room.InvalidationTracker
import de.jeanlucmakiola.agendula.data.tasks.ResetSubtask
import de.jeanlucmakiola.agendula.data.tasks.SeriesShift
import de.jeanlucmakiola.agendula.data.tasks.SubtaskDates
import de.jeanlucmakiola.agendula.data.tasks.SubtaskNode
import de.jeanlucmakiola.agendula.data.tasks.SubtaskNow
import de.jeanlucmakiola.agendula.data.tasks.SubtaskReset
import de.jeanlucmakiola.agendula.data.tasks.SubtaskState
import de.jeanlucmakiola.agendula.data.tasks.TaskQuery
@@ -24,7 +26,7 @@ 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.time.ZoneOffset
import de.jeanlucmakiola.agendula.domain.recurrence.dateZone
import java.util.UUID
import javax.inject.Inject
import javax.inject.Singleton
@@ -98,6 +100,8 @@ private val TASK_TABLES = arrayOf("tasks", "task_lists", "task_alarms")
/** Distinct alarm texts whose `ACKNOWLEDGED` is remembered between scheduler passes. */
private const val ACK_CACHE_SIZE = 512
private const val TAG = "RoomTasksDataSource"
/**
* [TasksDataSource] over Agendula's own Room store.
*
@@ -682,23 +686,21 @@ class RoomTasksDataSource @Inject constructor(
/**
* Resets what [SubtaskReset] picks under [master] for the series' next
* occurrence at [newAnchor], dated ones moved along; the lists it wrote to.
* A copy a provider tick of a recurring sub-task left, synced in, is known by
* its marker while it stays under the parent the marker names.
*/
private fun resetSubtasks(master: TaskEntity, newAnchor: Instant, now: Instant): Pair<List<ResetSubtask>, Set<Long>> {
val floating = ZoneId.of(zone())
val shift = master.recurrenceAnchor?.let {
SeriesShift(it.toEpochMilliseconds(), newAnchor.toEpochMilliseconds(), master.zoneId())
SeriesShift(it.toEpochMilliseconds(), newAnchor.toEpochMilliseconds(), dateZone(master.isAllDay, master.timezone, floating), floating)
}
val loaded = HashMap<Long, TaskEntity>()
val loaded = HashMap<Long, TaskEntity>().apply { put(master.id, master) }
val reset = SubtaskReset.toReset(master.id, shift) { id ->
val parentUid = loaded[id]?.uid
tasks.subtasks(id).map { row ->
val sub = row.task.also { loaded[it.id] = it }
SubtaskNode(
sub.id,
sub.isRecurring || SubtaskReset.hasCopyMarker(sub.unknownProperties),
sub.progress,
sub.dates,
sub.isAllDay,
sub.zoneId(),
)
val copy = SubtaskReset.isCopyOf(SubtaskReset.markerParentFromResidue(sub.unknownProperties), parentUid)
SubtaskNode(sub.id, sub.isRecurring || copy, sub.progress, sub.dates, sub.isAllDay, sub.timezone)
}
}
val lists = reset.mapNotNull { entry ->
@@ -711,8 +713,9 @@ class RoomTasksDataSource @Inject constructor(
private fun restoreSubtasks(record: AdvancedOccurrenceEntity, now: Instant): Set<Long> {
val entries = SubtaskReset.decode(record.resetSubtasks)
val current = entries.mapNotNull { entry -> tasks.entity(entry.id)?.takeUnless { it.isDeleted } }.associateBy { it.id }
val restore = SubtaskReset.toRestore(entries) { id -> current[id]?.let { it.progress to it.dates } }
return restore.mapNotNull { entry ->
val outcome = SubtaskReset.toRestore(entries) { id -> current[id]?.let { SubtaskNow(it.progress, it.dates, it.isAllDay) } }
if (outcome.changed.isNotEmpty()) Log.i(TAG, "Sub-tasks ${outcome.changed} changed since the reset and keep their state")
return outcome.restore.mapNotNull { entry ->
current[entry.id]?.also { tasks.update(it.withProgress(entry.prior, entry.priorDates, now)) }?.listId
}.toSet()
}
@@ -721,16 +724,13 @@ class RoomTasksDataSource @Inject constructor(
private val TaskEntity.dates get() = SubtaskDates(dtstart?.toEpochMilliseconds(), due?.toEpochMilliseconds())
/** The zone a row's dates are read in, as [RecurrenceExpander] reads a series. */
private fun TaskEntity.zoneId(): ZoneId =
if (isAllDay) ZoneOffset.UTC else timezone?.let { runCatching { ZoneId.of(it) }.getOrNull() } ?: ZoneId.systemDefault()
private fun TaskEntity.withProgress(state: SubtaskState, dates: SubtaskDates, now: Instant) = copy(
/** [state] onto the row, and [dates] unless they are unknown. */
private fun TaskEntity.withProgress(state: SubtaskState, dates: SubtaskDates?, now: Instant) = copy(
status = state.status,
percentComplete = state.percent,
completedAt = state.completedAt?.let(Instant::fromEpochMilliseconds),
dtstart = dates.start?.let(Instant::fromEpochMilliseconds),
due = dates.due?.let(Instant::fromEpochMilliseconds),
dtstart = if (dates == null) dtstart else dates.start?.let(Instant::fromEpochMilliseconds),
due = if (dates == null) due else dates.due?.let(Instant::fromEpochMilliseconds),
lastModified = now,
isDirty = true,
)
@@ -12,6 +12,16 @@ import kotlin.time.Instant
private const val MILLIS_PER_SECOND = 1000L
private const val MILLIS_PER_DAY = 24L * 60 * 60 * 1000
/**
* The zone a task's dates are read in: UTC for an all-day one, whose dates are
* midnights there; else its [timeZone], or [floating] when it has none or an
* unknown one.
*/
fun dateZone(isAllDay: Boolean, timeZone: String?, floating: ZoneId = ZoneId.systemDefault()): ZoneId {
if (isAllDay) return ZoneId.of("UTC")
return timeZone?.let { runCatching { ZoneId.of(it) }.getOrNull() } ?: floating
}
/** The rule set of one task series, as stored. All strings are raw iCalendar values. */
data class RecurrenceSpec(
val rrule: String?,
@@ -133,11 +143,8 @@ object RecurrenceExpander {
return occurrences.indices.map { it - current }
}
private fun zoneOf(spec: RecurrenceSpec, floatingZone: ZoneId): TimeZone {
if (spec.isAllDay) return TimeZone.getTimeZone(ZoneId.of("UTC"))
val stored = spec.timeZone?.let { runCatching { ZoneId.of(it) }.getOrNull() }
return TimeZone.getTimeZone(stored ?: floatingZone)
}
private fun zoneOf(spec: RecurrenceSpec, floatingZone: ZoneId): TimeZone =
TimeZone.getTimeZone(dateZone(spec.isAllDay, spec.timeZone, floatingZone))
/**
* All-day series are date-anchored: pin the anchor to UTC midnight, as it is
@@ -87,30 +87,58 @@ class SubtaskResetTest {
ResetSubtask(4, SubtaskState(TaskStatus.NEEDS_ACTION, 10, null), SubtaskDates(null, 5L), SubtaskDates(null, 15L)),
)
assertThat(SubtaskReset.decode(SubtaskReset.encode(reset))).isEqualTo(reset)
assertThat(SubtaskReset.decode("2,COMPLETED,100,1000")).containsExactly(ResetSubtask(2, done))
assertThat(SubtaskReset.decode("")).isEmpty()
assertThat(SubtaskReset.decode(null)).isEmpty()
assertThat(SubtaskReset.decode("x,COMPLETED,,;2,NOPE,,;3,IN_PROCESS")).isEmpty()
}
@Test
fun `a record from before dates were kept restores the state and leaves the dates`() {
val legacy = SubtaskReset.decode("2,COMPLETED,100,1000").single()
assertThat(legacy).isEqualTo(ResetSubtask(2, done, priorDates = null, dates = null))
val dated = SubtaskNow(SubtaskState.FRESH, SubtaskDates(at("2026-11-09T10:00:00Z"), null), isAllDay = false)
assertThat(SubtaskReset.toRestore(listOf(legacy)) { dated }.restore).containsExactly(legacy)
assertThat(SubtaskReset.encode(listOf(legacy))).isEqualTo("2,COMPLETED,100,1000,,,,")
}
private fun now(state: SubtaskState, dates: SubtaskDates = SubtaskDates.NONE, allDay: Boolean = false) = SubtaskNow(state, dates, allDay)
@Test
fun `moving back restores only the sub-tasks still as the reset left them`() {
val moved = SubtaskDates(20L, null)
val moved = SubtaskDates(20_000L, null)
val reset = listOf(
ResetSubtask(2, done),
ResetSubtask(3, halfway),
ResetSubtask(4, done),
ResetSubtask(5, done, SubtaskDates(10L, null), moved),
ResetSubtask(6, done, SubtaskDates(10L, null), moved),
ResetSubtask(5, done, SubtaskDates(10_000L, null), moved),
ResetSubtask(6, done, SubtaskDates(10_000L, null), moved),
)
val current = mapOf(
2L to (SubtaskState.FRESH to SubtaskDates.NONE),
3L to (done to SubtaskDates.NONE),
5L to (SubtaskState.FRESH to moved),
2L to now(SubtaskState.FRESH),
3L to now(done),
5L to now(SubtaskState.FRESH, moved),
// Re-dated since: the user's dates win.
6L to (SubtaskState.FRESH to SubtaskDates(30L, null)),
6L to now(SubtaskState.FRESH, SubtaskDates(30_000L, null)),
)
assertThat(SubtaskReset.toRestore(reset, current::get).map { it.id }).containsExactly(2L, 5L)
val outcome = SubtaskReset.toRestore(reset, current::get)
assertThat(outcome.restore.map { it.id }).containsExactly(2L, 5L)
// 4 is gone: neither restored nor reported as changed.
assertThat(outcome.changed).containsExactly(3L, 6L)
}
@Test
fun `dates compare as a store keeps them, to the second or the day`() {
val reset = ResetSubtask(2, done, SubtaskDates.NONE, SubtaskDates(at("2026-11-09T10:00:00.250Z"), null))
val allDay = ResetSubtask(3, done, SubtaskDates.NONE, SubtaskDates(null, at("2026-11-10T00:00:00Z")))
fun restores(entry: ResetSubtask, stored: Long, isAllDay: Boolean) =
SubtaskReset.toRestore(listOf(entry)) { now(SubtaskState.FRESH, SubtaskDates(if (isAllDay) null else stored, if (isAllDay) stored else null), isAllDay) }
.restore.isNotEmpty()
assertThat(restores(reset, at("2026-11-09T10:00:00Z"), isAllDay = false)).isTrue()
assertThat(restores(reset, at("2026-11-09T10:00:01Z"), isAllDay = false)).isFalse()
assertThat(restores(allDay, at("2026-11-10T12:00:00Z"), isAllDay = true)).isTrue()
assertThat(restores(allDay, at("2026-11-11T00:00:00Z"), isAllDay = true)).isFalse()
}
private val berlin = ZoneId.of("Europe/Berlin")
@@ -120,14 +148,30 @@ class SubtaskResetTest {
@Test
fun `a dated sub-task keeps its wall-clock place to the routine across a DST change`() {
// A weekly routine at 09:00 Berlin moves from the last Monday of summer time to the first of winter time.
val shift = SeriesShift(at("2026-10-19T07:00:00Z"), at("2026-10-26T08:00:00Z"), berlin)
assertThat(shift.apply(at("2026-10-20T08:00:00Z"), isAllDay = false, zone = berlin)).isEqualTo(at("2026-10-27T09:00:00Z"))
assertThat(shift.apply(at("2026-10-21T00:00:00Z"), isAllDay = true, zone = berlin)).isEqualTo(at("2026-10-28T00:00:00Z"))
val shift = SeriesShift(at("2026-10-19T07:00:00Z"), at("2026-10-26T08:00:00Z"), berlin, floating = ZoneOffset.UTC)
assertThat(shift.apply(at("2026-10-20T08:00:00Z"), isAllDay = false, timeZone = "Europe/Berlin")).isEqualTo(at("2026-10-27T09:00:00Z"))
assertThat(shift.apply(at("2026-10-21T00:00:00Z"), isAllDay = true)).isEqualTo(at("2026-10-28T00:00:00Z"))
}
@Test
fun `an all-day sub-task follows the routine's change of date, also on a step under a day`() {
// An eight-hourly routine moves from 20:00 to 04:00 the next day in Berlin.
val shift = SeriesShift(at("2026-11-09T19:00:00Z"), at("2026-11-10T03:00:00Z"), berlin, floating = ZoneOffset.UTC)
assertThat(shift.apply(at("2026-11-09T00:00:00Z"), isAllDay = true)).isEqualTo(at("2026-11-10T00:00:00Z"))
// From 04:00 to 12:00 the date stays.
val sameDay = SeriesShift(at("2026-11-10T03:00:00Z"), at("2026-11-10T11:00:00Z"), berlin, floating = ZoneOffset.UTC)
assertThat(sameDay.apply(at("2026-11-10T00:00:00Z"), isAllDay = true)).isEqualTo(at("2026-11-10T00:00:00Z"))
}
@Test
fun `a timed sub-task without a zone of its own is read in the floating zone`() {
val shift = SeriesShift(at("2026-10-19T07:00:00Z"), at("2026-10-26T08:00:00Z"), berlin, floating = berlin)
assertThat(shift.apply(at("2026-10-20T08:00:00Z"), isAllDay = false)).isEqualTo(at("2026-10-27T09:00:00Z"))
}
@Test
fun `moving on shifts dated sub-tasks, fresh ones included, and leaves undated fresh ones`() {
val shift = SeriesShift(at("2026-11-02T08:00:00Z"), at("2026-11-09T08:00:00Z"), ZoneOffset.UTC)
val shift = SeriesShift(at("2026-11-02T08:00:00Z"), at("2026-11-09T08:00:00Z"), ZoneOffset.UTC, floating = ZoneOffset.UTC)
val nodes = listOf(
SubtaskNode(2, false, done, SubtaskDates(at("2026-11-02T10:00:00Z"), null)),
SubtaskNode(3, false, SubtaskState.FRESH, SubtaskDates(null, at("2026-11-03T00:00:00Z")), isAllDay = true),
@@ -146,7 +190,7 @@ class SubtaskResetTest {
val before = mapOf<String, Any?>(Tasks.DTSTART to at("2026-10-19T07:00:00Z"), Tasks.TZ to "Europe/Berlin", Tasks.IS_ALLDAY to 0L)
val after = before + (Tasks.DTSTART to at("2026-10-26T08:00:00Z"))
val shift = SubtaskReset.shiftOf(before, after, floating = ZoneOffset.UTC)!!
assertThat(shift.apply(at("2026-10-20T08:00:00Z"), isAllDay = false, zone = berlin)).isEqualTo(at("2026-10-27T09:00:00Z"))
assertThat(shift.apply(at("2026-10-20T08:00:00Z"), isAllDay = false, timeZone = "Europe/Berlin")).isEqualTo(at("2026-10-27T09:00:00Z"))
}
@Test
@@ -158,28 +202,59 @@ class SubtaskResetTest {
val spec = SubtaskReset.specOf(state)!!
assertThat(spec.rrule).isEqualTo("FREQ=WEEKLY")
assertThat(spec.isAllDay).isTrue()
assertThat(SubtaskReset.specOf(state + (Tasks.RRULE to " "))).isNull()
assertThat(SubtaskReset.specOf(state + (Tasks.RRULE to " "))!!.rrule).isNull()
assertThat(SubtaskReset.specOf(state + (Tasks.DTSTART to null))).isNull()
}
@Test
fun `the copy marker is recognised in a provider row and in a synced residue`() {
assertThat(SubtaskReset.isCopyMarker(SubtaskReset.COPY_MARKER_JSON)).isTrue()
assertThat(SubtaskReset.isCopyMarker(" [\"x-agendula-tick-copy\",\"1\"]")).isTrue()
assertThat(SubtaskReset.isCopyMarker("[\"X-AGENDULA-TICK-COPYRIGHT\",\"1\"]")).isFalse()
assertThat(SubtaskReset.isCopyMarker(null)).isFalse()
assertThat(SubtaskReset.hasCopyMarker("X-OTHER:1\r\nX-AGENDULA-TICK-COPY:1")).isTrue()
assertThat(SubtaskReset.hasCopyMarker("X-AGENDULA-TICK-COPY;X-P=1:1")).isTrue()
assertThat(SubtaskReset.hasCopyMarker("X-AGENDULA-TICK-COPYRIGHT:1")).isFalse()
assertThat(SubtaskReset.hasCopyMarker(null)).isFalse()
fun `the copy marker names the parent it was left under`() {
val json = SubtaskReset.copyMarkerJson("parent-\"1\"")
assertThat(SubtaskReset.markerParentFromJson(json)).isEqualTo("parent-\"1\"")
assertThat(SubtaskReset.markerParentFromJson(" [\"x-agendula-tick-copy\", \"p\"]")).isEqualTo("p")
assertThat(SubtaskReset.markerParentFromJson("[\"X-AGENDULA-TICK-COPYRIGHT\",\"p\"]")).isNull()
assertThat(SubtaskReset.markerParentFromJson(null)).isNull()
assertThat(SubtaskReset.markerParentFromResidue("X-OTHER:1\r\nX-AGENDULA-TICK-COPY:p\\,1")).isEqualTo("p,1")
assertThat(SubtaskReset.markerParentFromResidue("X-AGENDULA-TICK-COPY;X-P=1:p")).isEqualTo("p")
assertThat(SubtaskReset.markerParentFromResidue("X-AGENDULA-TICK-COPYRIGHT:p")).isNull()
assertThat(SubtaskReset.markerParentFromResidue(null)).isNull()
}
@Test
fun `a provider tick resets only with a copy to record it in`() {
fun `a marked copy counts only under the parent it came from`() {
fun node(markerParent: String?, parentUid: String?) =
SubtaskReset.providerNode(2, null, null, emptySet(), markerParent = markerParent, parentUid = parentUid, state = done)
assertThat(node("routine", "routine").recurring).isTrue()
// Moved under another parent since: an ordinary completed sub-task there.
assertThat(node("routine", "other").recurring).isFalse()
assertThat(node(null, "routine").recurring).isFalse()
assertThat(node("routine", null).recurring).isFalse()
}
@Test
fun `a moved-on provider series resets with or without a copy, and its record is found by series and anchor`() {
val before = state(start) + (Tasks.RRULE to "FREQ=WEEKLY")
val after = state(start + week) + (Tasks.RRULE to "FREQ=WEEKLY")
assertThat(SubtaskReset.resetsOnTick(9L, before, after)).isTrue()
assertThat(SubtaskReset.resetsOnTick(null, before, after)).isFalse()
assertThat(SubtaskReset.resetsOnTick(9L, before, before)).isFalse()
assertThat(SubtaskReset.movedOn(before, after)).isTrue()
assertThat(SubtaskReset.movedOn(before, before)).isFalse()
val anchor = SubtaskReset.anchor(after)!!
val key = TickResets.key("org.dmfs.tasks", 4, anchor)
val record = SubtaskReset.encode(listOf(ResetSubtask(2, done)))
assertThat(key).isEqualTo("org.dmfs.tasks|4|${start + week}")
assertThat(TickResets.decode(TickResets.encode(1L, record))).isEqualTo(record)
assertThat(SubtaskReset.toRestore(SubtaskReset.decode(record)) { now(SubtaskState.FRESH) }.restore.map { it.id }).containsExactly(2L)
}
@Test
fun `a reset record expires with the tick horizon`() {
val now = 100L * 24 * 60 * 60 * 1000
val entries = mapOf(
"a|1|1" to TickResets.encode(now - 31L * 24 * 60 * 60 * 1000, "2,COMPLETED,,,,,,"),
"a|1|2" to TickResets.encode(now - 1, "3,COMPLETED,,,,,,"),
"garbage" to "x",
)
assertThat(TickResets.expire(entries, now)).containsExactly("a|1|1", "garbage")
assertThat(TickResets.decode("x")).isNull()
}
private val week = 7L * 24 * 60 * 60 * 1000