From 70df9c8a4d5021b7449958bd0474fd415c3c0d34 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Tue, 17 Nov 2026 10:56:59 +0100 Subject: [PATCH] Repeat a task from its completion date (#79) --- CHANGELOG.md | 9 ++ .../agendula/data/tasks/TasksRepository.kt | 3 + .../data/tasks/TasksRepositoryImpl.kt | 2 + .../data/tasks/room/RoomTaskMapper.kt | 7 + .../data/tasks/room/RoomTasksDataSource.kt | 60 ++++++--- .../data/tasks/room/TaskFormWriter.kt | 29 ++-- .../jeanlucmakiola/agendula/domain/Models.kt | 2 + .../agendula/domain/TaskForm.kt | 2 + .../domain/recurrence/RepeatFromCompletion.kt | 116 ++++++++++++++++ .../agendula/ui/detail/TaskDetailScreen.kt | 8 ++ .../agendula/ui/edit/RecurrencePicker.kt | 33 +++++ .../agendula/ui/edit/TaskEditScreen.kt | 10 +- .../agendula/ui/edit/TaskEditViewModel.kt | 15 ++- app/src/main/res/values/strings.xml | 6 + .../tasks/room/TaskFormWriterSeriesTest.kt | 45 +++++++ .../recurrence/RepeatFromCompletionTest.kt | 125 ++++++++++++++++++ .../agendula/ui/edit/TaskEditViewModelTest.kt | 29 ++++ 17 files changed, 474 insertions(+), 27 deletions(-) create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/domain/recurrence/RepeatFromCompletion.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/agendula/domain/recurrence/RepeatFromCompletionTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 67c3d4b..38711e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,15 @@ All notable changes to this project are documented here. The format follows ## [Unreleased] +### Added +- A repeating task can repeat from its completion date, as in tasks.org: + ticking it off moves the next date on from the day you did it rather than + from the schedule, so watering a plant a week after you last did is due a + week later even when you were late. Pick "Completion date" under "Repeat + from" in the repeat picker. With Agendula's own storage only; over CalDAV + the choice syncs between Agendula installs, and other apps see the moved + task with its plain rule (#79). + ## [1.3.2] - 2026-11-13 ### Added diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/TasksRepository.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/TasksRepository.kt index 347671e..56b43b2 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/TasksRepository.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/TasksRepository.kt @@ -99,4 +99,7 @@ interface TasksRepository { /** Synchronous snapshot for the permission/onboarding gate. */ fun providerStatus(): ProviderStatus + + /** Whether the active store can repeat a series from completion (#79): only Agendula's own. */ + fun supportsRepeatFromCompletion(): Boolean = false } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/TasksRepositoryImpl.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/TasksRepositoryImpl.kt index f747de2..d913797 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/TasksRepositoryImpl.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/TasksRepositoryImpl.kt @@ -265,6 +265,8 @@ class TasksRepositoryImpl @Inject constructor( override suspend fun reorderLists(listIds: List) = withContext(io) { dataSource.reorderLists(listIds) } + override fun supportsRepeatFromCompletion(): Boolean = providerResolver.mode() == StorageMode.OWN + override fun providerStatus(): ProviderStatus { // Our own store is always ready: it ships with the app, needs no provider // and no grant. The permission gate only ever applied to External mode — diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/room/RoomTaskMapper.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/room/RoomTaskMapper.kt index 3bf4214..d81fe58 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/room/RoomTaskMapper.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/room/RoomTaskMapper.kt @@ -7,6 +7,7 @@ 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 de.jeanlucmakiola.agendula.domain.recurrence.RepeatFromCompletion import kotlin.time.Instant /** Account type reported for a list attached to one of ours. */ @@ -43,6 +44,7 @@ object RoomTaskMapper { distanceFromCurrent: Int? = null, seriesId: Long? = if (row.task.isRecurring) row.task.id else null, recurrenceRule: String? = row.task.rrule, + repeatFromCompletion: Boolean = row.task.repeatsFromCompletion, ): Task = Task( taskId = row.task.id, listId = row.task.listId, @@ -71,6 +73,7 @@ object RoomTaskMapper { lastModified = row.task.lastModified, seriesId = seriesId, recurrenceRule = recurrenceRule, + repeatFromCompletion = recurrenceRule != null && repeatFromCompletion, isReadOnly = row.listReadOnly, ) @@ -101,6 +104,10 @@ object RoomTaskMapper { val TaskEntity.isRecurring: Boolean get() = !rrule.isNullOrBlank() || !rdate.isNullOrBlank() +/** The series moves on from its completion rather than its schedule (#79). */ +val TaskEntity.repeatsFromCompletion: Boolean + get() = !rrule.isNullOrBlank() && RepeatFromCompletion.isSet(unknownProperties) + /** Completed or cancelled. */ val TaskEntity.isClosed: Boolean get() = status.isClosed diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/room/RoomTasksDataSource.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/room/RoomTasksDataSource.kt index aa6499e..ec8a47f 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/room/RoomTasksDataSource.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/room/RoomTasksDataSource.kt @@ -25,6 +25,7 @@ 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 de.jeanlucmakiola.agendula.domain.recurrence.RepeatFromCompletion import java.time.ZoneId import de.jeanlucmakiola.agendula.domain.recurrence.dateZone import java.util.UUID @@ -39,7 +40,7 @@ private val WINDOW_BACK = 365.days 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") +private val SERIES_LINES = listOf("EXDATE", "RDATE", "RRULE", "RECURRENCE-ID", "UID", RepeatFromCompletion.PROPERTY) /** How long a record keeps mapping a ticked occurrence to its copy. */ private val RECORD_HORIZON = 30.days @@ -161,13 +162,16 @@ class RoomTasksDataSource @Inject constructor( } } - private fun overrideTask(row: TaskRow, anchor: Instant): Task = - RoomTaskMapper.task( + private fun overrideTask(row: TaskRow, anchor: Instant): Task { + val master = row.task.masterId?.let { tasks.entity(it) } + return RoomTaskMapper.task( row, occurrenceStart = anchor, seriesId = row.task.masterId, - recurrenceRule = row.task.masterId?.let { tasks.entity(it)?.rrule }, + recurrenceRule = master?.rrule, + repeatFromCompletion = master?.repeatsFromCompletion == true, ) + } override fun subtasks(parentTaskId: Long): List { val now = clock.now() @@ -222,6 +226,7 @@ class RoomTasksDataSource @Inject constructor( distanceFromCurrent = occurrence.distance, seriesId = row.task.id, recurrenceRule = row.task.rrule, + repeatFromCompletion = row.task.repeatsFromCompletion, ) } else { RoomTaskMapper.task( @@ -242,7 +247,7 @@ class RoomTasksDataSource @Inject constructor( val entity = TaskFormWriter.newTask(form, uid = UUID.randomUUID().toString(), now = clock.now(), tzId = zone()) var id = 0L tx { - id = tasks.insert(TaskFormWriter.withRule(entity, form.rrule)) + id = tasks.insert(TaskFormWriter.withRule(entity, form.rrule, form.repeatFromCompletion)) reminders?.let { alarms.syncForTask(id, it) } writes.onWritten(setOf(form.listId)) } @@ -268,7 +273,7 @@ class RoomTasksDataSource @Inject constructor( val remindersChanged = writeReminders(taskId, reminders) if (current.masterId == null && edited.listId != current.listId) { if (lists.exists(edited.listId) == 0) throw TaskWriteFailedException("move task: no list ${edited.listId}") - move(current, TaskFormWriter.withRule(edited, form.rrule)) + move(current, TaskFormWriter.withRule(edited, form.rrule, form.repeatFromCompletion)) writes.onWritten(setOf(current.listId, edited.listId)) return@tx } @@ -283,7 +288,7 @@ class RoomTasksDataSource @Inject constructor( saveRow( current, if (current.masterId == null) { - TaskFormWriter.withRule(edited, form.rrule) + TaskFormWriter.withRule(edited, form.rrule, form.repeatFromCompletion) } else { edited.copy(listId = current.listId, parentId = current.parentId) }, @@ -383,7 +388,7 @@ class RoomTasksDataSource @Inject constructor( val exceptions = if (rule == null) null else if (delta == null || delta == kotlin.time.Duration.ZERO) laterExceptions else TaskFormWriter.shiftValues(laterExceptions, delta, master.timezone ?: zone()) - val fresh = TaskFormWriter.withRule(applied, rule).let { if (it.rrule != null) it.copy(exdate = exceptions) else it } + val fresh = TaskFormWriter.withRule(applied, rule, form.repeatFromCompletion).let { if (it.rrule != null) it.copy(exdate = exceptions) else it } val newId = tasks.insert(fresh) // A new UID, so a new resource: the alarms are copies, not the same ones. alarms.copyToTask(master.id, newId, sameResource = false) @@ -612,6 +617,11 @@ class RoomTasksDataSource @Inject constructor( * 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. + * + * A series repeating from completion (#79) moves to the first occurrence of + * its rule after the day it was ticked instead. That leaves the old + * schedule behind, so every other override becomes a task of its own, and + * comes back with the rest should the tick be undone. */ private fun advance(master: TaskEntity, anchor: Instant, override: TaskEntity?, close: (TaskEntity) -> TaskEntity): Boolean { val rule = master.rrule?.takeIf { it.isNotBlank() } ?: return false @@ -622,18 +632,32 @@ class RoomTasksDataSource @Inject constructor( 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) + val newAnchor: Instant + val spent: Int + val toDetach: List> + if (master.repeatsFromCompletion) { + spent = spentBefore(spec, wholeSecond(anchor)) + 1 + val left = TaskFormWriter.countOf(rule)?.let { it - spent } + val next = RepeatFromCompletion.nextAnchor(spec, now, ZoneId.of(zone())) + if (next == null || (left != null && left < 1)) return true.also { closeSeries(master, override, close) } + newAnchor = next + toDetach = overrides.values.filter { it.id != override?.id } + .mapNotNull { row -> row.recurrenceId?.let { it to row } } + } else { + var nextIndex = index + 1 + while (nextIndex < leading.size && closedAt(leading[nextIndex])) nextIndex++ + val next = leading.getOrNull(nextIndex) ?: return true.also { closeSeries(master, override, close) } + // Expansion drops the anchor's sub-second part; the series keeps it. + newAnchor = next + (spec.anchor - wholeSecond(spec.anchor)) + spent = spentBefore(spec, next) + toDetach = (leading.take(index) + leading.subList(index + 1, nextIndex)).map { at -> + at to overrides.getValue(at.epochSeconds) + } } - // Expansion drops the anchor's sub-second part; the series keeps it. - val newAnchor = next + (spec.anchor - wholeSecond(spec.anchor)) - val spent = spentBefore(spec, next) + val detached = toDetach.map { (at, row) -> at to detach(row, now) } val (start, due) = occurrenceTimes(master, newAnchor) val ruleAfter = TaskFormWriter.remainingCount(rule, spent) tasks.update( @@ -694,7 +718,9 @@ class RoomTasksDataSource @Inject constructor( val to = newAnchor.toEpochMilliseconds() val shift = from?.let { SeriesShift(it, to, dateZone(master.isAllDay, master.timezone, ZoneId.of(zone()))) } val loaded = HashMap().apply { put(master.id, master) } - val reset = SubtaskReset.toReset(master.id, shift, since = from?.let { SubtaskReset.cycleStart(it, to) }) { id -> + // A series repeating from completion can move back, ticked early; there is no cycle to measure then. + val since = from?.takeIf { to > it }?.let { SubtaskReset.cycleStart(it, to) } + val reset = SubtaskReset.toReset(master.id, shift, since = since) { id -> val parentUid = loaded[id]?.uid tasks.subtasks(id).map { row -> val sub = row.task.also { loaded[it.id] = it } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/room/TaskFormWriter.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/room/TaskFormWriter.kt index c7743f0..7a84907 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/room/TaskFormWriter.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/room/TaskFormWriter.kt @@ -4,6 +4,7 @@ import de.jeanlucmakiola.agendula.domain.TaskForm import de.jeanlucmakiola.agendula.domain.TaskStatus import de.jeanlucmakiola.agendula.domain.ical.ICalValues import de.jeanlucmakiola.agendula.domain.normalizeTags +import de.jeanlucmakiola.agendula.domain.recurrence.RepeatFromCompletion import de.jeanlucmakiola.agendula.domain.toICal import kotlin.time.Duration.Companion.days import kotlin.time.Duration.Companion.seconds @@ -70,15 +71,22 @@ object TaskFormWriter { } /** - * [current] with its rule set to [rrule]. Only ever a master or a plain task: - * an override carries no rule of its own. + * [current] with its rule set to [rrule], repeating from completion when + * [fromCompletion] (#79). Only ever a master or a plain task: an override + * carries no rule of its own. */ - fun withRule(current: TaskEntity, rrule: String?): TaskEntity { + fun withRule(current: TaskEntity, rrule: String?, fromCompletion: Boolean = false): TaskEntity { val rule = rrule?.trim()?.removePrefix("RRULE:")?.ifEmpty { null } - if (current.masterId != null || rule == current.rrule) return current - // Dropping the rule ends the series, and its exceptions with it. - return if (rule == null) current.copy(rrule = null, rdate = null, exdate = null) - else current.copy(rrule = rule) + if (current.masterId != null) return current + val ruled = when { + rule == current.rrule -> current + // Dropping the rule ends the series, and its exceptions with it. + rule == null -> current.copy(rrule = null, rdate = null, exdate = null) + else -> current.copy(rrule = rule) + } + val flagged = rule != null && fromCompletion + if (RepeatFromCompletion.isSet(ruled.unknownProperties) == flagged) return ruled + return ruled.copy(unknownProperties = RepeatFromCompletion.applied(ruled.unknownProperties, flagged)) } /** @@ -94,7 +102,7 @@ object TaskFormWriter { now: Instant, tzId: String, ): TaskEntity { - val edited = withRule(apply(master, form, now, tzId), form.rrule) + val edited = withRule(apply(master, form, now, tzId), form.rrule, form.repeatFromCompletion) val dtstart = shifted(master.dtstart, occurrenceStart, form.start, form.isAllDay) val delta = if (dtstart != null && master.dtstart != null) dtstart - master.dtstart else null return edited.copy( @@ -210,6 +218,11 @@ object TaskFormWriter { else "COUNT=${((part.substringAfter('=').trim().toIntOrNull() ?: 1) - spent).coerceAtLeast(1)}" } + /** [rrule]'s `COUNT`, or null without a readable one. */ + fun countOf(rrule: String): Int? = rrule.split(';') + .firstOrNull { it.substringBefore('=').trim().equals("COUNT", ignoreCase = true) } + ?.substringAfter('=')?.trim()?.toIntOrNull() + /** Cancelled, or back to needs-action; either way no longer complete. */ fun cancelled(current: TaskEntity, cancelled: Boolean, now: Instant): TaskEntity = current.copy( status = if (cancelled) TaskStatus.CANCELLED else TaskStatus.NEEDS_ACTION, diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/Models.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/Models.kt index 55943f9..7e853fe 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/Models.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/Models.kt @@ -104,6 +104,8 @@ data class Task( val seriesId: Long? = null, /** The series' `RRULE`, for display and for prefilling the editor. */ val recurrenceRule: String? = null, + /** The series' next occurrence counts from completion, not its schedule (#79). */ + val repeatFromCompletion: Boolean = false, /** * The task's list is a read-only share. An edit here would never reach the * server, and the dirty row would then block every later download of it. diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskForm.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskForm.kt index 9bf41ec..aac0e51 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskForm.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskForm.kt @@ -27,6 +27,8 @@ data class TaskForm( val tags: List = emptyList(), /** The series' `RRULE` value; `null` = does not repeat. Ignored for a single-occurrence edit. */ val rrule: String? = null, + /** With [rrule], the next occurrence counts from completion rather than the schedule (#79). */ + val repeatFromCompletion: Boolean = false, ) { fun validate(): Set = buildSet { if (title.isBlank()) add(TaskFormError.BLANK_TITLE) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/recurrence/RepeatFromCompletion.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/recurrence/RepeatFromCompletion.kt new file mode 100644 index 0000000..7ed99f5 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/recurrence/RepeatFromCompletion.kt @@ -0,0 +1,116 @@ +package de.jeanlucmakiola.agendula.domain.recurrence + +import java.time.LocalDateTime +import java.time.ZoneId +import java.time.ZoneOffset +import kotlin.time.Duration.Companion.days +import kotlin.time.Instant + +/** + * A series whose next occurrence counts from when the current one was + * completed rather than from its schedule, as tasks.org's "repeat from + * completion date" (#79). + * + * No standard property says so, and tasks.org keeps its flag to itself, so it + * travels as the `X-` property [PROPERTY] on the series' `VTODO`: other clients + * keep it untouched (RFC 5545 §3.1) and read the plain `RRULE` from wherever + * the series was last moved to. + */ +object RepeatFromCompletion { + + const val PROPERTY = "X-AGENDULA-REPEAT-FROM" + private const val COMPLETION = "COMPLETION" + private const val LINE = "$PROPERTY:$COMPLETION" + + /** Only bounds the search for the next occurrence. */ + private val LOOKAHEAD = (366 * 1000).days + + private val SUB_DAY = setOf("HOURLY", "MINUTELY", "SECONDLY") + + /** Whether the stored residue [residue] marks its series as repeating from completion. */ + fun isSet(residue: String?): Boolean { + if (residue == null || !residue.contains(PROPERTY, ignoreCase = true)) return false + return topLevelLines(residue).any { line -> + val value = valueOf(line) + value != null && value.equals(COMPLETION, ignoreCase = true) + } + } + + /** [residue] with the marker set or cleared; null once nothing is left. */ + fun applied(residue: String?, on: Boolean): String? { + val kept = withoutMarker(residue) + return if (on) LINE + "\r\n" + kept.orEmpty() else kept + } + + /** [residue] without any [PROPERTY] line, folded continuations included. */ + fun withoutMarker(residue: String?): String? { + if (residue == null || !residue.contains(PROPERTY, ignoreCase = true)) return residue?.ifEmpty { null } + var depth = 0 + var dropping = false + val kept = residue.split("\r\n", "\n").filter { line -> + if (dropping && (line.startsWith(" ") || line.startsWith("\t"))) return@filter false + dropping = false + when { + line.startsWith("BEGIN:", ignoreCase = true) -> depth++ + line.startsWith("END:", ignoreCase = true) -> depth-- + depth == 0 && valueOf(line) != null -> dropping = true + } + !dropping && line.isNotEmpty() + } + return kept.joinToString("\r\n").ifEmpty { null }?.let { "$it\r\n" } + } + + /** + * The anchor [spec]'s series moves to once completed at [completedAt]: the + * first occurrence of its rule after the day it was completed, at the + * series' own time of day — or, for a rule repeating within a day, after the + * completion itself. `COUNT` is the caller's to spend. Null when the rule + * has nothing after it, an `UNTIL` passed, or there is no `RRULE`. + * + * [floatingZone] is the user's zone: it decides which day the completion + * fell on, and the wall time of a series without a zone of its own. + */ + fun nextAnchor(spec: RecurrenceSpec, completedAt: Instant, floatingZone: ZoneId): Instant? { + val parts = spec.rrule?.trim()?.removePrefix("RRULE:")?.split(';') + ?.map(String::trim)?.filter(String::isNotEmpty) + ?.takeIf { it.isNotEmpty() } ?: return null + val freq = parts.firstOrNull { it.substringBefore('=').equals("FREQ", ignoreCase = true) } + ?.substringAfter('=')?.trim()?.uppercase() ?: return null + val rule = parts.filterNot { it.substringBefore('=').trim().equals("COUNT", ignoreCase = true) }.joinToString(";") + val completedDay = java.time.Instant.ofEpochMilli(completedAt.toEpochMilliseconds()).atZone(floatingZone).toLocalDate() + val base = when { + freq in SUB_DAY -> Instant.fromEpochSeconds(completedAt.epochSeconds) + spec.isAllDay -> Instant.fromEpochSeconds(completedDay.atStartOfDay(ZoneOffset.UTC).toEpochSecond()) + else -> { + val zone = dateZone(false, spec.timeZone, floatingZone) + val time = java.time.Instant.ofEpochSecond(spec.anchor.epochSeconds).atZone(zone).toLocalTime() + Instant.fromEpochSeconds(LocalDateTime.of(completedDay, time).atZone(zone).toEpochSecond()) + } + } + val fresh = spec.copy(rrule = rule, rdate = null, exdate = null, anchor = base) + return RecurrenceExpander.expand( + fresh, + ExpansionWindow(from = base, until = base + LOOKAHEAD, maxOccurrences = 2), + floatingZone, + ).firstOrNull { it > base } + } + + private fun topLevelLines(residue: String): List { + var depth = 0 + return residue.split("\r\n", "\n").filter { line -> + when { + line.startsWith("BEGIN:", ignoreCase = true) -> { depth++; false } + line.startsWith("END:", ignoreCase = true) -> { depth--; false } + else -> depth == 0 + } + } + } + + /** The value of a [PROPERTY] content line, or null when [line] is another one. */ + private fun valueOf(line: String): String? { + if (!line.startsWith(PROPERTY, ignoreCase = true)) return null + val next = line.getOrNull(PROPERTY.length) + if (next != ':' && next != ';') return null + return line.substringAfter(':').trim() + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/detail/TaskDetailScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/detail/TaskDetailScreen.kt index 50312ab..f06c168 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/detail/TaskDetailScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/detail/TaskDetailScreen.kt @@ -349,6 +349,14 @@ private fun DetailBody( val locale = currentLocale() DetailCard(icon = Icons.Rounded.Repeat, iconContentDescription = stringResource(R.string.edit_recurrence_label)) { Text(recurrenceText(rule, locale), style = MaterialTheme.typography.titleMedium) + if (task.repeatFromCompletion) { + Spacer(Modifier.height(2.dp)) + Text( + stringResource(R.string.recurrence_from_completion_note), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } } } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/RecurrencePicker.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/RecurrencePicker.kt index 2f43cd1..58805c0 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/RecurrencePicker.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/RecurrencePicker.kt @@ -74,6 +74,8 @@ private enum class RecurrenceEndMode { Never, Until, Count } * [current] is the bare RRULE value (or null for none); [startDate] anchors the * "Next: …" previews — for a task, its start date or else its due date. * [onSelect] gets the new RRULE value, or null for "Does not repeat". + * [fromCompletion], when not null, offers "Repeat from" below the rules; a + * choice there applies at once through [onFromCompletionChange] (#79). */ @Composable fun RecurrencePicker( @@ -82,6 +84,8 @@ fun RecurrencePicker( firstDayOfWeek: DayOfWeek, onSelect: (String?) -> Unit, onDismiss: () -> Unit, + fromCompletion: Boolean? = null, + onFromCompletionChange: (Boolean) -> Unit = {}, ) { val startDay = startDate.dayOfWeek val parsed = remember(current) { current?.let { parseSimpleRecurrence(it) } } @@ -161,6 +165,7 @@ fun RecurrencePicker( onSelect = onSelect, onCustom = { customMode = true }, ) + fromCompletion?.let { RepeatFromSection(it, onFromCompletionChange) } } else { Column(modifier = Modifier.fillMaxWidth()) { // Live read-out of exactly what OK would save; minLines keeps the @@ -310,6 +315,7 @@ fun RecurrencePicker( } } } + fromCompletion?.let { RepeatFromSection(it, onFromCompletionChange) } } } } @@ -364,6 +370,33 @@ private fun PresetList( ) } +/** Whether the next occurrence keeps to the schedule or counts from completion. */ +@Composable +private fun RepeatFromSection(fromCompletion: Boolean, onChange: (Boolean) -> Unit) { + Column(modifier = Modifier.padding(top = 16.dp)) { + Text( + text = stringResource(R.string.recurrence_repeat_from), + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(start = 16.dp, bottom = 8.dp), + ) + CheckRow( + title = stringResource(R.string.recurrence_from_due), + summary = stringResource(R.string.recurrence_from_due_summary), + position = Position.Top, + selected = !fromCompletion, + onClick = { onChange(false) }, + ) + CheckRow( + title = stringResource(R.string.recurrence_from_completion), + summary = stringResource(R.string.recurrence_from_completion_summary), + position = Position.Bottom, + selected = fromCompletion, + onClick = { onChange(true) }, + ) + } +} + @Composable private fun CheckRow( title: String, diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/TaskEditScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/TaskEditScreen.kt index 318c249..a76466b 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/TaskEditScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/TaskEditScreen.kt @@ -419,7 +419,13 @@ private fun EditContent( style = MaterialTheme.typography.titleMedium, ) Text( - text = stringResource(R.string.edit_recurrence_label), + text = stringResource( + if (state.rrule != null && state.repeatFromCompletion) { + R.string.recurrence_from_completion_note + } else { + R.string.edit_recurrence_label + }, + ), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -788,6 +794,8 @@ private fun EditContent( firstDayOfWeek = LocalFirstDayOfWeek.current.toKotlinDayOfWeek(), onSelect = { viewModel.onRecurrenceChange(it); showRecurrencePicker = false }, onDismiss = { showRecurrencePicker = false }, + fromCompletion = state.repeatFromCompletion.takeIf { state.repeatFromAvailable }, + onFromCompletionChange = viewModel::onRepeatFromCompletionChange, ) } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/TaskEditViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/TaskEditViewModel.kt index 8eb09a5..3692e13 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/TaskEditViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/TaskEditViewModel.kt @@ -76,6 +76,12 @@ data class TaskEditUiState( /** Every tag already in use, for completing what the user types. */ val tagSuggestions: List = emptyList(), val rrule: String? = null, + /** The next occurrence counts from completion rather than the schedule (#79). */ + val repeatFromCompletion: Boolean = false, + /** [repeatFromCompletion] as loaded. */ + val originalFromCompletion: Boolean = false, + /** Whether the active store can repeat from completion, so the picker offers it. */ + val repeatFromAvailable: Boolean = false, /** Editing one occurrence of a series: saving asks how far the edit reaches. */ val isOccurrence: Boolean = false, /** The series' rule as loaded; a changed rule rules out "only this task". */ @@ -103,7 +109,8 @@ data class TaskEditUiState( /** Lists a task can be saved into: read-only shares drop out, except the one it is already in. */ val writableLists: List get() = lists.filter { it.acceptsWrites || it.id == listId } - val recurrenceChanged: Boolean get() = rrule != originalRule + val recurrenceChanged: Boolean + get() = rrule != originalRule || (rrule != null && repeatFromCompletion) != originalFromCompletion } @HiltViewModel @@ -209,6 +216,7 @@ class TaskEditViewModel @Inject constructor( priority = preset?.priority ?: Priority.NONE, parentId = parentId, lists = lists, + repeatFromAvailable = repository.supportsRepeatFromCompletion(), parentCandidates = loadParents(defaultList, selfId = null), title = initialTitle.orEmpty(), tags = (listOfNotNull(presetTag) + preset?.tags.orEmpty()).distinct(), @@ -263,6 +271,9 @@ class TaskEditViewModel @Inject constructor( tags = task.tags, rrule = task.recurrenceRule, originalRule = task.recurrenceRule, + repeatFromCompletion = task.repeatFromCompletion, + originalFromCompletion = task.repeatFromCompletion, + repeatFromAvailable = repository.supportsRepeatFromCompletion(), isOccurrence = task.isOccurrence, lists = lists, parentCandidates = loadParents(task.listId, selfId = taskId), @@ -496,6 +507,7 @@ class TaskEditViewModel @Inject constructor( fun commitTagDraft() = update { it.copy(tags = it.withDraft(it.tagDraft), tagDraft = "") } fun removeTag(name: String) = update { it.copy(tags = it.tags - name) } fun onRecurrenceChange(rrule: String?) = update { it.copy(rrule = rrule, errors = emptySet()) } + fun onRepeatFromCompletionChange(value: Boolean) = update { it.copy(repeatFromCompletion = value) } /** Dismiss the conflict prompt without saving (the user keeps editing). */ fun dismissConflict() = update { it.copy(saveConflict = false) } @@ -586,6 +598,7 @@ private fun TaskEditUiState.toForm(): TaskForm = TaskForm( url = url.ifBlank { null }, tags = withDraft(tagDraft), rrule = rrule, + repeatFromCompletion = rrule != null && repeatFromCompletion, ) private fun TaskEditUiState.withDraft(draft: String): List = normalizeTags(tags + draft.split(',')) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 5211b6b..490d4a2 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -184,6 +184,12 @@ On a date After a number of times times + Repeat from + Due date + Keeps to the schedule, however late you finish + Completion date + The next date counts from the day you tick it off + Repeats from the completion date Only this task This and following tasks All tasks in the series diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/room/TaskFormWriterSeriesTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/room/TaskFormWriterSeriesTest.kt index cdcc154..8a05908 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/room/TaskFormWriterSeriesTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/room/TaskFormWriterSeriesTest.kt @@ -118,4 +118,49 @@ class TaskFormWriterSeriesTest { assertThat(edited.status).isEqualTo(master.status) assertThat(edited.completedAt).isNull() } + + @Test + fun `repeating from completion is marked on the series and cleared again`() { + val residue = "X-FOO:bar\r\n" + val marked = TaskFormWriter.withRule(master.copy(unknownProperties = residue), master.rrule, fromCompletion = true) + + assertThat(marked.repeatsFromCompletion).isTrue() + assertThat(marked.unknownProperties).contains(residue) + + val cleared = TaskFormWriter.withRule(marked, master.rrule, fromCompletion = false) + assertThat(cleared.repeatsFromCompletion).isFalse() + assertThat(cleared.unknownProperties).isEqualTo(residue) + } + + @Test + fun `dropping the rule drops the mark with it`() { + val marked = TaskFormWriter.withRule(master, master.rrule, fromCompletion = true) + + val plain = TaskFormWriter.withRule(marked, null, fromCompletion = true) + + assertThat(plain.rrule).isNull() + assertThat(plain.unknownProperties).isNull() + } + + @Test + fun `an override carries no mark of its own`() { + val override = master.copy(id = 8, masterId = 7, rrule = null) + + assertThat(TaskFormWriter.withRule(override, "FREQ=DAILY", fromCompletion = true)).isEqualTo(override) + } + + @Test + fun `a series edit takes the form's choice`() { + val form = TaskForm(title = "Water plants", listId = 1, start = anchor, due = anchor + 1.hours, rrule = master.rrule, repeatFromCompletion = true) + + val edited = TaskFormWriter.seriesEdit(master, anchor, anchor + 1.hours, form, now, "Europe/Berlin") + + assertThat(edited.repeatsFromCompletion).isTrue() + } + + @Test + fun `COUNT is read from a rule in any order and case`() { + assertThat(TaskFormWriter.countOf("FREQ=DAILY;count=4;INTERVAL=2")).isEqualTo(4) + assertThat(TaskFormWriter.countOf("FREQ=DAILY")).isNull() + } } diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/domain/recurrence/RepeatFromCompletionTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/domain/recurrence/RepeatFromCompletionTest.kt new file mode 100644 index 0000000..1036d96 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/agendula/domain/recurrence/RepeatFromCompletionTest.kt @@ -0,0 +1,125 @@ +package de.jeanlucmakiola.agendula.domain.recurrence + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test +import java.time.ZoneId +import kotlin.time.Instant + +class RepeatFromCompletionTest { + + private val berlin = ZoneId.of("Europe/Berlin") + + private fun at(text: String) = Instant.parse(text) + + private fun allDay(rrule: String?, anchor: String) = + RecurrenceSpec(rrule, rdate = null, exdate = null, anchor = at(anchor), isAllDay = true, timeZone = null) + + private fun timed(rrule: String?, anchor: String) = + RecurrenceSpec(rrule, rdate = null, exdate = null, anchor = at(anchor), isAllDay = false, timeZone = "Europe/Berlin") + + private fun next(spec: RecurrenceSpec, completed: String) = + RepeatFromCompletion.nextAnchor(spec, at(completed), berlin)?.toString() + + // --- the next anchor ----------------------------------------------------- + + @Test + fun `a late tick moves the series a week on from the day it was done`() { + val spec = allDay("FREQ=DAILY;INTERVAL=7", "2026-03-02T00:00:00Z") + + assertThat(next(spec, "2026-03-10T15:00:00Z")).isEqualTo("2026-03-17T00:00:00Z") + } + + @Test + fun `the day of the tick is the user's, not UTC's`() { + val spec = allDay("FREQ=DAILY;INTERVAL=7", "2026-03-02T00:00:00Z") + + // 00:30 on 11 March in Berlin. + assertThat(next(spec, "2026-03-10T23:30:00Z")).isEqualTo("2026-03-18T00:00:00Z") + } + + @Test + fun `a timed series keeps its wall time across a DST change`() { + // 09:00 CET; the clocks go forward on 29 March. + val spec = timed("FREQ=DAILY;INTERVAL=7", "2026-03-02T08:00:00Z") + + assertThat(next(spec, "2026-03-24T17:00:00Z")).isEqualTo("2026-03-31T07:00:00Z") + } + + @Test + fun `an early tick moves the series earlier`() { + val spec = allDay("FREQ=WEEKLY", "2026-03-06T00:00:00Z") + + assertThat(next(spec, "2026-03-02T12:00:00Z")).isEqualTo("2026-03-09T00:00:00Z") + } + + @Test + fun `weekdays pick the first one after the day it was done`() { + val spec = allDay("FREQ=WEEKLY;BYDAY=MO,TH", "2026-03-02T00:00:00Z") + + // Tuesday 10 March. + assertThat(next(spec, "2026-03-10T12:00:00Z")).isEqualTo("2026-03-12T00:00:00Z") + } + + @Test + fun `COUNT is left to the caller`() { + val spec = allDay("FREQ=DAILY;COUNT=1", "2026-03-02T00:00:00Z") + + assertThat(next(spec, "2026-03-10T12:00:00Z")).isEqualTo("2026-03-11T00:00:00Z") + } + + @Test + fun `a passed UNTIL ends the series`() { + val spec = allDay("FREQ=DAILY;UNTIL=20260305", "2026-03-02T00:00:00Z") + + assertThat(next(spec, "2026-03-10T12:00:00Z")).isNull() + } + + @Test + fun `a rule repeating within a day counts from the tick itself`() { + val spec = timed("FREQ=HOURLY;INTERVAL=4", "2026-03-02T08:00:00Z") + + assertThat(next(spec, "2026-03-10T13:17:42.500Z")).isEqualTo("2026-03-10T17:17:42Z") + } + + @Test + fun `no rule has no next anchor`() { + assertThat(next(allDay(null, "2026-03-02T00:00:00Z"), "2026-03-10T12:00:00Z")).isNull() + } + + // --- the marker ---------------------------------------------------------- + + @Test + fun `the marker is read from the residue, in any case`() { + assertThat(RepeatFromCompletion.isSet("X-FOO:bar\r\nx-agendula-repeat-from:completion\r\n")).isTrue() + assertThat(RepeatFromCompletion.isSet("X-FOO:bar\r\n")).isFalse() + assertThat(RepeatFromCompletion.isSet(null)).isFalse() + assertThat(RepeatFromCompletion.isSet("X-AGENDULA-REPEAT-FROM:DUE\r\n")).isFalse() + assertThat(RepeatFromCompletion.isSet("X-AGENDULA-REPEAT-FROM-X:COMPLETION\r\n")).isFalse() + } + + @Test + fun `a marker inside a nested component is not the series'`() { + val residue = "BEGIN:VALARM\r\nX-AGENDULA-REPEAT-FROM:COMPLETION\r\nEND:VALARM\r\n" + + assertThat(RepeatFromCompletion.isSet(residue)).isFalse() + assertThat(RepeatFromCompletion.withoutMarker(residue)).isEqualTo(residue) + } + + @Test + fun `setting the marker keeps the rest of the residue, once`() { + val residue = "X-FOO:bar\r\nBEGIN:VALARM\r\nACTION:DISPLAY\r\nEND:VALARM\r\n" + + val set = RepeatFromCompletion.applied(RepeatFromCompletion.applied(residue, true), true) + + assertThat(set).isEqualTo("X-AGENDULA-REPEAT-FROM:COMPLETION\r\n$residue") + assertThat(RepeatFromCompletion.applied(null, true)).isEqualTo("X-AGENDULA-REPEAT-FROM:COMPLETION\r\n") + } + + @Test + fun `clearing the marker drops it with its folded lines`() { + val residue = "X-FOO:bar\r\nX-AGENDULA-REPEAT-FROM;X-P=1:COMP\r\n LETION\r\nX-BAZ:qux\r\n" + + assertThat(RepeatFromCompletion.applied(residue, false)).isEqualTo("X-FOO:bar\r\nX-BAZ:qux\r\n") + assertThat(RepeatFromCompletion.applied("X-AGENDULA-REPEAT-FROM:COMPLETION\r\n", false)).isNull() + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/ui/edit/TaskEditViewModelTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/ui/edit/TaskEditViewModelTest.kt index e294f42..98e3430 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/ui/edit/TaskEditViewModelTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/ui/edit/TaskEditViewModelTest.kt @@ -149,6 +149,34 @@ class TaskEditViewModelTest { assertThat(vm.state.value.isDirty).isFalse() } + @Test + fun `repeating from completion reaches the form and asks for the whole series`() { + repository.task = task(null, due).copy( + isRecurring = true, + seriesId = TASK_ID, + occurrenceStart = due, + recurrenceRule = "FREQ=DAILY", + ) + val vm = TaskEditViewModel(repository, settingsPrefs()).apply { bindEdit(TASK_ID) } + assertThat(vm.state.value.repeatFromAvailable).isTrue() + + vm.onRepeatFromCompletionChange(true) + assertThat(vm.state.value.recurrenceChanged).isTrue() + assertThat(vm.state.value.isDirty).isTrue() + + vm.save(scope = RecurringScope.AllOccurrences) + assertThat(repository.saved?.repeatFromCompletion).isTrue() + } + + @Test + fun `a task that does not repeat saves no completion mark`() { + val vm = editing() + vm.onRepeatFromCompletionChange(true) + vm.save() + + assertThat(repository.saved?.repeatFromCompletion).isFalse() + } + private fun task(start: Instant?, due: Instant?) = Task( taskId = TASK_ID, listId = LIST_ID, @@ -180,6 +208,7 @@ class TaskEditViewModelTest { var reminders: List = emptyList() var saved: TaskForm? = null + override fun supportsRepeatFromCompletion() = true override fun taskLists() = flowOf(emptyList()) override fun tasks(filter: TaskFilter): Flow> = flowOf(emptyList()) override fun taskDetail(taskId: Long, occurrenceStart: Instant?) =