Move untimed ends by whole days, keep their zone on the wire, review fixes (#101)

This commit is contained in:
makiolaj committed 2026-11-17 17:00:21 +01:00
1 parent e3a2d974c7
commit d04ef3d612
25 files changed
+354 -147

No files matched your search

@@ -3,8 +3,7 @@ package de.jeanlucmakiola.agendula.data.reminders
import de.jeanlucmakiola.agendula.data.prefs.Settings
import de.jeanlucmakiola.agendula.domain.AllDayReminder
import de.jeanlucmakiola.agendula.domain.Task
import de.jeanlucmakiola.agendula.domain.TaskEnd
import de.jeanlucmakiola.agendula.domain.reminderEnd
import de.jeanlucmakiola.agendula.domain.TaskDates
import de.jeanlucmakiola.agendula.domain.untimedDate
import de.jeanlucmakiola.agendula.domain.TaskReminder
import de.jeanlucmakiola.agendula.domain.calendarDate
@@ -57,19 +56,10 @@ internal object ReminderPlanner {
val reminders = own ?: settings.defaultRemindersFor(task.listId, task.isAllDay)
.filter { (if (it.fromStart) task.start else task.due) != null }
val created = task.created?.toEpochMilliseconds()
val dates = task.dates
reminders.mapNotNull { reminder ->
val anchor = task.valueOf(reminderEnd(reminder.fromStart, task.start != null, task.due != null))!!
val trigger = ringsAt(
task.start,
task.due,
task.isAllDay,
task.untimed,
task.timeZone,
reminder.fromStart,
reminder.minutesBefore,
settings.allDayReminderMinuteOfDay,
zone,
)
val anchor = dates.valueOf(dates.reminderEnd(reminder.fromStart))!!
val trigger = ringsAt(dates, reminder.fromStart, reminder.minutesBefore, settings.allDayReminderMinuteOfDay, zone)
// A default never rings for a moment before the task existed:
// that is a task saved after its default had passed, not a
// reminder missed while the device was off.
@@ -82,10 +72,14 @@ internal object ReminderPlanner {
// day: other clients ring it at midnight, or at their own hour,
// so a dismissal at 07:00 must still silence the 09:00 this
// device would ring it at.
val earliest = if (task.isAllDay && reminder.allDay.minuteOfDay == null) {
triggerAt(anchor, true, reminder.minutesBefore, 0, zone)
} else {
trigger
// Likewise one counting from a date without a time: other clients
// ring it at the midnight or last second it is stored as.
val earliest = when {
task.isAllDay && reminder.allDay.minuteOfDay == null ->
triggerAt(anchor, true, reminder.minutesBefore, 0, zone)
dates.countsFromUntimed(reminder.fromStart) ->
minOf(trigger, triggerAt(anchor, false, reminder.minutesBefore, 0, zone))
else -> trigger
}
val acknowledged = reminder.acknowledgedAt?.let { earliest <= it.toEpochMilliseconds() } == true
if (acknowledged) return@mapNotNull null
@@ -108,25 +102,15 @@ internal object ReminderPlanner {
/**
* When a reminder [leadMinutes] before the end [fromStart] picks (see
* [reminderEnd]) fires. An end without a time beside a timed one counts
* back from the all-day reminder time of its date, read in the task's
* [timeZone], not from the first or last second it is stored as (#101).
* [TaskDates.reminderEnd]) fires. An end without a time beside a timed one
* counts back from the all-day reminder time of its date, read in the
* task's zone, not from the first or last second it is stored as (#101).
*/
fun ringsAt(
start: Instant?,
due: Instant?,
isAllDay: Boolean,
untimed: TaskEnd?,
timeZone: String?,
fromStart: Boolean,
leadMinutes: Int,
allDayMinuteOfDay: Int,
zone: ZoneId,
): Long {
val end = reminderEnd(fromStart, start != null, due != null)
val anchor = checkNotNull(if (end == TaskEnd.START) start else due) { "A reminder needs a date" }
if (isAllDay || untimed != end) return triggerAt(anchor, isAllDay, leadMinutes, allDayMinuteOfDay, zone)
return atMinuteOfDay(anchor.untimedDate(timeZone, zone), allDayMinuteOfDay, zone) - leadMinutes.coerceAtLeast(0) * 60_000L
fun ringsAt(dates: TaskDates, fromStart: Boolean, leadMinutes: Int, allDayMinuteOfDay: Int, zone: ZoneId): Long {
val anchor = checkNotNull(dates.valueOf(dates.reminderEnd(fromStart))) { "A reminder needs a date" }
if (!dates.countsFromUntimed(fromStart)) return triggerAt(anchor, dates.isAllDay, leadMinutes, allDayMinuteOfDay, zone)
val date = anchor.untimedDate(dates.timeZone, zone)
return atMinuteOfDay(date, allDayMinuteOfDay, zone) - leadMinutes.coerceAtLeast(0) * 60_000L
}
/**
@@ -3,6 +3,7 @@ package de.jeanlucmakiola.agendula.data.tasks
import de.jeanlucmakiola.agendula.data.prefs.Settings
import de.jeanlucmakiola.agendula.data.reminders.ReminderPlanner
import de.jeanlucmakiola.agendula.domain.Task
import de.jeanlucmakiola.agendula.domain.TaskDates
import de.jeanlucmakiola.agendula.domain.TaskEnd
import de.jeanlucmakiola.agendula.domain.TaskForm
import de.jeanlucmakiola.agendula.domain.TaskReminder
@@ -37,7 +38,8 @@ internal object StoredReminders {
val wanted = form.reminders.map { it.lead }.distinct()
if (form.remindersChosen) return wanted
return withDefaults(
form, current?.start, current?.due, current?.isAllDay ?: form.isAllDay, settings, now, zone, current?.untimed,
form, current?.start, current?.due, current?.isAllDay ?: form.isAllDay, settings, now, zone,
current?.untimed, current?.timeZone,
)
}
@@ -51,9 +53,10 @@ internal object StoredReminders {
now: Long,
zone: ZoneId,
wasUntimed: TaskEnd? = null,
wasTimeZone: String? = null,
): List<TaskReminder> {
val wanted = form.reminders.map { it.lead }.distinct()
val fresh = freshAnchors(form, start, due, wasAllDay, settings, now, zone, wasUntimed)
val fresh = freshAnchors(form, start, due, wasAllDay, settings, now, zone, wasUntimed, wasTimeZone)
if (fresh.isEmpty()) return wanted
if (anchorsOf(start, due).isEmpty() || wanted.isEmpty()) return wanted.ifEmpty { defaultsFor(form, settings, now, zone) }
val named = wanted.map { it.fromStart }.toSet()
@@ -73,10 +76,12 @@ internal object StoredReminders {
now: Long,
zone: ZoneId,
wasUntimed: TaskEnd? = null,
wasTimeZone: String? = null,
): Set<Boolean> {
val wanted = form.reminders.map { it.lead }.distinct()
val gained = anchorsOf(form.start, form.due) - anchorsOf(start, due)
return gained + revived(form, start, due, wasAllDay, wasUntimed, wanted, settings, now, zone)
val was = TaskDates(start, due, wasAllDay, wasUntimed, wasTimeZone)
return gained + revived(form, was, wanted, settings, now, zone)
}
/**
@@ -116,10 +121,7 @@ internal object StoredReminders {
*/
private fun revived(
form: TaskForm,
start: Instant?,
due: Instant?,
wasAllDay: Boolean,
wasUntimed: TaskEnd?,
was: TaskDates,
wanted: List<TaskReminder>,
settings: Settings,
now: Long,
@@ -127,22 +129,23 @@ internal object StoredReminders {
): Set<Boolean> {
if (form.rrule != null || wanted.isEmpty()) return emptySet()
val named = wanted.map { it.fromStart }.toSet()
val defaults = settings.defaultRemindersFor(form.listId, wasAllDay)
fun revived(fromStart: Boolean, was: Instant?, isNow: Instant?): Boolean {
if (was == null || isNow == null || fromStart in named) return false
val moved = if (wasAllDay == form.isAllDay) {
isNow != was
val defaults = settings.defaultRemindersFor(form.listId, was.isAllDay)
fun revived(fromStart: Boolean, before: Instant?, isNow: Instant?): Boolean {
if (before == null || isNow == null || fromStart in named) return false
val moved = if (was.isAllDay == form.isAllDay) {
isNow != before
} else {
isNow.calendarDate(form.isAllDay, zone) != was.calendarDate(wasAllDay, zone)
isNow.calendarDate(form.isAllDay, zone) != before.calendarDate(was.isAllDay, zone)
}
val leads = defaults.filter { it.fromStart == fromStart }
return moved && leads.isNotEmpty() && leads.all {
ReminderPlanner.ringsAt(
start, due, wasAllDay, wasUntimed, null, fromStart, it.minutesBefore, settings.allDayReminderMinuteOfDay, zone,
) < now
ReminderPlanner.ringsAt(was, fromStart, it.minutesBefore, settings.allDayReminderMinuteOfDay, zone) < now
}
}
return setOfNotNull(true.takeIf { revived(true, start, form.start) }, false.takeIf { revived(false, due, form.due) })
return setOfNotNull(
true.takeIf { revived(true, was.start, form.start) },
false.takeIf { revived(false, was.due, form.due) },
)
}
/** The dates a reminder can count from, as [TaskReminder.fromStart]. */
@@ -157,11 +160,7 @@ internal object StoredReminders {
settings.defaultRemindersFor(form.listId, form.isAllDay).filter { reminder ->
if ((if (reminder.fromStart) form.start else form.due) == null) return@filter false
form.rrule != null || ReminderPlanner.ringsAt(
form.start,
form.due,
form.isAllDay,
form.untimed,
null,
TaskDates(form.start, form.due, form.isAllDay, form.untimed),
reminder.fromStart,
reminder.minutesBefore,
settings.allDayReminderMinuteOfDay,
@@ -10,6 +10,7 @@ import de.jeanlucmakiola.agendula.domain.Task
import de.jeanlucmakiola.agendula.domain.TaskDetail
import de.jeanlucmakiola.agendula.domain.TaskFilter
import de.jeanlucmakiola.agendula.domain.TaskFiltering
import de.jeanlucmakiola.agendula.domain.TaskEnd
import de.jeanlucmakiola.agendula.domain.TaskForm
import de.jeanlucmakiola.agendula.domain.TaskList
import de.jeanlucmakiola.agendula.domain.TaskSorting
@@ -140,8 +141,8 @@ class TasksRepositoryImpl @Inject constructor(
title = task.title,
listId = task.listId,
description = task.description,
start = task.start,
due = task.due,
start = task.formValueOf(TaskEnd.START),
due = task.formValueOf(TaskEnd.DUE),
isAllDay = task.isAllDay,
untimed = task.untimed,
priority = task.priority,
@@ -4,6 +4,8 @@ import de.jeanlucmakiola.agendula.data.tasks.room.TaskAlarmEntity
import de.jeanlucmakiola.agendula.data.tasks.room.TaskEntity
import de.jeanlucmakiola.agendula.domain.PRIORITY_NONE
import de.jeanlucmakiola.agendula.domain.TaskEnd
import de.jeanlucmakiola.agendula.domain.untimedInstantOf
import de.jeanlucmakiola.agendula.domain.zoneOr
import de.jeanlucmakiola.agendula.domain.TaskStatus
import de.jeanlucmakiola.agendula.domain.ical.ICalComponent
import de.jeanlucmakiola.agendula.domain.ical.ICalParam
@@ -12,6 +14,7 @@ import de.jeanlucmakiola.agendula.domain.ical.ICalProperty
import de.jeanlucmakiola.agendula.domain.ical.ICalSerializer
import de.jeanlucmakiola.agendula.domain.ical.ICalValues
import de.jeanlucmakiola.agendula.domain.normalizeTags
import java.time.LocalDateTime
import java.time.ZoneId
import kotlin.time.Clock
import kotlin.time.Instant
@@ -149,8 +152,9 @@ object VTodoMapper {
// write would emit the caller's minted UID alongside the empty one.
val uid = take(uidProperty, uidProperty?.value?.trim()).orEmpty()
val dtstart = readTime(vtodo, "DTSTART")
val due = readTime(vtodo, "DUE")
val zoneHint = vtodo.property("DTSTART")?.param("TZID") ?: vtodo.property("DUE")?.param("TZID")
val dtstart = readTime(vtodo, "DTSTART", TaskEnd.START, zoneHint)
val due = readTime(vtodo, "DUE", TaskEnd.DUE, zoneHint)
// A task's primary stamp is DUE; DTSTART only decides when there is no
// DUE. Deriving one all-day flag from "either is a DATE" turns a
@@ -158,11 +162,11 @@ object VTodoMapper {
val allDay = if (due.present) due.isDate else dtstart.isDate
val timezone = dtstart.tzid ?: due.tzid
// One end without a time beside a timed one (#101), marked on the
// date-time that stands in for its date.
// date-time that stands in for its date, in the zone the task is read in.
val untimed = when {
allDay || dtstart.noTime == due.noTime -> null
dtstart.noTime -> TaskEnd.START
else -> TaskEnd.DUE
dtstart.noTime -> TaskEnd.START.takeIf { dtstart.tzid == timezone }
else -> TaskEnd.DUE.takeIf { due.tzid == timezone }
}
// Claim a stamp only when the single is_all_day flag and the single
@@ -552,18 +556,32 @@ object VTodoMapper {
val isUtcDateTime get() = present && representable && !isDate && tzid == null
}
private fun readTime(vtodo: ICalComponent, name: String): TimeRead {
/**
* [name] as read. With [end] set, a marked value on its day boundary is an
* untimed end; a floating one (an export's) is placed in [zoneHint], the
* zone the task is read in, or this device's.
*/
private fun readTime(vtodo: ICalComponent, name: String, end: TaskEnd? = null, zoneHint: String? = null): TimeRead {
val property = vtodo.property(name) ?: return TimeRead(null, null, null, false, false)
val marked = end != null && ICalValues.isMarkedNoTime(property)
return when (val value = ICalValues.parseTime(property)) {
is ICalValues.TimeValue.Date -> TimeRead(property, value.instant, null, true, true)
is ICalValues.TimeValue.Timed -> TimeRead(
property, value.instant, value.tzid, false, true,
noTime = ICalValues.isMarkedNoTime(property) && onDayBoundary(name, property.value, value.tzid),
noTime = marked && value.tzid != null && onDayBoundary(end!!, value.instant, zoneOr(value.tzid)),
)
// Readable but not reproducible: the column gets the best-effort
// instant, the property round-trips from the residue verbatim.
is ICalValues.TimeValue.Unrepresentable ->
TimeRead(property, value.instant, null, false, false)
is ICalValues.TimeValue.Unrepresentable -> {
val wall = ICalValues.floatingWall(property)?.takeIf { marked }
val zone = zoneOr(zoneHint)
val instant = wall?.let { untimedInstantOf(end!!, it.toLocalDate(), zone) }
if (instant != null && wall == instant.wallIn(zone)) {
TimeRead(property, instant, zoneHint?.takeIf { runCatching { ZoneId.of(it) }.isSuccess }, false, true, noTime = true)
} else {
// Readable but not reproducible: the column gets the best-effort
// instant, the property round-trips from the residue verbatim.
TimeRead(property, value.instant, null, false, false)
}
}
}
}
@@ -579,23 +597,28 @@ object VTodoMapper {
// separately produces TZID on a `…Z` value, which §3.3.5 forbids and
// sabre answers 415 for.
val tzid = entity.timezone?.takeIf { runCatching { ZoneId.of(it) }.isSuccess }
val params = buildList {
if (entity.untimed?.propertyName == name) add(ICalParam(ICalValues.NO_TIME_PARAM, "TRUE"))
if (tzid != null) add(ICalParam("TZID", tzid))
if (entity.untimed?.propertyName == name) {
// A UTC value says nothing about its day: without a zone, the wall clock alone.
val mark = ICalParam(ICalValues.NO_TIME_PARAM, "TRUE")
return if (tzid == null) {
ICalProperty(name, listOf(mark), ICalValues.formatFloating(instant.wallIn(ZoneId.systemDefault())))
} else {
ICalProperty(name, listOf(mark, ICalParam("TZID", tzid)), ICalValues.formatDateTime(instant, tzid))
}
}
val params = if (tzid == null) emptyList() else listOf(ICalParam("TZID", tzid))
return ICalProperty(name, params, ICalValues.formatDateTime(instant, tzid))
}
/**
* Whether a zoned [value] still sits where an untimed [name] is written: a
* client that moved it but kept the mark has given it a time. A UTC value
* (an export) is taken at its word.
* Whether [instant] still sits where an untimed [end] is written in [zone]:
* a client that moved it but kept the mark has given it a time.
*/
private fun onDayBoundary(name: String, value: String, tzid: String?): Boolean {
if (tzid == null) return true
val time = value.trim().substringAfter('T', "")
return time == if (name.equals("DTSTART", ignoreCase = true)) "000000" else "235959"
}
private fun onDayBoundary(end: TaskEnd, instant: Instant, zone: ZoneId): Boolean =
instant == untimedInstantOf(end, instant.wallIn(zone).toLocalDate(), zone)
private fun Instant.wallIn(zone: ZoneId): LocalDateTime =
LocalDateTime.ofInstant(java.time.Instant.ofEpochMilli(toEpochMilliseconds()), zone)
private val TaskEnd.propertyName: String
get() = when (this) {
@@ -157,10 +157,10 @@ object ProviderTaskWriter {
due = due,
duration = duration,
isAllDay = allDay,
// A client sees and writes this end as a time; one it moves, or a
// switch to all-day, is its own value from then on.
// A client sees and writes this end as a time; one it moves, a new
// zone, or a switch to all-day, is its own value from then on.
untimed = current.untimed?.takeUnless { end ->
allDay || when (end) {
allDay || timezone != current.timezone || when (end) {
TaskEnd.START -> dtstart != current.dtstart
TaskEnd.DUE -> due != current.due
}
@@ -96,6 +96,7 @@ object RoomTaskMapper {
rdate = task.rdate,
parentId = task.parentId?.takeIf { it > 0 },
untimed = task.untimed,
timeZone = task.timezone,
)
}
@@ -2,7 +2,7 @@ package de.jeanlucmakiola.agendula.data.tasks.room
import de.jeanlucmakiola.agendula.domain.TaskEnd
import de.jeanlucmakiola.agendula.domain.untimedDate
import de.jeanlucmakiola.agendula.domain.untimedInstantOf
import de.jeanlucmakiola.agendula.domain.untimedMoved
import de.jeanlucmakiola.agendula.domain.zoneOr
import java.time.temporal.ChronoUnit
import android.util.Log
@@ -73,7 +73,7 @@ internal fun occurrenceTimes(master: TaskEntity, anchor: Instant): Pair<Instant?
val due = master.due ?: return anchor to null
if (master.untimed == TaskEnd.DUE && !master.isAllDay) {
val days = ChronoUnit.DAYS.between(master.dtstart.untimedDate(master.timezone), due.untimedDate(master.timezone))
return anchor to untimedInstantOf(TaskEnd.DUE, anchor.untimedDate(master.timezone).plusDays(days), zoneOr(master.timezone))
return anchor to untimedMoved(TaskEnd.DUE, anchor, days, master.timezone, zoneOr(master.timezone))
}
return anchor to anchor + (due - master.dtstart)
}
@@ -1,10 +1,16 @@
package de.jeanlucmakiola.agendula.data.tasks.room
import de.jeanlucmakiola.agendula.domain.TaskEnd
import de.jeanlucmakiola.agendula.domain.TaskForm
import de.jeanlucmakiola.agendula.domain.calendarDate
import de.jeanlucmakiola.agendula.domain.untimedDate
import de.jeanlucmakiola.agendula.domain.untimedMoved
import de.jeanlucmakiola.agendula.domain.zoneOr
import de.jeanlucmakiola.agendula.domain.TaskStatus
import de.jeanlucmakiola.agendula.domain.ical.ICalValues
import de.jeanlucmakiola.agendula.domain.normalizeTags
import de.jeanlucmakiola.agendula.domain.toICal
import java.time.temporal.ChronoUnit
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.seconds
import kotlin.time.Instant
@@ -96,11 +102,11 @@ object TaskFormWriter {
tzId: String,
): TaskEntity {
val edited = withRule(apply(master, form, now, tzId), form.rrule)
val dtstart = shifted(master.dtstart, occurrenceStart, form.start, form.isAllDay)
val dtstart = shifted(TaskEnd.START, master, occurrenceStart, form, tzId)
val delta = if (dtstart != null && master.dtstart != null) dtstart - master.dtstart else null
return edited.copy(
dtstart = dtstart,
due = shifted(master.due, occurrenceDue, form.due, form.isAllDay),
due = shifted(TaskEnd.DUE, master, occurrenceDue, form, tzId),
// The occurrence's completion is its own, not the series'.
status = master.status,
percentComplete = master.percentComplete,
@@ -159,10 +165,19 @@ object TaskFormWriter {
private val VALUE_DATE = java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd")
private val VALUE_DATE_TIME = java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss")
private fun shifted(anchor: Instant?, was: Instant?, now: Instant?, allDay: Boolean): Instant? = when {
now == null -> null
anchor == null || was == null -> now.forAllDay(allDay)
else -> (anchor + (now - was)).forAllDay(allDay)
/**
* [master]'s [end] moved as far as the occurrence's moved from [was] to the
* form's value. An end without a time moves by whole days, so a clock
* change in between cannot push it off its date.
*/
private fun shifted(end: TaskEnd, master: TaskEntity, was: Instant?, form: TaskForm, tzId: String): Instant? {
val anchor = if (end == TaskEnd.START) master.dtstart else master.due
val now = (if (end == TaskEnd.START) form.start else form.due) ?: return null
if (anchor == null || was == null) return now.forAllDay(form.isAllDay)
if (form.isAllDay || form.untimed != end) return (anchor + (now - was)).forAllDay(form.isAllDay)
val zone = zoneOr(tzId)
val days = ChronoUnit.DAYS.between(was.untimedDate(master.timezone), now.calendarDate(allDay = false, zone = zone))
return untimedMoved(end, anchor, days, master.timezone, zone)
}
/**
@@ -59,28 +59,63 @@ enum class TaskEnd {
val other: TaskEnd get() = if (this == START) DUE else START
}
/** Whether [end] of a task carries a time of day. */
fun hasTimeAt(end: TaskEnd, isAllDay: Boolean, untimed: TaskEnd?): Boolean = !isAllDay && untimed != end
/**
* A task's two ends and how to read them: all-day, one end [untimed], or both
* timed. [timeZone] is the zone an untimed end was written in; null reads it in
* the device's.
*/
data class TaskDates(
val start: Instant?,
val due: Instant?,
val isAllDay: Boolean,
val untimed: TaskEnd? = null,
val timeZone: String? = null,
) {
fun valueOf(end: TaskEnd): Instant? = if (end == TaskEnd.START) start else due
/** The end a reminder counts from: its own when the task has it, else the other. */
fun reminderEnd(fromStart: Boolean, hasStart: Boolean, hasDue: Boolean): TaskEnd = when {
fromStart -> if (hasStart) TaskEnd.START else TaskEnd.DUE
else -> if (hasDue) TaskEnd.DUE else TaskEnd.START
/** Whether [end] carries a time of day. */
fun hasTime(end: TaskEnd): Boolean = !isAllDay && untimed != end
/** The end a reminder counts from: its own when the task has it, else the other. */
fun reminderEnd(fromStart: Boolean): TaskEnd = when {
fromStart -> if (start != null) TaskEnd.START else TaskEnd.DUE
else -> if (due != null) TaskEnd.DUE else TaskEnd.START
}
/** Whether a reminder [fromStart] counts from an end without a time beside a timed one. */
fun countsFromUntimed(fromStart: Boolean): Boolean = !isAllDay && untimed == reminderEnd(fromStart)
}
/** [timeZone] when it names a zone this device knows, else [fallback]. */
fun zoneOr(timeZone: String?, fallback: ZoneId = ZoneId.systemDefault()): ZoneId =
timeZone?.let { runCatching { ZoneId.of(it) }.getOrNull() } ?: fallback
/** The stored instant for [date] on an untimed [end]: the first or the last second of the day. */
/**
* The stored instant for [date] on an untimed [end]: the first or the last
* second of the day. A day starting in a clock change starts at its first
* valid moment, not at a 00:00 that does not exist.
*/
fun untimedInstantOf(end: TaskEnd, date: java.time.LocalDate, zone: ZoneId = ZoneId.systemDefault()): Instant {
val local = when (end) {
TaskEnd.START -> date.atStartOfDay()
TaskEnd.DUE -> date.atTime(23, 59, 59)
val at = when (end) {
TaskEnd.START -> date.atStartOfDay(zone)
TaskEnd.DUE -> date.atTime(23, 59, 59).atZone(zone)
}
return Instant.fromEpochMilliseconds(local.atZone(zone).toInstant().toEpochMilli())
return Instant.fromEpochMilliseconds(at.toInstant().toEpochMilli())
}
/**
* The untimed [end] stored at [value] in [fromZone], moved by [days] whole
* days and written in [toZone]: whole days, so a clock change on the way
* cannot push it off its date.
*/
fun untimedMoved(
end: TaskEnd,
value: Instant,
days: Long,
fromZone: String?,
toZone: ZoneId = ZoneId.systemDefault(),
): Instant = untimedInstantOf(end, value.untimedDate(fromZone).plusDays(days), toZone)
/** The date an untimed end stored at this instant stands for, read in the task's [timeZone]. */
fun Instant.untimedDate(timeZone: String?, fallback: ZoneId = ZoneId.systemDefault()): java.time.LocalDate =
calendarDate(allDay = false, zone = zoneOr(timeZone, fallback))
@@ -114,10 +114,18 @@ data class Task(
/** The end that has a date but no time while the other has one; see [TaskEnd]. */
val untimed: TaskEnd? = null,
) {
val dates: TaskDates get() = TaskDates(start, due, isAllDay, untimed, timeZone)
fun valueOf(end: TaskEnd): Instant? = if (end == TaskEnd.START) start else due
/** Whether [end] carries a time of day. */
fun hasTime(end: TaskEnd): Boolean = hasTimeAt(end, isAllDay, untimed)
fun hasTime(end: TaskEnd): Boolean = dates.hasTime(end)
/** [end] as an editor holds it: an untimed end re-written in this device's zone, on its own date. */
fun formValueOf(end: TaskEnd): Instant? {
val value = valueOf(end) ?: return null
return if (isAllDay || untimed != end) value else untimedMoved(end, value, 0, timeZone)
}
/** The calendar date of [end]: all-day in UTC, untimed in the task's zone, timed in [zone]. */
fun dateOf(end: TaskEnd, zone: ZoneId = ZoneId.systemDefault()): LocalDate? = valueOf(end)?.let {
@@ -2,11 +2,14 @@ package de.jeanlucmakiola.agendula.domain
/** Default task ordering, extracted so it's unit-testable without the repository. */
object TaskSorting {
/** Open before completed; within each: due-soonest (none last), priority, title. */
/**
* Open before completed; within each: due-soonest (none last), priority,
* title. A due without a time, all-day or not, counts from the start of its day.
*/
val DEFAULT: Comparator<Task> = compareBy(
{ it.isCompleted },
{ it.due == null },
{ it.due?.toEpochMilliseconds() ?: Long.MAX_VALUE },
{ it.dueSortKey },
{ -it.priority.ordinal },
{ it.title.lowercase() },
)
@@ -20,7 +23,7 @@ fun TaskSortOrder.comparator(): Comparator<Task> = when (this) {
TaskSortOrder.PRIORITY -> compareBy<Task>(
{ it.isCompleted },
{ -it.priority.ordinal },
{ it.due?.toEpochMilliseconds() ?: Long.MAX_VALUE },
{ it.dueSortKey },
{ it.title.lowercase() },
)
TaskSortOrder.TITLE -> compareBy({ it.isCompleted }, { it.title.lowercase() })
@@ -30,3 +33,5 @@ fun TaskSortOrder.comparator(): Comparator<Task> = when (this) {
{ it.title.lowercase() },
)
}
private val Task.dueSortKey: Long get() = wallClock(TaskEnd.DUE)?.toEpochMilliseconds() ?: Long.MAX_VALUE
@@ -45,6 +45,8 @@ data class ExportTask(
val tags: List<String> = emptyList(),
/** See [de.jeanlucmakiola.agendula.domain.TaskEnd]. */
val untimed: de.jeanlucmakiola.agendula.domain.TaskEnd? = null,
/** The zone [untimed]'s date is read in; null for the device's. */
val timeZone: String? = null,
)
/** A task list and everything in it, ready to become one `.ics` document. */
@@ -7,6 +7,7 @@ import de.jeanlucmakiola.agendula.domain.calendarDate
import de.jeanlucmakiola.agendula.domain.ical.ICalSerializer
import de.jeanlucmakiola.agendula.domain.ical.ICalValues
import de.jeanlucmakiola.agendula.domain.toICal
import de.jeanlucmakiola.agendula.domain.untimedDate
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import kotlin.time.Instant
@@ -91,8 +92,8 @@ object ICalendarWriter {
task.url?.takeIf { it.isNotBlank() }?.let { rawProperty("URL", it) }
task.tags.takeIf { it.isNotEmpty() }?.let { rawProperty("CATEGORIES", ICalValues.formatTextList(it)) }
task.start?.let { dateProperty("DTSTART", it, task.isAllDay, task.untimed == TaskEnd.START) }
task.due?.let { dateProperty("DUE", it, task.isAllDay, task.untimed == TaskEnd.DUE) }
task.start?.let { dateProperty("DTSTART", it, task, TaskEnd.START) }
task.due?.let { dateProperty("DUE", it, task, TaskEnd.DUE) }
task.created?.let { rawProperty("CREATED", formatUtc(it)) }
task.lastModified?.let { rawProperty("LAST-MODIFIED", formatUtc(it)) }
// COMPLETED is defined as UTC date-time even for an all-day task.
@@ -117,13 +118,17 @@ object ICalendarWriter {
line("END:VTODO")
}
private fun StringBuilder.dateProperty(name: String, instant: Instant, allDay: Boolean, untimed: Boolean) {
if (allDay) {
private fun StringBuilder.dateProperty(name: String, instant: Instant, task: ExportTask, end: TaskEnd) {
if (task.isAllDay) {
// Read in UTC, matching the storage convention (see AllDayTime): an
// all-day value *is* UTC midnight of the intended calendar date.
rawProperty("$name;VALUE=DATE", instant.calendarDate(allDay = true).format(DATE))
} else if (untimed) {
rawProperty("$name;${ICalValues.NO_TIME_PARAM}=TRUE", formatUtc(instant))
} else if (task.untimed == end) {
// A date without a time is the wall clock alone: UTC would move it to
// another day for whoever imports it elsewhere (#101).
val date = instant.untimedDate(task.timeZone)
val wall = if (end == TaskEnd.START) date.atStartOfDay() else date.atTime(23, 59, 59)
rawProperty("$name;${ICalValues.NO_TIME_PARAM}=TRUE", ICalValues.formatFloating(wall))
} else {
rawProperty(name, formatUtc(instant))
}
@@ -17,7 +17,9 @@ object ICalValues {
/**
* Marks the date-time `DTSTART` or `DUE` that stands for a date without a
* time (see [de.jeanlucmakiola.agendula.domain.TaskEnd]). A parameter rather
* than a property, so a client that rewrites the value drops the mark with it.
* than a property, so a client that rewrites the value drops the mark with
* it. Only a zoned or floating value on its day boundary is read as one: a
* UTC one says nothing about which day it was meant for.
*/
const val NO_TIME_PARAM = "X-AGENDULA-NO-TIME"
@@ -161,6 +163,17 @@ object ICalValues {
.atZone(ZoneOffset.UTC)
.format(DATE)
/** `20260904T000000` — a floating date-time, the wall clock alone. */
fun formatFloating(local: LocalDateTime): String = local.format(DATE_TIME)
/** The wall clock of a floating date-time (no `Z`, no `TZID`), or null for any other value. */
fun floatingWall(property: ICalProperty): LocalDateTime? {
val raw = property.value.trim()
if (property.param("TZID") != null || raw.endsWith("Z") || !raw.contains('T')) return null
if (property.param("VALUE")?.equals("DATE", ignoreCase = true) == true) return null
return runCatching { LocalDateTime.parse(raw, DATE_TIME) }.getOrNull()
}
/** `20260904T080000Z`, or the local form when [tzid] names a zone we know. */
fun formatDateTime(instant: Instant, tzid: String?): String {
val moment = java.time.Instant.ofEpochMilli(instant.toEpochMilliseconds())
@@ -102,7 +102,6 @@ import de.jeanlucmakiola.agendula.R
import de.jeanlucmakiola.agendula.domain.readableDescription
import de.jeanlucmakiola.agendula.domain.Task
import de.jeanlucmakiola.agendula.domain.TaskEnd
import de.jeanlucmakiola.agendula.domain.reminderEnd
import de.jeanlucmakiola.agendula.domain.TaskDetail
import de.jeanlucmakiola.floret.components.revealOnFocus
import de.jeanlucmakiola.floret.components.GroupedSurface
@@ -365,8 +364,7 @@ private fun DetailBody(
task.isAllDay,
allDayMinuteOfDay,
anchored = task.start != null && task.due != null,
untimedAnchor = !task.isAllDay &&
task.untimed == reminderEnd(reminder.fromStart, task.start != null, task.due != null),
untimedAnchor = task.dates.countsFromUntimed(reminder.fromStart),
),
style = MaterialTheme.typography.titleMedium,
)
@@ -120,7 +120,6 @@ import de.jeanlucmakiola.floret.time.DayWindow
import de.jeanlucmakiola.agendula.domain.Priority
import de.jeanlucmakiola.agendula.domain.Task
import de.jeanlucmakiola.agendula.domain.TaskEnd
import de.jeanlucmakiola.agendula.domain.reminderEnd
import de.jeanlucmakiola.agendula.domain.TaskFormError
import de.jeanlucmakiola.agendula.domain.TaskFormField
import de.jeanlucmakiola.agendula.domain.TaskList
@@ -564,8 +563,7 @@ private fun EditContent(
state.isAllDay,
state.allDayMinuteOfDay,
anchored = bothDates,
untimedAnchor = !state.isAllDay &&
state.untimed == reminderEnd(reminder.fromStart, state.start != null, state.due != null),
untimedAnchor = state.dates.countsFromUntimed(reminder.fromStart),
),
onRemove = { viewModel.removeReminder(reminder) },
)
@@ -1084,7 +1082,7 @@ private fun ParentPickerSheet(
GroupedRow(
title = task.title.ifBlank { stringResource(R.string.task_untitled) },
position = positionOf(index, section.tasks.size),
summary = task.due?.formatDate(task.isAllDay),
summary = task.shownValue(TaskEnd.DUE)?.formatDate(!task.hasTime(TaskEnd.DUE)),
selected = selected,
trailing = if (selected) ({ SelectedCheck() }) else null,
minHeight = 56.dp,
@@ -18,7 +18,7 @@ import de.jeanlucmakiola.agendula.domain.TaskFormField
import de.jeanlucmakiola.agendula.domain.allDayInstantOf
import de.jeanlucmakiola.agendula.domain.TaskEnd
import de.jeanlucmakiola.agendula.ui.common.toLocalTime
import de.jeanlucmakiola.agendula.domain.hasTimeAt
import de.jeanlucmakiola.agendula.domain.TaskDates
import de.jeanlucmakiola.agendula.domain.calendarDate
import de.jeanlucmakiola.agendula.domain.untimedInstantOf
import de.jeanlucmakiola.agendula.ui.common.localToInstant
@@ -116,10 +116,12 @@ data class TaskEditUiState(
val recurrenceChanged: Boolean get() = rrule != originalRule
fun valueOf(end: TaskEnd): Instant? = if (end == TaskEnd.START) start else due
val dates: TaskDates get() = TaskDates(start, due, isAllDay, untimed)
fun valueOf(end: TaskEnd): Instant? = dates.valueOf(end)
/** Whether [end] carries a time of day, as opposed to a date alone. */
fun hasTime(end: TaskEnd): Boolean = hasTimeAt(end, isAllDay, untimed)
fun hasTime(end: TaskEnd): Boolean = dates.hasTime(end)
/**
* [end] as a local date-time, for the picker to keep the other end on its
@@ -273,8 +275,8 @@ class TaskEditViewModel @Inject constructor(
baselineLastModified = task.lastModified
loadedReminders = repository.remindersFor(taskId).map { it.lead }.distinct()
storedReminders = loadedReminders.toSet()
loadedStart = task.start
loadedDue = task.due
loadedStart = task.formValueOf(TaskEnd.START)
loadedDue = task.formValueOf(TaskEnd.DUE)
loadedAllDay = task.isAllDay
loadedUntimed = task.untimed
loadedKindAllDay = task.isAllDay
@@ -286,11 +288,8 @@ class TaskEditViewModel @Inject constructor(
description = task.description?.readableDescription().orEmpty(),
descriptionHtml = task.description?.takeIf { it.looksLikeHtml() },
listId = task.listId,
// An untimed end keeps its date across zones; the form holds it in this one.
start = task.start.takeIf { task.hasTime(TaskEnd.START) || task.isAllDay }
?: task.dateOf(TaskEnd.START)?.let { untimedInstantOf(TaskEnd.START, it) },
due = task.due.takeIf { task.hasTime(TaskEnd.DUE) || task.isAllDay }
?: task.dateOf(TaskEnd.DUE)?.let { untimedInstantOf(TaskEnd.DUE, it) },
start = loadedStart,
due = loadedDue,
isAllDay = task.isAllDay,
untimed = task.untimed,
untimedEnds = repository.supportsUntimedEnds(),
@@ -259,17 +259,21 @@ internal fun widgetRows(
}
/** This task as a [WidgetTaskRow], resolving its due bucket and overdue state against [today]. */
internal fun Task.toWidgetRow(now: Instant, today: LocalDate, zone: ZoneId): WidgetTaskRow = WidgetTaskRow(
taskId = taskId,
listId = listId,
occurrenceStart = occurrenceStart,
title = title,
due = shownValue(TaskEnd.DUE),
isAllDay = !hasTime(TaskEnd.DUE),
dueKind = shownValue(TaskEnd.DUE)?.let { dueKind(it, !hasTime(TaskEnd.DUE), today, zone) },
isOverdue = shownValue(TaskEnd.DUE)?.let { isOverdue(it, !hasTime(TaskEnd.DUE), now, today, zone) } ?: false,
color = effectiveColor,
)
internal fun Task.toWidgetRow(now: Instant, today: LocalDate, zone: ZoneId): WidgetTaskRow {
val shown = shownValue(TaskEnd.DUE)
val dateOnly = !hasTime(TaskEnd.DUE)
return WidgetTaskRow(
taskId = taskId,
listId = listId,
occurrenceStart = occurrenceStart,
title = title,
due = shown,
isAllDay = dateOnly,
dueKind = shown?.let { dueKind(it, dateOnly, today, zone) },
isOverdue = shown?.let { isOverdue(it, dateOnly, now, today, zone) } ?: false,
color = effectiveColor,
)
}
/**
* Live widget data for [filter]. Re-emits on every store change, since the
@@ -60,6 +60,22 @@ class ReminderPlannerTest {
)
}
@Test
fun `a dismissal on a client that rang the untimed end at its stored moment silences it here`() {
val start = untimedInstantOf(TaskEnd.START, date, berlin)
val due = Instant.fromEpochMilliseconds(millis(date.atTime(17, 0), berlin))
val task = testTask(id = 1, start = start, due = due).copy(untimed = TaskEnd.START)
val dismissed = Instant.fromEpochMilliseconds(millis(date.atTime(7, 30), berlin))
val plan = ReminderPlanner.plan(
tasks = listOf(task),
perTask = mapOf(1L to listOf(TaskReminder(0, fromStart = true, acknowledgedAt = dismissed))),
settings = Settings(allDayReminderMinuteOfDay = 9 * 60),
now = dismissed.toEpochMilliseconds(),
zone = berlin,
)
assertThat(plan).isEmpty()
}
@Test
fun `a default from before the task existed does not ring`() {
val created = Instant.fromEpochMilliseconds(millis(date.atTime(14, 0), berlin))
@@ -519,6 +519,46 @@ class VTodoMapperTest {
assertThat(VTodoMapper.write(mapped.entity).property("DUE")?.param(ICalValues.NO_TIME_PARAM)).isNull()
}
@Test
fun `a mark on a UTC value says nothing about its day and is not read`() {
val read = VTodoMapper.read(
vtodo("DTSTART;TZID=Europe/Berlin:20260901T090000", "DUE;X-AGENDULA-NO-TIME=TRUE:20260901T215959Z"),
).entity
assertThat(read.untimed).isNull()
}
@Test
fun `an untimed due in another zone than the task's is not read as one`() {
val read = VTodoMapper.read(
vtodo(
"DTSTART;TZID=Europe/Berlin:20260901T090000",
"DUE;X-AGENDULA-NO-TIME=TRUE;TZID=America/New_York:20260901T235959",
),
).entity
assertThat(read.untimed).isNull()
}
@Test
fun `a floating untimed end is placed in the task's zone, and written back zoned`() {
val mapped = VTodoMapper.read(
vtodo("DTSTART;X-AGENDULA-NO-TIME=TRUE:20260901T000000", "DUE;TZID=Europe/Berlin:20260901T170000"),
)
assertThat(mapped.entity.untimed).isEqualTo(TaskEnd.START)
assertThat(mapped.entity.dtstart).isEqualTo(Instant.parse("2026-08-31T22:00:00Z"))
assertThat(mapped.entity.unknownProperties).isNull()
val start = VTodoMapper.write(mapped.entity).property("DTSTART")!!
assertThat(start.value).isEqualTo("20260901T000000")
assertThat(start.param("TZID")).isEqualTo("Europe/Berlin")
}
@Test
fun `without a zone the untimed end is written floating, never as UTC`() {
val start = VTodoMapper.write(mixed.copy(timezone = null)).property("DTSTART")!!
assertThat(start.value).doesNotContain("Z")
assertThat(start.param("TZID")).isNull()
assertThat(start.param(ICalValues.NO_TIME_PARAM)).isEqualTo("TRUE")
}
@Test
fun `a mark on a DATE is ignored, the task is all-day`() {
val read = VTodoMapper.read(
@@ -416,6 +416,7 @@ class ProviderTaskWriterTest {
assertThat(patch(mixed, Tasks.DUE to millis(due + 1.hours)).untimed).isEqualTo(TaskEnd.START)
assertThat(patch(mixed, Tasks.DTSTART to millis(start + 9.hours)).untimed).isNull()
assertThat(patch(mixed, Tasks.IS_ALLDAY to 1).untimed).isNull()
assertThat(patch(mixed, Tasks.TZ to "America/New_York").untimed).isNull()
}
// --- no-op writes -------------------------------------------------------------
@@ -1,7 +1,10 @@
package de.jeanlucmakiola.agendula.data.tasks.room
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.agendula.domain.TaskEnd
import de.jeanlucmakiola.agendula.domain.TaskForm
import de.jeanlucmakiola.agendula.domain.untimedInstantOf
import java.time.LocalDate
import org.junit.jupiter.api.Test
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.hours
@@ -118,4 +121,28 @@ class TaskFormWriterSeriesTest {
assertThat(edited.status).isEqualTo(master.status)
assertThat(edited.completedAt).isNull()
}
@Test
fun `an untimed start moved for the whole series across a clock change stays on its day (#101)`() {
val berlin = java.time.ZoneId.of("Europe/Berlin")
val untimed = master.copy(
dtstart = untimedInstantOf(TaskEnd.START, LocalDate.of(2026, 1, 5), berlin),
due = Instant.parse("2026-01-05T16:00:00Z"),
untimed = TaskEnd.START,
rrule = "FREQ=WEEKLY",
)
val occurrenceStart = untimedInstantOf(TaskEnd.START, LocalDate.of(2026, 3, 23), berlin)
val form = TaskForm(
title = "Water plants",
listId = 1,
start = untimedInstantOf(TaskEnd.START, LocalDate.of(2026, 3, 30), berlin),
due = Instant.parse("2026-03-30T15:00:00Z"),
untimed = TaskEnd.START,
rrule = "FREQ=WEEKLY",
)
val edited = TaskFormWriter.seriesEdit(untimed, occurrenceStart, Instant.parse("2026-03-23T16:00:00Z"), form, now, "Europe/Berlin")
assertThat(edited.dtstart).isEqualTo(untimedInstantOf(TaskEnd.START, LocalDate.of(2026, 1, 12), berlin))
assertThat(edited.untimed).isEqualTo(TaskEnd.START)
}
}
@@ -78,4 +78,13 @@ class AllDayTimeTest {
assertThat(task.hasTime(TaskEnd.DUE)).isFalse()
assertThat(task.hasTime(TaskEnd.START)).isTrue()
}
@Test
fun `a day that starts in a clock change starts at its first valid moment`() {
val santiago = ZoneId.of("America/Santiago")
val transition = LocalDate.of(2026, 9, 6)
val start = untimedInstantOf(TaskEnd.START, transition, santiago)
assertThat(start.calendarDate(allDay = false, zone = santiago)).isEqualTo(transition)
assertThat(start).isEqualTo(Instant.fromEpochMilliseconds(transition.atStartOfDay(santiago).toInstant().toEpochMilli()))
}
}
@@ -29,4 +29,16 @@ class TaskSortingTest {
assertThat(sorted.map { it.taskId }).containsExactly(2L, 1L).inOrder()
}
@Test
fun `dues without a time sort from the start of their day, all-day or not`() {
val berlin = java.time.ZoneId.systemDefault()
val day = java.time.LocalDate.of(2026, 11, 17)
val allDay = testTask(id = 1, title = "a", due = allDayInstantOf(day), isAllDay = true)
val timed = testTask(id = 2, title = "b", due = kotlin.time.Instant.fromEpochMilliseconds(day.atTime(10, 0).atZone(berlin).toInstant().toEpochMilli()))
val untimed = testTask(id = 3, title = "c", start = timed.due, due = untimedInstantOf(TaskEnd.DUE, day, berlin))
.copy(untimed = TaskEnd.DUE)
val sorted = listOf(timed, untimed, allDay).sortedWith(TaskSorting.DEFAULT)
assertThat(sorted.map { it.taskId }).containsExactly(1L, 3L, 2L).inOrder()
}
}
@@ -4,6 +4,7 @@ import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.agendula.domain.Priority
import de.jeanlucmakiola.agendula.domain.TaskEnd
import de.jeanlucmakiola.agendula.domain.TaskStatus
import de.jeanlucmakiola.agendula.domain.untimedDate
import de.jeanlucmakiola.agendula.domain.allDayInstantOf
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
@@ -38,9 +39,10 @@ class ICalendarWriterTest {
parentId: Long? = null,
tags: List<String> = emptyList(),
untimed: TaskEnd? = null,
timeZone: String? = null,
) = ExportTask(
taskId, uid, title, description, location, url, priority, status, percentComplete,
start, due, isAllDay, completedAt, created, lastModified, rrule, rdate, parentId, tags, untimed,
start, due, isAllDay, completedAt, created, lastModified, rrule, rdate, parentId, tags, untimed, timeZone,
)
private fun write(vararg tasks: ExportTask, name: String = "Groceries"): String =
@@ -144,13 +146,23 @@ class ICalendarWriterTest {
}
@Test
fun `an untimed end stays a date-time beside a timed one, marked as having no time`() {
fun `an untimed end is a marked floating date-time, its own day wherever it is read`() {
val start = Instant.parse("2025-08-01T22:00:00Z")
val lines = linesOf(write(task(start = start, due = noon, untimed = TaskEnd.START)))
assertThat(lines).contains("DTSTART;X-AGENDULA-NO-TIME=TRUE:20250801T220000Z")
val lines = linesOf(write(task(start = start, due = noon, untimed = TaskEnd.START, timeZone = "Europe/Berlin")))
assertThat(lines).contains("DTSTART;X-AGENDULA-NO-TIME=TRUE:20250802T000000")
assertThat(lines).contains("DUE:20250802T120000Z")
}
@Test
fun `an exported untimed end reads back as one, on its date`() {
val start = Instant.parse("2025-08-01T22:00:00Z")
val ics = write(task(uid = "u-1", start = start, due = noon, untimed = TaskEnd.START, timeZone = "Europe/Berlin"))
val todo = de.jeanlucmakiola.agendula.domain.ical.ICalParser.parse(ics).components.single { it.name == "VTODO" }
val read = de.jeanlucmakiola.agendula.data.tasks.ical.VTodoMapper.read(todo).entity
assertThat(read.untimed).isEqualTo(TaskEnd.START)
assertThat(read.dtstart!!.untimedDate(read.timezone)).isEqualTo(LocalDate.of(2025, 8, 2))
}
@Test
fun `completion is always a UTC date-time even when all-day`() {
val lines = linesOf(