todo: calendar mirror, sync status, todo.txt/CSV/iCalendar import and export
- Commit
7ef3bf5d35926daf51d528c1b28e3d9599bf9ebe- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-01 00:00 UTC (1 month ago)
- Parents
390c419
- Optional mirror of open dated tasks into a read-only local "Tasks" calendar (all-day and timed, repeats as RRULE), fingerprinted so unchanged tasks are not rewritten; turning it off removes the calendar. Calendar access is asked only when enabled. - Sync status: the relay provider stamps each EverySync call; settings and the drawer show when it last synced and how many changes are waiting. - Import (format detected from content) and export as todo.txt, CSV or iCalendar VTODO, with lists created by name and subtasks linked; round-trip tested.
Diff
todo/src/main/AndroidManifest.xml
diff --git a/todo/src/main/AndroidManifest.xml b/todo/src/main/AndroidManifest.xmlindex 988f45dc1b..0592c84ebf 100644--- a/todo/src/main/AndroidManifest.xml+++ b/todo/src/main/AndroidManifest.xml@@ -9,6 +9,10 @@ android:name="android.permission.SCHEDULE_EXACT_ALARM" android:maxSdkVersion="32" /> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+ <!-- Optional "show tasks in calendar" mirror into a local read-only calendar; asked for+ only when the user turns it on in settings. -->+ <uses-permission android:name="android.permission.READ_CALENDAR" />+ <uses-permission android:name="android.permission.WRITE_CALENDAR" /> <!-- Alarms do not survive a reboot; re-armed by BootReceiver. --> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> @@ -29,6 +33,8 @@ <intent> <action android:name="android.speech.action.RECOGNIZE_SPEECH" /> </intent>+ <!-- Settings' sync row opens EverySync. -->+ <package android:name="com.vayunmathur.everysync" /> </queries> <application
todo/src/main/java/com/vayunmathur/todo/data/TodoDatabase.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/data/TodoDatabase.kt b/todo/src/main/java/com/vayunmathur/todo/data/TodoDatabase.ktindex 02ca468fc3..decc9d080a 100644--- a/todo/src/main/java/com/vayunmathur/todo/data/TodoDatabase.kt+++ b/todo/src/main/java/com/vayunmathur/todo/data/TodoDatabase.kt@@ -47,6 +47,10 @@ abstract class TodoDao { @Query("SELECT MAX(position) FROM Todo WHERE deleted = 0") abstract suspend fun maxPosition(): Double? + /** Rows (tombstones included) changed after [since]: what the next sync still has to carry. */+ @Query("SELECT COUNT(*) FROM Todo WHERE updatedAt > :since")+ abstract fun countUpdatedSinceFlow(since: Long): Flow<Int>+ @Query("SELECT * FROM Todo WHERE deleted = 0 AND listSyncId = :listSyncId") abstract suspend fun getInList(listSyncId: String): List<Todo>
todo/src/main/java/com/vayunmathur/todo/data/TodoRepository.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/data/TodoRepository.kt b/todo/src/main/java/com/vayunmathur/todo/data/TodoRepository.ktindex be82be98f6..c8935f2001 100644--- a/todo/src/main/java/com/vayunmathur/todo/data/TodoRepository.kt+++ b/todo/src/main/java/com/vayunmathur/todo/data/TodoRepository.kt@@ -29,6 +29,7 @@ class TodoRepository private constructor( val lists: Flow<List<TodoList>> get() = listDao.getAllFlow() fun todoBySyncIdFlow(syncId: String): Flow<Todo?> = dao.getBySyncIdFlow(syncId) fun subtasksFlow(parentSyncId: String): Flow<List<Todo>> = dao.getSubtasksFlow(parentSyncId)+ fun pendingSyncCount(since: Long): Flow<Int> = dao.countUpdatedSinceFlow(since) suspend fun <R> inTransaction(block: suspend () -> R): R = db.withWriteTransaction { block() }
todo/src/main/java/com/vayunmathur/todo/domain/format/ImportedTask.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/domain/format/ImportedTask.kt b/todo/src/main/java/com/vayunmathur/todo/domain/format/ImportedTask.ktnew file mode 100644index 0000000000..4887354a8a--- /dev/null+++ b/todo/src/main/java/com/vayunmathur/todo/domain/format/ImportedTask.kt@@ -0,0 +1,38 @@+package com.vayunmathur.todo.domain.format++import com.vayunmathur.todo.data.Todo+import com.vayunmathur.todo.data.TodoList++/**+ * A task read from a file, before it gets an identity in this app. Lists are by name (created+ * on import when missing); [ref]/[parentRef] link subtasks within the same file.+ */+data class ImportedTask(+ val title: String,+ val notes: String = "",+ val done: Boolean = false,+ val dueAt: Long? = null,+ val dueAllDay: Boolean = true,+ val priority: Int = 0,+ val listName: String? = null,+ val section: String? = null,+ val tags: List<String> = emptyList(),+ val recurrence: String? = null,+ val startAt: Long? = null,+ val createdAt: Long? = null,+ val completedAt: Long? = null,+ val ref: String? = null,+ val parentRef: String? = null,+)++/** What an exporter needs: every task plus list names. */+data class ExportSource(val todos: List<Todo>, val lists: List<TodoList>) {+ private val listNames = lists.associate { it.syncId to it.name }+ fun listName(todo: Todo): String? = todo.listSyncId?.let { listNames[it] }+}++enum class ExportFormat(val extension: String, val mimeType: String) {+ TODO_TXT("txt", "text/plain"),+ CSV("csv", "text/csv"),+ ICALENDAR("ics", "text/calendar"),+}
todo/src/main/java/com/vayunmathur/todo/domain/format/TodoCsv.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/domain/format/TodoCsv.kt b/todo/src/main/java/com/vayunmathur/todo/domain/format/TodoCsv.ktnew file mode 100644index 0000000000..49759f98da--- /dev/null+++ b/todo/src/main/java/com/vayunmathur/todo/domain/format/TodoCsv.kt@@ -0,0 +1,99 @@+package com.vayunmathur.todo.domain.format++import com.vayunmathur.todo.data.Todo+import com.vayunmathur.todo.domain.DueDates+import kotlinx.datetime.LocalDate+import kotlinx.datetime.LocalTime+import kotlinx.datetime.TimeZone++/** RFC 4180 CSV with a header row; dates ISO-8601 in the user's zone, times HH:MM. */+object TodoCsv {+ private val HEADER = listOf(+ "Title", "Notes", "Done", "Due date", "Due time", "Priority", "List", "Section", "Tags",+ "Repeat", "Start date", "Created", "Completed", "Id", "Parent id",+ )++ fun export(source: ExportSource, zone: TimeZone): String {+ val rows = source.todos.filter { !it.deleted }.map { t ->+ listOf(+ t.title,+ t.notes,+ if (t.done) "yes" else "no",+ t.dueAt?.let { DueDates.localDate(it, zone).toString() }.orEmpty(),+ t.dueAt?.takeIf { !t.dueAllDay }?.let { DueDates.localTime(it, zone).toString().take(HHMM) }.orEmpty(),+ t.priority.takeIf { it > 0 }?.toString().orEmpty(),+ source.listName(t).orEmpty(),+ t.section.orEmpty(),+ t.tags.joinToString(" "),+ t.recurrence.orEmpty(),+ t.startAt?.let { DueDates.localDate(it, zone).toString() }.orEmpty(),+ DueDates.localDate(t.createdAt, zone).toString(),+ t.completedAt?.let { DueDates.localDate(it, zone).toString() }.orEmpty(),+ t.syncId,+ t.parentSyncId.orEmpty(),+ )+ }+ return (listOf(HEADER) + rows).joinToString("\r\n") { row -> row.joinToString(",") { quote(it) } } + "\r\n"+ }++ private fun quote(field: String): String =+ if (field.any { it == ',' || it == '"' || it == '\n' || it == '\r' }) "\"" + field.replace("\"", "\"\"") + "\"" else field++ fun parse(text: String, zone: TimeZone): List<ImportedTask> {+ val rows = readRows(text)+ val header = rows.firstOrNull()?.map { it.trim().lowercase() } ?: return emptyList()+ fun col(row: List<String>, name: String) = header.indexOf(name.lowercase()).takeIf { it >= 0 }?.let { row.getOrNull(it) }.orEmpty()+ return rows.drop(1).filter { row -> row.any { it.isNotBlank() } }.map { row ->+ val dueDate = col(row, "Due date").takeIf { it.isNotBlank() }?.let { runCatching { LocalDate.parse(it) }.getOrNull() }+ val dueTime = col(row, "Due time").takeIf { it.isNotBlank() }?.let { runCatching { LocalTime.parse(it) }.getOrNull() }+ ImportedTask(+ title = col(row, "Title"),+ notes = col(row, "Notes"),+ done = col(row, "Done").lowercase() in setOf("yes", "true", "1", "x"),+ dueAt = dueDate?.let { d -> if (dueTime != null) DueDates.at(d, dueTime, zone) else DueDates.startOfDay(d, zone) },+ dueAllDay = dueTime == null,+ priority = col(row, "Priority").toIntOrNull()?.takeIf { it in 1..Todo.PRIORITY_MAX } ?: 0,+ listName = col(row, "List").ifBlank { null },+ section = col(row, "Section").ifBlank { null },+ tags = col(row, "Tags").split(' ', ',').map { it.trim().removePrefix("#") }.filter { it.isNotEmpty() },+ recurrence = col(row, "Repeat").ifBlank { null },+ startAt = date(col(row, "Start date"), zone),+ createdAt = date(col(row, "Created"), zone),+ completedAt = date(col(row, "Completed"), zone),+ ref = col(row, "Id").ifBlank { null },+ parentRef = col(row, "Parent id").ifBlank { null },+ )+ }+ }++ private fun date(raw: String, zone: TimeZone): Long? =+ raw.takeIf { it.isNotBlank() }?.let { runCatching { DueDates.startOfDay(LocalDate.parse(it), zone) }.getOrNull() }++ /** Splits CSV into rows of fields, honouring quoted commas, quotes and newlines. */+ internal fun readRows(text: String): List<List<String>> {+ val rows = mutableListOf<List<String>>()+ var row = mutableListOf<String>()+ val field = StringBuilder()+ var quoted = false+ var i = 0+ while (i < text.length) {+ val c = text[i]+ when {+ quoted && c == '"' && text.getOrNull(i + 1) == '"' -> { field.append('"'); i++ }+ c == '"' -> quoted = !quoted+ !quoted && c == ',' -> { row += field.toString(); field.clear() }+ !quoted && (c == '\n' || c == '\r') -> {+ if (c == '\r' && text.getOrNull(i + 1) == '\n') i+++ row += field.toString(); field.clear()+ rows += row; row = mutableListOf()+ }+ else -> field.append(c)+ }+ i+++ }+ if (field.isNotEmpty() || row.isNotEmpty()) { row += field.toString(); rows += row }+ return rows+ }++ private const val HHMM = 5+}
todo/src/main/java/com/vayunmathur/todo/domain/format/TodoTxt.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/domain/format/TodoTxt.kt b/todo/src/main/java/com/vayunmathur/todo/domain/format/TodoTxt.ktnew file mode 100644index 0000000000..649ab287e8--- /dev/null+++ b/todo/src/main/java/com/vayunmathur/todo/domain/format/TodoTxt.kt@@ -0,0 +1,126 @@+package com.vayunmathur.todo.domain.format++import com.vayunmathur.todo.data.Todo+import com.vayunmathur.todo.domain.DueDates+import com.vayunmathur.todo.domain.Recurrence+import kotlinx.datetime.LocalDate+import kotlinx.datetime.TimeZone++/**+ * todo.txt (https://github.com/todotxt/todo.txt): `x done-date created-date (A) title+ * +Project @context due:YYYY-MM-DD t:YYYY-MM-DD rec:[+]Nd|w|m|y`.+ *+ * Lists map to `+Project` (spaces as `_`), tags to `@context`, priorities 1–4 to (A)–(D).+ * `rec:+1w` repeats from the due date and `rec:1w` from completion, as in SimpleTask. Notes+ * and times of day have no todo.txt form and are dropped on export.+ */+object TodoTxt {+ private val DATE = Regex("^\\d{4}-\\d{2}-\\d{2}$")+ private val PRIORITY = Regex("^\\(([A-D])\\)$")+ private val REC = Regex("^(\\+?)(\\d+)([dwmy])$")+ private const val DAYS_PER_WEEK = 7++ fun export(source: ExportSource, zone: TimeZone): String =+ source.todos.filter { !it.deleted && it.parentSyncId == null }.joinToString("\n") { line(it, source, zone) } + "\n"++ private fun line(todo: Todo, source: ExportSource, zone: TimeZone): String {+ val parts = mutableListOf<String>()+ if (todo.done) {+ parts += "x"+ todo.completedAt?.let { parts += date(it, zone) }+ } else if (todo.priority in 1..Todo.PRIORITY_MAX) {+ parts += "(" + ('A' + todo.priority - 1) + ")"+ }+ parts += date(todo.createdAt, zone)+ parts += todo.title.replace('\n', ' ')+ source.listName(todo)?.let { parts += "+" + it.replace(' ', '_') }+ todo.tags.forEach { parts += "@" + it.replace(' ', '_') }+ todo.dueAt?.let { parts += "due:" + date(it, zone) }+ todo.startAt?.let { parts += "t:" + date(it, zone) }+ rec(todo.recurrence)?.let { parts += "rec:$it" }+ if (todo.done && todo.priority in 1..Todo.PRIORITY_MAX) parts += "pri:" + ('A' + todo.priority - 1)+ return parts.joinToString(" ")+ }++ private fun date(ms: Long, zone: TimeZone) = DueDates.localDate(ms, zone).toString()++ private fun rec(raw: String?): String? = when (val r = Recurrence.parse(raw)) {+ null -> null+ is Recurrence.Daily -> "+${r.interval}d"+ is Recurrence.Weekly -> "+${r.interval}w"+ is Recurrence.Monthly -> "+${r.interval}m"+ is Recurrence.Yearly -> "+${r.interval}y"+ is Recurrence.AfterCompletion ->+ if (r.interval % DAYS_PER_WEEK == 0) "${r.interval / DAYS_PER_WEEK}w" else "${r.interval}d"+ }++ fun parse(text: String, zone: TimeZone): List<ImportedTask> =+ text.lineSequence().map { it.trim() }.filter { it.isNotEmpty() }.map { parseLine(it, zone) }.toList()++ private fun parseLine(line: String, zone: TimeZone): ImportedTask {+ val words = line.split(Regex("\\s+")).toMutableList()+ var done = false+ var completedAt: Long? = null+ var priority = 0+ if (words.firstOrNull() == "x") {+ done = true+ words.removeAt(0)+ if (words.firstOrNull()?.matches(DATE) == true) completedAt = toMs(words.removeAt(0), zone)+ }+ PRIORITY.find(words.firstOrNull().orEmpty())?.let {+ priority = it.groupValues[1][0] - 'A' + 1+ words.removeAt(0)+ }+ val createdAt = if (words.firstOrNull()?.matches(DATE) == true) toMs(words.removeAt(0), zone) else null+ return parseBody(words, zone).copy(done = done, completedAt = completedAt, createdAt = createdAt).let {+ if (priority != 0) it.copy(priority = priority) else it+ }+ }++ private fun parseBody(words: List<String>, zone: TimeZone): ImportedTask {+ val title = mutableListOf<String>()+ val tags = mutableListOf<String>()+ var list: String? = null+ var due: Long? = null+ var start: Long? = null+ var recurrence: String? = null+ var priority = 0+ for (w in words) {+ val value = w.substringAfter(':', "")+ when {+ w.startsWith("+") && w.length > 1 && list == null -> list = w.drop(1).replace('_', ' ')+ w.startsWith("@") && w.length > 1 -> tags += w.drop(1)+ w.startsWith("due:") && value.matches(DATE) -> due = toMs(value, zone)+ w.startsWith("t:") && value.matches(DATE) -> start = toMs(value, zone)+ w.startsWith("rec:") -> recurrence = parseRec(value)+ w.startsWith("pri:") && value.length == 1 && value[0] in 'A'..'D' -> priority = value[0] - 'A' + 1+ else -> title += w+ }+ }+ return ImportedTask(+ title = title.joinToString(" "),+ dueAt = due,+ priority = priority,+ listName = list,+ tags = tags,+ recurrence = recurrence,+ startAt = start,+ )+ }++ private fun parseRec(value: String): String? {+ val (strict, n, unit) = REC.find(value)?.destructured ?: return null+ val count = n.toInt().coerceAtLeast(1)+ val r = when {+ strict.isEmpty() && unit == "d" -> Recurrence.AfterCompletion(count)+ strict.isEmpty() && unit == "w" -> Recurrence.AfterCompletion(count * DAYS_PER_WEEK)+ unit == "d" -> Recurrence.Daily(count)+ unit == "w" -> Recurrence.Weekly(count)+ unit == "m" -> Recurrence.Monthly(count)+ else -> Recurrence.Yearly(count)+ }+ return r.serialize()+ }++ private fun toMs(date: String, zone: TimeZone) = DueDates.startOfDay(LocalDate.parse(date), zone)+}
todo/src/main/java/com/vayunmathur/todo/domain/format/VTodo.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/domain/format/VTodo.kt b/todo/src/main/java/com/vayunmathur/todo/domain/format/VTodo.ktnew file mode 100644index 0000000000..4337ba24db--- /dev/null+++ b/todo/src/main/java/com/vayunmathur/todo/domain/format/VTodo.kt@@ -0,0 +1,168 @@+package com.vayunmathur.todo.domain.format++import com.vayunmathur.todo.data.Todo+import com.vayunmathur.todo.domain.DueDates+import kotlinx.datetime.LocalDate+import kotlinx.datetime.LocalDateTime+import kotlinx.datetime.TimeZone+import kotlinx.datetime.toInstant+import kotlinx.datetime.toLocalDateTime+import kotlin.time.Instant++/**+ * iCalendar VTODO (RFC 5545). All-day due dates use `DUE;VALUE=DATE`, timed ones UTC.+ * Priority 1–4 maps onto iCalendar's 1–9 scale as 1/3/5/7; subtasks use RELATED-TO;+ * the list rides in X-TODO-LIST so a round trip keeps it.+ */+object VTodo {+ private const val FOLD_AT = 75+ private const val PRODID = "-//Modern Apps//Todo//EN"+ private const val UID_HOST = "@com.vayunmathur.todo"+ private val ICAL_PRIORITY = mapOf(1 to 1, 2 to 3, 3 to 5, 4 to 7)++ fun export(source: ExportSource): String {+ val out = StringBuilder()+ out.line("BEGIN:VCALENDAR")+ out.line("VERSION:2.0")+ out.line("PRODID:$PRODID")+ source.todos.filter { !it.deleted }.forEach { t -> vtodo(out, t, source) }+ out.line("END:VCALENDAR")+ return out.toString()+ }++ private fun vtodo(out: StringBuilder, t: Todo, source: ExportSource) {+ out.line("BEGIN:VTODO")+ out.line("UID:${t.syncId}$UID_HOST")+ out.line("DTSTAMP:${utc(t.updatedAt)}")+ out.line("CREATED:${utc(t.createdAt)}")+ out.line("LAST-MODIFIED:${utc(t.updatedAt)}")+ out.line("SUMMARY:${escape(t.title)}")+ if (t.notes.isNotBlank()) out.line("DESCRIPTION:${escape(t.notes)}")+ t.dueAt?.let { due ->+ if (t.dueAllDay) out.line("DUE;VALUE=DATE:${basicDate(DueDates.localDate(due, TimeZone.currentSystemDefault()))}")+ else out.line("DUE:${utc(due)}")+ }+ t.startAt?.let { out.line("DTSTART;VALUE=DATE:${basicDate(DueDates.localDate(it, TimeZone.currentSystemDefault()))}") }+ out.line("STATUS:${if (t.done) "COMPLETED" else "NEEDS-ACTION"}")+ t.completedAt?.takeIf { t.done }?.let { out.line("COMPLETED:${utc(it)}") }+ ICAL_PRIORITY[t.priority]?.let { out.line("PRIORITY:$it") }+ if (t.tags.isNotEmpty()) out.line("CATEGORIES:${t.tags.joinToString(",") { escape(it) }}")+ t.recurrence?.substringBefore(";X-")?.let { out.line("RRULE:$it") }+ t.parentSyncId?.let { out.line("RELATED-TO;RELTYPE=PARENT:$it$UID_HOST") }+ source.listName(t)?.let { out.line("X-TODO-LIST:${escape(it)}") }+ t.section?.let { out.line("X-TODO-SECTION:${escape(it)}") }+ t.recurrence?.takeIf { "X-FROM=COMPLETION" in it }?.let { out.line("X-TODO-RECURRENCE:$it") }+ out.line("END:VTODO")+ }++ fun parse(text: String, zone: TimeZone): List<ImportedTask> {+ val lines = unfold(text)+ val tasks = mutableListOf<ImportedTask>()+ var props: MutableMap<String, Pair<Map<String, String>, String>>? = null+ for (line in lines) {+ when {+ line.equals("BEGIN:VTODO", true) -> props = mutableMapOf()+ line.equals("END:VTODO", true) -> props?.let { tasks += toTask(it, zone) }.also { props = null }+ props != null -> parseProperty(line)?.let { (name, params, value) -> props!![name] = params to value }+ }+ }+ return tasks+ }++ private fun toTask(p: Map<String, Pair<Map<String, String>, String>>, zone: TimeZone): ImportedTask {+ fun v(name: String) = p[name]?.second+ val due = p["DUE"]?.let { (params, value) -> parseDateTime(value, params, zone) }+ val icalPriority = v("PRIORITY")?.toIntOrNull() ?: 0+ return ImportedTask(+ title = unescape(v("SUMMARY").orEmpty()),+ notes = unescape(v("DESCRIPTION").orEmpty()),+ done = v("STATUS").equals("COMPLETED", true) || v("COMPLETED") != null,+ dueAt = due?.first,+ dueAllDay = due?.second ?: true,+ priority = ICAL_PRIORITY.entries.firstOrNull { icalPriority in 1..9 && icalPriority <= it.value }?.key+ ?: if (icalPriority in 1..9) Todo.PRIORITY_MAX else 0,+ listName = v("X-TODO-LIST")?.let { unescape(it) },+ section = v("X-TODO-SECTION")?.let { unescape(it) },+ tags = v("CATEGORIES")?.split(',')?.map { unescape(it).trim() }?.filter { it.isNotEmpty() }.orEmpty(),+ recurrence = v("X-TODO-RECURRENCE") ?: v("RRULE"),+ startAt = p["DTSTART"]?.let { (params, value) -> parseDateTime(value, params, zone)?.first },+ createdAt = v("CREATED")?.let { parseDateTime(it, emptyMap(), zone)?.first },+ completedAt = v("COMPLETED")?.let { parseDateTime(it, emptyMap(), zone)?.first },+ ref = v("UID")?.substringBefore(UID_HOST),+ parentRef = v("RELATED-TO")?.substringBefore(UID_HOST),+ )+ }++ /** Epoch ms plus whether it is a date-only (all-day) value. */+ private fun parseDateTime(value: String, params: Map<String, String>, zone: TimeZone): Pair<Long, Boolean>? = runCatching {+ if (params["VALUE"].equals("DATE", true) || value.length == BASIC_DATE_LEN) {+ DueDates.startOfDay(parseBasicDate(value), zone) to true+ } else {+ val date = parseBasicDate(value.take(BASIC_DATE_LEN))+ val t = value.drop(BASIC_DATE_LEN + 1)+ val ldt = LocalDateTime(date.year, date.month, date.day, t.take(2).toInt(), t.substring(2, 4).toInt(), t.substring(4, 6).toInt())+ val tz = when {+ value.endsWith("Z") -> TimeZone.UTC+ params["TZID"] != null -> runCatching { TimeZone.of(params.getValue("TZID")) }.getOrDefault(zone)+ else -> zone+ }+ ldt.toInstant(tz).toEpochMilliseconds() to false+ }+ }.getOrNull()++ private fun parseProperty(line: String): Triple<String, Map<String, String>, String>? {+ val colon = line.indexOf(':').takeIf { it > 0 } ?: return null+ val head = line.substring(0, colon).split(';')+ val params = head.drop(1).mapNotNull { kv -> kv.split('=', limit = 2).takeIf { it.size == 2 }?.let { it[0].uppercase() to it[1] } }.toMap()+ return Triple(head[0].uppercase(), params, line.substring(colon + 1))+ }++ private fun unfold(text: String): List<String> {+ val out = mutableListOf<String>()+ text.replace("\r\n", "\n").split('\n').forEach { line ->+ if ((line.startsWith(" ") || line.startsWith("\t")) && out.isNotEmpty()) out[out.lastIndex] += line.drop(1)+ else if (line.isNotEmpty()) out += line+ }+ return out+ }++ private fun StringBuilder.line(content: String) {+ var rest = content+ var first = true+ while (rest.isNotEmpty()) {+ val limit = if (first) FOLD_AT else FOLD_AT - 1+ val cut = safeCut(rest, limit)+ if (!first) append(' ')+ append(rest, 0, cut).append("\r\n")+ rest = rest.substring(cut)+ first = false+ }+ }++ /** Longest prefix of at most [limit] UTF-8 octets that does not split a character. */+ private fun safeCut(s: String, limit: Int): Int {+ var bytes = 0+ var i = 0+ while (i < s.length) {+ val cp = s.codePointAt(i)+ val size = String(Character.toChars(cp)).toByteArray(Charsets.UTF_8).size+ if (bytes + size > limit) break+ bytes += size+ i += Character.charCount(cp)+ }+ return i.coerceAtLeast(1)+ }++ private fun escape(s: String) = s.replace("\\", "\\\\").replace(";", "\\;").replace(",", "\\,").replace("\n", "\\n")+ private fun unescape(s: String) = s.replace("\\n", "\n").replace("\\N", "\n").replace("\\,", ",").replace("\\;", ";").replace("\\\\", "\\")++ private fun utc(ms: Long): String {+ val t = Instant.fromEpochMilliseconds(ms).toLocalDateTime(TimeZone.UTC)+ return basicDate(t.date) + "T" + t.hour.pad() + t.minute.pad() + t.second.pad() + "Z"+ }++ private fun basicDate(d: LocalDate) = d.toString().replace("-", "")+ private fun parseBasicDate(s: String) = LocalDate.parse("${s.take(4)}-${s.substring(4, 6)}-${s.substring(6, 8)}")+ private fun Int.pad() = toString().padStart(2, '0')+ private const val BASIC_DATE_LEN = 8+}
todo/src/main/java/com/vayunmathur/todo/platform/TodoBackground.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/platform/TodoBackground.kt b/todo/src/main/java/com/vayunmathur/todo/platform/TodoBackground.ktindex 16c4e16699..50b92897d5 100644--- a/todo/src/main/java/com/vayunmathur/todo/platform/TodoBackground.kt+++ b/todo/src/main/java/com/vayunmathur/todo/platform/TodoBackground.kt@@ -7,6 +7,7 @@ import com.vayunmathur.todo.notifications.DigestScheduler import com.vayunmathur.todo.notifications.NotificationChannels import com.vayunmathur.todo.notifications.ReminderScheduler import com.vayunmathur.todo.widget.TodayWidget+import com.vayunmathur.todo.sync.CalendarMirror import androidx.glance.appwidget.updateAll import com.vayunmathur.library.log.Log import kotlinx.coroutines.FlowPreview@@ -24,6 +25,7 @@ import java.util.concurrent.atomic.AtomicBoolean object TodoBackground { private val started = AtomicBoolean(false) private const val SETTLE_MS = 500L+ private const val MIRROR_SETTLE_MS = 2_000L private data class ReminderKey(val syncId: String, val reminderAt: Long?, val done: Boolean) @@ -51,6 +53,11 @@ object TodoBackground { repo.appScope.launch { combine(repo.todos, repo.lists) { _, _ -> }.debounce(SETTLE_MS).collect { refreshWidgets(app) } }+ repo.appScope.launch {+ combine(repo.todos, settings.calendarMirror) { todos, on -> todos to on }+ .debounce(MIRROR_SETTLE_MS)+ .collect { (todos, on) -> CalendarMirror.reconcile(app, on, todos) }+ } } // Broad catch: a widget host failure must never take the app process down.
todo/src/main/java/com/vayunmathur/todo/platform/TodoDataTransfer.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/platform/TodoDataTransfer.kt b/todo/src/main/java/com/vayunmathur/todo/platform/TodoDataTransfer.ktnew file mode 100644index 0000000000..2272f62d6b--- /dev/null+++ b/todo/src/main/java/com/vayunmathur/todo/platform/TodoDataTransfer.kt@@ -0,0 +1,80 @@+package com.vayunmathur.todo.platform++import android.content.Context+import android.net.Uri+import com.vayunmathur.todo.data.Todo+import com.vayunmathur.todo.data.TodoList+import com.vayunmathur.todo.data.TodoRepository+import com.vayunmathur.todo.data.newSyncId+import com.vayunmathur.todo.domain.Positions+import com.vayunmathur.todo.domain.format.ExportFormat+import com.vayunmathur.todo.domain.format.ExportSource+import com.vayunmathur.todo.domain.format.ImportedTask+import com.vayunmathur.todo.domain.format.TodoCsv+import com.vayunmathur.todo.domain.format.TodoTxt+import com.vayunmathur.todo.domain.format.VTodo+import kotlinx.datetime.TimeZone++/** Streams todo.txt / CSV / iCalendar files through the Storage Access Framework. */+class TodoDataTransfer(private val context: Context, private val repo: TodoRepository) {++ suspend fun export(uri: Uri, format: ExportFormat) {+ val source = ExportSource(repo.getAll(), repo.getLists())+ val zone = TimeZone.currentSystemDefault()+ val text = when (format) {+ ExportFormat.TODO_TXT -> TodoTxt.export(source, zone)+ ExportFormat.CSV -> TodoCsv.export(source, zone)+ ExportFormat.ICALENDAR -> VTodo.export(source)+ }+ context.contentResolver.openOutputStream(uri, "wt")?.use { it.write(text.toByteArray(Charsets.UTF_8)) }+ }++ /** Reads a file and picks the format from its content. */+ fun read(uri: Uri): List<ImportedTask> {+ val text = context.contentResolver.openInputStream(uri)?.use { it.readBytes().toString(Charsets.UTF_8) }.orEmpty()+ .removePrefix("\uFEFF")+ val zone = TimeZone.currentSystemDefault()+ return when {+ text.contains("BEGIN:VCALENDAR", ignoreCase = true) -> VTodo.parse(text, zone)+ text.lineSequence().firstOrNull()?.startsWith("Title,", ignoreCase = true) == true -> TodoCsv.parse(text, zone)+ else -> TodoTxt.parse(text, zone)+ }.filter { it.title.isNotBlank() }+ }++ /** Inserts [tasks] with fresh identities, creating missing lists by name. Returns the count. */+ suspend fun import(tasks: List<ImportedTask>): Int = repo.inTransaction {+ val lists = repo.getLists().associateBy { it.name.lowercase() }.toMutableMap()+ val idsByRef = tasks.mapNotNull { it.ref }.associateWith { newSyncId() }+ var position = repo.nextPosition()+ val now = System.currentTimeMillis()+ for (task in tasks) {+ val listSyncId = task.listName?.let { name ->+ lists.getOrPut(name.lowercase()) {+ TodoList(name = name, position = repo.nextListPosition()).also { repo.upsertList(it) }+ }.syncId+ }+ repo.upsert(+ Todo(+ syncId = task.ref?.let { idsByRef[it] } ?: newSyncId(),+ title = task.title,+ notes = task.notes,+ done = task.done,+ dueAt = task.dueAt,+ dueAllDay = task.dueAllDay,+ priority = task.priority,+ listSyncId = listSyncId,+ section = task.section,+ tags = task.tags,+ recurrence = task.recurrence,+ startAt = task.startAt,+ createdAt = task.createdAt ?: now,+ completedAt = task.completedAt ?: if (task.done) now else null,+ parentSyncId = task.parentRef?.let { idsByRef[it] },+ position = position,+ ),+ )+ position = Positions.after(position)+ }+ tasks.size+ }+}
todo/src/main/java/com/vayunmathur/todo/platform/TodoViewModel.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/platform/TodoViewModel.kt b/todo/src/main/java/com/vayunmathur/todo/platform/TodoViewModel.ktindex 5a084e399f..c2b4b5ce97 100644--- a/todo/src/main/java/com/vayunmathur/todo/platform/TodoViewModel.kt+++ b/todo/src/main/java/com/vayunmathur/todo/platform/TodoViewModel.kt@@ -23,6 +23,9 @@ import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.flatMapLatest+import com.vayunmathur.todo.domain.format.ExportFormat+import com.vayunmathur.todo.domain.format.ImportedTask import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn@@ -115,6 +118,31 @@ class TodoViewModel( viewModelScope.launch(io) { repository.upsertLists(moved) } } + /** Changes the next sync still has to carry; meaningful once a sync has happened. */+ @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)+ val pendingSync: StateFlow<Int> = settings.lastSyncAt+ .flatMapLatest { since -> repository.pendingSyncCount(since) }+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), 0)++ private val transfer = TodoDataTransfer(application, repository)++ fun export(uri: android.net.Uri, format: ExportFormat, onDone: () -> Unit) {+ viewModelScope.launch(io) {+ transfer.export(uri, format)+ kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.Main) { onDone() }+ }+ }++ suspend fun readImport(uri: android.net.Uri): List<ImportedTask> =+ kotlinx.coroutines.withContext(io) { runCatching { transfer.read(uri) }.getOrDefault(emptyList()) }++ fun import(tasks: List<ImportedTask>, onDone: (Int) -> Unit) {+ viewModelScope.launch(io) {+ val count = transfer.import(tasks)+ kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.Main) { onDone(count) }+ }+ }+ fun updateSettings(block: suspend TodoSettings.() -> Unit) { viewModelScope.launch(io) { settings.block() } }
todo/src/main/java/com/vayunmathur/todo/sync/CalendarMirror.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/sync/CalendarMirror.kt b/todo/src/main/java/com/vayunmathur/todo/sync/CalendarMirror.ktnew file mode 100644index 0000000000..47415fb436--- /dev/null+++ b/todo/src/main/java/com/vayunmathur/todo/sync/CalendarMirror.kt@@ -0,0 +1,138 @@+package com.vayunmathur.todo.sync++import android.Manifest+import android.content.ContentProviderOperation+import android.content.ContentUris+import android.content.ContentValues+import android.content.Context+import android.content.pm.PackageManager+import android.net.Uri+import android.provider.CalendarContract.Calendars+import android.provider.CalendarContract.Events+import androidx.core.content.ContextCompat+import com.vayunmathur.library.log.Log+import com.vayunmathur.todo.R+import com.vayunmathur.todo.data.Todo+import com.vayunmathur.todo.domain.DueDates+import com.vayunmathur.todo.domain.Recurrence+import kotlinx.datetime.TimeZone++/**+ * Mirrors open tasks with a due date into a read-only local "Tasks" calendar, so any calendar+ * app shows them. One event per task, keyed by `_SYNC_ID` = the task's sync id; `SYNC_DATA1`+ * holds a fingerprint so unchanged tasks are not rewritten. Turning the mirror off deletes+ * the calendar.+ */+object CalendarMirror {+ private const val TAG = "CalendarMirror"+ private const val ACCOUNT = "Todo"+ private const val CALENDAR_NAME = "todo_tasks"+ private const val COLOR = 0xFF3F51B5.toInt()+ private const val TIMED_DURATION = "PT30M"+ private const val ALL_DAY_DURATION = "P1D"+ private const val TIMED_LENGTH_MS = 30 * 60_000L+ private const val DAY_MS = 86_400_000L++ fun hasPermission(context: Context): Boolean = listOf(Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR)+ .all { ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED }++ // Broad catch: the calendar provider throws undocumented runtime exceptions, and a mirror+ // failure must never break the app.+ @Suppress("TooGenericExceptionCaught")+ fun reconcile(context: Context, enabled: Boolean, todos: List<Todo>) {+ if (!hasPermission(context)) return+ try {+ if (!enabled) {+ findCalendar(context)?.let { context.contentResolver.delete(asSync(ContentUris.withAppendedId(Calendars.CONTENT_URI, it)), null, null) }+ return+ }+ val calendarId = findCalendar(context) ?: createCalendar(context) ?: return+ write(context, calendarId, todos.filter { !it.done && !it.deleted && it.dueAt != null && it.parentSyncId == null })+ } catch (e: Exception) {+ Log.error(TAG, "reconcile failed", e)+ }+ }++ private fun write(context: Context, calendarId: Long, wanted: List<Todo>) {+ val existing = mutableMapOf<String, Pair<Long, String?>>()+ context.contentResolver.query(+ asSync(Events.CONTENT_URI),+ arrayOf(Events._ID, Events._SYNC_ID, Events.SYNC_DATA1),+ "${Events.CALENDAR_ID} = ?",+ arrayOf(calendarId.toString()),+ null,+ )?.use { c -> while (c.moveToNext()) c.getString(1)?.let { existing[it] = c.getLong(0) to c.getString(2) } }++ val ops = ArrayList<ContentProviderOperation>()+ val zone = TimeZone.currentSystemDefault()+ for (todo in wanted) {+ val values = eventValues(todo, calendarId, zone)+ val fingerprint = values.getAsString(Events.SYNC_DATA1)+ val current = existing.remove(todo.syncId)+ when {+ current == null -> ops += ContentProviderOperation.newInsert(asSync(Events.CONTENT_URI)).withValues(values).build()+ current.second != fingerprint -> ops += ContentProviderOperation+ .newUpdate(asSync(ContentUris.withAppendedId(Events.CONTENT_URI, current.first))).withValues(values).build()+ }+ }+ existing.values.forEach { (id, _) ->+ ops += ContentProviderOperation.newDelete(asSync(ContentUris.withAppendedId(Events.CONTENT_URI, id))).build()+ }+ if (ops.isNotEmpty()) context.contentResolver.applyBatch(android.provider.CalendarContract.AUTHORITY, ops)+ }++ /** Calendar rules: all-day events are UTC midnights; recurring events use DURATION, not DTEND. */+ private fun eventValues(todo: Todo, calendarId: Long, zone: TimeZone): ContentValues {+ val due = todo.dueAt!!+ val start = if (todo.dueAllDay) DueDates.startOfDay(DueDates.localDate(due, zone), TimeZone.UTC) else due+ val rrule = Recurrence.parse(todo.recurrence)?.toRRule()+ return ContentValues().apply {+ put(Events.CALENDAR_ID, calendarId)+ put(Events._SYNC_ID, todo.syncId)+ put(Events.TITLE, todo.title)+ put(Events.DESCRIPTION, todo.notes)+ put(Events.DTSTART, start)+ put(Events.ALL_DAY, if (todo.dueAllDay) 1 else 0)+ put(Events.EVENT_TIMEZONE, if (todo.dueAllDay) "UTC" else zone.id)+ if (rrule != null) {+ put(Events.RRULE, rrule)+ put(Events.DURATION, if (todo.dueAllDay) ALL_DAY_DURATION else TIMED_DURATION)+ putNull(Events.DTEND)+ } else {+ put(Events.DTEND, start + if (todo.dueAllDay) DAY_MS else TIMED_LENGTH_MS)+ putNull(Events.RRULE)+ putNull(Events.DURATION)+ }+ put(Events.SYNC_DATA1, listOf(todo.title, todo.notes, start, todo.dueAllDay, rrule, zone.id).joinToString("\u0000").hashCode().toString())+ }+ }++ private fun findCalendar(context: Context): Long? = context.contentResolver.query(+ Calendars.CONTENT_URI,+ arrayOf(Calendars._ID),+ "${Calendars.ACCOUNT_NAME} = ? AND ${Calendars.ACCOUNT_TYPE} = ? AND ${Calendars.NAME} = ?",+ arrayOf(ACCOUNT, android.provider.CalendarContract.ACCOUNT_TYPE_LOCAL, CALENDAR_NAME),+ null,+ )?.use { c -> if (c.moveToFirst()) c.getLong(0) else null }++ private fun createCalendar(context: Context): Long? {+ val values = ContentValues().apply {+ put(Calendars.ACCOUNT_NAME, ACCOUNT)+ put(Calendars.ACCOUNT_TYPE, android.provider.CalendarContract.ACCOUNT_TYPE_LOCAL)+ put(Calendars.NAME, CALENDAR_NAME)+ put(Calendars.CALENDAR_DISPLAY_NAME, context.getString(R.string.calendar_name))+ put(Calendars.CALENDAR_COLOR, COLOR)+ put(Calendars.CALENDAR_ACCESS_LEVEL, Calendars.CAL_ACCESS_READ)+ put(Calendars.OWNER_ACCOUNT, ACCOUNT)+ put(Calendars.VISIBLE, 1)+ put(Calendars.SYNC_EVENTS, 1)+ }+ return context.contentResolver.insert(asSync(Calendars.CONTENT_URI), values)?.let { ContentUris.parseId(it) }+ }++ private fun asSync(uri: Uri): Uri = uri.buildUpon()+ .appendQueryParameter(android.provider.CalendarContract.CALLER_IS_SYNCADAPTER, "true")+ .appendQueryParameter(Calendars.ACCOUNT_NAME, ACCOUNT)+ .appendQueryParameter(Calendars.ACCOUNT_TYPE, android.provider.CalendarContract.ACCOUNT_TYPE_LOCAL)+ .build()+}
todo/src/main/java/com/vayunmathur/todo/sync/RelayTodoProvider.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/sync/RelayTodoProvider.kt b/todo/src/main/java/com/vayunmathur/todo/sync/RelayTodoProvider.ktindex f800fe12aa..d77affeda0 100644--- a/todo/src/main/java/com/vayunmathur/todo/sync/RelayTodoProvider.kt+++ b/todo/src/main/java/com/vayunmathur/todo/sync/RelayTodoProvider.kt@@ -14,6 +14,7 @@ import androidx.core.net.toUri import com.vayunmathur.library.log.Log import com.vayunmathur.todo.data.SyncSnapshot import com.vayunmathur.todo.data.TodoRepository+import com.vayunmathur.todo.data.TodoSettings import kotlinx.coroutines.runBlocking /**@@ -100,7 +101,9 @@ class RelayTodoProvider : ContentProvider() { private fun <T> guarded(op: String, uri: Uri, fallback: T, block: suspend (TodoRepository) -> T): T { enforceRelayCaller()+ val fromEverysync = Binder.getCallingUid() != Process.myUid() return runBlocking(repo().io) {+ if (fromEverysync) context?.let { TodoSettings(it).markSynced() } try { block(repo()) } catch (e: IllegalArgumentException) {
todo/src/main/java/com/vayunmathur/todo/ui/DataSettingsSection.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/ui/DataSettingsSection.kt b/todo/src/main/java/com/vayunmathur/todo/ui/DataSettingsSection.ktnew file mode 100644index 0000000000..de9a8d8c80--- /dev/null+++ b/todo/src/main/java/com/vayunmathur/todo/ui/DataSettingsSection.kt@@ -0,0 +1,88 @@+package com.vayunmathur.todo.ui++import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalResources+import androidx.compose.ui.res.pluralStringResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.SettingsRow+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.rememberMessenger+import com.vayunmathur.todo.R+import com.vayunmathur.todo.domain.format.ExportFormat+import com.vayunmathur.todo.domain.format.ImportedTask+import com.vayunmathur.todo.platform.TodoViewModel+import kotlinx.coroutines.launch+import com.vayunmathur.library.ui.R as UiR++/** Backup/restore plus import (todo.txt, CSV, iCalendar — detected) and export in each format. */+@Composable+fun DataSettingsSection(viewModel: TodoViewModel) {+ val messenger = rememberMessenger()+ val resources = LocalResources.current+ val scope = rememberCoroutineScope()+ var preview by remember { mutableStateOf<List<ImportedTask>?>(null) }+ val exported = stringResource(R.string.export_done)+ val nothing = stringResource(R.string.import_nothing)++ val launchers = ExportFormat.entries.associateWith { format ->+ rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument(format.mimeType)) { uri ->+ uri?.let { viewModel.export(it, format) { messenger.show(exported) } }+ }+ }+ val importLauncher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->+ uri ?: return@rememberLauncherForActivityResult+ scope.launch {+ val tasks = viewModel.readImport(uri)+ if (tasks.isEmpty()) messenger.show(nothing) else preview = tasks+ }+ }++ Row(Modifier.padding(horizontal = 16.dp)) { TodoBackupButtons() }+ SettingsRow(+ title = stringResource(R.string.import_tasks),+ supportingText = stringResource(R.string.import_summary),+ onClick = { importLauncher.launch(arrayOf("text/*", "application/octet-stream")) },+ )+ ExportFormat.entries.forEach { format ->+ SettingsRow(+ title = stringResource(exportLabel(format)),+ onClick = { launchers.getValue(format).launch("tasks.${format.extension}") },+ )+ }++ preview?.let { tasks ->+ AlertDialog(+ onDismissRequest = { preview = null },+ title = { Text(pluralStringResource(R.plurals.import_confirm, tasks.size, tasks.size)) },+ text = { Text(tasks.take(PREVIEW).joinToString("\n") { "• " + it.title } + if (tasks.size > PREVIEW) "\n…" else "") },+ confirmButton = {+ TextButton(onClick = {+ viewModel.import(tasks) { n -> messenger.show(resources.getQuantityString(R.plurals.imported, n, n)) }+ preview = null+ }) { Text(stringResource(R.string.import_action)) }+ },+ dismissButton = { TextButton(onClick = { preview = null }) { Text(stringResource(UiR.string.cancel)) } },+ )+ }+}++private fun exportLabel(format: ExportFormat) = when (format) {+ ExportFormat.TODO_TXT -> R.string.export_todo_txt+ ExportFormat.CSV -> R.string.export_csv+ ExportFormat.ICALENDAR -> R.string.export_ics+}++private const val PREVIEW = 8
todo/src/main/java/com/vayunmathur/todo/ui/SettingsPage.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/ui/SettingsPage.kt b/todo/src/main/java/com/vayunmathur/todo/ui/SettingsPage.ktindex 0c59f123f3..acfc5eeb4c 100644--- a/todo/src/main/java/com/vayunmathur/todo/ui/SettingsPage.kt+++ b/todo/src/main/java/com/vayunmathur/todo/ui/SettingsPage.kt@@ -1,11 +1,7 @@ package com.vayunmathur.todo.ui -import androidx.compose.foundation.layout.Row-import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue-import androidx.compose.ui.Modifier-import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.todo.Route@@ -24,6 +20,9 @@ fun SettingsPage(backStack: NavBackStack<Route>, viewModel: TodoViewModel) { val lists by viewModel.lists.collectAsStateWithLifecycle() val digestEnabled by settings.digestEnabled.collectAsStateWithLifecycle(false) val digestMinutes by settings.digestMinutes.collectAsStateWithLifecycle(TodoSettings.DEFAULT_DIGEST_MINUTES)+ val calendarMirror by settings.calendarMirror.collectAsStateWithLifecycle(false)+ val lastSyncAt by settings.lastSyncAt.collectAsStateWithLifecycle(0L)+ val pendingSync by viewModel.pendingSync.collectAsStateWithLifecycle() SettingsScreen( state = SettingsUiState(defaultView, defaultSort, showCompleted, lists),@@ -40,9 +39,13 @@ fun SettingsPage(backStack: NavBackStack<Route>, viewModel: TodoViewModel) { onDigestEnabled = { on -> viewModel.updateSettings { setDigestEnabled(on) } }, onDigestMinutes = { m -> viewModel.updateSettings { setDigestMinutes(m) } }, )+ SyncSettingsSection(+ calendarMirror = calendarMirror,+ onCalendarMirror = { on -> viewModel.updateSettings { setCalendarMirror(on) } },+ lastSyncAt = lastSyncAt,+ pendingChanges = pendingSync,+ ) },- dataSection = {- Row(Modifier.padding(horizontal = 16.dp)) { TodoBackupButtons() }- },+ dataSection = { DataSettingsSection(viewModel) }, ) }
todo/src/main/java/com/vayunmathur/todo/ui/SyncSettingsSection.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/ui/SyncSettingsSection.kt b/todo/src/main/java/com/vayunmathur/todo/ui/SyncSettingsSection.ktnew file mode 100644index 0000000000..d8fef46f6c--- /dev/null+++ b/todo/src/main/java/com/vayunmathur/todo/ui/SyncSettingsSection.kt@@ -0,0 +1,62 @@+package com.vayunmathur.todo.ui++import android.Manifest+import android.content.Intent+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.runtime.Composable+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.pluralStringResource+import androidx.compose.ui.res.stringResource+import com.vayunmathur.library.ui.SettingsDivider+import com.vayunmathur.library.ui.SettingsRow+import com.vayunmathur.library.ui.SettingsSection+import com.vayunmathur.library.ui.SettingsSwitchRow+import com.vayunmathur.todo.R+import com.vayunmathur.todo.sync.CalendarMirror++/** Calendar mirror toggle (asks for calendar access when turned on) and sync status. */+@Composable+fun SyncSettingsSection(+ calendarMirror: Boolean,+ onCalendarMirror: (Boolean) -> Unit,+ lastSyncAt: Long,+ pendingChanges: Int,+) {+ val context = LocalContext.current+ val permission = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { granted ->+ if (granted.values.all { it }) onCalendarMirror(true)+ }+ SettingsSection(title = stringResource(R.string.settings_sync)) {+ SettingsSwitchRow(+ title = stringResource(R.string.settings_calendar_mirror),+ supportingText = stringResource(R.string.settings_calendar_mirror_summary),+ checked = calendarMirror && CalendarMirror.hasPermission(context),+ onCheckedChange = { on ->+ when {+ !on -> onCalendarMirror(false)+ CalendarMirror.hasPermission(context) -> onCalendarMirror(true)+ else -> permission.launch(arrayOf(Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR))+ }+ },+ )+ val status = syncStatus(lastSyncAt)+ val launch = context.packageManager.getLaunchIntentForPackage(EVERYSYNC)+ SettingsRow(+ title = stringResource(R.string.settings_everysync),+ supportingText = if (status == null) {+ stringResource(R.string.settings_everysync_never)+ } else {+ listOfNotNull(+ status,+ pendingChanges.takeIf { it > 0 }?.let { pluralStringResource(R.plurals.pending_changes, it, it) },+ ).joinToString(" · ")+ },+ enabled = launch != null,+ onClick = { launch?.let { context.startActivity(it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } },+ )+ }+ SettingsDivider()+}++private const val EVERYSYNC = "com.vayunmathur.everysync"
todo/src/main/res/values/strings.xml
diff --git a/todo/src/main/res/values/strings.xml b/todo/src/main/res/values/strings.xmlindex 0b9294a875..4a2aec8e4a 100644--- a/todo/src/main/res/values/strings.xml+++ b/todo/src/main/res/values/strings.xml@@ -374,4 +374,48 @@ <string name="widget_preview_3">Call Sam about Saturday</string> <!-- Quick add: voice input button description. Verb phrase. --> <string name="voice_input">Speak a task</string>++ <!-- Name of the local calendar holding mirrored tasks. Noun. -->+ <string name="calendar_name">Tasks</string>+ <!-- Settings section header for sync and calendar. Noun. -->+ <string name="settings_sync">Sync</string>+ <!-- Settings: calendar mirror toggle. Verb phrase. -->+ <string name="settings_calendar_mirror">Show tasks in calendar</string>+ <!-- Settings: calendar mirror explanation. -->+ <string name="settings_calendar_mirror_summary">Due tasks appear in a read-only \"Tasks\" calendar in any calendar app</string>+ <!-- Settings: EverySync sync status row title. Proper noun. -->+ <string name="settings_everysync">EverySync</string>+ <!-- Settings: sync status when never synced. -->+ <string name="settings_everysync_never">Not synced. Set up encrypted sync in EverySync.</string>+ <!-- Settings: local changes not yet synced. -->+ <plurals name="pending_changes">+ <item quantity="one"><xliff:g id="count" example="1">%d</xliff:g> change waiting</item>+ <item quantity="other"><xliff:g id="count" example="3">%d</xliff:g> changes waiting</item>+ </plurals>+ <!-- Settings: import row title. Verb phrase. -->+ <string name="import_tasks">Import tasks</string>+ <!-- Settings: import row explanation. -->+ <string name="import_summary">From a todo.txt, CSV or iCalendar file</string>+ <!-- Settings: export as todo.txt. Verb phrase. -->+ <string name="export_todo_txt">Export as todo.txt</string>+ <!-- Settings: export as CSV. Verb phrase. -->+ <string name="export_csv">Export as CSV</string>+ <!-- Settings: export as iCalendar. Verb phrase. -->+ <string name="export_ics">Export as iCalendar</string>+ <!-- Snackbar after exporting. -->+ <string name="export_done">Tasks exported</string>+ <!-- Snackbar when the chosen file had no tasks. -->+ <string name="import_nothing">No tasks found in that file</string>+ <!-- Import confirmation title. -->+ <plurals name="import_confirm">+ <item quantity="one">Import <xliff:g id="count" example="1">%d</xliff:g> task?</item>+ <item quantity="other">Import <xliff:g id="count" example="12">%d</xliff:g> tasks?</item>+ </plurals>+ <!-- Import confirmation button. Verb. -->+ <string name="import_action">Import</string>+ <!-- Snackbar after importing. -->+ <plurals name="imported">+ <item quantity="one"><xliff:g id="count" example="1">%d</xliff:g> task imported</item>+ <item quantity="other"><xliff:g id="count" example="12">%d</xliff:g> tasks imported</item>+ </plurals> </resources>
todo/src/test/java/com/vayunmathur/todo/domain/format/FormatsTest.kt
diff --git a/todo/src/test/java/com/vayunmathur/todo/domain/format/FormatsTest.kt b/todo/src/test/java/com/vayunmathur/todo/domain/format/FormatsTest.ktnew file mode 100644index 0000000000..c79989cd9a--- /dev/null+++ b/todo/src/test/java/com/vayunmathur/todo/domain/format/FormatsTest.kt@@ -0,0 +1,123 @@+package com.vayunmathur.todo.domain.format++import com.vayunmathur.todo.data.Todo+import com.vayunmathur.todo.data.TodoList+import com.vayunmathur.todo.domain.DueDates+import com.vayunmathur.todo.domain.Recurrence+import kotlinx.datetime.LocalDate+import kotlinx.datetime.LocalTime+import kotlinx.datetime.TimeZone+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class FormatsTest {+ private val zone = TimeZone.of("America/Los_Angeles")+ private fun day(m: Int, d: Int) = DueDates.startOfDay(LocalDate(2026, m, d), zone)+ private val work = TodoList(syncId = "w", name = "Work Stuff")+ private val parent = Todo(+ syncId = "p1",+ title = "Ship release, then \"celebrate\"",+ notes = "line one\nline two",+ dueAt = day(3, 5),+ priority = 1,+ listSyncId = "w",+ tags = listOf("release"),+ recurrence = Recurrence.Weekly(1).serialize(),+ createdAt = day(3, 1),+ )+ private val timed = Todo(+ syncId = "t1",+ title = "Call",+ dueAt = DueDates.at(LocalDate(2026, 3, 6), LocalTime(17, 30), zone),+ dueAllDay = false,+ createdAt = day(3, 1),+ )+ private val done = Todo(syncId = "d1", title = "Done thing", done = true, completedAt = day(3, 2), createdAt = day(3, 1))+ private val sub = Todo(syncId = "s1", title = "Sub step", parentSyncId = "p1", createdAt = day(3, 1))+ private val source = ExportSource(listOf(parent, timed, done, sub), listOf(work))++ @Test+ fun `todo txt round trips the fields it can carry`() {+ val text = TodoTxt.export(source, zone)+ assertTrue(text.lines().first().startsWith("(A) 2026-03-01 Ship release"), text)+ assertTrue("+Work_Stuff" in text && "@release" in text && "due:2026-03-05" in text && "rec:+1w" in text, text)+ val back = TodoTxt.parse(text, zone)+ assertEquals(3, back.size, "subtasks are not exported to todo.txt")+ val p = back[0]+ assertEquals("Ship release, then \"celebrate\"", p.title)+ assertEquals(1, p.priority)+ assertEquals("Work Stuff", p.listName)+ assertEquals(listOf("release"), p.tags)+ assertEquals(day(3, 5), p.dueAt)+ assertEquals(Recurrence.Weekly(1), Recurrence.parse(p.recurrence))+ assertTrue(back[2].done)+ assertEquals(day(3, 2), back[2].completedAt)+ }++ @Test+ fun `todo txt understands completion-based repeats and thresholds`() {+ val t = TodoTxt.parse("water plants rec:3d t:2026-03-04", zone).single()+ assertEquals(Recurrence.AfterCompletion(3), Recurrence.parse(t.recurrence))+ assertEquals(day(3, 4), t.startAt)+ assertEquals("water plants", t.title)+ }++ @Test+ fun `csv round trips everything including quotes, newlines and subtasks`() {+ val back = TodoCsv.parse(TodoCsv.export(source, zone), zone)+ assertEquals(4, back.size)+ val p = back[0]+ assertEquals(parent.title, p.title)+ assertEquals(parent.notes, p.notes)+ assertEquals("Work Stuff", p.listName)+ assertEquals(parent.recurrence, p.recurrence)+ assertEquals(timed.dueAt, back[1].dueAt)+ assertEquals(false, back[1].dueAllDay)+ assertEquals("p1", back[3].parentRef)+ assertEquals("p1", p.ref)+ }++ @Test+ fun `csv reader handles quoted commas and CRLF`() {+ val rows = TodoCsv.readRows("a,\"b,c\",\"d\"\"e\"\r\n1,2,3\r\n")+ assertEquals(listOf(listOf("a", "b,c", "d\"e"), listOf("1", "2", "3")), rows)+ }++ @Test+ fun `icalendar round trips with folding, escaping and relations`() {+ val text = VTodo.export(source)+ assertTrue(text.lines().all { it.toByteArray().size <= 76 }, "lines are folded")+ assertTrue("DUE;VALUE=DATE:" in text && "RELATED-TO;RELTYPE=PARENT:p1@" in text, text)+ val back = VTodo.parse(text, TimeZone.currentSystemDefault())+ assertEquals(4, back.size)+ assertEquals(parent.title, back[0].title)+ assertEquals(parent.notes, back[0].notes)+ assertEquals(1, back[0].priority)+ assertEquals(listOf("release"), back[0].tags)+ assertEquals("Work Stuff", back[0].listName)+ assertEquals(timed.dueAt, back[1].dueAt)+ assertTrue(back[2].done)+ assertEquals("p1", back[3].parentRef)+ }++ @Test+ fun `icalendar from other apps maps priority and dates`() {+ val ics = """+ BEGIN:VCALENDAR+ BEGIN:VTODO+ UID:abc+ SUMMARY:Pay\, rent+ DUE;TZID=America/Los_Angeles:20260305T090000+ PRIORITY:5+ STATUS:NEEDS-ACTION+ END:VTODO+ END:VCALENDAR+ """.trimIndent()+ val t = VTodo.parse(ics, zone).single()+ assertEquals("Pay, rent", t.title)+ assertEquals(3, t.priority)+ assertEquals(DueDates.at(LocalDate(2026, 3, 5), LocalTime(9, 0), zone), t.dueAt)+ assertEquals(false, t.dueAllDay)+ }+}