Merge #101 into release/v1.4.0

# Conflicts:
#	app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/TasksRepository.kt
#	app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/TasksRepositoryImpl.kt
#	app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/room/RoomTaskMapper.kt
#	app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/room/TaskFormWriter.kt
#	app/src/main/java/de/jeanlucmakiola/agendula/domain/TaskForm.kt
#	app/src/main/java/de/jeanlucmakiola/agendula/domain/export/ExportModels.kt
#	app/src/main/java/de/jeanlucmakiola/agendula/ui/edit/TaskEditViewModel.kt
#	app/src/test/java/de/jeanlucmakiola/agendula/data/tasks/room/TaskFormWriterSeriesTest.kt
This commit is contained in:
makiolaj committed 2026-11-18 19:47:30 +01:00
commit 55f149d0f3
50 files changed
+2431 -285

No files matched your search

+13
View File
@@ -19,6 +19,19 @@ All notable changes to this project are documented here. The format follows
from" in the repeat picker. With Agendula's own storage only; over CalDAV
the choice syncs between Agendula installs, and other apps see the moved
task with its plain rule (#79).
### 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).
- 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 gain or
drop their time together (#101).
## [1.3.2] - 2026-11-13
@@ -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')"
]
}
}
@@ -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"
}
@@ -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()
/**
@@ -3,8 +3,11 @@ 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.TaskDates
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
@@ -53,15 +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 = if (reminder.fromStart) task.start ?: task.due!! else task.due ?: task.start!!
val trigger = triggerAt(
anchor,
task.isAllDay,
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.
@@ -74,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
@@ -98,6 +100,19 @@ internal object ReminderPlanner {
.take(MAX_ALARMS)
.toSet()
/**
* When a reminder [leadMinutes] before the end [fromStart] picks (see
* [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(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
}
/**
* When a reminder [leadMinutes] before [anchor] fires.
*
@@ -116,9 +131,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()
}
@@ -17,6 +17,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.TaskEnd
import de.jeanlucmakiola.agendula.domain.readableDescription
import de.jeanlucmakiola.agendula.data.prefs.is24Hour
import de.jeanlucmakiola.agendula.data.di.ApplicationScope
@@ -67,12 +68,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.shownValue(TaskEnd.DUE)?.let { due ->
context.getString(
R.string.reminder_due_at,
formatReminderDue(
due.toEpochMilliseconds(),
task.isAllDay,
!task.hasTime(TaskEnd.DUE),
is24Hour = settings.timeFormat.is24Hour(DateFormat.is24HourFormat(context)),
relative = RelativeDays(
today = context.getString(R.string.reminder_day_today),
@@ -3,6 +3,8 @@ 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
import de.jeanlucmakiola.agendula.domain.calendarDate
@@ -35,7 +37,17 @@ internal object StoredReminders {
fun of(form: TaskForm, current: Task?, settings: Settings, now: Long, zone: ZoneId): List<TaskReminder> {
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)
// In the frame the form holds them in, so an untouched untimed end does not read as moved.
return withDefaults(
form,
current?.formValueOf(TaskEnd.START),
current?.formValueOf(TaskEnd.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 +59,10 @@ internal object StoredReminders {
settings: Settings,
now: Long,
zone: ZoneId,
wasUntimed: TaskEnd? = null,
): List<TaskReminder> {
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 +81,12 @@ internal object StoredReminders {
settings: Settings,
now: Long,
zone: ZoneId,
wasUntimed: TaskEnd? = null,
): Set<Boolean> {
val wanted = form.reminders.map { it.lead }.distinct()
val gained = anchorsOf(form.start, form.due) - anchorsOf(start, due)
return gained + revived(form, start, due, wasAllDay, wanted, settings, now, zone)
val was = TaskDates(start, due, wasAllDay, wasUntimed)
return gained + revived(form, was, wanted, settings, now, zone)
}
/**
@@ -111,9 +126,7 @@ internal object StoredReminders {
*/
private fun revived(
form: TaskForm,
start: Instant?,
due: Instant?,
wasAllDay: Boolean,
was: TaskDates,
wanted: List<TaskReminder>,
settings: Settings,
now: Long,
@@ -121,20 +134,23 @@ internal object StoredReminders {
): Set<Boolean> {
if (form.rrule != null || wanted.isEmpty()) return emptySet()
val named = wanted.map { it.fromStart }.toSet()
val defaults = settings.defaultRemindersFor(form.listId, wasAllDay)
fun revived(fromStart: Boolean, was: Instant?, isNow: Instant?): Boolean {
if (was == null || isNow == null || fromStart in named) return false
val moved = if (wasAllDay == form.isAllDay) {
isNow != was
val defaults = settings.defaultRemindersFor(form.listId, was.isAllDay)
fun revived(fromStart: Boolean, before: Instant?, isNow: Instant?): Boolean {
if (before == null || isNow == null || fromStart in named) return false
val moved = if (was.isAllDay == form.isAllDay) {
isNow != before
} else {
isNow.calendarDate(form.isAllDay, zone) != was.calendarDate(wasAllDay, zone)
isNow.calendarDate(form.isAllDay, zone) != before.calendarDate(was.isAllDay, zone)
}
val leads = defaults.filter { it.fromStart == fromStart }
return moved && leads.isNotEmpty() && leads.all {
ReminderPlanner.triggerAt(was, wasAllDay, 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]. */
@@ -147,10 +163,10 @@ internal object StoredReminders {
*/
private fun defaultsFor(form: TaskForm, settings: Settings, now: Long, zone: ZoneId): List<TaskReminder> =
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,
form.isAllDay,
if ((if (reminder.fromStart) form.start else form.due) == null) return@filter false
form.rrule != null || ReminderPlanner.ringsAt(
TaskDates(form.start, form.due, form.isAllDay, form.untimed),
reminder.fromStart,
reminder.minutesBefore,
settings.allDayReminderMinuteOfDay,
zone,
@@ -102,4 +102,9 @@ interface TasksRepository {
/** Whether the active store can repeat a series from completion (#79): only Agendula's own. */
fun supportsRepeatFromCompletion(): Boolean = false
/**
* 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
}
@@ -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,9 +141,10 @@ 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,
parentId = parentId,
location = task.location,
@@ -266,6 +268,7 @@ class TasksRepositoryImpl @Inject constructor(
withContext(io) { dataSource.reorderLists(listIds) }
override fun supportsRepeatFromCompletion(): Boolean = providerResolver.mode() == StorageMode.OWN
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
@@ -3,6 +3,12 @@ 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.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
import de.jeanlucmakiola.agendula.domain.ical.ICalParam
@@ -11,6 +17,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
@@ -148,20 +155,28 @@ 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 = 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)
// 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
// 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, in the zone the task is read in.
val untimed = when {
allDay || dtstart.noTime == due.noTime -> null
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
// 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 +262,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 +446,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)
@@ -528,26 +546,43 @@ 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
/** 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
/** 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
}
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)
// 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.Timed -> TimeRead(
property, value.instant, value.tzid, false, true,
noTime = marked && value.tzid != null && onDayBoundary(end!!, value.instant, zoneOr(value.tzid)),
)
is ICalValues.TimeValue.Unrepresentable -> {
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.
TimeRead(property, value.instant, null, false, false)
}
}
}
}
@@ -562,11 +597,37 @@ 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 }
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(untimedWall(untimed, instant.untimedDate(null))))
} 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 [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(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) {
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
@@ -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, a new
// zone, or a switch to all-day, is its own value from then on.
untimed = current.untimed?.takeUnless { end ->
allDay || timezone != current.timezone || when (end) {
TaskEnd.START -> dtstart != current.dtstart
TaskEnd.DUE -> due != current.due
}
},
timezone = timezone,
rrule = rrule,
rdate = rdate,
@@ -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
@@ -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
@@ -77,6 +77,7 @@ object RoomTaskMapper {
repeatFromCompletion = repeatFromCompletion,
hasRecurrenceDates = !series.rdate.isNullOrBlank(),
isReadOnly = row.listReadOnly,
untimed = row.task.untimed,
)
fun exportTask(task: TaskEntity): ExportTask = ExportTask(
@@ -100,6 +101,8 @@ object RoomTaskMapper {
rdate = task.rdate,
parentId = task.parentId?.takeIf { it > 0 },
repeatFromCompletion = task.repeatsFromCompletion,
untimed = task.untimed,
timeZone = task.timezone,
)
}
@@ -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.untimedMoved
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
@@ -61,12 +66,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<Instant?, Instant?> {
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 untimedMoved(TaskEnd.DUE, anchor, days, master.timezone, 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. */
@@ -590,6 +600,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
}
@@ -1,11 +1,17 @@
package de.jeanlucmakiola.agendula.data.tasks.room
import de.jeanlucmakiola.agendula.domain.TaskEnd
import de.jeanlucmakiola.agendula.domain.TaskForm
import de.jeanlucmakiola.agendula.domain.calendarDate
import de.jeanlucmakiola.agendula.domain.untimedDate
import de.jeanlucmakiola.agendula.domain.untimedMoved
import de.jeanlucmakiola.agendula.domain.zoneOr
import de.jeanlucmakiola.agendula.domain.TaskStatus
import de.jeanlucmakiola.agendula.domain.ical.ICalValues
import de.jeanlucmakiola.agendula.domain.normalizeTags
import de.jeanlucmakiola.agendula.domain.recurrence.RepeatFromCompletion
import de.jeanlucmakiola.agendula.domain.toICal
import java.time.temporal.ChronoUnit
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.seconds
import kotlin.time.Instant
@@ -62,6 +68,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,
@@ -104,17 +111,25 @@ object TaskFormWriter {
tzId: String,
): TaskEntity {
val edited = withRule(apply(master, form, now, tzId), form.rrule, form.repeatFromCompletion)
val dtstart = shifted(master.dtstart, occurrenceStart, form.start, form.isAllDay)
val dtstart = shifted(TaskEnd.START, master, occurrenceStart, form, tzId)
val delta = if (dtstart != null && master.dtstart != null) dtstart - master.dtstart else null
return edited.copy(
dtstart = dtstart,
due = shifted(master.due, occurrenceDue, form.due, form.isAllDay),
due = shifted(TaskEnd.DUE, master, occurrenceDue, form, tzId),
// The occurrence's completion is its own, not the series'.
status = master.status,
percentComplete = master.percentComplete,
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)
},
)
}
@@ -171,10 +186,19 @@ object TaskFormWriter {
private val VALUE_DATE = java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd")
private val VALUE_DATE_TIME = java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss")
private fun shifted(anchor: Instant?, was: Instant?, now: Instant?, allDay: Boolean): Instant? = when {
now == null -> null
anchor == null || was == null -> now.forAllDay(allDay)
else -> (anchor + (now - was)).forAllDay(allDay)
/**
* [master]'s [end] moved as far as the occurrence's moved from [was] to the
* form's value. An end without a time moves by whole days, so a clock
* change in between cannot push it off its date.
*/
private fun shifted(end: TaskEnd, master: TaskEntity, was: Instant?, form: TaskForm, tzId: String): Instant? {
val anchor = if (end == TaskEnd.START) master.dtstart else master.due
val now = (if (end == TaskEnd.START) form.start else form.due) ?: return null
if (anchor == null || was == null) return now.forAllDay(form.isAllDay)
if (form.isAllDay || form.untimed != end) return (anchor + (now - was)).forAllDay(form.isAllDay)
val zone = zoneOr(tzId)
val days = ChronoUnit.DAYS.between(was.untimedDate(master.timezone), now.calendarDate(allDay = false, zone = zone))
return untimedMoved(end, anchor, days, master.timezone, zone)
}
/**
@@ -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")
}
}
}
}
@@ -40,3 +40,91 @@ 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 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,
;
val other: TaskEnd get() = if (this == START) DUE else START
}
/**
* 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
/** 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 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 =
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
* 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 at = if (end == TaskEnd.START) date.atStartOfDay(zone) else untimedWall(end, date).atZone(zone)
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))
@@ -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. */
@@ -113,7 +115,44 @@ 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,
) {
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 = !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? {
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 {
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
@@ -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(
@@ -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))
}
}
@@ -29,6 +29,8 @@ data class TaskForm(
val rrule: String? = null,
/** With [rrule], the next occurrence counts from completion rather than the schedule (#79). */
val repeatFromCompletion: Boolean = false,
/** The end without a time on an otherwise timed task; see [TaskEnd]. */
val untimed: TaskEnd? = null,
) {
fun validate(): Set<TaskFormError> = buildSet {
if (title.isBlank()) add(TaskFormError.BLANK_TITLE)
@@ -2,11 +2,14 @@ package de.jeanlucmakiola.agendula.domain
/** Default task ordering, extracted so it's unit-testable without the repository. */
object TaskSorting {
/** Open before completed; within each: due-soonest (none last), priority, title. */
/**
* Open before completed; within each: due-soonest (none last), priority,
* title. A due without a time, all-day or not, counts from the start of its day.
*/
val DEFAULT: Comparator<Task> = compareBy(
{ it.isCompleted },
{ it.due == null },
{ it.due?.toEpochMilliseconds() ?: Long.MAX_VALUE },
{ it.dueSortMillis },
{ -it.priority.ordinal },
{ it.title.lowercase() },
)
@@ -20,7 +23,7 @@ fun TaskSortOrder.comparator(): Comparator<Task> = when (this) {
TaskSortOrder.PRIORITY -> compareBy<Task>(
{ it.isCompleted },
{ -it.priority.ordinal },
{ it.due?.toEpochMilliseconds() ?: Long.MAX_VALUE },
{ it.dueSortMillis },
{ it.title.lowercase() },
)
TaskSortOrder.TITLE -> compareBy({ it.isCompleted }, { it.title.lowercase() })
@@ -45,6 +45,10 @@ data class ExportTask(
val tags: List<String> = emptyList(),
/** The series repeats from completion (#79). */
val repeatFromCompletion: Boolean = false,
/** 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. */
@@ -1,12 +1,15 @@
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
import de.jeanlucmakiola.agendula.domain.ical.ICalValues
import de.jeanlucmakiola.agendula.domain.recurrence.RepeatFromCompletion
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
@@ -91,8 +94,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, 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.
@@ -118,11 +121,18 @@ object ICalendarWriter {
line("END:VTODO")
}
private fun StringBuilder.dateProperty(name: String, instant: Instant, allDay: 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 (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). 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))
}
@@ -14,6 +14,19 @@ 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. 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"
/** 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
@@ -150,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())
@@ -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) }
}
@@ -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(
@@ -101,6 +101,7 @@ 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.TaskDetail
import de.jeanlucmakiola.floret.components.revealOnFocus
import de.jeanlucmakiola.floret.components.GroupedSurface
@@ -371,6 +372,7 @@ private fun DetailBody(
task.isAllDay,
allDayMinuteOfDay,
anchored = task.start != null && task.due != null,
untimedAnchor = task.dates.countsFromUntimed(reminder.fromStart),
),
style = MaterialTheme.typography.titleMedium,
)
@@ -719,21 +721,27 @@ private fun DetailCard(
@Composable
private fun taskWhenLines(task: Task): Pair<String, String?>? {
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)}"
val secondary = if (allDay) null else "${start.formatTime(use24)} – ${due.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 –"
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(dueTime == null) to dueTime
start != null -> start.formatDate(startTime == null) to startTime
else -> null
}
}
@@ -0,0 +1,209 @@
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
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.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.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 de.jeanlucmakiola.floret.locale.localizedDateFormatter
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.format.DateTimeFormatter
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, 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, 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]. [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(
title: String,
initial: Instant?,
allDay: Boolean,
hasTime: Boolean,
dateOnly: Boolean,
linkedNote: String?,
notBefore: LocalDateTime?,
notAfter: LocalDateTime?,
onChange: (LocalDate, LocalTime?) -> Unit,
onDismiss: () -> Unit,
) {
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) }
var showClock by rememberSaveable { mutableStateOf(false) }
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 stagedTime(d: LocalDate) = defaultPickerTime(d, LocalDateTime.now(), notBefore, notAfter)
fun commit(d: LocalDate, t: LocalTime?) {
onChange(d, t)
onDismiss()
}
fun pickDate(d: LocalDate) {
if (staging) {
date = d
time = stagedTime(d)
} else {
commit(d, time)
}
}
fun pickTime(t: LocalTime) {
commit(date ?: defaultPickerDate(t, LocalDateTime.now(), notBefore, notAfter), t)
}
FullScreenPicker(
title = title,
onDismiss = onDismiss,
actions = {
if (staging) {
TextButton(
onClick = { date?.let { commit(it, time ?: stagedTime(it)) } },
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))
QuickDate.entries.forEachIndexed { index, quick ->
GroupedRow(
title = stringResource(quick.labelRes),
summary = dayLabel(quick.resolve(today)),
position = positionOf(index, dateRows),
checked = quick == quickDate,
onClick = { pickDate(quick.resolve(today)) },
)
}
val customDate = date?.takeIf { quickDate == null }
GroupedRow(
title = stringResource(R.string.picker_date_pick),
summary = customDate?.let(::dayLabel),
position = positionOf(QuickDate.entries.size, dateRows),
checked = customDate != null,
onClick = { showCalendar = true },
)
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(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),
position = positionOf(QuickTime.entries.size + 1, timeRows),
checked = date != null && time == 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) {
DatePickerAlert(
initial = date ?: today,
onConfirm = {
showCalendar = false
pickDate(it)
},
onDismiss = { showCalendar = false },
)
}
if (showClock) {
TimePickerAlert(
initial = time ?: stagedTime(date ?: today),
onConfirm = {
showClock = false
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 = localizedDateFormatter(locale, "EEEdMMM")
val otherYear: DateTimeFormatter = localizedDateFormatter(locale, "EEEdMMMyyyy")
}
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
}
@@ -0,0 +1,80 @@
package de.jeanlucmakiola.agendula.ui.edit
import java.time.LocalDate
import java.time.LocalDateTime
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) {
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? = time.truncatedTo(ChronoUnit.MINUTES).let { t -> entries.firstOrNull { it.time == t } }
}
}
/**
* 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 [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)
}
/** 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
}
@@ -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
@@ -40,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
@@ -328,8 +325,8 @@ fun RecurrencePicker(
}
if (showUntilPicker) {
UntilDatePicker(
initial = untilDate ?: startDate,
DatePickerAlert(
initial = (untilDate ?: startDate).toJavaLocalDate(),
onConfirm = {
untilIso = it.toString()
showUntilPicker = false
@@ -431,38 +428,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(
@@ -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
@@ -93,14 +91,10 @@ 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.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
@@ -125,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
@@ -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
@@ -323,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,
@@ -579,7 +564,13 @@ 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.dates.countsFromUntimed(reminder.fromStart),
),
onRemove = { viewModel.removeReminder(reminder) },
)
}
@@ -670,14 +661,24 @@ private fun EditContent(
}
pickerTarget?.let { target ->
val current = if (target == PickerTarget.Start) state.start else state.due
DateTimePickerFlow(
initial = current,
val end = if (target == PickerTarget.Start) TaskEnd.START else TaskEnd.DUE
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
}
DateTimePickerSheet(
title = stringResource(if (target == PickerTarget.Start) R.string.edit_start_label else R.string.edit_due_label),
initial = state.valueOf(end),
allDay = state.isAllDay,
onResult = {
if (target == PickerTarget.Start) viewModel.onStartChange(it) else viewModel.onDueChange(it)
pickerTarget = null
},
hasTime = state.hasTime(end),
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 },
)
}
@@ -900,8 +901,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.
*/
@@ -911,6 +912,7 @@ private fun ScheduleRow(
label: String,
value: Instant?,
allDay: Boolean,
hasTime: Boolean,
onPick: () -> Unit,
onClear: () -> Unit,
isError: Boolean = false,
@@ -947,7 +949,7 @@ private fun ScheduleRow(
color = valueColor,
modifier = valueModifier,
)
if (!allDay) {
if (hasTime) {
Text(
text = value.formatTime(LocalUse24HourFormat.current),
style = MaterialTheme.typography.titleMedium,
@@ -990,68 +992,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<java.time.LocalDate?>(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(
@@ -1150,7 +1090,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,
@@ -16,6 +16,13 @@ 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.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
import de.jeanlucmakiola.agendula.domain.taskReminderDisplayOrder
@@ -27,7 +34,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 de.jeanlucmakiola.agendula.domain.recurrence.RepeatFromCompletion
@@ -37,6 +43,8 @@ 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
import kotlin.time.Instant
@@ -57,6 +65,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,
@@ -121,6 +133,24 @@ data class TaskEditUiState(
val recurrenceChanged: Boolean
get() = rrule != originalRule || savesFromCompletion != originalFromCompletion
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 = dates.hasTime(end)
/**
* [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())
return untimedWall(end, value.calendarDate(isAllDay))
}
}
@HiltViewModel
@@ -167,6 +197,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
@@ -223,6 +257,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,
@@ -231,7 +266,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,9 +293,10 @@ 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
_state.value = withFields(
TaskEditUiState(
@@ -267,9 +306,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,
start = loadedStart,
due = loadedDue,
isAllDay = task.isAllDay,
untimed = task.untimed,
untimedEnds = repository.supportsUntimedEnds(),
priority = task.priority,
parentId = task.parentId,
percentComplete = task.percentComplete,
@@ -355,43 +396,83 @@ class TaskEditViewModel @Inject constructor(
}
}
fun onStartChange(value: Instant?) = update {
val next = it.copy(start = value)
next.withDatedReminders(lostDates = it.hasDates && !next.hasDates)
fun onStartChange(value: Instant?) = onValueChange(TaskEnd.START, value)
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)
}
fun onDueChange(value: Instant?) = update {
val next = it.copy(due = value)
next.withDatedReminders(lostDates = it.hasDates && !next.hasDates)
}
/**
* 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.
* 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 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),
fun onWhenChange(end: TaskEnd, date: LocalDate, time: LocalTime?) = update { s ->
val other = end.other
val otherValue = s.valueOf(other)
// 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)
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)
}
/** [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. */
@@ -450,6 +531,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(
@@ -460,6 +542,7 @@ class TaskEditViewModel @Inject constructor(
settings,
nowMillis(),
ZoneId.systemDefault(),
loadedUntimed,
).isNotEmpty()
return copy(
reminders = reminders,
@@ -603,6 +686,7 @@ private fun TaskEditUiState.toForm(): TaskForm = TaskForm(
start = start,
due = due,
isAllDay = isAllDay,
untimed = untimed,
priority = priority,
parentId = parentId,
percentComplete = percentComplete,
@@ -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.TaskEnd
import de.jeanlucmakiola.agendula.domain.Priority
import de.jeanlucmakiola.agendula.domain.SmartList
import de.jeanlucmakiola.agendula.domain.Task
@@ -860,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 -> due.formatDateTimeCompact(task.isAllDay, LocalUse24HourFormat.current)
else -> due.formatDateTimeCompact(!task.hasTime(TaskEnd.DUE), LocalUse24HourFormat.current)
}
}
@@ -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.TaskEnd
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.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 ||
@@ -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.TaskEnd
import de.jeanlucmakiola.agendula.domain.SmartList
import de.jeanlucmakiola.agendula.domain.Task
import de.jeanlucmakiola.agendula.domain.TaskFilter
@@ -258,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 = due,
isAllDay = isAllDay,
dueKind = due?.let { dueKind(it, isAllDay, today, zone) },
isOverdue = due?.let { isOverdue(it, isAllDay, 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
@@ -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<Task>, comparator: Comparator<Task>, 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
}
+15
View File
@@ -98,6 +98,21 @@
<string name="edit_title_hint">Task title</string>
<string name="edit_when">When</string>
<string name="edit_more_fields">More fields</string>
<string name="picker_section_date">Date</string>
<string name="picker_section_time">Time</string>
<string name="picker_date_today">Today</string>
<string name="picker_date_tomorrow">Tomorrow</string>
<string name="picker_date_next_week">Next week</string>
<string name="picker_date_pick">Pick a date</string>
<string name="picker_time_morning">Morning</string>
<string name="picker_time_noon">Noon</string>
<string name="picker_time_afternoon">Afternoon</string>
<string name="picker_time_evening">Evening</string>
<string name="picker_time_custom">Custom time</string>
<string name="picker_time_none">No time</string>
<string name="picker_time_linked_due">Your tasks app keeps one time setting for both dates, so the due date gets or loses a time along with this one</string>
<string name="picker_time_linked_start">Your tasks app keeps one time setting for both dates, so the start date gets or loses a time along with this one</string>
<string name="picker_done">Done</string>
<string name="close">Close</string>
<string name="dialog_cancel">Cancel</string>
@@ -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,40 @@ 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 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))
@@ -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,38 @@ 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 `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)
@@ -5,9 +5,12 @@ 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.untimedDate
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 +437,168 @@ 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(
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()
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 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 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).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(
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,
@@ -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,19 @@ class ProviderTaskWriterTest {
assertThrows<IllegalArgumentException> { 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()
assertThat(patch(mixed, Tasks.TZ to "America/New_York").untimed).isNull()
}
// --- no-op writes -------------------------------------------------------------
@Test
@@ -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))
}
}
@@ -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
@@ -172,4 +175,52 @@ class TaskFormWriterSeriesTest {
assertThat(TaskFormWriter.countOf("FREQ=DAILY;count=4;INTERVAL=2")).isEqualTo(4)
assertThat(TaskFormWriter.countOf("FREQ=DAILY")).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)
}
@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")
}
}
@@ -57,4 +57,34 @@ 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)
}
@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()
}
@Test
fun `a day that starts in a clock change starts at its first valid moment`() {
val santiago = ZoneId.of("America/Santiago")
val transition = LocalDate.of(2026, 9, 6)
val start = untimedInstantOf(TaskEnd.START, transition, santiago)
assertThat(start.calendarDate(allDay = false, zone = santiago)).isEqualTo(transition)
assertThat(start).isEqualTo(Instant.fromEpochMilliseconds(transition.atStartOfDay(santiago).toInstant().toEpochMilli()))
}
}
@@ -29,4 +29,16 @@ class TaskSortingTest {
assertThat(sorted.map { it.taskId }).containsExactly(2L, 1L).inOrder()
}
@Test
fun `dues without a time sort from the start of their day, all-day or not`() {
val berlin = java.time.ZoneId.systemDefault()
val day = java.time.LocalDate.of(2026, 11, 17)
val allDay = testTask(id = 1, title = "a", due = allDayInstantOf(day), isAllDay = true)
val timed = testTask(id = 2, title = "b", due = kotlin.time.Instant.fromEpochMilliseconds(day.atTime(10, 0).atZone(berlin).toInstant().toEpochMilli()))
val untimed = testTask(id = 3, title = "c", start = timed.due, due = untimedInstantOf(TaskEnd.DUE, day, berlin))
.copy(untimed = TaskEnd.DUE)
val sorted = listOf(timed, untimed, allDay).sortedWith(TaskSorting.DEFAULT)
assertThat(sorted.map { it.taskId }).containsExactly(1L, 3L, 2L).inOrder()
}
}
@@ -2,7 +2,9 @@ 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.untimedDate
import de.jeanlucmakiola.agendula.domain.allDayInstantOf
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
@@ -36,9 +38,12 @@ class ICalendarWriterTest {
rdate: String? = null,
parentId: Long? = null,
tags: List<String> = emptyList(),
untimed: TaskEnd? = null,
timeZone: String? = null,
) = ExportTask(
taskId, uid, title, description, location, url, priority, status, percentComplete,
start, due, isAllDay, completedAt, created, lastModified, rrule, rdate, parentId, tags,
untimed = untimed, timeZone = timeZone,
)
private fun write(vararg tasks: ExportTask, name: String = "Groceries"): String =
@@ -148,6 +153,33 @@ class ICalendarWriterTest {
assertThat(lines).contains("DUE;VALUE=DATE:20260802")
}
@Test
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, timeZone = "Europe/Berlin")))
assertThat(lines).contains("DTSTART;X-AGENDULA-NO-TIME=TRUE:20250802T000000")
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")
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(
@@ -0,0 +1,87 @@
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()
assertThat(QuickTime.of(LocalTime.of(8, 0, 30, 500))).isEqualTo(QuickTime.Morning)
}
@Test
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)
}
@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)
}
@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)
}
}
@@ -11,17 +11,21 @@ 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
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
@@ -29,6 +33,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
@@ -68,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 })
@@ -104,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()
@@ -141,6 +145,128 @@ 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 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)
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)
@@ -223,6 +349,9 @@ class TaskEditViewModelTest {
var task: Task? = null
var reminders: List<TaskReminder> = emptyList()
var saved: TaskForm? = null
var untimedEnds = true
override fun supportsUntimedEnds() = untimedEnds
override fun supportsRepeatFromCompletion() = true
override fun taskLists() = flowOf(emptyList<TaskList>())