From 4376a48b1e8e2ea12e7650024fae532401900304 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Mon, 16 Nov 2026 19:08:12 +0100 Subject: [PATCH 1/8] Pick start/due date and time in one sheet with quick presets (#101) --- .../agendula/ui/edit/DateTimePickerSheet.kt | 175 ++++++++++++++++++ .../agendula/ui/edit/QuickPicks.kt | 36 ++++ .../agendula/ui/edit/TaskEditScreen.kt | 74 +------- app/src/main/res/values/strings.xml | 12 ++ .../agendula/ui/edit/QuickPicksTest.kt | 40 ++++ 5 files changed, 265 insertions(+), 72 deletions(-) create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/DateTimePickerSheet.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicks.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicksTest.kt diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/DateTimePickerSheet.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/DateTimePickerSheet.kt new file mode 100644 index 0000000..93aba64 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/DateTimePickerSheet.kt @@ -0,0 +1,175 @@ +package de.jeanlucmakiola.agendula.ui.edit + +import android.text.format.DateFormat +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.height +import androidx.compose.material3.DatePicker +import androidx.compose.material3.DatePickerDialog +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.rememberDatePickerState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import de.jeanlucmakiola.agendula.R +import de.jeanlucmakiola.agendula.domain.allDayInstantOf +import de.jeanlucmakiola.agendula.domain.calendarDate +import de.jeanlucmakiola.agendula.ui.common.LocalUse24HourFormat +import de.jeanlucmakiola.agendula.ui.common.TimePickerAlert +import de.jeanlucmakiola.agendula.ui.common.formatMinuteOfDay +import de.jeanlucmakiola.agendula.ui.common.localToInstant +import de.jeanlucmakiola.agendula.ui.common.toLocalTime +import de.jeanlucmakiola.floret.components.FullScreenPicker +import de.jeanlucmakiola.floret.components.GroupedRow +import de.jeanlucmakiola.floret.components.GroupedSectionHeader +import de.jeanlucmakiola.floret.components.positionOf +import de.jeanlucmakiola.floret.locale.currentLocale +import java.time.LocalDate +import java.time.LocalTime +import java.time.ZoneOffset +import java.time.format.DateTimeFormatter +import kotlin.time.Instant + +/** + * Start / due picker (#101): quick dates and preset times of day in one + * full-screen sheet, so either half can be changed without walking through the + * other. A date tap only stages the day (an all-day value commits at once); a + * time tap commits the staged day with that time, and Done keeps both as staged. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +internal fun DateTimePickerSheet( + title: String, + initial: Instant?, + allDay: Boolean, + onResult: (Instant) -> Unit, + onDismiss: () -> Unit, +) { + val today = remember { LocalDate.now() } + var date by rememberSaveable { mutableStateOf(initial?.calendarDate(allDay) ?: today) } + val time = rememberSaveable { + initial?.takeUnless { allDay }?.toLocalTime() ?: defaultPickerTime(LocalTime.now()) + } + var showCalendar by rememberSaveable { mutableStateOf(false) } + var showClock by rememberSaveable { mutableStateOf(false) } + + val is24Hour = LocalUse24HourFormat.current + val locale = currentLocale() + val dayFormats = remember(locale) { + listOf("EEEdMMM", "EEEdMMMyyyy").map { DateTimeFormatter.ofPattern(DateFormat.getBestDateTimePattern(locale, it), locale) } + } + fun dayLabel(d: LocalDate) = d.format(dayFormats[if (d.year == today.year) 0 else 1]) + fun timeLabel(t: LocalTime) = formatMinuteOfDay(t.hour * 60 + t.minute, is24Hour, locale) + fun commit(d: LocalDate, t: LocalTime) = onResult(if (allDay) allDayInstantOf(d) else localToInstant(d, t)) + fun pickDate(d: LocalDate) { + if (allDay) commit(d, time) else date = d + } + + FullScreenPicker( + title = title, + onDismiss = onDismiss, + actions = { + if (!allDay) { + TextButton(onClick = { commit(date, time) }) { Text(stringResource(R.string.picker_done)) } + } + }, + ) { + val quickDate = QuickDate.of(date, today) + val dateRows = QuickDate.entries.size + 1 + GroupedSectionHeader(stringResource(R.string.picker_section_date)) + QuickDate.entries.forEachIndexed { index, quick -> + val day = quick.resolve(today) + GroupedRow( + title = stringResource(quick.labelRes), + summary = dayLabel(day), + position = positionOf(index, dateRows), + checked = quick == quickDate, + onClick = { pickDate(day) }, + ) + } + GroupedRow( + title = stringResource(R.string.picker_date_pick), + summary = dayLabel(date).takeIf { quickDate == null }, + position = positionOf(QuickDate.entries.size, dateRows), + checked = quickDate == null, + onClick = { showCalendar = true }, + ) + + if (!allDay) { + val quickTime = QuickTime.of(time) + val timeRows = QuickTime.entries.size + 1 + Spacer(Modifier.height(8.dp)) + GroupedSectionHeader(stringResource(R.string.picker_section_time)) + QuickTime.entries.forEachIndexed { index, quick -> + GroupedRow( + title = stringResource(quick.labelRes), + summary = timeLabel(quick.time), + position = positionOf(index, timeRows), + checked = quick == quickTime, + onClick = { commit(date, quick.time) }, + ) + } + GroupedRow( + title = stringResource(R.string.picker_time_custom), + summary = timeLabel(time).takeIf { quickTime == null }, + position = positionOf(QuickTime.entries.size, timeRows), + checked = quickTime == null, + onClick = { showClock = true }, + ) + } + } + + if (showCalendar) { + // M3's DatePicker speaks UTC millis. + val state = rememberDatePickerState( + initialSelectedDateMillis = date.atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli(), + ) + DatePickerDialog( + onDismissRequest = { showCalendar = false }, + confirmButton = { + TextButton(onClick = { + showCalendar = false + state.selectedDateMillis?.let { + pickDate(java.time.Instant.ofEpochMilli(it).atZone(ZoneOffset.UTC).toLocalDate()) + } + }) { Text(stringResource(android.R.string.ok)) } + }, + dismissButton = { + TextButton(onClick = { showCalendar = false }) { Text(stringResource(android.R.string.cancel)) } + }, + ) { DatePicker(state = state) } + } + + if (showClock) { + TimePickerAlert( + initial = time, + onConfirm = { + showClock = false + commit(date, it) + }, + onDismiss = { showClock = false }, + ) + } +} + +private val QuickDate.labelRes: Int + get() = when (this) { + QuickDate.Today -> R.string.picker_date_today + QuickDate.Tomorrow -> R.string.picker_date_tomorrow + QuickDate.NextWeek -> R.string.picker_date_next_week + } + +private val QuickTime.labelRes: Int + get() = when (this) { + QuickTime.Morning -> R.string.picker_time_morning + QuickTime.Noon -> R.string.picker_time_noon + QuickTime.Afternoon -> R.string.picker_time_afternoon + QuickTime.Evening -> R.string.picker_time_evening + } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicks.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicks.kt new file mode 100644 index 0000000..c6e45b4 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicks.kt @@ -0,0 +1,36 @@ +package de.jeanlucmakiola.agendula.ui.edit + +import java.time.LocalDate +import java.time.LocalTime + +/** The one-tap dates the start / due picker offers above its calendar row. */ +internal enum class QuickDate(val daysFromToday: Long) { + Today(0), + Tomorrow(1), + NextWeek(7), + ; + + fun resolve(today: LocalDate): LocalDate = today.plusDays(daysFromToday) + + companion object { + /** The quick date [date] matches, or null when it needs the calendar. */ + fun of(date: LocalDate, today: LocalDate): QuickDate? = entries.firstOrNull { it.resolve(today) == date } + } +} + +/** The one-tap times of day the start / due picker offers. */ +internal enum class QuickTime(val time: LocalTime) { + Morning(LocalTime.of(8, 0)), + Noon(LocalTime.of(12, 0)), + Afternoon(LocalTime.of(15, 0)), + Evening(LocalTime.of(20, 0)), + ; + + companion object { + fun of(time: LocalTime): QuickTime? = entries.firstOrNull { it.time == time } + } +} + +/** Time to stage for an empty value: the next full hour, kept on the same day. */ +internal fun defaultPickerTime(now: LocalTime): LocalTime = + if (now.hour == 23) LocalTime.of(23, 59) else LocalTime.of(now.hour + 1, 0) 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..363d43e 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 @@ -81,8 +81,6 @@ import androidx.compose.material.icons.rounded.Schedule import androidx.compose.material.icons.rounded.Search import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button -import androidx.compose.material3.DatePicker -import androidx.compose.material3.DatePickerDialog import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton @@ -96,11 +94,8 @@ import androidx.compose.material3.Surface import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.material3.TextButton -import androidx.compose.material3.TimePicker import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults -import androidx.compose.material3.rememberDatePickerState -import androidx.compose.material3.rememberTimePickerState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.focus.FocusRequester @@ -138,16 +133,12 @@ import de.jeanlucmakiola.floret.components.InlineTextField import de.jeanlucmakiola.agendula.ui.common.priorityFill import de.jeanlucmakiola.floret.time.formatDate import de.jeanlucmakiola.floret.time.formatTime -import de.jeanlucmakiola.agendula.ui.common.localToInstant import de.jeanlucmakiola.floret.components.pastelize import de.jeanlucmakiola.floret.components.positionOf -import de.jeanlucmakiola.agendula.domain.allDayInstantOf import de.jeanlucmakiola.agendula.domain.calendarDate -import de.jeanlucmakiola.agendula.ui.common.toLocalTime import de.jeanlucmakiola.agendula.ui.tasklist.priorityLabel import java.time.LocalTime import java.time.ZoneId -import java.time.ZoneOffset import kotlin.time.Clock import kotlin.time.Instant @@ -665,7 +656,8 @@ private fun EditContent( pickerTarget?.let { target -> val current = if (target == PickerTarget.Start) state.start else state.due - DateTimePickerFlow( + DateTimePickerSheet( + title = stringResource(if (target == PickerTarget.Start) R.string.edit_start_label else R.string.edit_due_label), initial = current, allDay = state.isAllDay, onResult = { @@ -982,68 +974,6 @@ private fun LabelledValueLayout(label: @Composable () -> Unit, value: @Composabl } } -private fun nowInstant(): Instant = Instant.fromEpochMilliseconds(System.currentTimeMillis()) - -/** Pick a date, then (unless all-day) a time; emits the combined instant once. */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -private fun DateTimePickerFlow( - initial: Instant?, - allDay: Boolean, - onResult: (Instant) -> Unit, - onDismiss: () -> Unit, -) { - var pendingDate by rememberSaveable { mutableStateOf(null) } - var showTime by rememberSaveable { mutableStateOf(false) } - - if (!showTime) { - // M3's DatePicker speaks UTC millis. An all-day value is already UTC-based, - // a timed one is read in the device zone — calendarDate picks the right frame - // so the dialog opens on the day the rest of the UI shows. - val initialMillis = (initial ?: nowInstant()) - .calendarDate(allDay).atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli() - val dateState = rememberDatePickerState(initialSelectedDateMillis = initialMillis) - DatePickerDialog( - onDismissRequest = onDismiss, - confirmButton = { - TextButton(onClick = { - val millis = dateState.selectedDateMillis ?: run { onDismiss(); return@TextButton } - val date = java.time.Instant.ofEpochMilli(millis).atZone(ZoneOffset.UTC).toLocalDate() - if (allDay) { - onResult(allDayInstantOf(date)) - } else { - pendingDate = date - showTime = true - } - }) { Text(stringResource(android.R.string.ok)) } - }, - dismissButton = { - TextButton(onClick = onDismiss) { Text(stringResource(android.R.string.cancel)) } - }, - ) { DatePicker(state = dateState) } - } else { - val base = initial ?: nowInstant() - val timeState = rememberTimePickerState( - initialHour = base.toLocalTime().hour, - initialMinute = base.toLocalTime().minute, - is24Hour = LocalUse24HourFormat.current, - ) - AlertDialog( - onDismissRequest = onDismiss, - text = { TimePicker(state = timeState) }, - confirmButton = { - TextButton(onClick = { - val date = pendingDate ?: return@TextButton - onResult(localToInstant(date, LocalTime.of(timeState.hour, timeState.minute))) - }) { Text(stringResource(android.R.string.ok)) } - }, - dismissButton = { - TextButton(onClick = onDismiss) { Text(stringResource(android.R.string.cancel)) } - }, - ) - } -} - /** The target list, full-screen and grouped under each list's account. */ @Composable private fun ListPickerDialog( diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 5211b6b..78ace1f 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -98,6 +98,18 @@ Task title When More fields + Date + Time + Today + Tomorrow + Next week + Pick a date + Morning + Noon + Afternoon + Evening + Custom time + Done Close Cancel diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicksTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicksTest.kt new file mode 100644 index 0000000..07a2337 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicksTest.kt @@ -0,0 +1,40 @@ +package de.jeanlucmakiola.agendula.ui.edit + +import com.google.common.truth.Truth.assertThat +import java.time.LocalDate +import java.time.LocalTime +import org.junit.jupiter.api.Test + +class QuickPicksTest { + + private val today = LocalDate.of(2026, 12, 28) + + @Test + fun `quick dates resolve relative to today across a year boundary`() { + assertThat(QuickDate.Today.resolve(today)).isEqualTo(today) + assertThat(QuickDate.Tomorrow.resolve(today)).isEqualTo(LocalDate.of(2026, 12, 29)) + assertThat(QuickDate.NextWeek.resolve(today)).isEqualTo(LocalDate.of(2027, 1, 4)) + } + + @Test + fun `a date maps back to its quick date or to none`() { + assertThat(QuickDate.of(today, today)).isEqualTo(QuickDate.Today) + assertThat(QuickDate.of(LocalDate.of(2027, 1, 4), today)).isEqualTo(QuickDate.NextWeek) + assertThat(QuickDate.of(LocalDate.of(2026, 12, 30), today)).isNull() + assertThat(QuickDate.of(today.minusDays(1), today)).isNull() + } + + @Test + fun `a time maps to its preset only on an exact match`() { + assertThat(QuickTime.of(LocalTime.of(8, 0))).isEqualTo(QuickTime.Morning) + assertThat(QuickTime.of(LocalTime.of(20, 0))).isEqualTo(QuickTime.Evening) + assertThat(QuickTime.of(LocalTime.of(8, 1))).isNull() + } + + @Test + fun `the default time is the next full hour without leaving the day`() { + assertThat(defaultPickerTime(LocalTime.of(9, 41))).isEqualTo(LocalTime.of(10, 0)) + assertThat(defaultPickerTime(LocalTime.of(0, 0))).isEqualTo(LocalTime.of(1, 0)) + assertThat(defaultPickerTime(LocalTime.of(23, 10))).isEqualTo(LocalTime.of(23, 59)) + } +} From a1bd03eae81b7687b2b7ebaa3961571339afc7c5 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Mon, 16 Nov 2026 19:17:33 +0100 Subject: [PATCH 2/8] Apply date/time picks live, share the date dialog, review fixes (#101) --- .../agendula/ui/common/DatePickerAlert.kt | 40 ++++++ .../agendula/ui/edit/DateTimePickerSheet.kt | 119 +++++++++--------- .../agendula/ui/edit/QuickPicks.kt | 3 +- .../agendula/ui/edit/RecurrencePicker.kt | 41 +----- .../agendula/ui/edit/TaskEditScreen.kt | 5 +- app/src/main/res/values/strings.xml | 3 - .../agendula/ui/edit/QuickPicksTest.kt | 1 + 7 files changed, 104 insertions(+), 108 deletions(-) create mode 100644 app/src/main/java/de/jeanlucmakiola/agendula/ui/common/DatePickerAlert.kt diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/common/DatePickerAlert.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/common/DatePickerAlert.kt new file mode 100644 index 0000000..d49903a --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/common/DatePickerAlert.kt @@ -0,0 +1,40 @@ +package de.jeanlucmakiola.agendula.ui.common + +import androidx.compose.material3.DatePicker +import androidx.compose.material3.DatePickerDialog +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.rememberDatePickerState +import androidx.compose.runtime.Composable +import androidx.compose.ui.res.stringResource +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneOffset + +/** M3 date picker dialog seeded with [initial]; confirming without a selection dismisses. */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun DatePickerAlert( + initial: LocalDate, + onConfirm: (LocalDate) -> Unit, + onDismiss: () -> Unit, +) { + // M3's DatePicker speaks UTC-midnight millis. + val state = rememberDatePickerState( + initialSelectedDateMillis = initial.atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli(), + ) + DatePickerDialog( + onDismissRequest = onDismiss, + confirmButton = { + TextButton(onClick = { + state.selectedDateMillis + ?.let { onConfirm(Instant.ofEpochMilli(it).atZone(ZoneOffset.UTC).toLocalDate()) } + ?: onDismiss() + }) { Text(stringResource(android.R.string.ok)) } + }, + dismissButton = { + TextButton(onClick = onDismiss) { Text(stringResource(android.R.string.cancel)) } + }, + ) { DatePicker(state = state) } +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/DateTimePickerSheet.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/DateTimePickerSheet.kt index 93aba64..017993d 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/DateTimePickerSheet.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/DateTimePickerSheet.kt @@ -3,12 +3,6 @@ package de.jeanlucmakiola.agendula.ui.edit import android.text.format.DateFormat import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height -import androidx.compose.material3.DatePicker -import androidx.compose.material3.DatePickerDialog -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.rememberDatePickerState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -21,6 +15,7 @@ import androidx.compose.ui.unit.dp import de.jeanlucmakiola.agendula.R import de.jeanlucmakiola.agendula.domain.allDayInstantOf import de.jeanlucmakiola.agendula.domain.calendarDate +import de.jeanlucmakiola.agendula.ui.common.DatePickerAlert import de.jeanlucmakiola.agendula.ui.common.LocalUse24HourFormat import de.jeanlucmakiola.agendula.ui.common.TimePickerAlert import de.jeanlucmakiola.agendula.ui.common.formatMinuteOfDay @@ -33,77 +28,76 @@ import de.jeanlucmakiola.floret.components.positionOf import de.jeanlucmakiola.floret.locale.currentLocale import java.time.LocalDate import java.time.LocalTime -import java.time.ZoneOffset import java.time.format.DateTimeFormatter +import java.time.format.FormatStyle +import java.util.Locale import kotlin.time.Instant /** * Start / due picker (#101): quick dates and preset times of day in one * full-screen sheet, so either half can be changed without walking through the - * other. A date tap only stages the day (an all-day value commits at once); a - * time tap commits the staged day with that time, and Done keeps both as staged. + * other. A date applies at once and keeps the sheet open for a time (an all-day + * value closes it); a time applies and closes. The user leaves via back. */ -@OptIn(ExperimentalMaterial3Api::class) @Composable internal fun DateTimePickerSheet( title: String, initial: Instant?, allDay: Boolean, - onResult: (Instant) -> Unit, + onChange: (Instant) -> Unit, onDismiss: () -> Unit, ) { - val today = remember { LocalDate.now() } - var date by rememberSaveable { mutableStateOf(initial?.calendarDate(allDay) ?: today) } - val time = rememberSaveable { - initial?.takeUnless { allDay }?.toLocalTime() ?: defaultPickerTime(LocalTime.now()) - } + var date by rememberSaveable { mutableStateOf(initial?.calendarDate(allDay)) } + var time by rememberSaveable { mutableStateOf(initial?.takeUnless { allDay }?.toLocalTime()) } var showCalendar by rememberSaveable { mutableStateOf(false) } var showClock by rememberSaveable { mutableStateOf(false) } + val today = LocalDate.now() val is24Hour = LocalUse24HourFormat.current val locale = currentLocale() - val dayFormats = remember(locale) { - listOf("EEEdMMM", "EEEdMMMyyyy").map { DateTimeFormatter.ofPattern(DateFormat.getBestDateTimePattern(locale, it), locale) } - } - fun dayLabel(d: LocalDate) = d.format(dayFormats[if (d.year == today.year) 0 else 1]) + val dayFormats = remember(locale) { DayFormats(locale) } + fun dayLabel(d: LocalDate) = d.format(if (d.year == today.year) dayFormats.thisYear else dayFormats.otherYear) fun timeLabel(t: LocalTime) = formatMinuteOfDay(t.hour * 60 + t.minute, is24Hour, locale) - fun commit(d: LocalDate, t: LocalTime) = onResult(if (allDay) allDayInstantOf(d) else localToInstant(d, t)) + fun pickDate(d: LocalDate) { - if (allDay) commit(d, time) else date = d + date = d + if (allDay) { + onChange(allDayInstantOf(d)) + onDismiss() + } else { + val t = time ?: defaultPickerTime(LocalTime.now()).also { time = it } + onChange(localToInstant(d, t)) + } + } + fun pickTime(t: LocalTime) { + onChange(localToInstant(date ?: LocalDate.now(), t)) + onDismiss() } - FullScreenPicker( - title = title, - onDismiss = onDismiss, - actions = { - if (!allDay) { - TextButton(onClick = { commit(date, time) }) { Text(stringResource(R.string.picker_done)) } - } - }, - ) { - val quickDate = QuickDate.of(date, today) + FullScreenPicker(title = title, onDismiss = onDismiss) { + val quickDate = date?.let { QuickDate.of(it, today) } val dateRows = QuickDate.entries.size + 1 GroupedSectionHeader(stringResource(R.string.picker_section_date)) QuickDate.entries.forEachIndexed { index, quick -> - val day = quick.resolve(today) GroupedRow( title = stringResource(quick.labelRes), - summary = dayLabel(day), + summary = dayLabel(quick.resolve(today)), position = positionOf(index, dateRows), checked = quick == quickDate, - onClick = { pickDate(day) }, + onClick = { pickDate(quick.resolve(LocalDate.now())) }, ) } + val customDate = date?.takeIf { quickDate == null } GroupedRow( title = stringResource(R.string.picker_date_pick), - summary = dayLabel(date).takeIf { quickDate == null }, + summary = customDate?.let(::dayLabel), position = positionOf(QuickDate.entries.size, dateRows), - checked = quickDate == null, + checked = customDate != null, onClick = { showCalendar = true }, ) if (!allDay) { - val quickTime = QuickTime.of(time) + val quickTime = time?.let { QuickTime.of(it) } val timeRows = QuickTime.entries.size + 1 Spacer(Modifier.height(8.dp)) GroupedSectionHeader(stringResource(R.string.picker_section_time)) @@ -113,56 +107,57 @@ internal fun DateTimePickerSheet( summary = timeLabel(quick.time), position = positionOf(index, timeRows), checked = quick == quickTime, - onClick = { commit(date, quick.time) }, + onClick = { pickTime(quick.time) }, ) } + val customTime = time?.takeIf { quickTime == null } GroupedRow( title = stringResource(R.string.picker_time_custom), - summary = timeLabel(time).takeIf { quickTime == null }, + summary = customTime?.let(::timeLabel), position = positionOf(QuickTime.entries.size, timeRows), - checked = quickTime == null, + checked = customTime != null, onClick = { showClock = true }, ) } } if (showCalendar) { - // M3's DatePicker speaks UTC millis. - val state = rememberDatePickerState( - initialSelectedDateMillis = date.atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli(), + DatePickerAlert( + initial = date ?: today, + onConfirm = { + showCalendar = false + pickDate(it) + }, + onDismiss = { showCalendar = false }, ) - DatePickerDialog( - onDismissRequest = { showCalendar = false }, - confirmButton = { - TextButton(onClick = { - showCalendar = false - state.selectedDateMillis?.let { - pickDate(java.time.Instant.ofEpochMilli(it).atZone(ZoneOffset.UTC).toLocalDate()) - } - }) { Text(stringResource(android.R.string.ok)) } - }, - dismissButton = { - TextButton(onClick = { showCalendar = false }) { Text(stringResource(android.R.string.cancel)) } - }, - ) { DatePicker(state = state) } } if (showClock) { TimePickerAlert( - initial = time, + initial = time ?: defaultPickerTime(LocalTime.now()), onConfirm = { showClock = false - commit(date, it) + pickTime(it) }, onDismiss = { showClock = false }, ) } } +/** Weekday + day + month, with the year only when it isn't the current one. */ +private class DayFormats(locale: Locale) { + val thisYear: DateTimeFormatter = bestPattern(locale, "EEEdMMM") + val otherYear: DateTimeFormatter = bestPattern(locale, "EEEdMMMyyyy") + + private fun bestPattern(locale: Locale, skeleton: String): DateTimeFormatter = + runCatching { DateTimeFormatter.ofPattern(DateFormat.getBestDateTimePattern(locale, skeleton), locale) } + .getOrElse { DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(locale) } +} + private val QuickDate.labelRes: Int get() = when (this) { - QuickDate.Today -> R.string.picker_date_today - QuickDate.Tomorrow -> R.string.picker_date_tomorrow + QuickDate.Today -> R.string.home_due_today + QuickDate.Tomorrow -> R.string.home_due_tomorrow QuickDate.NextWeek -> R.string.picker_date_next_week } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicks.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicks.kt index c6e45b4..1a48224 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicks.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicks.kt @@ -2,6 +2,7 @@ package de.jeanlucmakiola.agendula.ui.edit import java.time.LocalDate import java.time.LocalTime +import java.time.temporal.ChronoUnit /** The one-tap dates the start / due picker offers above its calendar row. */ internal enum class QuickDate(val daysFromToday: Long) { @@ -27,7 +28,7 @@ internal enum class QuickTime(val time: LocalTime) { ; companion object { - fun of(time: LocalTime): QuickTime? = entries.firstOrNull { it.time == time } + fun of(time: LocalTime): QuickTime? = time.truncatedTo(ChronoUnit.MINUTES).let { t -> entries.firstOrNull { it.time == t } } } } 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..4a9056f 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 @@ -12,9 +12,6 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape -import androidx.compose.material3.DatePicker -import androidx.compose.material3.DatePickerDialog -import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.SegmentedButton import androidx.compose.material3.SegmentedButtonDefaults @@ -22,7 +19,6 @@ import androidx.compose.material3.SingleChoiceSegmentedButtonRow import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextButton -import androidx.compose.material3.rememberDatePickerState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -57,6 +53,7 @@ import kotlinx.datetime.LocalDate import kotlinx.datetime.isoDayNumber import kotlinx.datetime.toJavaDayOfWeek import kotlinx.datetime.toJavaLocalDate +import de.jeanlucmakiola.agendula.ui.common.DatePickerAlert import java.time.format.DateTimeFormatter import java.time.format.FormatStyle import java.time.format.TextStyle as JavaTextStyle @@ -315,8 +312,8 @@ fun RecurrencePicker( } if (showUntilPicker) { - UntilDatePicker( - initial = untilDate ?: startDate, + DatePickerAlert( + initial = (untilDate ?: startDate).toJavaLocalDate(), onConfirm = { untilIso = it.toString() showUntilPicker = false @@ -386,38 +383,6 @@ private fun CheckRow( ) } -/** M3 date picker for the UNTIL day; the picker speaks UTC-midnight millis. */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -private fun UntilDatePicker( - initial: LocalDate, - onConfirm: (LocalDate) -> Unit, - onDismiss: () -> Unit, -) { - val state = rememberDatePickerState( - initialSelectedDateMillis = initial.toEpochDays() * MILLIS_PER_DAY, - ) - DatePickerDialog( - onDismissRequest = onDismiss, - confirmButton = { - TextButton( - onClick = { - state.selectedDateMillis?.let { millis -> - onConfirm(LocalDate.fromEpochDays((millis / MILLIS_PER_DAY).toInt())) - } ?: onDismiss() - }, - ) { Text(stringResource(android.R.string.ok)) } - }, - dismissButton = { - TextButton(onClick = onDismiss) { Text(stringResource(android.R.string.cancel)) } - }, - ) { - DatePicker(state = state) - } -} - -private const val MILLIS_PER_DAY: Long = 86_400_000L - /** One tappable circle per weekday in locale week order, multi-select (BYDAY picks). */ @Composable private fun WeekdayToggleRow( 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 363d43e..3f2fdfd 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 @@ -660,10 +660,7 @@ private fun EditContent( title = stringResource(if (target == PickerTarget.Start) R.string.edit_start_label else R.string.edit_due_label), initial = current, allDay = state.isAllDay, - onResult = { - if (target == PickerTarget.Start) viewModel.onStartChange(it) else viewModel.onDueChange(it) - pickerTarget = null - }, + onChange = { if (target == PickerTarget.Start) viewModel.onStartChange(it) else viewModel.onDueChange(it) }, onDismiss = { pickerTarget = null }, ) } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 78ace1f..3721842 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -100,8 +100,6 @@ More fields Date Time - Today - Tomorrow Next week Pick a date Morning @@ -109,7 +107,6 @@ Afternoon Evening Custom time - Done Close Cancel diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicksTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicksTest.kt index 07a2337..a2e253c 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicksTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicksTest.kt @@ -29,6 +29,7 @@ class QuickPicksTest { assertThat(QuickTime.of(LocalTime.of(8, 0))).isEqualTo(QuickTime.Morning) assertThat(QuickTime.of(LocalTime.of(20, 0))).isEqualTo(QuickTime.Evening) assertThat(QuickTime.of(LocalTime.of(8, 1))).isNull() + assertThat(QuickTime.of(LocalTime.of(8, 0, 30, 500))).isEqualTo(QuickTime.Morning) } @Test From 1f8d8d230d90ba10e80c1faa07085d87eb700b6a Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Tue, 17 Nov 2026 00:42:24 +0100 Subject: [PATCH 3/8] Stage date picks behind Done, keep quick times ahead, review fixes (#101) --- CHANGELOG.md | 7 ++ .../agendula/ui/edit/DateTimePickerSheet.kt | 64 ++++++++++++------- .../agendula/ui/edit/QuickPicks.kt | 17 ++++- .../agendula/ui/edit/RecurrencePicker.kt | 2 +- .../agendula/ui/edit/TaskEditScreen.kt | 1 + app/src/main/res/values/strings.xml | 3 + .../agendula/ui/edit/QuickPicksTest.kt | 27 ++++++-- 7 files changed, 89 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 67c3d4b..6012b5d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,13 @@ All notable changes to this project are documented here. The format follows ## [Unreleased] +### Changed +- Start and due dates are picked in one full-screen sheet with quick dates + (today, tomorrow, next week) and preset times (morning, noon, afternoon, + evening), so the date or the time can be changed on its own without walking + through both pickers. A calendar and a clock are still there for anything + else (#101). + ## [1.3.2] - 2026-11-13 ### Added diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/DateTimePickerSheet.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/DateTimePickerSheet.kt index 017993d..020e53b 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/DateTimePickerSheet.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/DateTimePickerSheet.kt @@ -1,8 +1,9 @@ package de.jeanlucmakiola.agendula.ui.edit -import android.text.format.DateFormat import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -26,55 +27,74 @@ import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.GroupedSectionHeader import de.jeanlucmakiola.floret.components.positionOf import de.jeanlucmakiola.floret.locale.currentLocale +import de.jeanlucmakiola.floret.locale.localizedDateFormatter import java.time.LocalDate +import java.time.LocalDateTime import java.time.LocalTime import java.time.format.DateTimeFormatter -import java.time.format.FormatStyle import java.util.Locale import kotlin.time.Instant /** * Start / due picker (#101): quick dates and preset times of day in one * full-screen sheet, so either half can be changed without walking through the - * other. A date applies at once and keeps the sheet open for a time (an all-day - * value closes it); a time applies and closes. The user leaves via back. + * other. A tap that completes the value applies it and closes: any time, or a + * date when the value already has a time (or is all-day). A date for a value + * without a time is staged with a default time and committed by Done. Back + * discards anything staged. + * + * [notBefore] keeps a time picked for an empty value from landing before it + * (the start, when picking a due). */ @Composable internal fun DateTimePickerSheet( title: String, initial: Instant?, allDay: Boolean, + notBefore: Instant?, onChange: (Instant) -> Unit, onDismiss: () -> Unit, ) { + val timeKnown = initial != null && !allDay var date by rememberSaveable { mutableStateOf(initial?.calendarDate(allDay)) } var time by rememberSaveable { mutableStateOf(initial?.takeUnless { allDay }?.toLocalTime()) } var showCalendar by rememberSaveable { mutableStateOf(false) } var showClock by rememberSaveable { mutableStateOf(false) } - val today = LocalDate.now() + val today = remember { LocalDate.now() } val is24Hour = LocalUse24HourFormat.current val locale = currentLocale() val dayFormats = remember(locale) { DayFormats(locale) } fun dayLabel(d: LocalDate) = d.format(if (d.year == today.year) dayFormats.thisYear else dayFormats.otherYear) fun timeLabel(t: LocalTime) = formatMinuteOfDay(t.hour * 60 + t.minute, is24Hour, locale) + fun commit(d: LocalDate, t: LocalTime?) { + onChange(if (allDay) allDayInstantOf(d) else localToInstant(d, t ?: defaultPickerTime(d, LocalDateTime.now()))) + onDismiss() + } fun pickDate(d: LocalDate) { - date = d - if (allDay) { - onChange(allDayInstantOf(d)) - onDismiss() + if (allDay || timeKnown) { + commit(d, time) } else { - val t = time ?: defaultPickerTime(LocalTime.now()).also { time = it } - onChange(localToInstant(d, t)) + date = d + time = time ?: defaultPickerTime(d, LocalDateTime.now()) } } fun pickTime(t: LocalTime) { - onChange(localToInstant(date ?: LocalDate.now(), t)) - onDismiss() + val floor = notBefore?.takeUnless { allDay }?.let { LocalDateTime.of(it.calendarDate(false), it.toLocalTime()) } + commit(date ?: defaultPickerDate(t, LocalDateTime.now(), floor), t) } - FullScreenPicker(title = title, onDismiss = onDismiss) { + FullScreenPicker( + title = title, + onDismiss = onDismiss, + actions = { + TextButton( + onClick = { date?.let { commit(it, time) } }, + enabled = date != null, + ) { Text(stringResource(R.string.picker_done)) } + }, + ) { val quickDate = date?.let { QuickDate.of(it, today) } val dateRows = QuickDate.entries.size + 1 GroupedSectionHeader(stringResource(R.string.picker_section_date)) @@ -84,7 +104,7 @@ internal fun DateTimePickerSheet( summary = dayLabel(quick.resolve(today)), position = positionOf(index, dateRows), checked = quick == quickDate, - onClick = { pickDate(quick.resolve(LocalDate.now())) }, + onClick = { pickDate(quick.resolve(today)) }, ) } val customDate = date?.takeIf { quickDate == null } @@ -134,7 +154,7 @@ internal fun DateTimePickerSheet( if (showClock) { TimePickerAlert( - initial = time ?: defaultPickerTime(LocalTime.now()), + initial = time ?: defaultPickerTime(date ?: today, LocalDateTime.now()), onConfirm = { showClock = false pickTime(it) @@ -146,18 +166,14 @@ internal fun DateTimePickerSheet( /** Weekday + day + month, with the year only when it isn't the current one. */ private class DayFormats(locale: Locale) { - val thisYear: DateTimeFormatter = bestPattern(locale, "EEEdMMM") - val otherYear: DateTimeFormatter = bestPattern(locale, "EEEdMMMyyyy") - - private fun bestPattern(locale: Locale, skeleton: String): DateTimeFormatter = - runCatching { DateTimeFormatter.ofPattern(DateFormat.getBestDateTimePattern(locale, skeleton), locale) } - .getOrElse { DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(locale) } + val thisYear: DateTimeFormatter = localizedDateFormatter(locale, "EEEdMMM") + val otherYear: DateTimeFormatter = localizedDateFormatter(locale, "EEEdMMMyyyy") } private val QuickDate.labelRes: Int get() = when (this) { - QuickDate.Today -> R.string.home_due_today - QuickDate.Tomorrow -> R.string.home_due_tomorrow + QuickDate.Today -> R.string.picker_date_today + QuickDate.Tomorrow -> R.string.picker_date_tomorrow QuickDate.NextWeek -> R.string.picker_date_next_week } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicks.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicks.kt index 1a48224..20ae257 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicks.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicks.kt @@ -1,6 +1,7 @@ package de.jeanlucmakiola.agendula.ui.edit import java.time.LocalDate +import java.time.LocalDateTime import java.time.LocalTime import java.time.temporal.ChronoUnit @@ -32,6 +33,16 @@ internal enum class QuickTime(val time: LocalTime) { } } -/** Time to stage for an empty value: the next full hour, kept on the same day. */ -internal fun defaultPickerTime(now: LocalTime): LocalTime = - if (now.hour == 23) LocalTime.of(23, 59) else LocalTime.of(now.hour + 1, 0) +/** Time to stage for a date picked without one: the next full hour today, the morning preset on another day. */ +internal fun defaultPickerTime(date: LocalDate, now: LocalDateTime): LocalTime = when { + date != now.toLocalDate() -> QuickTime.Morning.time + now.hour == 23 -> LocalTime.of(23, 59) + else -> LocalTime.of(now.hour + 1, 0) +} + +/** Date for a time picked without one: the first day on which [time] is not behind [now] or [notBefore]. */ +internal fun defaultPickerDate(time: LocalTime, now: LocalDateTime, notBefore: LocalDateTime? = null): LocalDate { + val floor = if (notBefore != null && notBefore > now) notBefore else now + val day = floor.toLocalDate() + return if (day.atTime(time) < floor.truncatedTo(ChronoUnit.MINUTES)) day.plusDays(1) else day +} 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 4a9056f..b355ac5 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 @@ -36,6 +36,7 @@ import de.jeanlucmakiola.agendula.domain.recurrence.RecurrenceFreq import de.jeanlucmakiola.agendula.domain.recurrence.SimpleRecurrence import de.jeanlucmakiola.agendula.domain.recurrence.parseSimpleRecurrence import de.jeanlucmakiola.agendula.domain.recurrence.toRRule +import de.jeanlucmakiola.agendula.ui.common.DatePickerAlert import de.jeanlucmakiola.agendula.ui.common.nextOccurrencesText import de.jeanlucmakiola.agendula.ui.common.recurrenceText import de.jeanlucmakiola.floret.components.DialogAmountField @@ -53,7 +54,6 @@ import kotlinx.datetime.LocalDate import kotlinx.datetime.isoDayNumber import kotlinx.datetime.toJavaDayOfWeek import kotlinx.datetime.toJavaLocalDate -import de.jeanlucmakiola.agendula.ui.common.DatePickerAlert import java.time.format.DateTimeFormatter import java.time.format.FormatStyle import java.time.format.TextStyle as JavaTextStyle 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 3f2fdfd..5936244 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 @@ -660,6 +660,7 @@ private fun EditContent( title = stringResource(if (target == PickerTarget.Start) R.string.edit_start_label else R.string.edit_due_label), initial = current, allDay = state.isAllDay, + notBefore = state.start.takeIf { target == PickerTarget.Due }, onChange = { if (target == PickerTarget.Start) viewModel.onStartChange(it) else viewModel.onDueChange(it) }, onDismiss = { pickerTarget = null }, ) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 3721842..78ace1f 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -100,6 +100,8 @@ More fields Date Time + Today + Tomorrow Next week Pick a date Morning @@ -107,6 +109,7 @@ Afternoon Evening Custom time + Done Close Cancel diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicksTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicksTest.kt index a2e253c..c2307aa 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicksTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicksTest.kt @@ -33,9 +33,28 @@ class QuickPicksTest { } @Test - fun `the default time is the next full hour without leaving the day`() { - assertThat(defaultPickerTime(LocalTime.of(9, 41))).isEqualTo(LocalTime.of(10, 0)) - assertThat(defaultPickerTime(LocalTime.of(0, 0))).isEqualTo(LocalTime.of(1, 0)) - assertThat(defaultPickerTime(LocalTime.of(23, 10))).isEqualTo(LocalTime.of(23, 59)) + fun `the default time is the next full hour today and the morning on another day`() { + assertThat(defaultPickerTime(today, today.atTime(9, 41))).isEqualTo(LocalTime.of(10, 0)) + assertThat(defaultPickerTime(today, today.atTime(0, 0))).isEqualTo(LocalTime.of(1, 0)) + assertThat(defaultPickerTime(today, today.atTime(23, 10))).isEqualTo(LocalTime.of(23, 59)) + assertThat(defaultPickerTime(today.plusDays(1), today.atTime(23, 10))).isEqualTo(LocalTime.of(8, 0)) + } + + @Test + fun `a time without a date lands on the first day it is still ahead`() { + val now = today.atTime(16, 30) + assertThat(defaultPickerDate(LocalTime.of(20, 0), now)).isEqualTo(today) + assertThat(defaultPickerDate(LocalTime.of(16, 30), now)).isEqualTo(today) + assertThat(defaultPickerDate(LocalTime.of(8, 0), now)).isEqualTo(LocalDate.of(2026, 12, 29)) + assertThat(defaultPickerDate(LocalTime.of(8, 0), today.atTime(23, 0))).isEqualTo(LocalDate.of(2026, 12, 29)) + } + + @Test + fun `a time without a date does not land before the floor`() { + val now = today.atTime(16, 30) + val start = LocalDate.of(2027, 1, 4).atTime(9, 0) + assertThat(defaultPickerDate(LocalTime.of(20, 0), now, start)).isEqualTo(LocalDate.of(2027, 1, 4)) + assertThat(defaultPickerDate(LocalTime.of(8, 0), now, start)).isEqualTo(LocalDate.of(2027, 1, 5)) + assertThat(defaultPickerDate(LocalTime.of(20, 0), now, today.minusDays(3).atTime(9, 0))).isEqualTo(today) } } From 3f009666c27af0e3d87d81ca9d1afac48f55fe8b Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Tue, 17 Nov 2026 00:46:42 +0100 Subject: [PATCH 4/8] Restage the default time per date, bound start by due, Done only when staging (#101) --- .../agendula/ui/edit/DateTimePickerSheet.kt | 46 +++++++++++-------- .../agendula/ui/edit/QuickPicks.kt | 45 ++++++++++++++---- .../agendula/ui/edit/TaskEditScreen.kt | 1 + .../agendula/ui/edit/QuickPicksTest.kt | 19 ++++++++ 4 files changed, 83 insertions(+), 28 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/DateTimePickerSheet.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/DateTimePickerSheet.kt index 020e53b..f0eefbb 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/DateTimePickerSheet.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/DateTimePickerSheet.kt @@ -43,8 +43,8 @@ import kotlin.time.Instant * without a time is staged with a default time and committed by Done. Back * discards anything staged. * - * [notBefore] keeps a time picked for an empty value from landing before it - * (the start, when picking a due). + * [notBefore] / [notAfter] keep a date or time filled in for an empty value on + * the right side of the other end (the start for a due, the due for a start). */ @Composable internal fun DateTimePickerSheet( @@ -52,47 +52,55 @@ internal fun DateTimePickerSheet( initial: Instant?, allDay: Boolean, notBefore: Instant?, + notAfter: Instant?, onChange: (Instant) -> Unit, onDismiss: () -> Unit, ) { - val timeKnown = initial != null && !allDay + val staging = initial == null && !allDay var date by rememberSaveable { mutableStateOf(initial?.calendarDate(allDay)) } var time by rememberSaveable { mutableStateOf(initial?.takeUnless { allDay }?.toLocalTime()) } var showCalendar by rememberSaveable { mutableStateOf(false) } var showClock by rememberSaveable { mutableStateOf(false) } - val today = remember { LocalDate.now() } + val today = LocalDate.now() val is24Hour = LocalUse24HourFormat.current val locale = currentLocale() val dayFormats = remember(locale) { DayFormats(locale) } fun dayLabel(d: LocalDate) = d.format(if (d.year == today.year) dayFormats.thisYear else dayFormats.otherYear) fun timeLabel(t: LocalTime) = formatMinuteOfDay(t.hour * 60 + t.minute, is24Hour, locale) - fun commit(d: LocalDate, t: LocalTime?) { - onChange(if (allDay) allDayInstantOf(d) else localToInstant(d, t ?: defaultPickerTime(d, LocalDateTime.now()))) + val floor = notBefore?.toLocalDateTime() + val ceiling = notAfter?.toLocalDateTime() + fun stagedTime(d: LocalDate) = defaultPickerTime(d, LocalDateTime.now(), floor, ceiling) + + fun commit(value: Instant) { + onChange(value) onDismiss() } fun pickDate(d: LocalDate) { - if (allDay || timeKnown) { - commit(d, time) - } else { - date = d - time = time ?: defaultPickerTime(d, LocalDateTime.now()) + when { + allDay -> commit(allDayInstantOf(d)) + staging -> { + date = d + time = stagedTime(d) + } + else -> commit(localToInstant(d, checkNotNull(time))) } } fun pickTime(t: LocalTime) { - val floor = notBefore?.takeUnless { allDay }?.let { LocalDateTime.of(it.calendarDate(false), it.toLocalTime()) } - commit(date ?: defaultPickerDate(t, LocalDateTime.now(), floor), t) + commit(localToInstant(date ?: defaultPickerDate(t, LocalDateTime.now(), floor, ceiling), t)) } FullScreenPicker( title = title, onDismiss = onDismiss, actions = { - TextButton( - onClick = { date?.let { commit(it, time) } }, - enabled = date != null, - ) { Text(stringResource(R.string.picker_done)) } + if (staging) { + TextButton( + onClick = { date?.let { commit(localToInstant(it, stagedTime(it))) } }, + enabled = date != null, + ) { Text(stringResource(R.string.picker_done)) } + } }, ) { val quickDate = date?.let { QuickDate.of(it, today) } @@ -154,7 +162,7 @@ internal fun DateTimePickerSheet( if (showClock) { TimePickerAlert( - initial = time ?: defaultPickerTime(date ?: today, LocalDateTime.now()), + initial = time ?: stagedTime(date ?: today), onConfirm = { showClock = false pickTime(it) @@ -170,6 +178,8 @@ private class DayFormats(locale: Locale) { val otherYear: DateTimeFormatter = localizedDateFormatter(locale, "EEEdMMMyyyy") } +private fun Instant.toLocalDateTime(): LocalDateTime = LocalDateTime.of(calendarDate(false), toLocalTime()) + private val QuickDate.labelRes: Int get() = when (this) { QuickDate.Today -> R.string.picker_date_today diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicks.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicks.kt index 20ae257..51ed9b0 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicks.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicks.kt @@ -33,16 +33,41 @@ internal enum class QuickTime(val time: LocalTime) { } } -/** Time to stage for a date picked without one: the next full hour today, the morning preset on another day. */ -internal fun defaultPickerTime(date: LocalDate, now: LocalDateTime): LocalTime = when { - date != now.toLocalDate() -> QuickTime.Morning.time - now.hour == 23 -> LocalTime.of(23, 59) - else -> LocalTime.of(now.hour + 1, 0) +/** + * Time to stage for a date picked without one: the next full hour after now + * (or [floor], when later) on that day, the morning preset on any other day, + * and never past [ceiling] on its day. + */ +internal fun defaultPickerTime( + date: LocalDate, + now: LocalDateTime, + floor: LocalDateTime? = null, + ceiling: LocalDateTime? = null, +): LocalTime { + val from = if (floor != null && floor > now) floor else now + val time = when { + date != from.toLocalDate() -> QuickTime.Morning.time + from.hour == 23 -> LocalTime.of(23, 59) + else -> LocalTime.of(from.hour + 1, 0) + } + val cap = ceiling?.takeIf { it.toLocalDate() == date }?.toLocalTime()?.truncatedTo(ChronoUnit.MINUTES) + return if (cap != null && time > cap) cap else time } -/** Date for a time picked without one: the first day on which [time] is not behind [now] or [notBefore]. */ -internal fun defaultPickerDate(time: LocalTime, now: LocalDateTime, notBefore: LocalDateTime? = null): LocalDate { - val floor = if (notBefore != null && notBefore > now) notBefore else now - val day = floor.toLocalDate() - return if (day.atTime(time) < floor.truncatedTo(ChronoUnit.MINUTES)) day.plusDays(1) else day +/** + * Date for a time picked without one: the first day on which [time] is not + * behind now or [floor], pulled back to the last day that keeps it within + * [ceiling]. + */ +internal fun defaultPickerDate( + time: LocalTime, + now: LocalDateTime, + floor: LocalDateTime? = null, + ceiling: LocalDateTime? = null, +): LocalDate { + val from = (if (floor != null && floor > now) floor else now).truncatedTo(ChronoUnit.MINUTES) + val day = from.toLocalDate().let { if (it.atTime(time) < from) it.plusDays(1) else it } + if (ceiling == null || day.atTime(time) <= ceiling) return day + val last = ceiling.toLocalDate() + return if (last.atTime(time) <= ceiling) last else last.minusDays(1) } 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 5936244..7bda8db 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 @@ -661,6 +661,7 @@ private fun EditContent( initial = current, allDay = state.isAllDay, notBefore = state.start.takeIf { target == PickerTarget.Due }, + notAfter = state.due.takeIf { target == PickerTarget.Start }, onChange = { if (target == PickerTarget.Start) viewModel.onStartChange(it) else viewModel.onDueChange(it) }, onDismiss = { pickerTarget = null }, ) diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicksTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicksTest.kt index c2307aa..6f12820 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicksTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicksTest.kt @@ -57,4 +57,23 @@ class QuickPicksTest { assertThat(defaultPickerDate(LocalTime.of(8, 0), now, start)).isEqualTo(LocalDate.of(2027, 1, 5)) assertThat(defaultPickerDate(LocalTime.of(20, 0), now, today.minusDays(3).atTime(9, 0))).isEqualTo(today) } + + @Test + fun `the default time keeps after the floor and before the ceiling`() { + val now = today.atTime(16, 30) + val start = LocalDate.of(2027, 1, 4).atTime(9, 0) + assertThat(defaultPickerTime(start.toLocalDate(), now, floor = start)).isEqualTo(LocalTime.of(10, 0)) + assertThat(defaultPickerTime(today.plusDays(1), now, floor = start)).isEqualTo(LocalTime.of(8, 0)) + val due = today.atTime(16, 45) + assertThat(defaultPickerTime(today, now, ceiling = due)).isEqualTo(LocalTime.of(16, 45)) + } + + @Test + fun `a time without a date does not land after the ceiling`() { + val now = today.atTime(16, 30) + val due = today.atTime(10, 0) + assertThat(defaultPickerDate(LocalTime.of(8, 0), now, ceiling = due)).isEqualTo(today) + assertThat(defaultPickerDate(LocalTime.of(12, 0), now, ceiling = due)).isEqualTo(today.minusDays(1)) + assertThat(defaultPickerDate(LocalTime.of(20, 0), now, ceiling = today.plusDays(3).atTime(9, 0))).isEqualTo(today) + } } From 3adfeb16a5808374da1ee135143a612ca2b68810 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Tue, 17 Nov 2026 16:31:17 +0100 Subject: [PATCH 5/8] Let start and due go without a time on their own (#101) --- CHANGELOG.md | 7 + .../7.json | 780 ++++++++++++++++++ .../tasks/room/TasksDatabaseMigrationTest.kt | 17 + .../agendula/data/di/DataModule.kt | 2 +- .../data/reminders/ReminderPlanner.kt | 20 +- .../agendula/data/reminders/TaskNotifier.kt | 5 +- .../agendula/data/tasks/TasksRepository.kt | 6 + .../data/tasks/TasksRepositoryImpl.kt | 3 + .../agendula/data/tasks/ical/VTodoMapper.kt | 39 +- .../data/tasks/provider/ProviderTaskWriter.kt | 9 + .../agendula/data/tasks/room/Converters.kt | 7 + .../agendula/data/tasks/room/Entities.kt | 3 + .../data/tasks/room/RoomTaskMapper.kt | 2 + .../data/tasks/room/RoomTasksDataSource.kt | 1 + .../data/tasks/room/TaskFormWriter.kt | 1 + .../agendula/data/tasks/room/TasksDatabase.kt | 9 +- .../data/tasks/transfer/ExternalImport.kt | 1 + .../agendula/domain/AllDayTime.kt | 20 + .../jeanlucmakiola/agendula/domain/Models.kt | 16 + .../agendula/domain/TaskForm.kt | 2 + .../agendula/domain/export/ExportModels.kt | 2 + .../agendula/domain/export/ICalendarWriter.kt | 9 +- .../agendula/domain/ical/ICalValues.kt | 11 + .../agendula/ui/detail/TaskDetailScreen.kt | 15 +- .../agendula/ui/edit/DateTimePickerSheet.kt | 90 +- .../agendula/ui/edit/QuickPicks.kt | 7 + .../agendula/ui/edit/TaskEditScreen.kt | 58 +- .../agendula/ui/edit/TaskEditViewModel.kt | 79 +- .../agendula/ui/lists/ListsScreen.kt | 3 +- .../agendula/ui/tasklist/TaskListScreen.kt | 3 +- .../agendula/widget/WidgetData.kt | 9 +- app/src/main/res/values/strings.xml | 3 + .../data/reminders/ReminderPlannerTest.kt | 20 + .../data/tasks/ical/VTodoMapperTest.kt | 96 +++ .../tasks/provider/ProviderTaskWriterTest.kt | 13 + .../agendula/domain/AllDayTimeTest.kt | 10 + .../domain/export/ICalendarWriterTest.kt | 12 +- .../agendula/ui/edit/QuickPicksTest.kt | 8 + .../agendula/ui/edit/TaskEditViewModelTest.kt | 85 ++ 39 files changed, 1379 insertions(+), 104 deletions(-) create mode 100644 app/schemas/de.jeanlucmakiola.agendula.data.tasks.room.TasksDatabase/7.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 6012b5d..89c3dee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,13 @@ All notable changes to this project are documented here. The format follows evening), so the date or the time can be changed on its own without walking through both pickers. A calendar and a clock are still there for anything else (#101). +- Start and due each have their own "No time", so one can be a plain date + while the other keeps its time; it replaces the all-day switch, and both + without a time is an all-day task as before. A date without a time beside a + timed one syncs as the start or the end of its day, marked so Agendula reads + it back as a date; other apps show that time. Reminders for it ring at the + all-day reminder time. With a tasks app as the store, both ends drop their + time together (#101). ## [1.3.2] - 2026-11-13 diff --git a/app/schemas/de.jeanlucmakiola.agendula.data.tasks.room.TasksDatabase/7.json b/app/schemas/de.jeanlucmakiola.agendula.data.tasks.room.TasksDatabase/7.json new file mode 100644 index 0000000..b2a704d --- /dev/null +++ b/app/schemas/de.jeanlucmakiola.agendula.data.tasks.room.TasksDatabase/7.json @@ -0,0 +1,780 @@ +{ + "formatVersion": 1, + "database": { + "version": 7, + "identityHash": "6b4e1394949216ad24168835d260a73f", + "entities": [ + { + "tableName": "accounts", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `display_name` TEXT NOT NULL, `principal_url` TEXT, `home_set_url` TEXT, `username` TEXT, `last_sync_at` INTEGER, `last_sync_error` TEXT, `label` TEXT)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "displayName", + "columnName": "display_name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "principalUrl", + "columnName": "principal_url", + "affinity": "TEXT" + }, + { + "fieldPath": "homeSetUrl", + "columnName": "home_set_url", + "affinity": "TEXT" + }, + { + "fieldPath": "username", + "columnName": "username", + "affinity": "TEXT" + }, + { + "fieldPath": "lastSyncAt", + "columnName": "last_sync_at", + "affinity": "INTEGER" + }, + { + "fieldPath": "lastSyncError", + "columnName": "last_sync_error", + "affinity": "TEXT" + }, + { + "fieldPath": "label", + "columnName": "label", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + } + }, + { + "tableName": "task_lists", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `color` INTEGER NOT NULL, `account_id` INTEGER, `is_visible` INTEGER NOT NULL DEFAULT 1, `is_synced` INTEGER NOT NULL DEFAULT 1, `owner` TEXT, `is_read_only` INTEGER NOT NULL DEFAULT 0, `sort_order` INTEGER NOT NULL DEFAULT 0, `href` TEXT, `ctag` TEXT, `sync_token` TEXT, `is_dirty` INTEGER NOT NULL DEFAULT 0, FOREIGN KEY(`account_id`) REFERENCES `accounts`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "color", + "columnName": "color", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "accountId", + "columnName": "account_id", + "affinity": "INTEGER" + }, + { + "fieldPath": "isVisible", + "columnName": "is_visible", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "1" + }, + { + "fieldPath": "isSynced", + "columnName": "is_synced", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "1" + }, + { + "fieldPath": "owner", + "columnName": "owner", + "affinity": "TEXT" + }, + { + "fieldPath": "isReadOnly", + "columnName": "is_read_only", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "sortOrder", + "columnName": "sort_order", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "href", + "columnName": "href", + "affinity": "TEXT" + }, + { + "fieldPath": "ctag", + "columnName": "ctag", + "affinity": "TEXT" + }, + { + "fieldPath": "syncToken", + "columnName": "sync_token", + "affinity": "TEXT" + }, + { + "fieldPath": "isDirty", + "columnName": "is_dirty", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_task_lists_account_id", + "unique": false, + "columnNames": [ + "account_id" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_task_lists_account_id` ON `${TABLE_NAME}` (`account_id`)" + } + ], + "foreignKeys": [ + { + "table": "accounts", + "onDelete": "SET NULL", + "onUpdate": "NO ACTION", + "columns": [ + "account_id" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "tasks", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `list_id` INTEGER NOT NULL, `uid` TEXT NOT NULL, `href` TEXT, `etag` TEXT, `title` TEXT, `description` TEXT, `location` TEXT, `url` TEXT, `color` INTEGER, `categories` TEXT NOT NULL DEFAULT '', `status` INTEGER NOT NULL DEFAULT 0, `percent_complete` INTEGER, `completed_at` INTEGER, `priority` INTEGER NOT NULL DEFAULT 0, `classification` INTEGER, `dtstart` INTEGER, `due` INTEGER, `duration` TEXT, `is_all_day` INTEGER NOT NULL DEFAULT 0, `untimed` TEXT, `timezone` TEXT, `rrule` TEXT, `rdate` TEXT, `exdate` TEXT, `recurrence_id` INTEGER, `master_id` INTEGER, `parent_id` INTEGER, `sort_order` INTEGER NOT NULL DEFAULT 0, `created_at` INTEGER, `last_modified` INTEGER, `sequence` INTEGER NOT NULL DEFAULT 0, `is_dirty` INTEGER NOT NULL DEFAULT 0, `is_deleted` INTEGER NOT NULL DEFAULT 0, `unknown_properties` TEXT, `reminders_off` INTEGER NOT NULL DEFAULT 0, FOREIGN KEY(`list_id`) REFERENCES `task_lists`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`master_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`parent_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "listId", + "columnName": "list_id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "uid", + "columnName": "uid", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "href", + "columnName": "href", + "affinity": "TEXT" + }, + { + "fieldPath": "etag", + "columnName": "etag", + "affinity": "TEXT" + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT" + }, + { + "fieldPath": "description", + "columnName": "description", + "affinity": "TEXT" + }, + { + "fieldPath": "location", + "columnName": "location", + "affinity": "TEXT" + }, + { + "fieldPath": "url", + "columnName": "url", + "affinity": "TEXT" + }, + { + "fieldPath": "color", + "columnName": "color", + "affinity": "INTEGER" + }, + { + "fieldPath": "categories", + "columnName": "categories", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "percentComplete", + "columnName": "percent_complete", + "affinity": "INTEGER" + }, + { + "fieldPath": "completedAt", + "columnName": "completed_at", + "affinity": "INTEGER" + }, + { + "fieldPath": "priority", + "columnName": "priority", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "classification", + "columnName": "classification", + "affinity": "INTEGER" + }, + { + "fieldPath": "dtstart", + "columnName": "dtstart", + "affinity": "INTEGER" + }, + { + "fieldPath": "due", + "columnName": "due", + "affinity": "INTEGER" + }, + { + "fieldPath": "duration", + "columnName": "duration", + "affinity": "TEXT" + }, + { + "fieldPath": "isAllDay", + "columnName": "is_all_day", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "untimed", + "columnName": "untimed", + "affinity": "TEXT" + }, + { + "fieldPath": "timezone", + "columnName": "timezone", + "affinity": "TEXT" + }, + { + "fieldPath": "rrule", + "columnName": "rrule", + "affinity": "TEXT" + }, + { + "fieldPath": "rdate", + "columnName": "rdate", + "affinity": "TEXT" + }, + { + "fieldPath": "exdate", + "columnName": "exdate", + "affinity": "TEXT" + }, + { + "fieldPath": "recurrenceId", + "columnName": "recurrence_id", + "affinity": "INTEGER" + }, + { + "fieldPath": "masterId", + "columnName": "master_id", + "affinity": "INTEGER" + }, + { + "fieldPath": "parentId", + "columnName": "parent_id", + "affinity": "INTEGER" + }, + { + "fieldPath": "sortOrder", + "columnName": "sort_order", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "createdAt", + "columnName": "created_at", + "affinity": "INTEGER" + }, + { + "fieldPath": "lastModified", + "columnName": "last_modified", + "affinity": "INTEGER" + }, + { + "fieldPath": "sequence", + "columnName": "sequence", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "isDirty", + "columnName": "is_dirty", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "isDeleted", + "columnName": "is_deleted", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "unknownProperties", + "columnName": "unknown_properties", + "affinity": "TEXT" + }, + { + "fieldPath": "remindersOff", + "columnName": "reminders_off", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_tasks_list_id_is_deleted", + "unique": false, + "columnNames": [ + "list_id", + "is_deleted" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_list_id_is_deleted` ON `${TABLE_NAME}` (`list_id`, `is_deleted`)" + }, + { + "name": "index_tasks_parent_id", + "unique": false, + "columnNames": [ + "parent_id" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_parent_id` ON `${TABLE_NAME}` (`parent_id`)" + }, + { + "name": "index_tasks_master_id_recurrence_id", + "unique": false, + "columnNames": [ + "master_id", + "recurrence_id" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_master_id_recurrence_id` ON `${TABLE_NAME}` (`master_id`, `recurrence_id`)" + }, + { + "name": "index_tasks_is_dirty", + "unique": false, + "columnNames": [ + "is_dirty" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_is_dirty` ON `${TABLE_NAME}` (`is_dirty`)" + }, + { + "name": "index_tasks_list_id_uid_recurrence_id", + "unique": true, + "columnNames": [ + "list_id", + "uid", + "recurrence_id" + ], + "orders": [], + "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_tasks_list_id_uid_recurrence_id` ON `${TABLE_NAME}` (`list_id`, `uid`, `recurrence_id`)" + } + ], + "foreignKeys": [ + { + "table": "task_lists", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "list_id" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "tasks", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "master_id" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "tasks", + "onDelete": "SET NULL", + "onUpdate": "NO ACTION", + "columns": [ + "parent_id" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "task_alarms", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task_id` INTEGER NOT NULL, `minutes_before` INTEGER NOT NULL, `reference` TEXT NOT NULL DEFAULT 'DUE', `message` TEXT, `uid` TEXT NOT NULL DEFAULT '', `raw` TEXT, FOREIGN KEY(`task_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "taskId", + "columnName": "task_id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "minutesBefore", + "columnName": "minutes_before", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "reference", + "columnName": "reference", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "'DUE'" + }, + { + "fieldPath": "message", + "columnName": "message", + "affinity": "TEXT" + }, + { + "fieldPath": "uid", + "columnName": "uid", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "raw", + "columnName": "raw", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_task_alarms_task_id", + "unique": false, + "columnNames": [ + "task_id" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_task_alarms_task_id` ON `${TABLE_NAME}` (`task_id`)" + } + ], + "foreignKeys": [ + { + "table": "tasks", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "task_id" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "advanced_occurrences", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`copy_id` INTEGER NOT NULL, `master_id` INTEGER NOT NULL, `anchor` INTEGER NOT NULL, `advanced_to` INTEGER NOT NULL, `prior_dtstart` INTEGER, `prior_due` INTEGER, `prior_status` INTEGER NOT NULL, `prior_percent_complete` INTEGER, `prior_completed_at` INTEGER, `spent` INTEGER NOT NULL, `rule_after` TEXT, `dropped_exdates` TEXT NOT NULL DEFAULT '', `from_override` INTEGER NOT NULL, `undoable` INTEGER NOT NULL DEFAULT 1, `settled` INTEGER NOT NULL DEFAULT 0, `reset_subtasks` TEXT NOT NULL DEFAULT '', PRIMARY KEY(`copy_id`), FOREIGN KEY(`copy_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`master_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "copyId", + "columnName": "copy_id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "masterId", + "columnName": "master_id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "anchor", + "columnName": "anchor", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "advancedTo", + "columnName": "advanced_to", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "priorDtstart", + "columnName": "prior_dtstart", + "affinity": "INTEGER" + }, + { + "fieldPath": "priorDue", + "columnName": "prior_due", + "affinity": "INTEGER" + }, + { + "fieldPath": "priorStatus", + "columnName": "prior_status", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "priorPercentComplete", + "columnName": "prior_percent_complete", + "affinity": "INTEGER" + }, + { + "fieldPath": "priorCompletedAt", + "columnName": "prior_completed_at", + "affinity": "INTEGER" + }, + { + "fieldPath": "spent", + "columnName": "spent", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "ruleAfter", + "columnName": "rule_after", + "affinity": "TEXT" + }, + { + "fieldPath": "droppedExdates", + "columnName": "dropped_exdates", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "fromOverride", + "columnName": "from_override", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "undoable", + "columnName": "undoable", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "1" + }, + { + "fieldPath": "settled", + "columnName": "settled", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "resetSubtasks", + "columnName": "reset_subtasks", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "copy_id" + ] + }, + "indices": [ + { + "name": "index_advanced_occurrences_master_id_anchor", + "unique": false, + "columnNames": [ + "master_id", + "anchor" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_advanced_occurrences_master_id_anchor` ON `${TABLE_NAME}` (`master_id`, `anchor`)" + } + ], + "foreignKeys": [ + { + "table": "tasks", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "copy_id" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "tasks", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "master_id" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "advanced_detached", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `copy_id` INTEGER NOT NULL, `anchor` INTEGER NOT NULL, `task_id` INTEGER, FOREIGN KEY(`copy_id`) REFERENCES `advanced_occurrences`(`copy_id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`task_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "copyId", + "columnName": "copy_id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "anchor", + "columnName": "anchor", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "taskId", + "columnName": "task_id", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_advanced_detached_copy_id", + "unique": false, + "columnNames": [ + "copy_id" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_advanced_detached_copy_id` ON `${TABLE_NAME}` (`copy_id`)" + }, + { + "name": "index_advanced_detached_task_id", + "unique": false, + "columnNames": [ + "task_id" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_advanced_detached_task_id` ON `${TABLE_NAME}` (`task_id`)" + } + ], + "foreignKeys": [ + { + "table": "advanced_occurrences", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "copy_id" + ], + "referencedColumns": [ + "copy_id" + ] + }, + { + "table": "tasks", + "onDelete": "SET NULL", + "onUpdate": "NO ACTION", + "columns": [ + "task_id" + ], + "referencedColumns": [ + "id" + ] + } + ] + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '6b4e1394949216ad24168835d260a73f')" + ] + } +} \ No newline at end of file diff --git a/app/src/androidTest/java/de/jeanlucmakiola/agendula/data/tasks/room/TasksDatabaseMigrationTest.kt b/app/src/androidTest/java/de/jeanlucmakiola/agendula/data/tasks/room/TasksDatabaseMigrationTest.kt index 0cd200c..84e60bb 100644 --- a/app/src/androidTest/java/de/jeanlucmakiola/agendula/data/tasks/room/TasksDatabaseMigrationTest.kt +++ b/app/src/androidTest/java/de/jeanlucmakiola/agendula/data/tasks/room/TasksDatabaseMigrationTest.kt @@ -193,6 +193,23 @@ class TasksDatabaseMigrationTest { } } + @Test + fun leavesExistingTasksWithBothEndsAsTheyWere() { + helper.createDatabase(TEST_DB, 6).use { db -> + db.execSQL("INSERT INTO task_lists (id, name, color) VALUES (1, 'Personal', 0)") + db.execSQL("INSERT INTO tasks (id, list_id, uid, dtstart, due, is_all_day) VALUES (1, 1, 'a', 0, 3600000, 0)") + } + + helper.runMigrationsAndValidate(TEST_DB, 7, true, TasksDatabase.MIGRATION_6_7).use { db -> + db.query("SELECT untimed, dtstart, due FROM tasks").use { c -> + assertThat(c.moveToFirst()).isTrue() + assertThat(c.isNull(0)).isTrue() + assertThat(c.getLong(1)).isEqualTo(0L) + assertThat(c.getLong(2)).isEqualTo(3_600_000L) + } + } + } + private companion object { const val TEST_DB = "migration-test.db" } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/di/DataModule.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/di/DataModule.kt index ab88919..6cf4785 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/di/DataModule.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/di/DataModule.kt @@ -89,7 +89,7 @@ object DataProvideModule { // backed-up `.db` does not. The backup rules carry all three files and // the app checkpoints on ON_STOP. .setJournalMode(RoomDatabase.JournalMode.WRITE_AHEAD_LOGGING) - .addMigrations(TasksDatabase.MIGRATION_1_2, TasksDatabase.MIGRATION_2_3, TasksDatabase.MIGRATION_3_4, TasksDatabase.MIGRATION_4_5, TasksDatabase.MIGRATION_5_6) + .addMigrations(TasksDatabase.MIGRATION_1_2, TasksDatabase.MIGRATION_2_3, TasksDatabase.MIGRATION_3_4, TasksDatabase.MIGRATION_4_5, TasksDatabase.MIGRATION_5_6, TasksDatabase.MIGRATION_6_7) .build() /** diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/ReminderPlanner.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/ReminderPlanner.kt index 7049d48..1ab41f6 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/ReminderPlanner.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/ReminderPlanner.kt @@ -3,6 +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.TaskReminder import de.jeanlucmakiola.agendula.domain.calendarDate import java.time.LocalTime @@ -54,7 +55,12 @@ internal object ReminderPlanner { .filter { (if (it.fromStart) task.start else task.due) != null } val created = task.created?.toEpochMilliseconds() reminders.mapNotNull { reminder -> - val anchor = if (reminder.fromStart) task.start ?: task.due!! else task.due ?: task.start!! + val end = when { + reminder.fromStart -> if (task.start != null) TaskEnd.START else TaskEnd.DUE + else -> if (task.due != null) TaskEnd.DUE else TaskEnd.START + } + val anchor = untimedAnchor(task, end, settings.allDayReminderMinuteOfDay, zone) + ?: if (end == TaskEnd.START) task.start!! else task.due!! val trigger = triggerAt( anchor, task.isAllDay, @@ -98,6 +104,18 @@ internal object ReminderPlanner { .take(MAX_ALARMS) .toSet() + /** + * A date without a time on a timed task rings at the all-day reminder time + * of its day, not at the midnight or last second it is stored as (#101). + */ + fun untimedAnchor(task: Task, end: TaskEnd, allDayMinuteOfDay: Int, zone: ZoneId): Instant? { + if (task.untimed != end || task.isAllDay) return null + val value = (if (end == TaskEnd.START) task.start else task.due) ?: return null + val time = LocalTime.of(allDayMinuteOfDay / 60 % 24, allDayMinuteOfDay % 60) + val millis = value.calendarDate(allDay = false, zone = zone).atTime(time).atZone(zone).toInstant().toEpochMilli() + return Instant.fromEpochMilliseconds(millis) + } + /** * When a reminder [leadMinutes] before [anchor] fires. * diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/TaskNotifier.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/TaskNotifier.kt index 081b2f9..bf5cada 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/TaskNotifier.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/TaskNotifier.kt @@ -21,6 +21,7 @@ import de.jeanlucmakiola.agendula.MainActivity import de.jeanlucmakiola.agendula.R import de.jeanlucmakiola.agendula.data.prefs.ReminderDescription import de.jeanlucmakiola.agendula.data.prefs.Settings +import de.jeanlucmakiola.agendula.domain.dueAsShown import de.jeanlucmakiola.agendula.domain.readableDescription import de.jeanlucmakiola.agendula.data.prefs.is24Hour import de.jeanlucmakiola.agendula.data.di.ApplicationScope @@ -74,12 +75,12 @@ class TaskNotifier @Inject constructor( if (!canPost()) return val channelId = ensureListChannel(task.listId, task.listName) val title = task.title.ifBlank { context.getString(R.string.task_untitled) } - val text = task.due?.let { due -> + val text = task.dueAsShown?.let { due -> context.getString( R.string.reminder_due_at, formatReminderDue( due.toEpochMilliseconds(), - task.isAllDay, + !task.dueHasTime, is24Hour = settings.timeFormat.is24Hour(DateFormat.is24HourFormat(context)), relative = RelativeDays( today = context.getString(R.string.reminder_day_today), 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..5c14f95 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,10 @@ interface TasksRepository { /** Synchronous snapshot for the permission/onboarding gate. */ fun providerStatus(): ProviderStatus + + /** + * Whether the store keeps one end of a timed task without a time (#101). + * A provider's single `IS_ALLDAY` cannot, so there both ends go together. + */ + fun supportsUntimedEnds(): Boolean = true } 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..9bc658e 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 @@ -143,6 +143,7 @@ class TasksRepositoryImpl @Inject constructor( start = task.start, due = task.due, isAllDay = task.isAllDay, + untimed = task.untimed, priority = task.priority, parentId = parentId, location = task.location, @@ -265,6 +266,8 @@ class TasksRepositoryImpl @Inject constructor( override suspend fun reorderLists(listIds: List) = withContext(io) { dataSource.reorderLists(listIds) } + override fun supportsUntimedEnds(): 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/ical/VTodoMapper.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapper.kt index 92b8383..eaa8172 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapper.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapper.kt @@ -3,6 +3,7 @@ package de.jeanlucmakiola.agendula.data.tasks.ical 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.TaskStatus import de.jeanlucmakiola.agendula.domain.ical.ICalComponent import de.jeanlucmakiola.agendula.domain.ical.ICalParam @@ -156,12 +157,19 @@ object VTodoMapper { // date/date-time pair into two DATEs and destroys the time half. 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. + val untimed = when { + allDay || dtstart.noTime == due.noTime -> null + dtstart.noTime -> TaskEnd.START + else -> TaskEnd.DUE + } // Claim a stamp only when the single is_all_day flag and the single // timezone column can reproduce it. Otherwise it stays in the residue and // is re-emitted exactly as it arrived. - if (dtstart.reproducible(allDay, timezone)) claim(dtstart.property) - if (due.reproducible(allDay, timezone)) claim(due.property) + if (dtstart.reproducible(allDay, timezone, untimed == TaskEnd.START)) claim(dtstart.property) + if (due.reproducible(allDay, timezone, untimed == TaskEnd.DUE)) claim(due.property) val recurrenceId = readTime(vtodo, "RECURRENCE-ID") if (recurrenceId.reproducible(allDay, timezone)) claim(recurrenceId.property) @@ -247,6 +255,7 @@ object VTodoMapper { due = due.instant, duration = take(vtodo.property("DURATION"), vtodo.property("DURATION")?.value?.trim()), isAllDay = allDay, + untimed = untimed, timezone = timezone, rrule = take(vtodo.property("RRULE"), vtodo.property("RRULE")?.value?.trim()), rdate = dateList(vtodo, "RDATE", ::claim), @@ -430,8 +439,10 @@ object VTodoMapper { ICalValues.readInstant(ICalValues.parseTime(property)) == column return when (property.name.uppercase()) { - "DTSTART" -> !sameInstant(entity.dtstart) - "DUE" -> !sameInstant(entity.due) + "DTSTART" -> !sameInstant(entity.dtstart) || + ICalValues.isMarkedNoTime(property) != (entity.untimed == TaskEnd.START) + "DUE" -> !sameInstant(entity.due) || + ICalValues.isMarkedNoTime(property) != (entity.untimed == TaskEnd.DUE) "COMPLETED" -> !sameInstant(entity.completedAt) "RECURRENCE-ID" -> !sameInstant(entity.recurrenceId) "RDATE" -> listChanged(entity.rdate) @@ -531,9 +542,12 @@ object VTodoMapper { ) { val present get() = property != null - /** True when one `is_all_day` flag and one `timezone` column reproduce it. */ - fun reproducible(allDay: Boolean, timezone: String?) = - present && representable && isDate == allDay && tzid == timezone + /** A date-time marked as standing for a date alone. */ + val noTime get() = property != null && !isDate && ICalValues.isMarkedNoTime(property) + + /** True when one `is_all_day` flag, one `timezone` column and the untimed end reproduce it. */ + fun reproducible(allDay: Boolean, timezone: String?, untimed: Boolean = false) = + present && representable && isDate == allDay && tzid == timezone && noTime == untimed /** True when it is a UTC date-time — the only form we author for these. */ val isUtcDateTime get() = present && representable && !isDate && tzid == null @@ -563,10 +577,19 @@ 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 = if (tzid == null) emptyList() else listOf(ICalParam("TZID", tzid)) + val params = buildList { + if (entity.untimed?.propertyName == name) add(ICalParam(ICalValues.NO_TIME_PARAM, "TRUE")) + if (tzid != null) add(ICalParam("TZID", tzid)) + } return ICalProperty(name, params, ICalValues.formatDateTime(instant, tzid)) } + private val TaskEnd.propertyName: String + get() = when (this) { + TaskEnd.START -> "DTSTART" + TaskEnd.DUE -> "DUE" + } + /** The same DATE test [ICalValues.parseTime] applies, so the two cannot disagree. */ private fun isDateValue(property: ICalProperty): Boolean = ICalValues.parseTime(property) is ICalValues.TimeValue.Date diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/provider/ProviderTaskWriter.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/provider/ProviderTaskWriter.kt index 0fa71c6..8eddb6c 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/provider/ProviderTaskWriter.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/provider/ProviderTaskWriter.kt @@ -4,6 +4,7 @@ import de.jeanlucmakiola.agendula.data.tasks.TasksContract import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Tasks import de.jeanlucmakiola.agendula.data.tasks.room.TaskEntity import de.jeanlucmakiola.agendula.data.tasks.room.forAllDay +import de.jeanlucmakiola.agendula.domain.TaskEnd import de.jeanlucmakiola.agendula.domain.TaskStatus import de.jeanlucmakiola.agendula.domain.statusFromInt import org.dmfs.rfc5545.recur.RecurrenceRule @@ -156,6 +157,14 @@ 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. + untimed = current.untimed?.takeUnless { end -> + allDay || when (end) { + TaskEnd.START -> dtstart != current.dtstart + TaskEnd.DUE -> due != current.due + } + }, timezone = timezone, rrule = rrule, rdate = rdate, diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/room/Converters.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/room/Converters.kt index caf307d..a2133cb 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/room/Converters.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/room/Converters.kt @@ -1,6 +1,7 @@ package de.jeanlucmakiola.agendula.data.tasks.room import androidx.room.TypeConverter +import de.jeanlucmakiola.agendula.domain.TaskEnd import de.jeanlucmakiola.agendula.domain.TaskStatus import de.jeanlucmakiola.agendula.domain.ical.ICalValues import de.jeanlucmakiola.agendula.domain.normalizeTags @@ -31,6 +32,12 @@ object Converters { @TypeConverter fun statusFrom(value: Int): TaskStatus = statusFromInt(value) + @TypeConverter + fun taskEndToString(value: TaskEnd?): String? = value?.name + + @TypeConverter + fun taskEndFrom(value: String?): TaskEnd? = value?.let { runCatching { TaskEnd.valueOf(it) }.getOrNull() } + @TypeConverter fun alarmReferenceToString(value: AlarmReference): String = value.name diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/room/Entities.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/room/Entities.kt index d668783..54347e3 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/room/Entities.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/room/Entities.kt @@ -7,6 +7,7 @@ import androidx.room.Index import androidx.room.PrimaryKey import androidx.room.TypeConverters import de.jeanlucmakiola.agendula.domain.PRIORITY_NONE +import de.jeanlucmakiola.agendula.domain.TaskEnd import de.jeanlucmakiola.agendula.domain.TaskStatus import java.util.UUID import kotlin.time.Instant @@ -173,6 +174,8 @@ data class TaskEntity( /** RFC 5545 `DURATION`, verbatim. Mutually exclusive with [due]. */ @ColumnInfo(name = "duration") val duration: String? = null, @ColumnInfo(name = "is_all_day", defaultValue = "0") val isAllDay: Boolean = false, + /** The end stored as a date without a time on an otherwise timed task (#101); see [TaskEnd]. */ + @ColumnInfo(name = "untimed") val untimed: TaskEnd? = null, @ColumnInfo(name = "timezone") val timezone: String? = null, // recurrence 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..30ae0eb 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 @@ -72,6 +72,7 @@ object RoomTaskMapper { seriesId = seriesId, recurrenceRule = recurrenceRule, isReadOnly = row.listReadOnly, + untimed = row.task.untimed, ) fun exportTask(task: TaskEntity): ExportTask = ExportTask( @@ -94,6 +95,7 @@ object RoomTaskMapper { rrule = task.rrule, rdate = task.rdate, parentId = task.parentId?.takeIf { it > 0 }, + untimed = task.untimed, ) } 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..2a1b6b9 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 @@ -588,6 +588,7 @@ class RoomTasksDataSource @Inject constructor( return text(a.title) == text(b.title) && text(a.description) == text(b.description) && text(a.location) == text(b.location) && text(a.url) == text(b.url) && a.priority == b.priority && a.dtstart == b.dtstart && a.due == b.due && a.isAllDay == b.isAllDay && + a.untimed == b.untimed && a.listId == b.listId && a.parentId == b.parentId && a.rrule == b.rrule && a.rdate == b.rdate && normalizeTags(a.categories) == normalizeTags(b.categories) && a.color == b.color } 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..db87a50 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 @@ -61,6 +61,7 @@ object TaskFormWriter { // DUE and DURATION are mutually exclusive (RFC 5545 §3.6.2). duration = null, isAllDay = form.isAllDay, + untimed = form.untimed.takeUnless { form.isAllDay }, timezone = if (timed) tzId else null, parentId = form.parentId?.takeIf { it > 0 }, remindersOff = if (form.remindersChosen) form.reminders.isEmpty() else current.remindersOff, diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/room/TasksDatabase.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/room/TasksDatabase.kt index 84e1cb8..f93a22f 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/room/TasksDatabase.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/room/TasksDatabase.kt @@ -24,7 +24,7 @@ import kotlin.time.Instant AdvancedOccurrenceEntity::class, AdvancedDetachedEntity::class, ], - version = 6, + version = 7, exportSchema = true, ) @TypeConverters(Converters::class) @@ -211,5 +211,12 @@ abstract class TasksDatabase : RoomDatabase() { db.execSQL("ALTER TABLE advanced_occurrences ADD COLUMN `reset_subtasks` TEXT NOT NULL DEFAULT ''") } } + + /** v7 lets one end of a timed task go without a time (#101). */ + val MIGRATION_6_7 = object : Migration(6, 7) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL("ALTER TABLE tasks ADD COLUMN `untimed` TEXT") + } + } } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/transfer/ExternalImport.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/transfer/ExternalImport.kt index b08107b..e21774f 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/transfer/ExternalImport.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/transfer/ExternalImport.kt @@ -224,6 +224,7 @@ class ExternalImport @Inject constructor( dtstart = start, due = due, isAllDay = isAllDay, + untimed = untimed, rrule = rrule, rdate = rdate, createdAt = created, diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/AllDayTime.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/AllDayTime.kt index e86fca0..7a455d9 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/AllDayTime.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/AllDayTime.kt @@ -40,3 +40,23 @@ fun Instant.rebasedForAllDay(allDay: Boolean, zone: ZoneId = ZoneId.systemDefaul else Instant.fromEpochMilliseconds( calendarDate(allDay = true).atStartOfDay(zone).toInstant().toEpochMilli(), ) + +/** + * The one end of a task's span that has a date but no time of day while the + * other end has one (#101). Both ends without a time are an all-day task. + * + * RFC 5545 makes `DTSTART` and `DUE` share a value type, so such a task is + * timed on the wire and in storage: the untimed end is the start of its day + * ([START]) or its last second ([DUE]) in the device zone, and only this flag + * (`X-AGENDULA-NO-TIME` on the property) says it carries no time. + */ +enum class TaskEnd { START, DUE } + +/** The stored instant for [date] on an untimed [end]: the first or the last second of the day. */ +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) + } + return Instant.fromEpochMilliseconds(local.atZone(zone).toInstant().toEpochMilli()) +} 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..6195365 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/Models.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/Models.kt @@ -109,7 +109,15 @@ data class Task( * server, and the dirty row would then block every later download of it. */ val isReadOnly: Boolean = false, + /** The end that has a date but no time while the other has one; see [TaskEnd]. */ + val untimed: TaskEnd? = null, ) { + /** Whether [start] carries a time of day. */ + val startHasTime: Boolean get() = !isAllDay && untimed != TaskEnd.START + + /** Whether [due] carries a time of day. */ + val dueHasTime: Boolean get() = !isAllDay && untimed != TaskEnd.DUE + /** One occurrence of a series, whether generated or overridden. */ val isOccurrence: Boolean get() = seriesId != null && occurrenceStart != null @@ -129,6 +137,14 @@ data class Task( get() = if (occurrenceStart == null) "$taskId" else "$taskId@${occurrenceStart.toEpochMilliseconds()}" } +/** + * [Task.due] for code that shows a date without a time by the all-day + * convention: an untimed due becomes the all-day value of its date. Read it + * with `allDay = !dueHasTime`. + */ +val Task.dueAsShown: Instant? + get() = if (dueHasTime || isAllDay) due else due?.let { allDayInstantOf(it.calendarDate(allDay = false)) } + /** Detail bundle: a task, its parent (if it's a subtask), and its direct children. */ data class TaskDetail( val task: Task, 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..aeb59ee 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, + /** The end without a time on an otherwise timed task; see [TaskEnd]. */ + val untimed: TaskEnd? = null, ) { fun validate(): Set = buildSet { if (title.isBlank()) add(TaskFormError.BLANK_TITLE) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/export/ExportModels.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/export/ExportModels.kt index 8bc65a7..1da0013 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/export/ExportModels.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/export/ExportModels.kt @@ -43,6 +43,8 @@ data class ExportTask( /** `tasks._id` of the parent, for `RELATED-TO;RELTYPE=PARENT`. */ val parentId: Long?, val tags: List = emptyList(), + /** See [de.jeanlucmakiola.agendula.domain.TaskEnd]. */ + val untimed: de.jeanlucmakiola.agendula.domain.TaskEnd? = null, ) /** A task list and everything in it, ready to become one `.ics` document. */ diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/export/ICalendarWriter.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/export/ICalendarWriter.kt index bdd16e2..9329c9c 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/export/ICalendarWriter.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/export/ICalendarWriter.kt @@ -1,6 +1,7 @@ package de.jeanlucmakiola.agendula.domain.export import de.jeanlucmakiola.agendula.domain.Priority +import de.jeanlucmakiola.agendula.domain.TaskEnd import de.jeanlucmakiola.agendula.domain.TaskStatus import de.jeanlucmakiola.agendula.domain.calendarDate import de.jeanlucmakiola.agendula.domain.ical.ICalSerializer @@ -90,8 +91,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.due?.let { dateProperty("DUE", it, task.isAllDay) } + 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.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. @@ -116,11 +117,13 @@ object ICalendarWriter { line("END:VTODO") } - private fun StringBuilder.dateProperty(name: String, instant: Instant, allDay: Boolean) { + private fun StringBuilder.dateProperty(name: String, instant: Instant, allDay: Boolean, untimed: Boolean) { if (allDay) { // 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 { rawProperty(name, formatUtc(instant)) } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/ical/ICalValues.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/ical/ICalValues.kt index f5bc0e1..0c9208a 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/ical/ICalValues.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/ical/ICalValues.kt @@ -14,6 +14,17 @@ object ICalValues { private val DATE = DateTimeFormatter.ofPattern("yyyyMMdd") private val DATE_TIME = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss") + /** + * 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. + */ + const val NO_TIME_PARAM = "X-AGENDULA-NO-TIME" + + /** Whether [property] carries [NO_TIME_PARAM]. */ + fun isMarkedNoTime(property: ICalProperty): Boolean = + property.param(NO_TIME_PARAM).equals("TRUE", ignoreCase = true) + /** * RFC 5545 §3.3.11. Note the asymmetry with [unescapeText]: a literal colon * needs no escape in a property value, and escaping it is a common bug that 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..557b7a5 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 @@ -720,12 +720,19 @@ private fun taskWhenLines(task: Task): Pair? { val primary = if (sameDay) due.formatDate(allDay) else "${start.formatDate(allDay)} – ${due.formatDate(allDay)}" - val secondary = if (allDay) null else "${start.formatTime(use24)} – ${due.formatTime(use24)}" + // One end without a time (#101) keeps its side of the range open. + val startTime = start.takeIf { task.startHasTime }?.formatTime(use24) + val dueTime = due.takeIf { task.dueHasTime }?.formatTime(use24) + val secondary = when { + startTime != null && dueTime != null -> "$startTime – $dueTime" + startTime != null -> "$startTime –" + dueTime != null -> "– $dueTime" + else -> null + } primary to secondary } - due != null -> due.formatDate(task.isAllDay) to if (task.isAllDay) null else due.formatTime(use24) - start != null -> - start.formatDate(task.isAllDay) to if (task.isAllDay) null else start.formatTime(use24) + due != null -> due.formatDate(task.isAllDay) to due.takeIf { task.dueHasTime }?.formatTime(use24) + start != null -> start.formatDate(task.isAllDay) to start.takeIf { task.startHasTime }?.formatTime(use24) else -> null } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/DateTimePickerSheet.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/DateTimePickerSheet.kt index f0eefbb..1bd0eaf 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/DateTimePickerSheet.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/DateTimePickerSheet.kt @@ -14,13 +14,11 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import de.jeanlucmakiola.agendula.R -import de.jeanlucmakiola.agendula.domain.allDayInstantOf import de.jeanlucmakiola.agendula.domain.calendarDate import de.jeanlucmakiola.agendula.ui.common.DatePickerAlert import de.jeanlucmakiola.agendula.ui.common.LocalUse24HourFormat import de.jeanlucmakiola.agendula.ui.common.TimePickerAlert import de.jeanlucmakiola.agendula.ui.common.formatMinuteOfDay -import de.jeanlucmakiola.agendula.ui.common.localToInstant import de.jeanlucmakiola.agendula.ui.common.toLocalTime import de.jeanlucmakiola.floret.components.FullScreenPicker import de.jeanlucmakiola.floret.components.GroupedRow @@ -38,27 +36,32 @@ import kotlin.time.Instant /** * Start / due picker (#101): quick dates and preset times of day in one * full-screen sheet, so either half can be changed without walking through the - * other. A tap that completes the value applies it and closes: any time, or a - * date when the value already has a time (or is all-day). A date for a value - * without a time is staged with a default time and committed by Done. Back - * discards anything staged. + * other, and "No time" for a date alone. A tap that completes the value applies + * it and closes: any time, "No time", or a date for a value that is already + * set. A date for an empty value is staged with a default time and committed by + * Done. Back discards anything staged. * - * [notBefore] / [notAfter] keep a date or time filled in for an empty value on - * the right side of the other end (the start for a due, the due for a start). + * [initial] is read as all-day when [allDay], and its time only when + * [hasTime]. [noTimeNote] explains a "No time" that also takes the other end's + * time. [notBefore] / [notAfter] keep a date or time filled in for an empty + * value on the right side of the other end (the start for a due, the due for a + * start). [onChange] gets the date and the time, null for none. */ @Composable internal fun DateTimePickerSheet( title: String, initial: Instant?, allDay: Boolean, + hasTime: Boolean, + noTimeNote: String?, notBefore: Instant?, notAfter: Instant?, - onChange: (Instant) -> Unit, + onChange: (LocalDate, LocalTime?) -> Unit, onDismiss: () -> Unit, ) { - val staging = initial == null && !allDay + val staging = initial == null var date by rememberSaveable { mutableStateOf(initial?.calendarDate(allDay)) } - var time by rememberSaveable { mutableStateOf(initial?.takeUnless { allDay }?.toLocalTime()) } + var time by rememberSaveable { mutableStateOf(initial?.takeIf { hasTime }?.toLocalTime()) } var showCalendar by rememberSaveable { mutableStateOf(false) } var showClock by rememberSaveable { mutableStateOf(false) } @@ -73,22 +76,20 @@ internal fun DateTimePickerSheet( val ceiling = notAfter?.toLocalDateTime() fun stagedTime(d: LocalDate) = defaultPickerTime(d, LocalDateTime.now(), floor, ceiling) - fun commit(value: Instant) { - onChange(value) + fun commit(d: LocalDate, t: LocalTime?) { + onChange(d, t) onDismiss() } fun pickDate(d: LocalDate) { - when { - allDay -> commit(allDayInstantOf(d)) - staging -> { - date = d - time = stagedTime(d) - } - else -> commit(localToInstant(d, checkNotNull(time))) + if (staging) { + date = d + time = stagedTime(d) + } else { + commit(d, time) } } fun pickTime(t: LocalTime) { - commit(localToInstant(date ?: defaultPickerDate(t, LocalDateTime.now(), floor, ceiling), t)) + commit(date ?: defaultPickerDate(t, LocalDateTime.now(), floor, ceiling), t) } FullScreenPicker( @@ -97,7 +98,7 @@ internal fun DateTimePickerSheet( actions = { if (staging) { TextButton( - onClick = { date?.let { commit(localToInstant(it, stagedTime(it))) } }, + onClick = { date?.let { commit(it, stagedTime(it)) } }, enabled = date != null, ) { Text(stringResource(R.string.picker_done)) } } @@ -124,29 +125,34 @@ internal fun DateTimePickerSheet( onClick = { showCalendar = true }, ) - if (!allDay) { - val quickTime = time?.let { QuickTime.of(it) } - val timeRows = QuickTime.entries.size + 1 - Spacer(Modifier.height(8.dp)) - GroupedSectionHeader(stringResource(R.string.picker_section_time)) - QuickTime.entries.forEachIndexed { index, quick -> - GroupedRow( - title = stringResource(quick.labelRes), - summary = timeLabel(quick.time), - position = positionOf(index, timeRows), - checked = quick == quickTime, - onClick = { pickTime(quick.time) }, - ) - } - val customTime = time?.takeIf { quickTime == null } + val quickTime = time?.let { QuickTime.of(it) } + val timeRows = QuickTime.entries.size + 2 + Spacer(Modifier.height(8.dp)) + GroupedSectionHeader(stringResource(R.string.picker_section_time)) + QuickTime.entries.forEachIndexed { index, quick -> GroupedRow( - title = stringResource(R.string.picker_time_custom), - summary = customTime?.let(::timeLabel), - position = positionOf(QuickTime.entries.size, timeRows), - checked = customTime != null, - onClick = { showClock = true }, + title = stringResource(quick.labelRes), + summary = timeLabel(quick.time), + position = positionOf(index, timeRows), + checked = quick == quickTime, + onClick = { pickTime(quick.time) }, ) } + val customTime = time?.takeIf { quickTime == null } + GroupedRow( + title = stringResource(R.string.picker_time_custom), + summary = customTime?.let(::timeLabel), + position = positionOf(QuickTime.entries.size, timeRows), + checked = customTime != null, + onClick = { showClock = true }, + ) + GroupedRow( + title = stringResource(R.string.picker_time_none), + summary = noTimeNote, + position = positionOf(QuickTime.entries.size + 1, timeRows), + checked = date != null && time == null, + onClick = { commit(date ?: defaultNoTimeDate(today, floor, ceiling), null) }, + ) } if (showCalendar) { diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicks.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicks.kt index 51ed9b0..7281ef2 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicks.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicks.kt @@ -71,3 +71,10 @@ internal fun defaultPickerDate( val last = ceiling.toLocalDate() return if (last.atTime(time) <= ceiling) last else last.minusDays(1) } + +/** Date for "No time" picked without one: today, or the nearest day [floor] and [ceiling] allow. */ +internal fun defaultNoTimeDate(today: LocalDate, floor: LocalDateTime? = null, ceiling: LocalDateTime? = null): LocalDate { + val day = floor?.toLocalDate()?.takeIf { it > today } ?: today + val last = ceiling?.toLocalDate() + return if (last != null && day > last) last else day +} 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 7bda8db..5bea5fc 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 @@ -91,7 +91,6 @@ import androidx.compose.material3.SegmentedButtonDefaults import androidx.compose.material3.SingleChoiceSegmentedButtonRow import androidx.compose.material3.Slider import androidx.compose.material3.Surface -import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.TopAppBar @@ -120,6 +119,7 @@ import de.jeanlucmakiola.agendula.R 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.TaskFormError import de.jeanlucmakiola.agendula.domain.TaskFormField import de.jeanlucmakiola.agendula.domain.TaskList @@ -314,34 +314,28 @@ private fun EditContent( Spacer(Modifier.height(20.dp)) - // "When" card: the icon centres on the all-day row (header); the start / - // due rows continue below in the same text column. + // "When" card: the icon centres on the start row (header); the due row + // continues below in the same text column. Each end has its own "No + // time", so there is no all-day switch (#101). EditCard( icon = Icons.Rounded.Schedule, iconContentDescription = stringResource(R.string.edit_when), header = { - Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) { - Text( - text = stringResource(R.string.edit_all_day), - style = MaterialTheme.typography.titleMedium, - modifier = Modifier.weight(1f), - ) - Switch(checked = state.isAllDay, onCheckedChange = viewModel::onAllDayChange) - } + ScheduleRow( + label = stringResource(R.string.edit_start_label), + value = state.start, + allDay = state.isAllDay, + hasTime = state.hasTime(TaskEnd.START), + onPick = { pickerTarget = PickerTarget.Start }, + onClear = { viewModel.onStartChange(null) }, + ) }, ) { - Spacer(Modifier.height(4.dp)) - ScheduleRow( - label = stringResource(R.string.edit_start_label), - value = state.start, - allDay = state.isAllDay, - onPick = { pickerTarget = PickerTarget.Start }, - onClear = { viewModel.onStartChange(null) }, - ) ScheduleRow( label = stringResource(R.string.edit_due_label), value = state.due, allDay = state.isAllDay, + hasTime = state.hasTime(TaskEnd.DUE), onPick = { pickerTarget = PickerTarget.Due }, onClear = { viewModel.onDueChange(null) }, isError = TaskFormError.DUE_BEFORE_START in state.errors, @@ -655,14 +649,23 @@ private fun EditContent( } pickerTarget?.let { target -> - val current = if (target == PickerTarget.Start) state.start else state.due + val end = if (target == PickerTarget.Start) TaskEnd.START else TaskEnd.DUE + val other = if (end == TaskEnd.START) TaskEnd.DUE else TaskEnd.START + // A store without per-end times drops both together; say so where it would bite. + val noTimeNote = if (!state.untimedEnds && state.valueOf(other) != null && state.hasTime(other)) { + stringResource(if (other == TaskEnd.DUE) R.string.picker_time_none_also_due else R.string.picker_time_none_also_start) + } else { + null + } DateTimePickerSheet( title = stringResource(if (target == PickerTarget.Start) R.string.edit_start_label else R.string.edit_due_label), - initial = current, + initial = state.valueOf(end), allDay = state.isAllDay, - notBefore = state.start.takeIf { target == PickerTarget.Due }, - notAfter = state.due.takeIf { target == PickerTarget.Start }, - onChange = { if (target == PickerTarget.Start) viewModel.onStartChange(it) else viewModel.onDueChange(it) }, + hasTime = state.hasTime(end), + noTimeNote = noTimeNote, + notBefore = state.start.takeIf { end == TaskEnd.DUE }, + notAfter = state.due.takeIf { end == TaskEnd.START }, + onChange = { date, time -> viewModel.onWhenChange(end, date, time) }, onDismiss = { pickerTarget = null }, ) } @@ -883,8 +886,8 @@ private fun InlineField( } /** - * One schedule row: label, then the tappable date and (unless all-day) time — - * or "Set" when empty. Tapping runs the date → time picker flow; a clear + * One schedule row: label, then the tappable date and (when [hasTime]) time — + * or "Set" when empty. Tapping opens the date / time sheet; a clear * affordance appears once a value is set. Tappable values read as links * (primary); an error flips them to the error colour. */ @@ -894,6 +897,7 @@ private fun ScheduleRow( label: String, value: Instant?, allDay: Boolean, + hasTime: Boolean, onPick: () -> Unit, onClear: () -> Unit, isError: Boolean = false, @@ -930,7 +934,7 @@ private fun ScheduleRow( color = valueColor, modifier = valueModifier, ) - if (!allDay) { + if (hasTime) { Text( text = value.formatTime(LocalUse24HourFormat.current), style = MaterialTheme.typography.titleMedium, 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..2e0f638 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 @@ -16,6 +16,10 @@ import de.jeanlucmakiola.agendula.domain.TaskForm import de.jeanlucmakiola.agendula.domain.TaskFormError import de.jeanlucmakiola.agendula.domain.TaskFormField import de.jeanlucmakiola.agendula.domain.allDayInstantOf +import de.jeanlucmakiola.agendula.domain.TaskEnd +import de.jeanlucmakiola.agendula.domain.calendarDate +import de.jeanlucmakiola.agendula.domain.untimedInstantOf +import de.jeanlucmakiola.agendula.ui.common.localToInstant import de.jeanlucmakiola.agendula.domain.TaskList import de.jeanlucmakiola.agendula.domain.TaskReminder import de.jeanlucmakiola.agendula.domain.taskReminderDisplayOrder @@ -36,6 +40,7 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import java.time.LocalDate +import java.time.LocalTime import javax.inject.Inject import kotlin.time.Clock import kotlin.time.Instant @@ -56,6 +61,10 @@ data class TaskEditUiState( val start: Instant? = null, val due: Instant? = null, val isAllDay: Boolean = false, + /** The end without a time beside a timed one; see [TaskEnd]. */ + val untimed: TaskEnd? = null, + /** Whether the store keeps [untimed]; otherwise both ends have a time or neither does. */ + val untimedEnds: Boolean = true, val priority: Priority = Priority.NONE, val parentId: Long? = null, val percentComplete: Int? = null, @@ -104,6 +113,11 @@ data class TaskEditUiState( val writableLists: List get() = lists.filter { it.acceptsWrites || it.id == listId } val recurrenceChanged: Boolean get() = rrule != originalRule + + fun valueOf(end: TaskEnd): Instant? = if (end == TaskEnd.START) start else due + + /** Whether [end] carries a time of day, as opposed to a date alone. */ + fun hasTime(end: TaskEnd): Boolean = !isAllDay && untimed != end } @HiltViewModel @@ -206,6 +220,7 @@ class TaskEditViewModel @Inject constructor( // The same all-day value picking the date in the date field gives. due = presetDue?.let(::allDayInstantOf), isAllDay = presetDue != null, + untimedEnds = repository.supportsUntimedEnds(), priority = preset?.priority ?: Priority.NONE, parentId = parentId, lists = lists, @@ -252,6 +267,8 @@ class TaskEditViewModel @Inject constructor( start = task.start, due = task.due, isAllDay = task.isAllDay, + untimed = task.untimed, + untimedEnds = repository.supportsUntimedEnds(), priority = task.priority, parentId = task.parentId, percentComplete = task.percentComplete, @@ -334,14 +351,51 @@ class TaskEditViewModel @Inject constructor( } fun onStartChange(value: Instant?) = update { - val next = it.copy(start = value) + val next = it.copy(start = value, untimed = it.untimed.takeUnless { end -> end == TaskEnd.START && value == null }) next.withDatedReminders(lostDates = it.hasDates && !next.hasDates) } fun onDueChange(value: Instant?) = update { - val next = it.copy(due = value) + val next = it.copy(due = value, untimed = it.untimed.takeUnless { end -> end == TaskEnd.DUE && value == null }) next.withDatedReminders(lostDates = it.hasDates && !next.hasDates) } + + /** + * Sets [end] to [date] at [time], or to the date alone when [time] is null + * (#101). With the other end also without a time, or a store that cannot + * keep one end apart, that makes the whole task all-day; a time on one end + * of an all-day task leaves the other end's date without one. + */ + fun onWhenChange(end: TaskEnd, date: LocalDate, time: LocalTime?) = update { s -> + val other = if (end == TaskEnd.START) TaskEnd.DUE else TaskEnd.START + val otherValue = s.valueOf(other) + val allDay = time == null && (otherValue == null || !s.hasTime(other) || !s.untimedEnds) + val value = when { + time != null -> localToInstant(date, time) + allDay -> allDayInstantOf(date) + else -> untimedInstantOf(end, date) + } + val otherNext = otherValue?.let { at -> + when { + allDay == s.isAllDay -> at + allDay -> allDayInstantOf(at.calendarDate(allDay = false)) + else -> untimedInstantOf(other, at.calendarDate(allDay = true)) + } + } + val untimed = when { + allDay -> null + time == null -> end + s.isAllDay -> other.takeIf { otherValue != null && s.untimedEnds } + else -> s.untimed.takeUnless { e -> e == end } + } + val next = s.copy( + start = if (end == TaskEnd.START) value else otherNext, + due = if (end == TaskEnd.DUE) value else otherNext, + isAllDay = allDay, + untimed = untimed, + ) + if (allDay == s.isAllDay) next.withDatedReminders() else switchedKind(s, next) + } /** * All-day and timed values use different conventions (UTC midnight vs. a real * instant in the device zone), so the switch has to move the timestamps too — @@ -352,24 +406,32 @@ class TaskEditViewModel @Inject constructor( */ fun onAllDayChange(value: Boolean) = update { if (it.isAllDay == value) return@update it - val switched = it.copy( - isAllDay = value, - start = it.start?.rebasedForAllDay(value), - due = it.due?.rebasedForAllDay(value), + switchedKind( + it, + it.copy( + isAllDay = value, + untimed = null, + start = it.start?.rebasedForAllDay(value), + due = it.due?.rebasedForAllDay(value), + ), ) + } + + /** [switched], [it] made all-day or timed, with its reminders made the new kind. */ + private fun switchedKind(it: TaskEditUiState, switched: TaskEditUiState): TaskEditUiState { if (!it.remindersTouched) { val before = loadedReminders val next = switched.withDatedReminders() // The loaded reminders only change kind on a dated task; the list's defaults swapped in show the hint. val swapped = before.isNotEmpty() && loadedReminders !== before && StoredReminders.keptAcrossSwitch(before, switched.toForm(), settings) == null - return@update if (swapped && next.listDefaultsHint == null) { + return if (swapped && next.listDefaultsHint == null) { next.withListHint(applied = true, wanted = emptyList()) } else { next } } - switched.copy(reminders = carried(it.reminders, switched).sortedForDisplay(switched)) + return switched.copy(reminders = carried(it.reminders, switched).sortedForDisplay(switched)) } /** [reminders] as [switched]'s kind; straight back after a switch, the ones before it. */ @@ -577,6 +639,7 @@ private fun TaskEditUiState.toForm(): TaskForm = TaskForm( start = start, due = due, isAllDay = isAllDay, + untimed = untimed.takeUnless { isAllDay }, priority = priority, parentId = parentId, percentComplete = percentComplete, diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt index 6cfc0d3..30da744 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt @@ -89,6 +89,7 @@ import androidx.compose.ui.unit.dp import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import de.jeanlucmakiola.agendula.R +import de.jeanlucmakiola.agendula.domain.dueAsShown import de.jeanlucmakiola.agendula.domain.Priority import de.jeanlucmakiola.agendula.domain.SmartList import de.jeanlucmakiola.agendula.domain.Task @@ -869,7 +870,7 @@ private fun upcomingDueLabel(task: Task): String? { return when (dueDate) { today -> stringResource(R.string.home_due_today) today.plusDays(1) -> stringResource(R.string.home_due_tomorrow) - else -> due.formatDateTimeCompact(task.isAllDay, LocalUse24HourFormat.current) + else -> task.dueAsShown?.formatDateTimeCompact(!task.dueHasTime, LocalUse24HourFormat.current) } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt index a6efcd5..b2f8a0f 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt @@ -69,6 +69,7 @@ import androidx.compose.material.icons.rounded.Tune import androidx.compose.material3.AlertDialog import androidx.compose.material3.SwipeToDismissBox import androidx.compose.ui.res.pluralStringResource +import de.jeanlucmakiola.agendula.domain.dueAsShown import de.jeanlucmakiola.agendula.domain.TaskSortOrder import de.jeanlucmakiola.floret.components.revealOnFocus import de.jeanlucmakiola.floret.components.InlineTextField @@ -702,7 +703,7 @@ internal fun TaskRowContent( val full by animateDpAsState(if (pressed) 36.dp else 22.dp, label = "fullCorner") val small by animateDpAsState(if (pressed) 36.dp else 6.dp, label = "smallCorner") val dark = isSystemInDarkTheme() - val due = task.due?.formatDateTimeCompact(task.isAllDay, LocalUse24HourFormat.current) + val due = task.dueAsShown?.formatDateTimeCompact(!task.dueHasTime, LocalUse24HourFormat.current) val listName = task.listName?.takeIf { showListName && it.isNotBlank() } // Everything secondary collapses into one quiet supporting line below the title. val hasMeta = task.priority != Priority.NONE || due != null || subtaskTotal > 0 || diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetData.kt b/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetData.kt index 42b43dd..d177d5d 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetData.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetData.kt @@ -6,6 +6,7 @@ import de.jeanlucmakiola.agendula.data.prefs.ThemeMode import de.jeanlucmakiola.agendula.data.prefs.is24Hour import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey +import de.jeanlucmakiola.agendula.domain.dueAsShown import de.jeanlucmakiola.agendula.domain.SmartList import de.jeanlucmakiola.agendula.domain.Task import de.jeanlucmakiola.agendula.domain.TaskFilter @@ -263,10 +264,10 @@ internal fun Task.toWidgetRow(now: Instant, today: LocalDate, zone: ZoneId): Wid listId = listId, occurrenceStart = occurrenceStart, title = title, - due = due, - isAllDay = isAllDay, - dueKind = due?.let { dueKind(it, isAllDay, today, zone) }, - isOverdue = due?.let { isOverdue(it, isAllDay, now, today, zone) } ?: false, + due = dueAsShown, + isAllDay = !dueHasTime, + dueKind = dueAsShown?.let { dueKind(it, !dueHasTime, today, zone) }, + isOverdue = dueAsShown?.let { isOverdue(it, !dueHasTime, now, today, zone) } ?: false, color = effectiveColor, ) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 78ace1f..a3f2aec 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -109,6 +109,9 @@ Afternoon Evening Custom time + No time + The due date loses its time too + The start date loses its time too Done Close Cancel diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/data/reminders/ReminderPlannerTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/data/reminders/ReminderPlannerTest.kt index 9d9ad13..5a803b1 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/data/reminders/ReminderPlannerTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/reminders/ReminderPlannerTest.kt @@ -2,7 +2,9 @@ package de.jeanlucmakiola.agendula.data.reminders import com.google.common.truth.Truth.assertThat import de.jeanlucmakiola.agendula.data.prefs.Settings +import de.jeanlucmakiola.agendula.domain.TaskEnd import de.jeanlucmakiola.agendula.domain.TaskReminder +import de.jeanlucmakiola.agendula.domain.untimedInstantOf import de.jeanlucmakiola.agendula.domain.allDayInstantOf import de.jeanlucmakiola.agendula.domain.testTask import de.jeanlucmakiola.agendula.domain.asReminderLead @@ -40,6 +42,24 @@ class ReminderPlannerTest { assertThat(trigger).isEqualTo(millis(date.minusDays(1).atTime(8, 30), berlin)) } + @Test + fun `a due without a time rings at the all-day time of its day, not at its last second`() { + val start = Instant.fromEpochMilliseconds(millis(date.minusDays(1).atTime(14, 0), berlin)) + val due = untimedInstantOf(TaskEnd.DUE, date, berlin) + val task = testTask(id = 1, start = start, due = due).copy(untimed = TaskEnd.DUE) + val plan = ReminderPlanner.plan( + tasks = listOf(task), + perTask = mapOf(1L to listOf(TaskReminder(0), TaskReminder(0, fromStart = true))), + settings = Settings(allDayReminderMinuteOfDay = 9 * 60), + now = start.toEpochMilliseconds() - 60_000, + zone = berlin, + ) + assertThat(plan.map { it.triggerAt }).containsExactly( + millis(date.atTime(9, 0), berlin), + start.toEpochMilliseconds(), + ) + } + @Test fun `a default from before the task existed does not ring`() { val created = Instant.fromEpochMilliseconds(millis(date.atTime(14, 0), berlin)) diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapperTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapperTest.kt index 6f4daf3..389aba0 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapperTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapperTest.kt @@ -5,9 +5,11 @@ import de.jeanlucmakiola.agendula.data.tasks.room.AlarmReference 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.TaskStatus import de.jeanlucmakiola.agendula.domain.ical.ICalComponent import de.jeanlucmakiola.agendula.domain.ical.ICalParser +import de.jeanlucmakiola.agendula.domain.ical.ICalValues import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import kotlin.time.Duration.Companion.days @@ -434,6 +436,100 @@ class VTodoMapperTest { } } + /** One end without a time beside a timed one (#101). */ + @Nested + inner class UntimedEnd { + + private val mixed = TaskEntity( + listId = 1L, + uid = "t-1", + dtstart = Instant.parse("2026-08-31T22:00:00Z"), + due = Instant.parse("2026-09-01T15:00:00Z"), + timezone = "Europe/Berlin", + untimed = TaskEnd.START, + ) + + @Test + fun `the untimed end is written as a marked date-time, so both ends share a value type`() { + val written = VTodoMapper.write(mixed) + val start = written.property("DTSTART")!! + val due = written.property("DUE")!! + assertThat(start.value).isEqualTo("20260901T000000") + assertThat(start.param("TZID")).isEqualTo("Europe/Berlin") + assertThat(start.param(ICalValues.NO_TIME_PARAM)).isEqualTo("TRUE") + assertThat(start.param("VALUE")).isNull() + assertThat(due.value).isEqualTo("20260901T170000") + assertThat(due.param(ICalValues.NO_TIME_PARAM)).isNull() + assertThat(VTodoMapper.validate(written)).isEmpty() + } + + @Test + fun `a written mixed task reads back as itself, with nothing left in the residue`() { + val read = VTodoMapper.read(VTodoMapper.write(mixed)).entity + assertThat(read.untimed).isEqualTo(TaskEnd.START) + assertThat(read.isAllDay).isFalse() + assertThat(read.dtstart).isEqualTo(mixed.dtstart) + assertThat(read.due).isEqualTo(mixed.due) + assertThat(read.unknownProperties).isNull() + } + + @Test + fun `an untimed due round-trips too`() { + val dueOnly = mixed.copy(untimed = TaskEnd.DUE) + val written = VTodoMapper.write(dueOnly) + assertThat(written.property("DUE")?.param(ICalValues.NO_TIME_PARAM)).isEqualTo("TRUE") + assertThat(written.property("DTSTART")?.param(ICalValues.NO_TIME_PARAM)).isNull() + assertThat(VTodoMapper.read(written).entity.untimed).isEqualTo(TaskEnd.DUE) + } + + @Test + fun `a value another client rewrote without the mark has a time again`() { + val read = VTodoMapper.read( + vtodo("DTSTART;TZID=Europe/Berlin:20260901T000000", "DUE;TZID=Europe/Berlin:20260901T170000"), + ).entity + assertThat(read.untimed).isNull() + } + + @Test + fun `a mark on both ends is not ours to read, and stays as it arrived`() { + val mapped = VTodoMapper.read( + vtodo( + "DTSTART;X-AGENDULA-NO-TIME=TRUE;TZID=Europe/Berlin:20260901T000000", + "DUE;X-AGENDULA-NO-TIME=TRUE;TZID=Europe/Berlin:20260901T235959", + ), + ) + assertThat(mapped.entity.untimed).isNull() + assertThat(mapped.entity.unknownProperties).contains("DTSTART;X-AGENDULA-NO-TIME=TRUE") + assertThat(mapped.entity.unknownProperties).contains("DUE;X-AGENDULA-NO-TIME=TRUE") + } + + @Test + fun `a mark on a DATE is ignored, the task is all-day`() { + val read = VTodoMapper.read( + vtodo("DTSTART;X-AGENDULA-NO-TIME=TRUE;VALUE=DATE:20260901", "DUE;VALUE=DATE:20260902"), + ).entity + assertThat(read.isAllDay).isTrue() + assertThat(read.untimed).isNull() + } + + @Test + fun `giving the untimed end a time evicts the marked residue copy`() { + val residue = "DTSTART;X-AGENDULA-NO-TIME=TRUE;TZID=Europe/Berlin:20260901T000000\r\n" + val entity = mixed.copy(untimed = null, unknownProperties = residue) + val start = VTodoMapper.write(entity).properties("DTSTART") + assertThat(start).hasSize(1) + assertThat(start.single().param(ICalValues.NO_TIME_PARAM)).isNull() + } + + @Test + fun `all-day wins over a stray untimed flag`() { + val entity = mixed.copy(isAllDay = true, dtstart = Instant.parse("2026-09-01T00:00:00Z")) + val start = VTodoMapper.write(entity).property("DTSTART")!! + assertThat(start.param("VALUE")).isEqualTo("DATE") + assertThat(start.param(ICalValues.NO_TIME_PARAM)).isNull() + } + } + private fun entity( sequence: Int = 0, completedAt: Instant? = null, diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/provider/ProviderTaskWriterTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/provider/ProviderTaskWriterTest.kt index 41c4967..4be4cb1 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/provider/ProviderTaskWriterTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/provider/ProviderTaskWriterTest.kt @@ -5,6 +5,7 @@ import de.jeanlucmakiola.agendula.data.tasks.TasksContract import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Instances import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Tasks import de.jeanlucmakiola.agendula.data.tasks.room.TaskEntity +import de.jeanlucmakiola.agendula.domain.TaskEnd import de.jeanlucmakiola.agendula.domain.TaskStatus import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows @@ -405,6 +406,18 @@ class ProviderTaskWriterTest { assertThrows { patch(task, Tasks.IS_ALLDAY to "yes") } } + @Test + fun `an untimed end keeps its mark until a client moves it (#101)`() { + val start = Instant.parse("2026-10-19T22:00:00Z") + val due = Instant.parse("2026-10-20T15:00:00Z") + val mixed = task.copy(dtstart = start, due = due, timezone = "Europe/Berlin", untimed = TaskEnd.START) + + assertThat(patch(mixed, Tasks.TITLE to "New").untimed).isEqualTo(TaskEnd.START) + 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() + } + // --- no-op writes ------------------------------------------------------------- @Test diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/domain/AllDayTimeTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/domain/AllDayTimeTest.kt index 957192f..b6820e9 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/domain/AllDayTimeTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/domain/AllDayTimeTest.kt @@ -57,4 +57,14 @@ class AllDayTimeTest { val back = there.rebasedForAllDay(allDay = true, zone = newYork) assertThat(back).isEqualTo(original) } + + @Test + fun `an untimed end is the first or the last second of its day in the zone`() { + val start = untimedInstantOf(TaskEnd.START, julyTwentieth, newYork) + val due = untimedInstantOf(TaskEnd.DUE, julyTwentieth, newYork) + assertThat(start).isEqualTo(Instant.parse("2026-07-20T04:00:00Z")) + assertThat(due).isEqualTo(Instant.parse("2026-07-21T03:59:59Z")) + assertThat(start.calendarDate(allDay = false, zone = newYork)).isEqualTo(julyTwentieth) + assertThat(due.calendarDate(allDay = false, zone = newYork)).isEqualTo(julyTwentieth) + } } diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/domain/export/ICalendarWriterTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/domain/export/ICalendarWriterTest.kt index 43bf0ed..a751f07 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/domain/export/ICalendarWriterTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/domain/export/ICalendarWriterTest.kt @@ -2,6 +2,7 @@ package de.jeanlucmakiola.agendula.domain.export 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.allDayInstantOf import org.junit.jupiter.api.Nested @@ -36,9 +37,10 @@ class ICalendarWriterTest { rdate: String? = null, parentId: Long? = null, tags: List = emptyList(), + untimed: TaskEnd? = null, ) = ExportTask( taskId, uid, title, description, location, url, priority, status, percentComplete, - start, due, isAllDay, completedAt, created, lastModified, rrule, rdate, parentId, tags, + start, due, isAllDay, completedAt, created, lastModified, rrule, rdate, parentId, tags, untimed, ) private fun write(vararg tasks: ExportTask, name: String = "Groceries"): String = @@ -141,6 +143,14 @@ class ICalendarWriterTest { assertThat(lines).contains("DUE;VALUE=DATE:20260802") } + @Test + fun `an untimed end stays a date-time beside a timed one, marked as having no time`() { + 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") + assertThat(lines).contains("DUE:20250802T120000Z") + } + @Test fun `completion is always a UTC date-time even when all-day`() { val lines = linesOf( diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicksTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicksTest.kt index 6f12820..f283ea6 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicksTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/ui/edit/QuickPicksTest.kt @@ -76,4 +76,12 @@ class QuickPicksTest { assertThat(defaultPickerDate(LocalTime.of(12, 0), now, ceiling = due)).isEqualTo(today.minusDays(1)) assertThat(defaultPickerDate(LocalTime.of(20, 0), now, ceiling = today.plusDays(3).atTime(9, 0))).isEqualTo(today) } + + @Test + fun `no time without a date lands on today, or the nearest day the other end allows`() { + assertThat(defaultNoTimeDate(today)).isEqualTo(today) + assertThat(defaultNoTimeDate(today, floor = today.plusDays(2).atTime(9, 0))).isEqualTo(today.plusDays(2)) + assertThat(defaultNoTimeDate(today, ceiling = today.minusDays(1).atTime(9, 0))).isEqualTo(today.minusDays(1)) + assertThat(defaultNoTimeDate(today, floor = today.minusDays(3).atTime(9, 0))).isEqualTo(today) + } } 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..17d393a 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 @@ -11,11 +11,14 @@ import de.jeanlucmakiola.agendula.data.tasks.TasksRepository import de.jeanlucmakiola.agendula.domain.Priority import de.jeanlucmakiola.agendula.domain.Task import de.jeanlucmakiola.agendula.domain.TaskDetail +import de.jeanlucmakiola.agendula.domain.TaskEnd import de.jeanlucmakiola.agendula.domain.TaskFilter import de.jeanlucmakiola.agendula.domain.TaskForm import de.jeanlucmakiola.agendula.domain.TaskList import de.jeanlucmakiola.agendula.domain.TaskReminder import de.jeanlucmakiola.agendula.domain.TaskStatus +import de.jeanlucmakiola.agendula.domain.allDayInstantOf +import de.jeanlucmakiola.agendula.domain.untimedInstantOf import de.jeanlucmakiola.agendula.domain.recurrence.RecurringScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi @@ -29,6 +32,8 @@ import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import java.lang.reflect.Proxy +import java.time.LocalDate +import java.time.LocalTime import kotlin.time.Clock import kotlin.time.Duration.Companion.days import kotlin.time.Instant @@ -141,6 +146,83 @@ class TaskEditViewModelTest { assertThat(vm.state.value.reminders).containsExactly(reminder) } + @Test + fun `no time on the due of a timed task leaves the start's time alone (#101)`() { + val vm = editing(start = due - 1.days) + val day = LocalDate.now().plusDays(3) + vm.onWhenChange(TaskEnd.DUE, day, null) + + val state = vm.state.value + assertThat(state.isAllDay).isFalse() + assertThat(state.untimed).isEqualTo(TaskEnd.DUE) + assertThat(state.start).isEqualTo(due - 1.days) + assertThat(state.due).isEqualTo(untimedInstantOf(TaskEnd.DUE, day)) + assertThat(state.reminders).containsExactly(reminder) + vm.save() + assertThat(repository.saved?.untimed).isEqualTo(TaskEnd.DUE) + assertThat(repository.saved?.isAllDay).isFalse() + } + + @Test + fun `no time on both ends makes the task all-day`() { + val vm = editing(start = due - 1.days) + val day = LocalDate.now().plusDays(3) + vm.onWhenChange(TaskEnd.DUE, day, null) + vm.onWhenChange(TaskEnd.START, day.minusDays(1), null) + + val state = vm.state.value + assertThat(state.isAllDay).isTrue() + assertThat(state.untimed).isNull() + assertThat(state.start).isEqualTo(allDayInstantOf(day.minusDays(1))) + assertThat(state.due).isEqualTo(allDayInstantOf(day)) + } + + @Test + fun `a time on one end of an all-day task leaves the other end without one`() { + val vm = editing(start = due - 1.days) + val day = LocalDate.now().plusDays(3) + vm.onWhenChange(TaskEnd.DUE, day, null) + vm.onWhenChange(TaskEnd.START, day.minusDays(1), null) + vm.onWhenChange(TaskEnd.START, day.minusDays(1), LocalTime.of(9, 0)) + + val state = vm.state.value + assertThat(state.isAllDay).isFalse() + assertThat(state.untimed).isEqualTo(TaskEnd.DUE) + assertThat(state.due).isEqualTo(untimedInstantOf(TaskEnd.DUE, day)) + assertThat(state.hasTime(TaskEnd.START)).isTrue() + } + + @Test + fun `a time on the untimed end gives the task both times back`() { + val vm = editing(start = due - 1.days) + val day = LocalDate.now().plusDays(3) + vm.onWhenChange(TaskEnd.DUE, day, null) + vm.onWhenChange(TaskEnd.DUE, day, LocalTime.of(17, 0)) + + assertThat(vm.state.value.untimed).isNull() + assertThat(vm.state.value.isAllDay).isFalse() + } + + @Test + fun `a store without untimed ends drops both times together`() { + repository.untimedEnds = false + val vm = editing(start = due - 1.days) + val day = LocalDate.now().plusDays(3) + vm.onWhenChange(TaskEnd.DUE, day, null) + + assertThat(vm.state.value.isAllDay).isTrue() + assertThat(vm.state.value.untimed).isNull() + } + + @Test + fun `clearing the untimed end drops its mark`() { + val vm = editing(start = due - 1.days) + vm.onWhenChange(TaskEnd.DUE, LocalDate.now().plusDays(3), null) + vm.onDueChange(null) + + assertThat(vm.state.value.untimed).isNull() + } + @Test fun `a task stored without dates opens without its reminders`() { val vm = editing(due = null) @@ -179,6 +261,9 @@ class TaskEditViewModelTest { var task: Task? = null var reminders: List = emptyList() var saved: TaskForm? = null + var untimedEnds = true + + override fun supportsUntimedEnds() = untimedEnds override fun taskLists() = flowOf(emptyList()) override fun tasks(filter: TaskFilter): Flow> = flowOf(emptyList()) From e3a2d974c7dd283a009bbfaa662601d2c1e2754d Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Tue, 17 Nov 2026 16:45:00 +0100 Subject: [PATCH 6/8] Read untimed ends in the task's zone, ring them by their date, review fixes (#101) --- CHANGELOG.md | 4 +- .../data/reminders/ReminderPlanner.kt | 53 +++++++---- .../agendula/data/reminders/TaskNotifier.kt | 6 +- .../agendula/data/tasks/StoredReminders.kt | 26 +++-- .../agendula/data/tasks/ical/VTodoMapper.kt | 21 ++++- .../data/tasks/room/RoomTasksDataSource.kt | 16 +++- .../agendula/domain/AllDayTime.kt | 30 +++++- .../jeanlucmakiola/agendula/domain/Models.kt | 34 ++++--- .../agendula/domain/SavedFilter.kt | 11 ++- .../agendula/domain/TaskFilter.kt | 2 +- .../agendula/ui/common/ReminderFormatting.kt | 19 +++- .../agendula/ui/detail/TaskDetailScreen.kt | 27 +++--- .../agendula/ui/edit/DateTimePickerSheet.kt | 43 +++++---- .../agendula/ui/edit/TaskEditScreen.kt | 25 +++-- .../agendula/ui/edit/TaskEditViewModel.kt | 94 ++++++++++++------- .../agendula/ui/lists/ListsScreen.kt | 10 +- .../agendula/ui/tasklist/TaskListScreen.kt | 4 +- .../agendula/widget/WidgetData.kt | 10 +- .../agendula/widget/WidgetStats.kt | 10 +- app/src/main/res/values/strings.xml | 4 +- .../data/tasks/StoredRemindersTest.kt | 21 +++++ .../data/tasks/ical/VTodoMapperTest.kt | 18 +++- .../data/tasks/room/OccurrenceTimesTest.kt | 45 +++++++++ .../agendula/domain/AllDayTimeTest.kt | 11 +++ .../agendula/ui/edit/TaskEditViewModelTest.kt | 54 ++++++++++- 25 files changed, 438 insertions(+), 160 deletions(-) create mode 100644 app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/room/OccurrenceTimesTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 89c3dee..2802aa5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,8 +18,8 @@ All notable changes to this project are documented here. The format follows without a time is an all-day task as before. A date without a time beside a timed one syncs as the start or the end of its day, marked so Agendula reads it back as a date; other apps show that time. Reminders for it ring at the - all-day reminder time. With a tasks app as the store, both ends drop their - time together (#101). + all-day reminder time. With a tasks app as the store, both ends gain or + drop their time together (#101). ## [1.3.2] - 2026-11-13 diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/ReminderPlanner.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/ReminderPlanner.kt index 1ab41f6..5f5eb50 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/ReminderPlanner.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/ReminderPlanner.kt @@ -4,8 +4,11 @@ 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.untimedDate import de.jeanlucmakiola.agendula.domain.TaskReminder import de.jeanlucmakiola.agendula.domain.calendarDate +import java.time.LocalDate import java.time.LocalTime import java.time.ZoneId import kotlin.time.Instant @@ -55,15 +58,14 @@ internal object ReminderPlanner { .filter { (if (it.fromStart) task.start else task.due) != null } val created = task.created?.toEpochMilliseconds() reminders.mapNotNull { reminder -> - val end = when { - reminder.fromStart -> if (task.start != null) TaskEnd.START else TaskEnd.DUE - else -> if (task.due != null) TaskEnd.DUE else TaskEnd.START - } - val anchor = untimedAnchor(task, end, settings.allDayReminderMinuteOfDay, zone) - ?: if (end == TaskEnd.START) task.start!! else task.due!! - val trigger = triggerAt( - anchor, + 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, @@ -105,15 +107,26 @@ internal object ReminderPlanner { .toSet() /** - * A date without a time on a timed task rings at the all-day reminder time - * of its day, not at the midnight or last second it is stored as (#101). + * 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). */ - fun untimedAnchor(task: Task, end: TaskEnd, allDayMinuteOfDay: Int, zone: ZoneId): Instant? { - if (task.untimed != end || task.isAllDay) return null - val value = (if (end == TaskEnd.START) task.start else task.due) ?: return null - val time = LocalTime.of(allDayMinuteOfDay / 60 % 24, allDayMinuteOfDay % 60) - val millis = value.calendarDate(allDay = false, zone = zone).atTime(time).atZone(zone).toInstant().toEpochMilli() - return Instant.fromEpochMilliseconds(millis) + 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 } /** @@ -134,9 +147,9 @@ internal object ReminderPlanner { ): Long { if (!allDay) return anchor.toEpochMilliseconds() - leadMinutes.coerceAtLeast(0) * 60_000L val (days, minuteOfDay) = AllDayReminder.of(leadMinutes) - val minute = minuteOfDay ?: allDayMinuteOfDay - val time = LocalTime.of(minute / 60 % 24, minute % 60) - return anchor.calendarDate(allDay = true).minusDays(days.toLong()) - .atTime(time).atZone(zone).toInstant().toEpochMilli() + return atMinuteOfDay(anchor.calendarDate(allDay = true).minusDays(days.toLong()), minuteOfDay ?: allDayMinuteOfDay, zone) } + + private fun atMinuteOfDay(date: LocalDate, minuteOfDay: Int, zone: ZoneId): Long = + date.atTime(LocalTime.of(minuteOfDay / 60 % 24, minuteOfDay % 60)).atZone(zone).toInstant().toEpochMilli() } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/TaskNotifier.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/TaskNotifier.kt index bf5cada..c06131d 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/TaskNotifier.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/TaskNotifier.kt @@ -21,7 +21,7 @@ import de.jeanlucmakiola.agendula.MainActivity import de.jeanlucmakiola.agendula.R import de.jeanlucmakiola.agendula.data.prefs.ReminderDescription import de.jeanlucmakiola.agendula.data.prefs.Settings -import de.jeanlucmakiola.agendula.domain.dueAsShown +import de.jeanlucmakiola.agendula.domain.TaskEnd import de.jeanlucmakiola.agendula.domain.readableDescription import de.jeanlucmakiola.agendula.data.prefs.is24Hour import de.jeanlucmakiola.agendula.data.di.ApplicationScope @@ -75,12 +75,12 @@ class TaskNotifier @Inject constructor( if (!canPost()) return val channelId = ensureListChannel(task.listId, task.listName) val title = task.title.ifBlank { context.getString(R.string.task_untitled) } - val text = task.dueAsShown?.let { due -> + val text = task.shownValue(TaskEnd.DUE)?.let { due -> context.getString( R.string.reminder_due_at, formatReminderDue( due.toEpochMilliseconds(), - !task.dueHasTime, + !task.hasTime(TaskEnd.DUE), is24Hour = settings.timeFormat.is24Hour(DateFormat.is24HourFormat(context)), relative = RelativeDays( today = context.getString(R.string.reminder_day_today), diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/StoredReminders.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/StoredReminders.kt index 3e4d29d..0cf2b19 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/StoredReminders.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/StoredReminders.kt @@ -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.TaskEnd import de.jeanlucmakiola.agendula.domain.TaskForm import de.jeanlucmakiola.agendula.domain.TaskReminder import de.jeanlucmakiola.agendula.domain.calendarDate @@ -35,7 +36,9 @@ internal object StoredReminders { fun of(form: TaskForm, current: Task?, settings: Settings, now: Long, zone: ZoneId): List { 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) + return withDefaults( + form, current?.start, current?.due, current?.isAllDay ?: form.isAllDay, settings, now, zone, current?.untimed, + ) } /** [of] for a task whose dates were [start] and [due], whatever the form chose. */ @@ -47,9 +50,10 @@ internal object StoredReminders { settings: Settings, now: Long, zone: ZoneId, + wasUntimed: TaskEnd? = null, ): List { val wanted = form.reminders.map { it.lead }.distinct() - val fresh = freshAnchors(form, start, due, wasAllDay, settings, now, zone) + val fresh = freshAnchors(form, start, due, wasAllDay, settings, now, zone, wasUntimed) 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() @@ -68,10 +72,11 @@ internal object StoredReminders { settings: Settings, now: Long, zone: ZoneId, + wasUntimed: TaskEnd? = null, ): Set { 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, wanted, settings, now, zone) + return gained + revived(form, start, due, wasAllDay, wasUntimed, wanted, settings, now, zone) } /** @@ -114,6 +119,7 @@ internal object StoredReminders { start: Instant?, due: Instant?, wasAllDay: Boolean, + wasUntimed: TaskEnd?, wanted: List, settings: Settings, now: Long, @@ -131,7 +137,9 @@ internal object StoredReminders { } val leads = defaults.filter { it.fromStart == fromStart } return moved && leads.isNotEmpty() && leads.all { - ReminderPlanner.triggerAt(was, wasAllDay, it.minutesBefore, settings.allDayReminderMinuteOfDay, zone) < now + ReminderPlanner.ringsAt( + start, due, wasAllDay, wasUntimed, null, fromStart, it.minutesBefore, settings.allDayReminderMinuteOfDay, zone, + ) < now } } return setOfNotNull(true.takeIf { revived(true, start, form.start) }, false.takeIf { revived(false, due, form.due) }) @@ -147,10 +155,14 @@ internal object StoredReminders { */ private fun defaultsFor(form: TaskForm, settings: Settings, now: Long, zone: ZoneId): List = settings.defaultRemindersFor(form.listId, form.isAllDay).filter { reminder -> - val anchor = (if (reminder.fromStart) form.start else form.due) ?: return@filter false - form.rrule != null || ReminderPlanner.triggerAt( - anchor, + 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, + reminder.fromStart, reminder.minutesBefore, settings.allDayReminderMinuteOfDay, zone, diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapper.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapper.kt index eaa8172..ee07c48 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapper.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapper.kt @@ -539,12 +539,11 @@ object VTodoMapper { val tzid: String?, val isDate: Boolean, val representable: Boolean, + /** A date-time marked as standing for a date alone, still on its day boundary. */ + val noTime: Boolean = false, ) { val present get() = property != null - /** A date-time marked as standing for a date alone. */ - val noTime get() = property != null && !isDate && ICalValues.isMarkedNoTime(property) - /** True when one `is_all_day` flag, one `timezone` column and the untimed end reproduce it. */ fun reproducible(allDay: Boolean, timezone: String?, untimed: Boolean = false) = present && representable && isDate == allDay && tzid == timezone && noTime == untimed @@ -557,7 +556,10 @@ object VTodoMapper { val property = vtodo.property(name) ?: return TimeRead(null, null, null, false, false) 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) + is ICalValues.TimeValue.Timed -> TimeRead( + property, value.instant, value.tzid, false, true, + noTime = ICalValues.isMarkedNoTime(property) && onDayBoundary(name, property.value, 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 -> @@ -584,6 +586,17 @@ object VTodoMapper { 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. + */ + 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 val TaskEnd.propertyName: String get() = when (this) { TaskEnd.START -> "DTSTART" 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 2a1b6b9..de50ef4 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 @@ -1,5 +1,10 @@ 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.zoneOr +import java.time.temporal.ChronoUnit import android.util.Log import androidx.room.InvalidationTracker import de.jeanlucmakiola.agendula.data.tasks.ResetSubtask @@ -60,12 +65,17 @@ internal fun expansionWindow(now: Instant) = ExpansionWindow( /** * One occurrence's resolved start and due. A timed series keeps each * occurrence's duration; a due-anchored one has no start to offset from, so - * the anchor *is* the due date. + * the anchor *is* the due date. A due without a time (#101) keeps its distance + * in days instead, so a clock change in between cannot push it onto the next day. */ internal fun occurrenceTimes(master: TaskEntity, anchor: Instant): Pair { if (master.dtstart == null) return null to anchor - val length = master.due?.let { it - master.dtstart } - return anchor to length?.let { anchor + it } + 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 anchor + (due - master.dtstart) } /** One occurrence of a series: its anchor, the override replacing it if any, and its resolved times. */ diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/AllDayTime.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/AllDayTime.kt index 7a455d9..6cc4ca6 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/AllDayTime.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/AllDayTime.kt @@ -47,10 +47,30 @@ fun Instant.rebasedForAllDay(allDay: Boolean, zone: ZoneId = ZoneId.systemDefaul * * RFC 5545 makes `DTSTART` and `DUE` share a value type, so such a task is * timed on the wire and in storage: the untimed end is the start of its day - * ([START]) or its last second ([DUE]) in the device zone, and only this flag - * (`X-AGENDULA-NO-TIME` on the property) says it carries no time. + * ([START]) or its last second ([DUE]) in the task's zone, and only this flag + * (`X-AGENDULA-NO-TIME` on the property) says it carries no time. Its date is + * read back in that same zone ([untimedDate]), never in the device's. */ -enum class TaskEnd { START, DUE } +enum class TaskEnd { + START, + DUE, + ; + + 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 + +/** 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 +} + +/** [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. */ fun untimedInstantOf(end: TaskEnd, date: java.time.LocalDate, zone: ZoneId = ZoneId.systemDefault()): Instant { @@ -60,3 +80,7 @@ fun untimedInstantOf(end: TaskEnd, date: java.time.LocalDate, zone: ZoneId = Zon } return Instant.fromEpochMilliseconds(local.atZone(zone).toInstant().toEpochMilli()) } + +/** 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)) 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 6195365..7d40aa9 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/Models.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/Models.kt @@ -1,5 +1,7 @@ package de.jeanlucmakiola.agendula.domain +import java.time.LocalDate +import java.time.ZoneId import kotlin.time.Instant /** A task list (the `tasklists` table). Lists group under their account. */ @@ -112,11 +114,27 @@ data class Task( /** The end that has a date but no time while the other has one; see [TaskEnd]. */ val untimed: TaskEnd? = null, ) { - /** Whether [start] carries a time of day. */ - val startHasTime: Boolean get() = !isAllDay && untimed != TaskEnd.START + fun valueOf(end: TaskEnd): Instant? = if (end == TaskEnd.START) start else due - /** Whether [due] carries a time of day. */ - val dueHasTime: Boolean get() = !isAllDay && untimed != TaskEnd.DUE + /** Whether [end] carries a time of day. */ + fun hasTime(end: TaskEnd): Boolean = hasTimeAt(end, isAllDay, untimed) + + /** 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 { + when { + isAllDay -> it.calendarDate(allDay = true) + untimed == end -> it.untimedDate(timeZone) + else -> it.calendarDate(allDay = false, zone = zone) + } + } + + /** + * [end] for code that shows or buckets a date without a time by the + * all-day convention: without a time it is the all-day value of its date. + * Read it with `allDay = !hasTime(end)`. + */ + fun shownValue(end: TaskEnd): Instant? = + if (hasTime(end)) valueOf(end) else dateOf(end)?.let(::allDayInstantOf) /** One occurrence of a series, whether generated or overridden. */ val isOccurrence: Boolean get() = seriesId != null && occurrenceStart != null @@ -137,14 +155,6 @@ data class Task( get() = if (occurrenceStart == null) "$taskId" else "$taskId@${occurrenceStart.toEpochMilliseconds()}" } -/** - * [Task.due] for code that shows a date without a time by the all-day - * convention: an untimed due becomes the all-day value of its date. Read it - * with `allDay = !dueHasTime`. - */ -val Task.dueAsShown: Instant? - get() = if (dueHasTime || isAllDay) due else due?.let { allDayInstantOf(it.calendarDate(allDay = false)) } - /** Detail bundle: a task, its parent (if it's a subtask), and its direct children. */ data class TaskDetail( val task: Task, diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/SavedFilter.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/SavedFilter.kt index 294e651..d363e25 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/SavedFilter.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/SavedFilter.kt @@ -59,7 +59,7 @@ fun dueWindowOf( todayEnd: Instant, zone: ZoneId = ZoneId.systemDefault(), ): DueWindow { - val due = task.wallClock(task.due, zone) + val due = task.wallClock(TaskEnd.DUE, zone) return when { due == null -> DueWindow.NO_DATE due < todayStart -> DueWindow.OVERDUE @@ -68,9 +68,12 @@ fun dueWindowOf( } } -/** [at], one of this task's dates, as a local instant: an all-day date is read as its calendar date. */ -fun Task.wallClock(at: Instant?, zone: ZoneId = ZoneId.systemDefault()): Instant? = - at?.let { if (isAllDay) it.rebasedForAllDay(allDay = false, zone = zone) else it } +/** [end] as a local instant: a date without a time is read as the start of its day. */ +fun Task.wallClock(end: TaskEnd, zone: ZoneId = ZoneId.systemDefault()): Instant? { + if (hasTime(end)) return valueOf(end) + val date = dateOf(end, zone) ?: return null + return Instant.fromEpochMilliseconds(date.atStartOfDay(zone).toInstant().toEpochMilli()) +} /** What a task created from a [SavedFilter] starts with, so it lands in that filter. */ data class NewTaskPreset( diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskFilter.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskFilter.kt index e898062..274ebfb 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskFilter.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskFilter.kt @@ -55,7 +55,7 @@ object TaskFiltering { return when (dueWindowOf(task, todayStart, todayEnd, zone)) { DueWindow.TODAY -> true DueWindow.OVERDUE -> false - DueWindow.UPCOMING, DueWindow.NO_DATE -> inToday(task.wallClock(task.start, zone)) + DueWindow.UPCOMING, DueWindow.NO_DATE -> inToday(task.wallClock(TaskEnd.START, zone)) } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/common/ReminderFormatting.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/common/ReminderFormatting.kt index 2781143..165a0e8 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/common/ReminderFormatting.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/common/ReminderFormatting.kt @@ -73,10 +73,25 @@ fun reminderLabel(minutes: Int, allDay: Boolean, fromStart: Boolean, anchored: B /** * One of a task's own reminders in one line, naming its date when [anchored]. * An all-day one names its day and the time it rings at — its own, or - * [allDayMinuteOfDay] when it has none. + * [allDayMinuteOfDay] when it has none. One counting from a date without a + * time ([untimedAnchor], #101) names the time it rings at, counted back from + * [allDayMinuteOfDay]. */ @Composable -fun taskReminderLabel(reminder: TaskReminder, allDay: Boolean, allDayMinuteOfDay: Int, anchored: Boolean): String { +fun taskReminderLabel( + reminder: TaskReminder, + allDay: Boolean, + allDayMinuteOfDay: Int, + anchored: Boolean, + untimedAnchor: Boolean = false, +): String { + if (!allDay && untimedAnchor) { + return stringResource( + R.string.reminder_at_time, + reminderLabel(reminder.minutesBefore, false, reminder.fromStart, anchored), + formatMinuteOfDay(Math.floorMod(allDayMinuteOfDay - reminder.minutesBefore, DAY_MINUTES), LocalUse24HourFormat.current), + ) + } if (!allDay) return reminderLabel(reminder.minutesBefore, false, reminder.fromStart, anchored) val (days, minuteOfDay) = reminder.allDay return stringResource( 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 557b7a5..7d90b0f 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 @@ -101,6 +101,8 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle 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 @@ -363,6 +365,8 @@ 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), ), style = MaterialTheme.typography.titleMedium, ) @@ -711,18 +715,17 @@ private fun DetailCard( @Composable private fun taskWhenLines(task: Task): Pair? { val use24 = LocalUse24HourFormat.current - val start = task.start - val due = task.due + val start = task.shownValue(TaskEnd.START) + val due = task.shownValue(TaskEnd.DUE) + // Without a time, an end is read as its date by the all-day convention (#101). + val startTime = start?.takeIf { task.hasTime(TaskEnd.START) }?.formatTime(use24) + val dueTime = due?.takeIf { task.hasTime(TaskEnd.DUE) }?.formatTime(use24) return when { start != null && due != null -> { - val allDay = task.isAllDay - val sameDay = start.formatDate(allDay) == due.formatDate(allDay) - val primary = - if (sameDay) due.formatDate(allDay) - else "${start.formatDate(allDay)} – ${due.formatDate(allDay)}" - // One end without a time (#101) keeps its side of the range open. - val startTime = start.takeIf { task.startHasTime }?.formatTime(use24) - val dueTime = due.takeIf { task.dueHasTime }?.formatTime(use24) + val startDay = start.formatDate(startTime == null) + val dueDay = due.formatDate(dueTime == null) + val primary = if (startDay == dueDay) dueDay else "$startDay – $dueDay" + // One end without a time keeps its side of the range open. val secondary = when { startTime != null && dueTime != null -> "$startTime – $dueTime" startTime != null -> "$startTime –" @@ -731,8 +734,8 @@ private fun taskWhenLines(task: Task): Pair? { } primary to secondary } - due != null -> due.formatDate(task.isAllDay) to due.takeIf { task.dueHasTime }?.formatTime(use24) - start != null -> start.formatDate(task.isAllDay) to start.takeIf { task.startHasTime }?.formatTime(use24) + due != null -> due.formatDate(dueTime == null) to dueTime + start != null -> start.formatDate(startTime == null) to startTime else -> null } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/DateTimePickerSheet.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/DateTimePickerSheet.kt index 1bd0eaf..091affc 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/DateTimePickerSheet.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/DateTimePickerSheet.kt @@ -2,6 +2,8 @@ package de.jeanlucmakiola.agendula.ui.edit import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable @@ -39,13 +41,14 @@ import kotlin.time.Instant * other, and "No time" for a date alone. A tap that completes the value applies * it and closes: any time, "No time", or a date for a value that is already * set. A date for an empty value is staged with a default time and committed by - * Done. Back discards anything staged. + * Done, unless [dateOnly] (the other end has no time either), where it applies + * as a date alone. Back discards anything staged. * * [initial] is read as all-day when [allDay], and its time only when - * [hasTime]. [noTimeNote] explains a "No time" that also takes the other end's - * time. [notBefore] / [notAfter] keep a date or time filled in for an empty - * value on the right side of the other end (the start for a due, the due for a - * start). [onChange] gets the date and the time, null for none. + * [hasTime]. [linkedNote] explains a store where the other end's time comes + * and goes with this one's. [notBefore] / [notAfter] keep a date or time filled + * in for an empty value on the right side of the other end (the start for a + * due, the due for a start). [onChange] gets the date and the time, null for none. */ @Composable internal fun DateTimePickerSheet( @@ -53,13 +56,14 @@ internal fun DateTimePickerSheet( initial: Instant?, allDay: Boolean, hasTime: Boolean, - noTimeNote: String?, - notBefore: Instant?, - notAfter: Instant?, + dateOnly: Boolean, + linkedNote: String?, + notBefore: LocalDateTime?, + notAfter: LocalDateTime?, onChange: (LocalDate, LocalTime?) -> Unit, onDismiss: () -> Unit, ) { - val staging = initial == null + val staging = initial == null && !dateOnly var date by rememberSaveable { mutableStateOf(initial?.calendarDate(allDay)) } var time by rememberSaveable { mutableStateOf(initial?.takeIf { hasTime }?.toLocalTime()) } var showCalendar by rememberSaveable { mutableStateOf(false) } @@ -72,9 +76,7 @@ internal fun DateTimePickerSheet( fun dayLabel(d: LocalDate) = d.format(if (d.year == today.year) dayFormats.thisYear else dayFormats.otherYear) fun timeLabel(t: LocalTime) = formatMinuteOfDay(t.hour * 60 + t.minute, is24Hour, locale) - val floor = notBefore?.toLocalDateTime() - val ceiling = notAfter?.toLocalDateTime() - fun stagedTime(d: LocalDate) = defaultPickerTime(d, LocalDateTime.now(), floor, ceiling) + fun stagedTime(d: LocalDate) = defaultPickerTime(d, LocalDateTime.now(), notBefore, notAfter) fun commit(d: LocalDate, t: LocalTime?) { onChange(d, t) @@ -89,7 +91,7 @@ internal fun DateTimePickerSheet( } } fun pickTime(t: LocalTime) { - commit(date ?: defaultPickerDate(t, LocalDateTime.now(), floor, ceiling), t) + commit(date ?: defaultPickerDate(t, LocalDateTime.now(), notBefore, notAfter), t) } FullScreenPicker( @@ -98,7 +100,7 @@ internal fun DateTimePickerSheet( actions = { if (staging) { TextButton( - onClick = { date?.let { commit(it, stagedTime(it)) } }, + onClick = { date?.let { commit(it, time ?: stagedTime(it)) } }, enabled = date != null, ) { Text(stringResource(R.string.picker_done)) } } @@ -148,11 +150,18 @@ internal fun DateTimePickerSheet( ) GroupedRow( title = stringResource(R.string.picker_time_none), - summary = noTimeNote, position = positionOf(QuickTime.entries.size + 1, timeRows), checked = date != null && time == null, - onClick = { commit(date ?: defaultNoTimeDate(today, floor, ceiling), null) }, + onClick = { commit(date ?: defaultNoTimeDate(today, notBefore, notAfter), null) }, ) + linkedNote?.let { + Text( + text = it, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), + ) + } } if (showCalendar) { @@ -184,8 +193,6 @@ private class DayFormats(locale: Locale) { val otherYear: DateTimeFormatter = localizedDateFormatter(locale, "EEEdMMMyyyy") } -private fun Instant.toLocalDateTime(): LocalDateTime = LocalDateTime.of(calendarDate(false), toLocalTime()) - private val QuickDate.labelRes: Int get() = when (this) { QuickDate.Today -> R.string.picker_date_today 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 5bea5fc..b8908bb 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 @@ -120,6 +120,7 @@ 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 @@ -558,7 +559,14 @@ private fun EditContent( state.reminders.forEachIndexed { index, reminder -> ReminderItemCard( position = positionOf(index, rows), - title = taskReminderLabel(reminder, state.isAllDay, state.allDayMinuteOfDay, anchored = bothDates), + title = taskReminderLabel( + reminder, + state.isAllDay, + state.allDayMinuteOfDay, + anchored = bothDates, + untimedAnchor = !state.isAllDay && + state.untimed == reminderEnd(reminder.fromStart, state.start != null, state.due != null), + ), onRemove = { viewModel.removeReminder(reminder) }, ) } @@ -650,10 +658,10 @@ private fun EditContent( pickerTarget?.let { target -> val end = if (target == PickerTarget.Start) TaskEnd.START else TaskEnd.DUE - val other = if (end == TaskEnd.START) TaskEnd.DUE else TaskEnd.START - // A store without per-end times drops both together; say so where it would bite. - val noTimeNote = if (!state.untimedEnds && state.valueOf(other) != null && state.hasTime(other)) { - stringResource(if (other == TaskEnd.DUE) R.string.picker_time_none_also_due else R.string.picker_time_none_also_start) + val otherSet = state.valueOf(end.other) != null + // A store without per-end times moves both together; say so where it would bite. + val linkedNote = if (!state.untimedEnds && otherSet) { + stringResource(if (end.other == TaskEnd.DUE) R.string.picker_time_linked_due else R.string.picker_time_linked_start) } else { null } @@ -662,9 +670,10 @@ private fun EditContent( initial = state.valueOf(end), allDay = state.isAllDay, hasTime = state.hasTime(end), - noTimeNote = noTimeNote, - notBefore = state.start.takeIf { end == TaskEnd.DUE }, - notAfter = state.due.takeIf { end == TaskEnd.START }, + dateOnly = otherSet && !state.hasTime(end.other), + linkedNote = linkedNote, + notBefore = state.localValueOf(TaskEnd.START).takeIf { end == TaskEnd.DUE }, + notAfter = state.localValueOf(TaskEnd.DUE).takeIf { end == TaskEnd.START }, onChange = { date, time -> viewModel.onWhenChange(end, date, time) }, onDismiss = { pickerTarget = null }, ) 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 2e0f638..f6cbb3b 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 @@ -17,6 +17,8 @@ import de.jeanlucmakiola.agendula.domain.TaskFormError 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.calendarDate import de.jeanlucmakiola.agendula.domain.untimedInstantOf import de.jeanlucmakiola.agendula.ui.common.localToInstant @@ -31,7 +33,6 @@ import de.jeanlucmakiola.agendula.domain.looksLikeHtml import de.jeanlucmakiola.agendula.domain.newTaskPreset import de.jeanlucmakiola.agendula.domain.normalizeTags import de.jeanlucmakiola.agendula.domain.tagsInUse -import de.jeanlucmakiola.agendula.domain.rebasedForAllDay import de.jeanlucmakiola.agendula.domain.readableDescription import de.jeanlucmakiola.agendula.domain.recurrence.RecurringScope import kotlinx.coroutines.flow.MutableStateFlow @@ -40,6 +41,7 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import java.time.LocalDate +import java.time.LocalDateTime import java.time.LocalTime import javax.inject.Inject import kotlin.time.Clock @@ -117,7 +119,19 @@ data class TaskEditUiState( fun valueOf(end: TaskEnd): Instant? = if (end == TaskEnd.START) start else due /** Whether [end] carries a time of day, as opposed to a date alone. */ - fun hasTime(end: TaskEnd): Boolean = !isAllDay && untimed != end + fun hasTime(end: TaskEnd): Boolean = hasTimeAt(end, isAllDay, untimed) + + /** + * [end] as a local date-time, for the picker to keep the other end on its + * side of: a date without a time is the start of its day for a start, the + * end of it for a due. + */ + fun localValueOf(end: TaskEnd): LocalDateTime? { + val value = valueOf(end) ?: return null + if (hasTime(end)) return LocalDateTime.of(value.calendarDate(allDay = false), value.toLocalTime()) + val date = value.calendarDate(isAllDay) + return if (end == TaskEnd.START) date.atStartOfDay() else date.atTime(23, 59) + } } @HiltViewModel @@ -164,6 +178,10 @@ class TaskEditViewModel @Inject constructor( private var loadedStart: Instant? = null private var loadedDue: Instant? = null private var loadedAllDay = false + private var loadedUntimed: TaskEnd? = null + + /** A new task's start is still the "now" it was given; a due without a time then takes it along. */ + private var startIsDefault = false /** Whether [loadedReminders] are all-day ones; a task without dates converts them once it gets one. */ private var loadedKindAllDay = false @@ -228,7 +246,10 @@ class TaskEditViewModel @Inject constructor( title = initialTitle.orEmpty(), tags = (listOfNotNull(presetTag) + preset?.tags.orEmpty()).distinct(), ).withDefaultReminders(), - ).also { baseline = it.toForm().copy(title = "") } + ).also { + baseline = it.toForm().copy(title = "") + startIsDefault = it.start != null && !it.isAllDay + } } } @@ -255,6 +276,7 @@ class TaskEditViewModel @Inject constructor( loadedStart = task.start loadedDue = task.due loadedAllDay = task.isAllDay + loadedUntimed = task.untimed loadedKindAllDay = task.isAllDay _state.value = withFields( TaskEditUiState( @@ -264,8 +286,11 @@ class TaskEditViewModel @Inject constructor( description = task.description?.readableDescription().orEmpty(), descriptionHtml = task.description?.takeIf { it.looksLikeHtml() }, listId = task.listId, - start = task.start, - due = task.due, + // 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) }, isAllDay = task.isAllDay, untimed = task.untimed, untimedEnds = repository.supportsUntimedEnds(), @@ -350,14 +375,27 @@ class TaskEditViewModel @Inject constructor( } } - fun onStartChange(value: Instant?) = update { - val next = it.copy(start = value, untimed = it.untimed.takeUnless { end -> end == TaskEnd.START && value == null }) - next.withDatedReminders(lostDates = it.hasDates && !next.hasDates) - } + fun onStartChange(value: Instant?) = onValueChange(TaskEnd.START, value) - fun onDueChange(value: Instant?) = update { - val next = it.copy(due = value, untimed = it.untimed.takeUnless { end -> end == TaskEnd.DUE && value == null }) - next.withDatedReminders(lostDates = it.hasDates && !next.hasDates) + fun onDueChange(value: Instant?) = onValueChange(TaskEnd.DUE, value) + + /** + * [end] set to [value] in the form's current kind, or cleared. Clearing the + * timed end leaves the other one alone without a time, which is all-day. + */ + private fun onValueChange(end: TaskEnd, value: Instant?) = update { s -> + if (end == TaskEnd.START) startIsDefault = false + val withValue = if (end == TaskEnd.START) s.copy(start = value) else s.copy(due = value) + val loneUntimed = value == null && s.untimed == end.other + if (loneUntimed) { + val date = checkNotNull(s.valueOf(end.other)).calendarDate(allDay = false) + val allDay = withValue.copy(isAllDay = true, untimed = null).let { + if (end.other == TaskEnd.START) it.copy(start = allDayInstantOf(date)) else it.copy(due = allDayInstantOf(date)) + } + return@update switchedKind(s, allDay) + } + val next = withValue.copy(untimed = s.untimed.takeUnless { it == end && value == null }) + next.withDatedReminders(lostDates = s.hasDates && !next.hasDates) } /** @@ -367,9 +405,12 @@ class TaskEditViewModel @Inject constructor( * of an all-day task leaves the other end's date without one. */ fun onWhenChange(end: TaskEnd, date: LocalDate, time: LocalTime?) = update { s -> - val other = if (end == TaskEnd.START) TaskEnd.DUE else TaskEnd.START + val other = end.other val otherValue = s.valueOf(other) - val allDay = time == null && (otherValue == null || !s.hasTime(other) || !s.untimedEnds) + // A new task's untouched "now" start goes along with a due picked without a time. + val otherFollows = end == TaskEnd.DUE && startIsDefault + if (end == TaskEnd.START) startIsDefault = false + val allDay = time == null && (otherValue == null || !s.hasTime(other) || !s.untimedEnds || otherFollows) val value = when { time != null -> localToInstant(date, time) allDay -> allDayInstantOf(date) @@ -396,27 +437,6 @@ class TaskEditViewModel @Inject constructor( ) if (allDay == s.isAllDay) next.withDatedReminders() else switchedKind(s, next) } - /** - * All-day and timed values use different conventions (UTC midnight vs. a real - * instant in the device zone), so the switch has to move the timestamps too — - * flipping the flag alone makes an all-day task read back as "02:00", which - * looks to the user like the time reset itself. The reminders are made - * the new kind's here, so the editor shows what will be stored; switching - * straight back gives the old ones back. - */ - fun onAllDayChange(value: Boolean) = update { - if (it.isAllDay == value) return@update it - switchedKind( - it, - it.copy( - isAllDay = value, - untimed = null, - start = it.start?.rebasedForAllDay(value), - due = it.due?.rebasedForAllDay(value), - ), - ) - } - /** [switched], [it] made all-day or timed, with its reminders made the new kind. */ private fun switchedKind(it: TaskEditUiState, switched: TaskEditUiState): TaskEditUiState { if (!it.remindersTouched) { @@ -490,6 +510,7 @@ class TaskEditViewModel @Inject constructor( settings, nowMillis(), ZoneId.systemDefault(), + loadedUntimed, ).sortedForDisplay(this) val visible = if (reminders.isEmpty()) visibleFields else visibleFields + TaskFormField.Reminder val applied = StoredReminders.freshAnchors( @@ -500,6 +521,7 @@ class TaskEditViewModel @Inject constructor( settings, nowMillis(), ZoneId.systemDefault(), + loadedUntimed, ).isNotEmpty() return copy( reminders = reminders, @@ -639,7 +661,7 @@ private fun TaskEditUiState.toForm(): TaskForm = TaskForm( start = start, due = due, isAllDay = isAllDay, - untimed = untimed.takeUnless { isAllDay }, + untimed = untimed, priority = priority, parentId = parentId, percentComplete = percentComplete, diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt index 30da744..dd0c277 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt @@ -89,7 +89,7 @@ import androidx.compose.ui.unit.dp import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import de.jeanlucmakiola.agendula.R -import de.jeanlucmakiola.agendula.domain.dueAsShown +import de.jeanlucmakiola.agendula.domain.TaskEnd import de.jeanlucmakiola.agendula.domain.Priority import de.jeanlucmakiola.agendula.domain.SmartList import de.jeanlucmakiola.agendula.domain.Task @@ -861,16 +861,14 @@ private fun UpcomingRow(task: Task, onClick: () -> Unit) { /** "Today" / "Tomorrow" for the near dates, else the compact date. */ @Composable private fun upcomingDueLabel(task: Task): String? { - val due = task.due ?: return null + val due = task.shownValue(TaskEnd.DUE) ?: return null val zone = remember { ZoneId.systemDefault() } val today = remember { LocalDate.now(zone) } - val dueDate = remember(due) { - java.time.Instant.ofEpochMilli(due.toEpochMilliseconds()).atZone(zone).toLocalDate() - } + val dueDate = remember(task) { task.dateOf(TaskEnd.DUE, zone) } return when (dueDate) { today -> stringResource(R.string.home_due_today) today.plusDays(1) -> stringResource(R.string.home_due_tomorrow) - else -> task.dueAsShown?.formatDateTimeCompact(!task.dueHasTime, LocalUse24HourFormat.current) + else -> due.formatDateTimeCompact(!task.hasTime(TaskEnd.DUE), LocalUse24HourFormat.current) } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt index b2f8a0f..43d8c2a 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt @@ -69,7 +69,7 @@ import androidx.compose.material.icons.rounded.Tune import androidx.compose.material3.AlertDialog import androidx.compose.material3.SwipeToDismissBox import androidx.compose.ui.res.pluralStringResource -import de.jeanlucmakiola.agendula.domain.dueAsShown +import de.jeanlucmakiola.agendula.domain.TaskEnd import de.jeanlucmakiola.agendula.domain.TaskSortOrder import de.jeanlucmakiola.floret.components.revealOnFocus import de.jeanlucmakiola.floret.components.InlineTextField @@ -703,7 +703,7 @@ internal fun TaskRowContent( val full by animateDpAsState(if (pressed) 36.dp else 22.dp, label = "fullCorner") val small by animateDpAsState(if (pressed) 36.dp else 6.dp, label = "smallCorner") val dark = isSystemInDarkTheme() - val due = task.dueAsShown?.formatDateTimeCompact(!task.dueHasTime, LocalUse24HourFormat.current) + val due = task.shownValue(TaskEnd.DUE)?.formatDateTimeCompact(!task.hasTime(TaskEnd.DUE), LocalUse24HourFormat.current) val listName = task.listName?.takeIf { showListName && it.isNotBlank() } // Everything secondary collapses into one quiet supporting line below the title. val hasMeta = task.priority != Priority.NONE || due != null || subtaskTotal > 0 || diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetData.kt b/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetData.kt index d177d5d..93fc500 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetData.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetData.kt @@ -6,7 +6,7 @@ import de.jeanlucmakiola.agendula.data.prefs.ThemeMode import de.jeanlucmakiola.agendula.data.prefs.is24Hour import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey -import de.jeanlucmakiola.agendula.domain.dueAsShown +import de.jeanlucmakiola.agendula.domain.TaskEnd import de.jeanlucmakiola.agendula.domain.SmartList import de.jeanlucmakiola.agendula.domain.Task import de.jeanlucmakiola.agendula.domain.TaskFilter @@ -264,10 +264,10 @@ internal fun Task.toWidgetRow(now: Instant, today: LocalDate, zone: ZoneId): Wid listId = listId, occurrenceStart = occurrenceStart, title = title, - due = dueAsShown, - isAllDay = !dueHasTime, - dueKind = dueAsShown?.let { dueKind(it, !dueHasTime, today, zone) }, - isOverdue = dueAsShown?.let { isOverdue(it, !dueHasTime, now, today, zone) } ?: false, + 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, ) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetStats.kt b/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetStats.kt index 14b85b1..6ef934f 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetStats.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetStats.kt @@ -6,10 +6,10 @@ import de.jeanlucmakiola.agendula.data.prefs.ThemeMode import de.jeanlucmakiola.agendula.data.prefs.is24Hour import de.jeanlucmakiola.agendula.domain.SmartList import de.jeanlucmakiola.agendula.domain.Task +import de.jeanlucmakiola.agendula.domain.TaskEnd import de.jeanlucmakiola.agendula.domain.TaskFilter import de.jeanlucmakiola.agendula.domain.TaskFiltering import de.jeanlucmakiola.agendula.domain.TaskList -import de.jeanlucmakiola.agendula.domain.calendarDate import de.jeanlucmakiola.agendula.domain.comparator import de.jeanlucmakiola.floret.time.DayWindow import kotlinx.coroutines.flow.Flow @@ -50,7 +50,7 @@ private const val MAX_TODAY_ROWS = 20 /** Whether this open task is on the Today widget's plate: in the app's Today, or overdue. */ private fun Task.isDueToday(now: Instant, today: LocalDate, todayStart: Instant, todayEnd: Instant, zone: ZoneId): Boolean = TaskFiltering.isToday(this, todayStart, todayEnd, zone) || - due?.let { isOverdue(it, isAllDay, now, today, zone) } == true + shownValue(TaskEnd.DUE)?.let { isOverdue(it, !hasTime(TaskEnd.DUE), now, today, zone) } == true /** * How far through today a set of [open] and [completed] tasks says you are: @@ -90,10 +90,12 @@ internal fun weekDays(open: List, comparator: Comparator, now: Insta val dayTasks = if (offset == 0L) { todays } else { - later.filter { task -> task.due?.calendarDate(task.isAllDay, zone) == date } + later.filter { task -> task.dateOf(TaskEnd.DUE, zone) == date } } val overdueCount = if (offset == 0L) { - dayTasks.count { task -> task.due?.let { isOverdue(it, task.isAllDay, now, today, zone) } == true } + dayTasks.count { task -> + task.shownValue(TaskEnd.DUE)?.let { isOverdue(it, !task.hasTime(TaskEnd.DUE), now, today, zone) } == true + } } else { 0 } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index a3f2aec..eae9015 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -110,8 +110,8 @@ Evening Custom time No time - The due date loses its time too - The start date loses its time too + Your tasks app keeps one time setting for both dates, so the due date gets or loses a time along with this one + Your tasks app keeps one time setting for both dates, so the start date gets or loses a time along with this one Done Close Cancel diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/StoredRemindersTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/StoredRemindersTest.kt index 78ea5ce..d626e2a 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/StoredRemindersTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/StoredRemindersTest.kt @@ -2,10 +2,12 @@ package de.jeanlucmakiola.agendula.data.tasks import com.google.common.truth.Truth.assertThat import de.jeanlucmakiola.agendula.data.prefs.Settings +import de.jeanlucmakiola.agendula.domain.TaskEnd import de.jeanlucmakiola.agendula.domain.TaskForm import de.jeanlucmakiola.agendula.domain.TaskReminder import de.jeanlucmakiola.agendula.domain.allDayInstantOf import de.jeanlucmakiola.agendula.domain.testTask +import de.jeanlucmakiola.agendula.domain.untimedInstantOf import de.jeanlucmakiola.agendula.domain.asReminderLead import de.jeanlucmakiola.floret.reminders.asReminderLeads import org.junit.jupiter.api.Test @@ -29,6 +31,25 @@ class StoredRemindersTest { private fun stored(form: TaskForm, current: de.jeanlucmakiola.agendula.domain.Task? = null, with: Settings = settings) = StoredReminders.of(form, current, with, now.toEpochMilliseconds(), zone) + @Test + fun `an end without a time is past or not by the time it rings at, not the one it is stored at`() { + val today = LocalDate.of(2026, 10, 1) + val withTimes = Settings( + defaultReminders = listOf(TaskReminder(60), TaskReminder(0, fromStart = true)).map { it.asReminderLead() }, + allDayReminderMinuteOfDay = 13 * 60, + ) + val untimedDue = TaskForm( + title = "t", listId = 1, start = now - 1.hours, + due = untimedInstantOf(TaskEnd.DUE, today, zone), untimed = TaskEnd.DUE, + ) + val untimedStart = TaskForm( + title = "t", listId = 1, start = untimedInstantOf(TaskEnd.START, today, zone), + due = now + 5.days, untimed = TaskEnd.START, + ) + assertThat(stored(untimedDue, with = withTimes.copy(allDayReminderMinuteOfDay = 9 * 60))).isEmpty() + assertThat(stored(untimedStart, with = withTimes)).contains(TaskReminder(0, fromStart = true)) + } + @Test fun `a new task takes the defaults for the dates it has`() { val form = TaskForm(title = "t", listId = 1, start = now + 2.days, due = now + 5.days) diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapperTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapperTest.kt index 389aba0..89e9e93 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapperTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapperTest.kt @@ -475,7 +475,11 @@ class VTodoMapperTest { @Test fun `an untimed due round-trips too`() { - val dueOnly = mixed.copy(untimed = TaskEnd.DUE) + val dueOnly = mixed.copy( + dtstart = Instant.parse("2026-09-01T07:00:00Z"), + due = Instant.parse("2026-09-01T21:59:59Z"), + untimed = TaskEnd.DUE, + ) val written = VTodoMapper.write(dueOnly) assertThat(written.property("DUE")?.param(ICalValues.NO_TIME_PARAM)).isEqualTo("TRUE") assertThat(written.property("DTSTART")?.param(ICalValues.NO_TIME_PARAM)).isNull() @@ -503,6 +507,18 @@ class VTodoMapperTest { assertThat(mapped.entity.unknownProperties).contains("DUE;X-AGENDULA-NO-TIME=TRUE") } + @Test + fun `a marked value another client moved off its day boundary has a time, and loses the mark`() { + val mapped = VTodoMapper.read( + vtodo( + "DTSTART;TZID=Europe/Berlin:20260901T090000", + "DUE;X-AGENDULA-NO-TIME=TRUE;TZID=Europe/Berlin:20260901T150000", + ), + ) + assertThat(mapped.entity.untimed).isNull() + assertThat(VTodoMapper.write(mapped.entity).property("DUE")?.param(ICalValues.NO_TIME_PARAM)).isNull() + } + @Test fun `a mark on a DATE is ignored, the task is all-day`() { val read = VTodoMapper.read( diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/room/OccurrenceTimesTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/room/OccurrenceTimesTest.kt new file mode 100644 index 0000000..16baf26 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/room/OccurrenceTimesTest.kt @@ -0,0 +1,45 @@ +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.untimedInstantOf +import org.junit.jupiter.api.Test +import java.time.LocalDate +import java.time.ZoneId +import kotlin.time.Instant + +class OccurrenceTimesTest { + + private val berlin = ZoneId.of("Europe/Berlin") + + private fun at(date: LocalDate, hour: Int) = + Instant.fromEpochMilliseconds(date.atTime(hour, 0).atZone(berlin).toInstant().toEpochMilli()) + + @Test + fun `a due without a time stays on its day across a clock change (#101)`() { + val master = TaskEntity( + listId = 1, + uid = "u", + dtstart = at(LocalDate.of(2026, 10, 24), 10), + due = untimedInstantOf(TaskEnd.DUE, LocalDate.of(2026, 10, 26), berlin), + timezone = "Europe/Berlin", + untimed = TaskEnd.DUE, + rrule = "FREQ=WEEKLY", + ) + val (_, due) = occurrenceTimes(master, at(LocalDate.of(2026, 10, 31), 10)) + assertThat(due).isEqualTo(untimedInstantOf(TaskEnd.DUE, LocalDate.of(2026, 11, 2), berlin)) + } + + @Test + fun `a timed due keeps the master's length`() { + val master = TaskEntity( + listId = 1, + uid = "u", + dtstart = at(LocalDate.of(2026, 9, 1), 10), + due = at(LocalDate.of(2026, 9, 1), 12), + timezone = "Europe/Berlin", + ) + val (_, due) = occurrenceTimes(master, at(LocalDate.of(2026, 9, 8), 10)) + assertThat(due).isEqualTo(at(LocalDate.of(2026, 9, 8), 12)) + } +} diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/domain/AllDayTimeTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/domain/AllDayTimeTest.kt index b6820e9..135949f 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/domain/AllDayTimeTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/domain/AllDayTimeTest.kt @@ -67,4 +67,15 @@ class AllDayTimeTest { assertThat(start.calendarDate(allDay = false, zone = newYork)).isEqualTo(julyTwentieth) assertThat(due.calendarDate(allDay = false, zone = newYork)).isEqualTo(julyTwentieth) } + + @Test + fun `an untimed end reads as its date in the task's zone, wherever the device is`() { + val due = untimedInstantOf(TaskEnd.DUE, julyTwentieth, berlin) + val task = testTask(start = due - kotlin.time.Duration.parse("2h"), due = due) + .copy(untimed = TaskEnd.DUE, timeZone = "Europe/Berlin") + assertThat(task.dateOf(TaskEnd.DUE, ZoneId.of("Asia/Tokyo"))).isEqualTo(julyTwentieth) + assertThat(task.shownValue(TaskEnd.DUE)).isEqualTo(allDayInstantOf(julyTwentieth)) + assertThat(task.hasTime(TaskEnd.DUE)).isFalse() + assertThat(task.hasTime(TaskEnd.START)).isTrue() + } } 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 17d393a..cb268dd 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 @@ -25,6 +25,7 @@ import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain @@ -73,11 +74,10 @@ class TaskEditViewModelTest { } @Test - fun `untouched reminders survive an all-day switch while the task has no date`() { + fun `untouched reminders survive the task coming back all-day`() { val vm = editing(reminders = listOf(TaskReminder(0))) vm.onDueChange(null) - vm.onAllDayChange(true) - vm.onDueChange(due) + vm.onWhenChange(TaskEnd.DUE, LocalDate.now().plusDays(3), null) assertThat(vm.state.value.reminders).isNotEmpty() assertThat(vm.state.value.reminders.all { it.allDay.minuteOfDay != null || it.minutesBefore % (24 * 60) == 0 }) @@ -109,10 +109,9 @@ class TaskEditViewModelTest { } @Test - fun `an all-day switch or another list does not bring them back`() { + fun `another list does not bring them back`() { val vm = editing() vm.onDueChange(null) - vm.onAllDayChange(true) vm.onListChange(LIST_ID + 1) assertThat(vm.state.value.reminders).isEmpty() @@ -214,6 +213,51 @@ class TaskEditViewModelTest { assertThat(vm.state.value.untimed).isNull() } + @Test + fun `clearing the timed end leaves the other one all-day`() { + val vm = editing(start = due - 1.days) + val day = LocalDate.now().plusDays(3) + vm.onWhenChange(TaskEnd.DUE, day, null) + vm.onStartChange(null) + + val state = vm.state.value + assertThat(state.isAllDay).isTrue() + assertThat(state.untimed).isNull() + assertThat(state.due).isEqualTo(allDayInstantOf(day)) + } + + @Test + fun `a new task's untouched start goes all-day with a due picked without a time`() { + val prefs = settingsPrefs().apply { runBlocking { setDefaultStartToday(true) } } + val vm = TaskEditViewModel(repository, prefs).apply { bindNew() } + val day = LocalDate.now().plusDays(2) + vm.onWhenChange(TaskEnd.DUE, day, null) + + assertThat(vm.state.value.isAllDay).isTrue() + assertThat(vm.state.value.start).isEqualTo(allDayInstantOf(LocalDate.now())) + } + + @Test + fun `a start the user picked keeps its time beside a due without one`() { + val prefs = settingsPrefs().apply { runBlocking { setDefaultStartToday(true) } } + val vm = TaskEditViewModel(repository, prefs).apply { bindNew() } + vm.onWhenChange(TaskEnd.START, LocalDate.now(), LocalTime.of(9, 0)) + vm.onWhenChange(TaskEnd.DUE, LocalDate.now().plusDays(2), null) + + assertThat(vm.state.value.untimed).isEqualTo(TaskEnd.DUE) + } + + @Test + fun `an untimed end from another zone opens on its own date`() { + val berlinDue = untimedInstantOf(TaskEnd.DUE, LocalDate.of(2026, 11, 20), java.time.ZoneId.of("Pacific/Kiritimati")) + repository.task = task(due - 1.days, berlinDue).copy(untimed = TaskEnd.DUE, timeZone = "Pacific/Kiritimati") + repository.reminders = emptyList() + val vm = TaskEditViewModel(repository, settingsPrefs()).apply { bindEdit(TASK_ID) } + + assertThat(vm.state.value.due).isEqualTo(untimedInstantOf(TaskEnd.DUE, LocalDate.of(2026, 11, 20))) + assertThat(vm.state.value.isDirty).isFalse() + } + @Test fun `clearing the untimed end drops its mark`() { val vm = editing(start = due - 1.days) From d04ef3d6120e32d42c6ad30e4d3e4244b0e1f93d Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Tue, 17 Nov 2026 17:00:21 +0100 Subject: [PATCH 7/8] Move untimed ends by whole days, keep their zone on the wire, review fixes (#101) --- .../data/reminders/ReminderPlanner.kt | 56 ++++++---------- .../agendula/data/tasks/StoredReminders.kt | 43 ++++++------ .../data/tasks/TasksRepositoryImpl.kt | 5 +- .../agendula/data/tasks/ical/VTodoMapper.kt | 67 +++++++++++++------ .../data/tasks/provider/ProviderTaskWriter.kt | 6 +- .../data/tasks/room/RoomTaskMapper.kt | 1 + .../data/tasks/room/RoomTasksDataSource.kt | 4 +- .../data/tasks/room/TaskFormWriter.kt | 27 ++++++-- .../agendula/domain/AllDayTime.kt | 57 +++++++++++++--- .../jeanlucmakiola/agendula/domain/Models.kt | 10 ++- .../agendula/domain/TaskSorting.kt | 11 ++- .../agendula/domain/export/ExportModels.kt | 2 + .../agendula/domain/export/ICalendarWriter.kt | 17 +++-- .../agendula/domain/ical/ICalValues.kt | 15 ++++- .../agendula/ui/detail/TaskDetailScreen.kt | 4 +- .../agendula/ui/edit/TaskEditScreen.kt | 6 +- .../agendula/ui/edit/TaskEditViewModel.kt | 19 +++--- .../agendula/widget/WidgetData.kt | 26 ++++--- .../data/reminders/ReminderPlannerTest.kt | 16 +++++ .../data/tasks/ical/VTodoMapperTest.kt | 40 +++++++++++ .../tasks/provider/ProviderTaskWriterTest.kt | 1 + .../tasks/room/TaskFormWriterSeriesTest.kt | 27 ++++++++ .../agendula/domain/AllDayTimeTest.kt | 9 +++ .../agendula/domain/TaskSortingTest.kt | 12 ++++ .../domain/export/ICalendarWriterTest.kt | 20 ++++-- 25 files changed, 354 insertions(+), 147 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/ReminderPlanner.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/ReminderPlanner.kt index 5f5eb50..0396183 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/ReminderPlanner.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/ReminderPlanner.kt @@ -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 } /** diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/StoredReminders.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/StoredReminders.kt index 0cf2b19..bed566c 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/StoredReminders.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/StoredReminders.kt @@ -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 { 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 { 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, settings: Settings, now: Long, @@ -127,22 +129,23 @@ internal object StoredReminders { ): Set { 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, 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 9bc658e..21d5103 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 @@ -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, diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapper.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapper.kt index ee07c48..a2d2ce5 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapper.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapper.kt @@ -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) { diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/provider/ProviderTaskWriter.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/provider/ProviderTaskWriter.kt index 8eddb6c..e7e0cb0 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/provider/ProviderTaskWriter.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/provider/ProviderTaskWriter.kt @@ -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 } 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 30ae0eb..103d546 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 @@ -96,6 +96,7 @@ object RoomTaskMapper { rdate = task.rdate, parentId = task.parentId?.takeIf { it > 0 }, untimed = task.untimed, + timeZone = task.timezone, ) } 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 de50ef4..397af68 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 @@ -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 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) } /** diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/AllDayTime.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/AllDayTime.kt index 6cc4ca6..b5a5963 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/AllDayTime.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/AllDayTime.kt @@ -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)) 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 7d40aa9..90d1d5b 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/Models.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/Models.kt @@ -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 { diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSorting.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSorting.kt index 69bf990..38a7d0e 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSorting.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSorting.kt @@ -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 = 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 = when (this) { TaskSortOrder.PRIORITY -> compareBy( { 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 = when (this) { { it.title.lowercase() }, ) } + +private val Task.dueSortKey: Long get() = wallClock(TaskEnd.DUE)?.toEpochMilliseconds() ?: Long.MAX_VALUE diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/export/ExportModels.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/export/ExportModels.kt index 1da0013..8936ae7 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/export/ExportModels.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/export/ExportModels.kt @@ -45,6 +45,8 @@ data class ExportTask( val tags: List = 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. */ diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/export/ICalendarWriter.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/export/ICalendarWriter.kt index 9329c9c..8bf7235 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/export/ICalendarWriter.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/export/ICalendarWriter.kt @@ -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)) } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/ical/ICalValues.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/ical/ICalValues.kt index 0c9208a..05d4dad 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/ical/ICalValues.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/ical/ICalValues.kt @@ -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()) 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 7d90b0f..6093f1f 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 @@ -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, ) 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 b8908bb..404dad1 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 @@ -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, 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 f6cbb3b..ce27084 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 @@ -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(), diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetData.kt b/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetData.kt index 93fc500..0792edb 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetData.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetData.kt @@ -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 diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/data/reminders/ReminderPlannerTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/data/reminders/ReminderPlannerTest.kt index 5a803b1..db7f10c 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/data/reminders/ReminderPlannerTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/reminders/ReminderPlannerTest.kt @@ -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)) diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapperTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapperTest.kt index 89e9e93..c6fb6cb 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapperTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapperTest.kt @@ -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( diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/provider/ProviderTaskWriterTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/provider/ProviderTaskWriterTest.kt index 4be4cb1..f562ee4 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/provider/ProviderTaskWriterTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/provider/ProviderTaskWriterTest.kt @@ -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 ------------------------------------------------------------- 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..60089a3 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 @@ -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) + } } diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/domain/AllDayTimeTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/domain/AllDayTimeTest.kt index 135949f..6500f7e 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/domain/AllDayTimeTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/domain/AllDayTimeTest.kt @@ -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())) + } } diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskSortingTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskSortingTest.kt index d1853d9..a7f4feb 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskSortingTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/domain/TaskSortingTest.kt @@ -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() + } } diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/domain/export/ICalendarWriterTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/domain/export/ICalendarWriterTest.kt index a751f07..db3b3e5 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/domain/export/ICalendarWriterTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/domain/export/ICalendarWriterTest.kt @@ -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 = 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( From d95fb9c5f9932ac21ea4e1236a3e8cd68696caa2 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Tue, 17 Nov 2026 17:08:08 +0100 Subject: [PATCH 8/8] Share the untimed wall clock and zone checks, shift exceptions by days, review fixes (#101) --- .../agendula/data/tasks/StoredReminders.kt | 17 ++++++++----- .../agendula/data/tasks/ical/VTodoMapper.kt | 20 +++++++++------- .../data/tasks/room/TaskFormWriter.kt | 12 ++++++++-- .../data/tasks/transfer/ExternalImport.kt | 1 - .../agendula/domain/AllDayTime.kt | 19 +++++++++++---- .../jeanlucmakiola/agendula/domain/Models.kt | 7 +++++- .../agendula/domain/TaskSorting.kt | 6 ++--- .../agendula/domain/export/ICalendarWriter.kt | 10 ++++---- .../agendula/ui/edit/TaskEditViewModel.kt | 4 ++-- .../data/tasks/StoredRemindersTest.kt | 13 ++++++++++ .../data/tasks/ical/VTodoMapperTest.kt | 15 +++++++++++- .../tasks/room/TaskFormWriterSeriesTest.kt | 24 +++++++++++++++++++ .../domain/export/ICalendarWriterTest.kt | 9 +++++++ 13 files changed, 122 insertions(+), 35 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/StoredReminders.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/StoredReminders.kt index bed566c..0dde6b6 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/StoredReminders.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/StoredReminders.kt @@ -37,9 +37,16 @@ internal object StoredReminders { fun of(form: TaskForm, current: Task?, settings: Settings, now: Long, zone: ZoneId): List { val wanted = form.reminders.map { it.lead }.distinct() if (form.remindersChosen) return wanted + // In the frame the form holds them in, so an untouched untimed end does not read as moved. return withDefaults( - form, current?.start, current?.due, current?.isAllDay ?: form.isAllDay, settings, now, zone, - current?.untimed, current?.timeZone, + form, + current?.formValueOf(TaskEnd.START), + current?.formValueOf(TaskEnd.DUE), + current?.isAllDay ?: form.isAllDay, + settings, + now, + zone, + current?.untimed, ) } @@ -53,10 +60,9 @@ internal object StoredReminders { now: Long, zone: ZoneId, wasUntimed: TaskEnd? = null, - wasTimeZone: String? = null, ): List { val wanted = form.reminders.map { it.lead }.distinct() - val fresh = freshAnchors(form, start, due, wasAllDay, settings, now, zone, wasUntimed, wasTimeZone) + val fresh = freshAnchors(form, start, due, wasAllDay, settings, now, zone, wasUntimed) 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() @@ -76,11 +82,10 @@ internal object StoredReminders { now: Long, zone: ZoneId, wasUntimed: TaskEnd? = null, - wasTimeZone: String? = null, ): Set { val wanted = form.reminders.map { it.lead }.distinct() val gained = anchorsOf(form.start, form.due) - anchorsOf(start, due) - val was = TaskDates(start, due, wasAllDay, wasUntimed, wasTimeZone) + val was = TaskDates(start, due, wasAllDay, wasUntimed) return gained + revived(form, was, wanted, settings, now, zone) } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapper.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapper.kt index a2d2ce5..faa5e5b 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapper.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapper.kt @@ -4,7 +4,10 @@ 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.knownZone +import de.jeanlucmakiola.agendula.domain.untimedDate import de.jeanlucmakiola.agendula.domain.untimedInstantOf +import de.jeanlucmakiola.agendula.domain.untimedWall import de.jeanlucmakiola.agendula.domain.zoneOr import de.jeanlucmakiola.agendula.domain.TaskStatus import de.jeanlucmakiola.agendula.domain.ical.ICalComponent @@ -152,7 +155,7 @@ object VTodoMapper { // write would emit the caller's minted UID alongside the empty one. val uid = take(uidProperty, uidProperty?.value?.trim()).orEmpty() - val zoneHint = vtodo.property("DTSTART")?.param("TZID") ?: vtodo.property("DUE")?.param("TZID") + val zoneHint = knownZone(vtodo.property("DTSTART")?.param("TZID")) ?: knownZone(vtodo.property("DUE")?.param("TZID")) val dtstart = readTime(vtodo, "DTSTART", TaskEnd.START, zoneHint) val due = readTime(vtodo, "DUE", TaskEnd.DUE, zoneHint) @@ -571,11 +574,9 @@ object VTodoMapper { noTime = marked && value.tzid != null && onDayBoundary(end!!, value.instant, zoneOr(value.tzid)), ) 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) + val wall = ICalValues.floatingWall(property)?.takeIf { marked && it == untimedWall(end!!, it.toLocalDate()) } + if (wall != null) { + TimeRead(property, untimedInstantOf(end!!, wall.toLocalDate(), zoneOr(zoneHint)), zoneHint, false, true, noTime = true) } else { // Readable but not reproducible: the column gets the best-effort // instant, the property round-trips from the residue verbatim. @@ -596,12 +597,13 @@ object VTodoMapper { // Resolve the zone once. Letting the parameter and the value each decide // 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 } - if (entity.untimed?.propertyName == name) { + val tzid = knownZone(entity.timezone) + val untimed = entity.untimed + if (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()))) + ICalProperty(name, listOf(mark), ICalValues.formatFloating(untimedWall(untimed, instant.untimedDate(null)))) } else { ICalProperty(name, listOf(mark, ICalParam("TZID", tzid)), ICalValues.formatDateTime(instant, tzid)) } 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 94ecb49..51d33dd 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 @@ -111,8 +111,16 @@ object TaskFormWriter { status = master.status, percentComplete = master.percentComplete, completedAt = master.completedAt, - exdate = if (delta == null || delta == kotlin.time.Duration.ZERO) edited.exdate - else shiftValues(edited.exdate, delta, master.timezone ?: tzId), + exdate = when { + delta == null || delta == kotlin.time.Duration.ZERO -> edited.exdate + // Exceptions of a start without a time move by whole days, as the start does. + !form.isAllDay && form.untimed == TaskEnd.START -> { + val zone = master.timezone ?: tzId + val days = ChronoUnit.DAYS.between(master.dtstart!!.untimedDate(zone), dtstart!!.untimedDate(tzId)) + mapValues(edited.exdate, zone) { untimedMoved(TaskEnd.START, it, days, zone, zoneOr(zone)) } + } + else -> shiftValues(edited.exdate, delta, master.timezone ?: tzId) + }, ) } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/transfer/ExternalImport.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/transfer/ExternalImport.kt index e21774f..b08107b 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/transfer/ExternalImport.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/transfer/ExternalImport.kt @@ -224,7 +224,6 @@ class ExternalImport @Inject constructor( dtstart = start, due = due, isAllDay = isAllDay, - untimed = untimed, rrule = rrule, rdate = rdate, createdAt = created, diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/AllDayTime.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/AllDayTime.kt index b5a5963..0b3a592 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/AllDayTime.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/AllDayTime.kt @@ -86,9 +86,21 @@ data class TaskDates( fun countsFromUntimed(fromStart: Boolean): Boolean = !isAllDay && untimed == reminderEnd(fromStart) } +/** [timeZone] when it names a zone this device knows, else null. */ +fun knownZone(timeZone: String?): String? = timeZone?.takeIf { runCatching { ZoneId.of(it) }.isSuccess } + /** [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 + knownZone(timeZone)?.let(ZoneId::of) ?: fallback + +/** + * The wall clock an untimed [end] on [date] is written at where no zone + * applies (a floating value): the first or the last second of the day. + */ +fun untimedWall(end: TaskEnd, date: java.time.LocalDate): java.time.LocalDateTime = when (end) { + TaskEnd.START -> date.atStartOfDay() + TaskEnd.DUE -> date.atTime(23, 59, 59) +} /** * The stored instant for [date] on an untimed [end]: the first or the last @@ -96,10 +108,7 @@ fun zoneOr(timeZone: String?, fallback: ZoneId = ZoneId.systemDefault()): ZoneId * 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 at = when (end) { - TaskEnd.START -> date.atStartOfDay(zone) - TaskEnd.DUE -> date.atTime(23, 59, 59).atZone(zone) - } + val at = if (end == TaskEnd.START) date.atStartOfDay(zone) else untimedWall(end, date).atZone(zone) return Instant.fromEpochMilliseconds(at.toInstant().toEpochMilli()) } 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 90d1d5b..42540a6 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/Models.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/Models.kt @@ -119,7 +119,12 @@ data class Task( fun valueOf(end: TaskEnd): Instant? = if (end == TaskEnd.START) start else due /** Whether [end] carries a time of day. */ - fun hasTime(end: TaskEnd): Boolean = dates.hasTime(end) + fun hasTime(end: TaskEnd): Boolean = !isAllDay && untimed != end + + /** The due as sorting reads it, worked out once: a due without a time counts from the start of its day. */ + internal val dueSortMillis: Long by lazy(LazyThreadSafetyMode.NONE) { + wallClock(TaskEnd.DUE)?.toEpochMilliseconds() ?: Long.MAX_VALUE + } /** [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? { diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSorting.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSorting.kt index 38a7d0e..6562c38 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSorting.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskSorting.kt @@ -9,7 +9,7 @@ object TaskSorting { val DEFAULT: Comparator = compareBy( { it.isCompleted }, { it.due == null }, - { it.dueSortKey }, + { it.dueSortMillis }, { -it.priority.ordinal }, { it.title.lowercase() }, ) @@ -23,7 +23,7 @@ fun TaskSortOrder.comparator(): Comparator = when (this) { TaskSortOrder.PRIORITY -> compareBy( { it.isCompleted }, { -it.priority.ordinal }, - { it.dueSortKey }, + { it.dueSortMillis }, { it.title.lowercase() }, ) TaskSortOrder.TITLE -> compareBy({ it.isCompleted }, { it.title.lowercase() }) @@ -33,5 +33,3 @@ fun TaskSortOrder.comparator(): Comparator = when (this) { { it.title.lowercase() }, ) } - -private val Task.dueSortKey: Long get() = wallClock(TaskEnd.DUE)?.toEpochMilliseconds() ?: Long.MAX_VALUE diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/domain/export/ICalendarWriter.kt b/app/src/main/java/de/jeanlucmakiola/agendula/domain/export/ICalendarWriter.kt index 8bf7235..5d42145 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/domain/export/ICalendarWriter.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/domain/export/ICalendarWriter.kt @@ -8,6 +8,7 @@ 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 de.jeanlucmakiola.agendula.domain.untimedWall import java.time.ZoneOffset import java.time.format.DateTimeFormatter import kotlin.time.Instant @@ -123,11 +124,12 @@ object ICalendarWriter { // 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 (task.untimed == end) { + } else if (task.untimed == end && (end == TaskEnd.DUE || task.rrule.isNullOrBlank() && task.rdate.isNullOrBlank())) { // 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) + // another day for whoever imports it elsewhere (#101). Not for the + // start of a series, whose UNTIL and RDATE stay UTC and §3.3.10 wants + // them floating alongside a floating start: that one goes out timed. + val wall = untimedWall(end, instant.untimedDate(task.timeZone)) rawProperty("$name;${ICalValues.NO_TIME_PARAM}=TRUE", ICalValues.formatFloating(wall)) } else { rawProperty(name, formatUtc(instant)) 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 ce27084..651e527 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 @@ -21,6 +21,7 @@ import de.jeanlucmakiola.agendula.ui.common.toLocalTime import de.jeanlucmakiola.agendula.domain.TaskDates import de.jeanlucmakiola.agendula.domain.calendarDate import de.jeanlucmakiola.agendula.domain.untimedInstantOf +import de.jeanlucmakiola.agendula.domain.untimedWall import de.jeanlucmakiola.agendula.ui.common.localToInstant import de.jeanlucmakiola.agendula.domain.TaskList import de.jeanlucmakiola.agendula.domain.TaskReminder @@ -131,8 +132,7 @@ data class TaskEditUiState( fun localValueOf(end: TaskEnd): LocalDateTime? { val value = valueOf(end) ?: return null if (hasTime(end)) return LocalDateTime.of(value.calendarDate(allDay = false), value.toLocalTime()) - val date = value.calendarDate(isAllDay) - return if (end == TaskEnd.START) date.atStartOfDay() else date.atTime(23, 59) + return untimedWall(end, value.calendarDate(isAllDay)) } } diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/StoredRemindersTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/StoredRemindersTest.kt index d626e2a..548cfca 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/StoredRemindersTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/StoredRemindersTest.kt @@ -50,6 +50,19 @@ class StoredRemindersTest { assertThat(stored(untimedStart, with = withTimes)).contains(TaskReminder(0, fromStart = true)) } + @Test + fun `an untouched untimed end from another zone does not count as moved`() { + val day = LocalDate.of(2026, 9, 3) + val current = testTask(id = 1, start = now - 30.days, due = untimedInstantOf(TaskEnd.DUE, day, ZoneId.of("America/New_York"))) + .copy(untimed = TaskEnd.DUE, timeZone = "America/New_York") + val own = TaskReminder(0, fromStart = true) + val form = TaskForm( + title = "t", listId = 1, start = current.start, due = current.formValueOf(TaskEnd.DUE), + untimed = TaskEnd.DUE, reminders = listOf(own), + ) + assertThat(stored(form, current)).containsExactly(own) + } + @Test fun `a new task takes the defaults for the dates it has`() { val form = TaskForm(title = "t", listId = 1, start = now + 2.days, due = now + 5.days) diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapperTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapperTest.kt index c6fb6cb..5559de9 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapperTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/ical/VTodoMapperTest.kt @@ -6,6 +6,7 @@ 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.untimedDate import de.jeanlucmakiola.agendula.domain.TaskStatus import de.jeanlucmakiola.agendula.domain.ical.ICalComponent import de.jeanlucmakiola.agendula.domain.ical.ICalParser @@ -554,11 +555,23 @@ class VTodoMapperTest { @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.value).endsWith("T000000") assertThat(start.param("TZID")).isNull() assertThat(start.param(ICalValues.NO_TIME_PARAM)).isEqualTo("TRUE") } + @Test + fun `a floating untimed start on a day without a midnight still reads as one`() { + val read = VTodoMapper.read( + vtodo( + "DTSTART;X-AGENDULA-NO-TIME=TRUE:20260906T000000", + "DUE;TZID=America/Santiago:20260906T170000", + ), + ).entity + assertThat(read.untimed).isEqualTo(TaskEnd.START) + assertThat(read.dtstart!!.untimedDate(read.timezone)).isEqualTo(java.time.LocalDate.of(2026, 9, 6)) + } + @Test fun `a mark on a DATE is ignored, the task is all-day`() { val read = VTodoMapper.read( 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 60089a3..4bba15b 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 @@ -145,4 +145,28 @@ class TaskFormWriterSeriesTest { assertThat(edited.dtstart).isEqualTo(untimedInstantOf(TaskEnd.START, LocalDate.of(2026, 1, 12), berlin)) assertThat(edited.untimed).isEqualTo(TaskEnd.START) } + + @Test + fun `its exceptions move by whole days with it`() { + val berlin = java.time.ZoneId.of("Europe/Berlin") + val untimed = master.copy( + dtstart = untimedInstantOf(TaskEnd.START, LocalDate.of(2026, 3, 20), berlin), + due = null, + untimed = TaskEnd.START, + rrule = "FREQ=DAILY", + exdate = "20260327T000000", + ) + val occurrence = untimedInstantOf(TaskEnd.START, LocalDate.of(2026, 3, 28), berlin) + val form = TaskForm( + title = "Water plants", + listId = 1, + start = untimedInstantOf(TaskEnd.START, LocalDate.of(2026, 3, 30), berlin), + due = Instant.parse("2026-03-31T10:00:00Z"), + untimed = TaskEnd.START, + rrule = "FREQ=DAILY", + ) + val edited = TaskFormWriter.seriesEdit(untimed, occurrence, null, form, now, "Europe/Berlin") + + assertThat(edited.exdate).isEqualTo("20260329T000000") + } } diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/domain/export/ICalendarWriterTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/domain/export/ICalendarWriterTest.kt index db3b3e5..d7b4586 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/domain/export/ICalendarWriterTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/domain/export/ICalendarWriterTest.kt @@ -153,6 +153,15 @@ class ICalendarWriterTest { assertThat(lines).contains("DUE:20250802T120000Z") } + @Test + fun `the untimed start of a series goes out timed, beside its UTC rule`() { + val start = Instant.parse("2025-08-01T22:00:00Z") + val lines = linesOf( + write(task(start = start, due = noon, untimed = TaskEnd.START, timeZone = "Europe/Berlin", rrule = "FREQ=DAILY;UNTIL=20250901T215959Z")), + ) + assertThat(lines).contains("DTSTART:20250801T220000Z") + } + @Test fun `an exported untimed end reads back as one, on its date`() { val start = Instant.parse("2025-08-01T22:00:00Z")