Merge #106 into release/v1.4.0
# Conflicts: # app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/SettingsPrefs.kt # app/src/main/java/de/jeanlucmakiola/agendula/data/reminders/ReminderPlanner.kt # app/src/main/java/de/jeanlucmakiola/agendula/data/tasks/StoredReminders.kt # app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/SettingsViewModel.kt
This commit is contained in:
commit
31a62d4c08
19 files changed
+411
-73
No files matched your search
@@ -45,6 +45,9 @@ All notable changes to this project are documented here. The format follows
|
||||
Persistent reminders also come back after a reboot. Each list can follow
|
||||
that setting or keep its reminders always or never persistent, under
|
||||
Per-list reminders (#100).
|
||||
- A "Remind right away when past" setting under Notifications: saving a task
|
||||
whose reminder time has already passed, such as one starting now, notifies
|
||||
at once instead of leaving the reminder out (#106).
|
||||
|
||||
## [1.3.2] - 2026-11-13
|
||||
|
||||
|
||||
@@ -101,6 +101,8 @@ data class Settings(
|
||||
val allDayReminderMinuteOfDay: Int = DEFAULT_ALL_DAY_REMINDER_MINUTE,
|
||||
/** Master switch for due reminders; off clears every scheduled alarm. */
|
||||
val remindersEnabled: Boolean = true,
|
||||
/** Ring at once when a save puts a task's reminder in the past, instead of leaving it out (#106). */
|
||||
val remindPastOnSave: Boolean = false,
|
||||
/** Whether the inline "add a subtask" row shows on expanded task-list groups. */
|
||||
val showAddSubtaskRow: Boolean = true,
|
||||
/**
|
||||
@@ -147,6 +149,9 @@ data class Settings(
|
||||
/** How far ahead the Upcoming smart list reaches. */
|
||||
val upcomingRange: UpcomingRange = UpcomingRange.ALL,
|
||||
) {
|
||||
/** Whether a save rings the reminders it puts in the past (#106). */
|
||||
val ringsPastOnSave: Boolean get() = remindersEnabled && remindPastOnSave
|
||||
|
||||
/**
|
||||
* [tasks] as [filter] shows them: a smart list drops the lists kept out of it,
|
||||
* and Upcoming whatever is due past [upcomingRange].
|
||||
@@ -251,6 +256,7 @@ class SettingsPrefs @Inject constructor(
|
||||
allDayReminderMinuteOfDay = p[ALL_DAY_REMINDER_MINUTE]?.takeIf { it in 0 until 24 * 60 }
|
||||
?: DEFAULT_ALL_DAY_REMINDER_MINUTE,
|
||||
remindersEnabled = p[REMINDERS_ENABLED] ?: true,
|
||||
remindPastOnSave = p[REMIND_PAST_ON_SAVE] ?: false,
|
||||
showAddSubtaskRow = p[SHOW_ADD_SUBTASK_ROW] ?: true,
|
||||
bottomAddBar = p[BOTTOM_ADD_BAR] ?: false,
|
||||
perListReminderOverride = reminderCodec.parseLeads(p[LIST_REMINDER_OVERRIDE]),
|
||||
@@ -339,6 +345,8 @@ class SettingsPrefs @Inject constructor(
|
||||
it.remove(DEFAULT_START_TODAY)
|
||||
}
|
||||
|
||||
suspend fun setRemindPastOnSave(enabled: Boolean) = dataStore.edit { it[REMIND_PAST_ON_SAVE] = enabled }
|
||||
|
||||
suspend fun setTimeFormat(pref: TimeFormatPref) = dataStore.edit { it[TIME_FORMAT] = pref.name }
|
||||
|
||||
suspend fun setWeekStart(day: DayOfWeek?) = dataStore.edit {
|
||||
@@ -489,6 +497,7 @@ class SettingsPrefs @Inject constructor(
|
||||
val DEFAULT_START_TODAY = booleanPreferencesKey("default_start_today")
|
||||
val DEFAULT_START_DATE = stringPreferencesKey("default_start_date")
|
||||
val DEFAULT_DUE_DATE = stringPreferencesKey("default_due_date")
|
||||
val REMIND_PAST_ON_SAVE = booleanPreferencesKey("remind_past_on_save")
|
||||
val COLLAPSED_SECTIONS = stringSetPreferencesKey("collapsed_sections")
|
||||
val UPCOMING_RANGE = stringPreferencesKey("upcoming_range")
|
||||
val SAVED_FILTERS = stringPreferencesKey("saved_filters")
|
||||
|
||||
@@ -40,56 +40,7 @@ internal object ReminderPlanner {
|
||||
// One reminder per *occurrence* and lead: a recurring series yields a row
|
||||
// per occurrence, all sharing a taskId, so this is a Set rather than a
|
||||
// taskId-keyed Map.
|
||||
.filter { !it.isClosed && (it.due != null || it.start != null) }
|
||||
.flatMap { task ->
|
||||
// Reminders set on the task itself win — every one of them;
|
||||
// otherwise the task's list may override the global lead, or opt
|
||||
// out entirely (override = null). All-day tasks have their own
|
||||
// day-scale defaults.
|
||||
//
|
||||
// ⚠️ Present-but-empty is "none", not "the default": the store's
|
||||
// answer for a task whose alarms another client turned off. A
|
||||
// default here would keep ringing for what the user switched off.
|
||||
// A default counts only from a date the task has; its own reminders
|
||||
// stand in each date for the other when the task lacks it.
|
||||
val own = perTask[task.taskId]
|
||||
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 = 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.
|
||||
if (own == null && created != null && trigger < created) return@mapNotNull null
|
||||
// Dismissed on another client already: firing it here within
|
||||
// the missed-reminder grace would ring for something done with.
|
||||
//
|
||||
// ⚠️ An all-day reminder without a time of its own is compared
|
||||
// from the start of its day, not from this device's time of
|
||||
// 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.
|
||||
// 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
|
||||
ScheduledReminder(
|
||||
taskId = task.taskId,
|
||||
triggerAt = trigger,
|
||||
occurrenceStart = task.occurrenceStart?.toEpochMilliseconds() ?: ScheduledReminder.NO_OCCURRENCE,
|
||||
)
|
||||
}
|
||||
}
|
||||
.flatMap { triggers(it, perTask[it.taskId], settings, zone) }
|
||||
// The lower bound trails `now` so a reminder missed while the device was
|
||||
// off still fires once on boot instead of being silently dropped.
|
||||
.filter { it.triggerAt in (now - MISSED_GRACE_MS)..(now + WINDOW_MS) }
|
||||
@@ -113,6 +64,87 @@ internal object ReminderPlanner {
|
||||
return atMinuteOfDay(date, allDayMinuteOfDay, zone) - leadMinutes.coerceAtLeast(0) * 60_000L
|
||||
}
|
||||
|
||||
/**
|
||||
* Every reminder of [task] not yet dismissed, past ones included: [own] if it
|
||||
* has reminders of its own, else its list's or the app's default — of which
|
||||
* [sinceCreated] keeps only those after the task was created.
|
||||
*/
|
||||
fun triggers(
|
||||
task: Task,
|
||||
own: List<TaskReminder>?,
|
||||
settings: Settings,
|
||||
zone: ZoneId,
|
||||
sinceCreated: Boolean = true,
|
||||
): List<ScheduledReminder> {
|
||||
if (task.isClosed || (task.due == null && task.start == null)) return emptyList()
|
||||
// Reminders set on the task itself win — every one of them;
|
||||
// otherwise the task's list may override the global lead, or opt
|
||||
// out entirely (override = null). All-day tasks have their own
|
||||
// day-scale defaults.
|
||||
//
|
||||
// ⚠️ Present-but-empty is "none", not "the default": the store's
|
||||
// answer for a task whose alarms another client turned off. A
|
||||
// default here would keep ringing for what the user switched off.
|
||||
// A default counts only from a date the task has; its own reminders
|
||||
// stand in each date for the other when the task lacks it.
|
||||
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
|
||||
return reminders.mapNotNull { reminder ->
|
||||
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.
|
||||
if (sinceCreated && own == null && created != null && trigger < created) return@mapNotNull null
|
||||
// Dismissed on another client already: firing it here within
|
||||
// the missed-reminder grace would ring for something done with.
|
||||
//
|
||||
// ⚠️ An all-day reminder without a time of its own is compared
|
||||
// from the start of its day, not from this device's time of
|
||||
// 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.
|
||||
// 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
|
||||
ScheduledReminder(
|
||||
taskId = task.taskId,
|
||||
triggerAt = trigger,
|
||||
occurrenceStart = task.occurrenceStart?.toEpochMilliseconds() ?: ScheduledReminder.NO_OCCURRENCE,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [task]'s reminders once saved: its [own], with defaults older than the
|
||||
* task, and the [pastDefaults] the save left out of them.
|
||||
*/
|
||||
fun afterSave(
|
||||
task: Task,
|
||||
own: List<TaskReminder>?,
|
||||
pastDefaults: List<TaskReminder>,
|
||||
settings: Settings,
|
||||
zone: ZoneId,
|
||||
): Set<ScheduledReminder> =
|
||||
(triggers(task, own, settings, zone, sinceCreated = false) + triggers(task, pastDefaults, settings, zone)).toSet()
|
||||
|
||||
/**
|
||||
* The reminders a save just put at or before [now] (#106): those of [after]
|
||||
* that [before], the task as it was, did not have already.
|
||||
*/
|
||||
fun pastOnSave(before: Collection<ScheduledReminder>, after: Collection<ScheduledReminder>, now: Long): Set<ScheduledReminder> =
|
||||
after.filterTo(HashSet()) { it.triggerAt <= now } - before.toSet()
|
||||
|
||||
/**
|
||||
* When a reminder [leadMinutes] before [anchor] fires.
|
||||
*
|
||||
|
||||
@@ -10,6 +10,7 @@ import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TaskQuery
|
||||
import de.jeanlucmakiola.agendula.data.tasks.TasksDataSource
|
||||
import de.jeanlucmakiola.agendula.domain.TaskReminder
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
@@ -56,6 +57,41 @@ class ReminderScheduler @Inject constructor(
|
||||
suspend fun markFired(reminder: ScheduledReminder) =
|
||||
withContext(io) { syncLock.withLock { store.markFired(reminder) } }
|
||||
|
||||
/**
|
||||
* Rings [taskId] at once for [past], the reminders its save put at or before
|
||||
* now (#106), and marks them fired so [sync] does not arm them again within
|
||||
* the missed-reminder grace. [pastDefaults] are the defaults the save left
|
||||
* out of the task's own as past.
|
||||
*/
|
||||
suspend fun remindPastOnSave(taskId: Long, past: Set<ScheduledReminder>, pastDefaults: List<TaskReminder>) =
|
||||
withContext(io) {
|
||||
syncLock.withLock {
|
||||
// Read under the lock, as a reminder going off would: the task may
|
||||
// have closed or moved again, or the setting been turned off.
|
||||
val settings = settingsPrefs.settings.first()
|
||||
if (!settings.ringsPastOnSave) return@withLock
|
||||
val task = dataSource.task(taskId)?.takeUnless { it.isRecurring } ?: return@withLock
|
||||
val still = ReminderPlanner.afterSave(task, dataSource.reminders(taskId), pastDefaults, settings, ZoneId.systemDefault())
|
||||
val due = past intersect still
|
||||
if (due.isEmpty()) return@withLock
|
||||
val fired = store.fired()
|
||||
if (due.any { it in fired }) {
|
||||
store.markFired(due)
|
||||
return@withLock
|
||||
}
|
||||
// Armed by a pass that got in first: an exact alarm in the past
|
||||
// goes off at once and its receiver marks it, an inexact one may
|
||||
// wait, so it is rung here instead.
|
||||
val armed = store.all().intersect(due)
|
||||
val ringing = if (store.armedExact() == true) armed else emptySet()
|
||||
if (ringing.isEmpty()) {
|
||||
armed.forEach { cancel(it) }
|
||||
notifier.postIfOpen(dataSource, taskId, ScheduledReminder.NO_OCCURRENCE)
|
||||
}
|
||||
store.markFired(due - ringing)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param afterReboot every alarm is gone, so nothing in the store is armed;
|
||||
* skips asking the system about each one.
|
||||
|
||||
+4
-2
@@ -61,9 +61,11 @@ class ScheduledReminderStore @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun markFired(reminder: ScheduledReminder) {
|
||||
suspend fun markFired(reminder: ScheduledReminder) = markFired(setOf(reminder))
|
||||
|
||||
suspend fun markFired(reminders: Set<ScheduledReminder>) {
|
||||
dataStore.edit { prefs ->
|
||||
prefs[FIRED_KEY] = prefs[FIRED_KEY].orEmpty() + encode(setOf(reminder))
|
||||
prefs[FIRED_KEY] = prefs[FIRED_KEY].orEmpty() + encode(reminders)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -589,6 +589,9 @@ class AndroidTasksDataSource @Inject constructor(
|
||||
override fun reminders(): Map<Long, List<TaskReminder>> =
|
||||
readAlarms(null).groupBy({ it.first }) { it.third }
|
||||
|
||||
override fun reminders(taskId: Long): List<TaskReminder>? =
|
||||
readAlarms(taskId).map { it.third }.ifEmpty { null }
|
||||
|
||||
/** `(property_id, reminder)` for [taskId]'s alarm rows, in stored order. */
|
||||
private fun alarmRows(taskId: Long): List<Pair<Long, TaskReminder>> =
|
||||
readAlarms(taskId).map { it.second to it.third }
|
||||
|
||||
@@ -54,6 +54,7 @@ class ModeRoutingTasksDataSource(
|
||||
active().updateInstance(taskId, occurrenceStart, form, reminders)
|
||||
|
||||
override fun reminders(): Map<Long, List<TaskReminder>> = active().reminders()
|
||||
override fun reminders(taskId: Long): List<TaskReminder>? = active().reminders(taskId)
|
||||
override fun setReminders(taskId: Long, reminders: List<TaskReminder>) =
|
||||
active().setReminders(taskId, reminders)
|
||||
override fun exportTasks(listId: Long): List<ExportTask> = active().exportTasks(listId)
|
||||
|
||||
@@ -60,13 +60,61 @@ internal object StoredReminders {
|
||||
now: Long,
|
||||
zone: ZoneId,
|
||||
wasUntimed: TaskEnd? = null,
|
||||
): List<TaskReminder> = withDefaults(form, start, due, wasAllDay, settings, now, zone, wasUntimed, keepPast = false)
|
||||
|
||||
/** The defaults [withDefaults] leaves out of [form] as already past. */
|
||||
fun leftOutAsPast(
|
||||
form: TaskForm,
|
||||
start: Instant?,
|
||||
due: Instant?,
|
||||
wasAllDay: Boolean,
|
||||
settings: Settings,
|
||||
now: Long,
|
||||
zone: ZoneId,
|
||||
wasUntimed: TaskEnd? = null,
|
||||
): List<TaskReminder> =
|
||||
withDefaults(form, start, due, wasAllDay, settings, now, zone, wasUntimed, keepPast = true) -
|
||||
withDefaults(form, start, due, wasAllDay, settings, now, zone, wasUntimed, keepPast = false).toSet()
|
||||
|
||||
/**
|
||||
* The defaults [of] leaves out of [form] as already past, for a save to ring
|
||||
* at once instead (#106): those the editor noted, or for a form it did not
|
||||
* choose, the ones [withDefaults] leaves out.
|
||||
*/
|
||||
fun pastDefaults(form: TaskForm, current: Task?, settings: Settings, now: Long, zone: ZoneId): List<TaskReminder> =
|
||||
if (form.remindersChosen) {
|
||||
form.pastReminders
|
||||
} else {
|
||||
leftOutAsPast(
|
||||
form,
|
||||
current?.formValueOf(TaskEnd.START),
|
||||
current?.formValueOf(TaskEnd.DUE),
|
||||
current?.isAllDay ?: form.isAllDay,
|
||||
settings,
|
||||
now,
|
||||
zone,
|
||||
current?.untimed,
|
||||
)
|
||||
}
|
||||
|
||||
private fun withDefaults(
|
||||
form: TaskForm,
|
||||
start: Instant?,
|
||||
due: Instant?,
|
||||
wasAllDay: Boolean,
|
||||
settings: Settings,
|
||||
now: Long,
|
||||
zone: ZoneId,
|
||||
wasUntimed: TaskEnd?,
|
||||
keepPast: Boolean,
|
||||
): List<TaskReminder> {
|
||||
val wanted = form.reminders.map { it.lead }.distinct()
|
||||
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 defaults = defaultsFor(form, settings, now, zone, keepPast)
|
||||
if (anchorsOf(start, due).isEmpty() || wanted.isEmpty()) return wanted.ifEmpty { defaults }
|
||||
val named = wanted.map { it.fromStart }.toSet()
|
||||
return wanted + defaultsFor(form, settings, now, zone).filter { it.fromStart in fresh && it.fromStart !in named }
|
||||
return wanted + defaults.filter { it.fromStart in fresh && it.fromStart !in named }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -161,10 +209,16 @@ internal object StoredReminders {
|
||||
* The defaults [form] takes: those counting from a date it has. A one-off
|
||||
* task leaves out what is already past — a start of "now" would ring at once.
|
||||
*/
|
||||
private fun defaultsFor(form: TaskForm, settings: Settings, now: Long, zone: ZoneId): List<TaskReminder> =
|
||||
private fun defaultsFor(
|
||||
form: TaskForm,
|
||||
settings: Settings,
|
||||
now: Long,
|
||||
zone: ZoneId,
|
||||
keepPast: Boolean = false,
|
||||
): List<TaskReminder> =
|
||||
settings.defaultRemindersFor(form.listId, form.isAllDay).filter { reminder ->
|
||||
if ((if (reminder.fromStart) form.start else form.due) == null) return@filter false
|
||||
form.rrule != null || ReminderPlanner.ringsAt(
|
||||
form.rrule != null || keepPast || ReminderPlanner.ringsAt(
|
||||
TaskDates(form.start, form.due, form.isAllDay, form.untimed),
|
||||
reminder.fromStart,
|
||||
reminder.minutesBefore,
|
||||
|
||||
@@ -104,6 +104,9 @@ interface TasksDataSource {
|
||||
*/
|
||||
fun reminders(): Map<Long, List<TaskReminder>>
|
||||
|
||||
/** [reminders] for [taskId] alone, without reading every task's. */
|
||||
fun reminders(taskId: Long): List<TaskReminder>? = reminders()[taskId]
|
||||
|
||||
/**
|
||||
* Every task in [listId] read from the **`tasks` table**, for export. Masters,
|
||||
* not occurrences — see [TaskMapper.exportTask] for why that distinction
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
package de.jeanlucmakiola.agendula.data.tasks
|
||||
|
||||
import android.util.Log
|
||||
import de.jeanlucmakiola.agendula.domain.TaskReminder
|
||||
import de.jeanlucmakiola.agendula.data.di.ApplicationScope
|
||||
import de.jeanlucmakiola.agendula.data.di.IoDispatcher
|
||||
import de.jeanlucmakiola.agendula.data.prefs.Settings
|
||||
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
||||
import de.jeanlucmakiola.agendula.data.reminders.ReminderPlanner
|
||||
import de.jeanlucmakiola.agendula.data.reminders.ReminderScheduler
|
||||
import de.jeanlucmakiola.agendula.data.reminders.ScheduledReminder
|
||||
import de.jeanlucmakiola.floret.time.DayWindow
|
||||
import de.jeanlucmakiola.agendula.domain.SavedFilter
|
||||
import de.jeanlucmakiola.agendula.domain.SeriesCollapse
|
||||
@@ -16,7 +22,9 @@ import de.jeanlucmakiola.agendula.domain.TaskList
|
||||
import de.jeanlucmakiola.agendula.domain.TaskSorting
|
||||
import de.jeanlucmakiola.agendula.domain.TaskStatus
|
||||
import de.jeanlucmakiola.agendula.domain.recurrence.RecurringScope
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.channels.awaitClose
|
||||
import kotlinx.coroutines.channels.consumeEach
|
||||
@@ -41,6 +49,8 @@ class TasksRepositoryImpl @Inject constructor(
|
||||
private val providerResolver: ProviderResolver,
|
||||
private val startupGate: StartupGate,
|
||||
private val settingsPrefs: SettingsPrefs,
|
||||
private val reminderScheduler: ReminderScheduler,
|
||||
@ApplicationScope private val appScope: CoroutineScope,
|
||||
@IoDispatcher private val io: CoroutineDispatcher,
|
||||
) : TasksRepository {
|
||||
|
||||
@@ -114,17 +124,15 @@ class TasksRepositoryImpl @Inject constructor(
|
||||
|
||||
override suspend fun createTask(form: TaskForm): Long =
|
||||
withContext(io) {
|
||||
dataSource.insertTask(form, storedRemindersFor(form, current = null))
|
||||
val settings = settingsPrefs.settings.first()
|
||||
val now = Clock.System.now().toEpochMilliseconds()
|
||||
val before = remindersBeforeSave(form, current = null, settings)
|
||||
dataSource.insertTask(form, storedRemindersFor(form, current = null, settings, now))
|
||||
.also { id -> before?.let { remindPastOnSave(id, it, form, current = null, settings, now) } }
|
||||
}
|
||||
|
||||
private suspend fun storedRemindersFor(form: TaskForm, current: Task?): List<TaskReminder> =
|
||||
StoredReminders.of(
|
||||
form,
|
||||
current,
|
||||
settingsPrefs.settings.first(),
|
||||
Clock.System.now().toEpochMilliseconds(),
|
||||
ZoneId.systemDefault(),
|
||||
)
|
||||
private fun storedRemindersFor(form: TaskForm, current: Task?, settings: Settings, now: Long): List<TaskReminder> =
|
||||
StoredReminders.of(form, current, settings, now, ZoneId.systemDefault())
|
||||
|
||||
override suspend fun duplicateTask(taskId: Long, occurrenceStart: Instant?): Long =
|
||||
withContext(io) {
|
||||
@@ -135,7 +143,7 @@ class TasksRepositoryImpl @Inject constructor(
|
||||
private fun copyOf(task: Task, parentId: Long?, depth: Int): Long {
|
||||
// In the same write as the copy: inserted first and given its reminders
|
||||
// after, a sync landing in between uploads the copy without them.
|
||||
val reminders = dataSource.reminders()[task.taskId].orEmpty().map { it.lead }
|
||||
val reminders = dataSource.reminders(task.taskId).orEmpty().map { it.lead }
|
||||
val id = dataSource.insertTask(
|
||||
TaskForm(
|
||||
title = task.title,
|
||||
@@ -162,7 +170,7 @@ class TasksRepositoryImpl @Inject constructor(
|
||||
}
|
||||
|
||||
override suspend fun remindersFor(taskId: Long): List<TaskReminder> =
|
||||
withContext(io) { runCatching { dataSource.reminders()[taskId].orEmpty() }.getOrDefault(emptyList()) }
|
||||
withContext(io) { runCatching { dataSource.reminders(taskId).orEmpty() }.getOrDefault(emptyList()) }
|
||||
|
||||
override suspend fun setReminders(taskId: Long, reminders: List<TaskReminder>) =
|
||||
withContext(io) { dataSource.setReminders(taskId, reminders) }
|
||||
@@ -186,7 +194,9 @@ class TasksRepositoryImpl @Inject constructor(
|
||||
val seen = current?.lastModified
|
||||
if (seen != null && seen != expectedLastModified) throw TaskConflictException(taskId)
|
||||
}
|
||||
val reminders = storedRemindersFor(form, current)
|
||||
val settings = settingsPrefs.settings.first()
|
||||
val now = Clock.System.now().toEpochMilliseconds()
|
||||
val reminders = storedRemindersFor(form, current, settings, now)
|
||||
val seriesId = current?.seriesId
|
||||
val occurrence = current?.occurrenceStart
|
||||
if (seriesId != null && occurrence != null) {
|
||||
@@ -207,8 +217,15 @@ class TasksRepositoryImpl @Inject constructor(
|
||||
// Going through the occurrence forks an override instead, which takes
|
||||
// the reminders on its own row and leaves the series' alone.
|
||||
val instance = current?.takeIf { it.isRecurring }?.occurrenceStart
|
||||
if (instance == null) dataSource.updateTask(resolvedRow(current, taskId), form, reminders)
|
||||
else dataSource.updateInstance(taskId, instance, form, reminders)
|
||||
if (instance == null) {
|
||||
// A task that could not be read has no baseline to tell its new reminders by.
|
||||
val before = current?.let { remindersBeforeSave(form, it, settings) }
|
||||
val row = resolvedRow(current, taskId)
|
||||
dataSource.updateTask(row, form, reminders)
|
||||
before?.let { remindPastOnSave(row, it, form, current, settings, now) }
|
||||
} else {
|
||||
dataSource.updateInstance(taskId, instance, form, reminders)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun setCancelled(taskId: Long, occurrenceStart: Instant?, cancelled: Boolean) =
|
||||
@@ -309,7 +326,66 @@ class TasksRepositoryImpl @Inject constructor(
|
||||
*/
|
||||
private fun resolvedRow(resolved: Task?, taskId: Long): Long = resolved?.taskId ?: taskId
|
||||
|
||||
/**
|
||||
* The reminders [current] (null: a new task) has before a save of [form],
|
||||
* past ones and defaults older than the task included; null when the save
|
||||
* rings nothing at once (#106) — as for a task that had a reminder go off
|
||||
* already: it rang for that, and moving an overdue task about is no news.
|
||||
*/
|
||||
private fun remindersBeforeSave(form: TaskForm, current: Task?, settings: Settings): List<ScheduledReminder>? {
|
||||
if (!settings.ringsPastOnSave || form.rrule != null || (form.start == null && form.due == null)) return null
|
||||
if (current == null) return emptyList()
|
||||
if (current.isRecurring) return null
|
||||
return logFailure("Reading the reminders before a save failed") {
|
||||
val own = dataSource.reminders(current.taskId)
|
||||
val zone = ZoneId.systemDefault()
|
||||
val now = Clock.System.now().toEpochMilliseconds()
|
||||
if (ReminderPlanner.triggers(current, own, settings, zone).any { it.triggerAt <= now }) return null
|
||||
ReminderPlanner.triggers(current, own, settings, zone, sinceCreated = false)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rings [taskId] for the reminders its save put at or before now that it
|
||||
* did not have [before]. Worked out here, against the task as this save
|
||||
* left it, so a later save cannot change what this one rings; the ringing
|
||||
* itself runs off the save's path, which neither waits on a scheduler pass
|
||||
* nor fails with it.
|
||||
*/
|
||||
private fun remindPastOnSave(
|
||||
taskId: Long,
|
||||
before: List<ScheduledReminder>,
|
||||
form: TaskForm,
|
||||
current: Task?,
|
||||
settings: Settings,
|
||||
now: Long,
|
||||
) {
|
||||
logFailure("Ringing a reminder on save failed") {
|
||||
val zone = ZoneId.systemDefault()
|
||||
val pastDefaults = StoredReminders.pastDefaults(form, current, settings, now, zone)
|
||||
val saved = dataSource.task(taskId) ?: return@logFailure
|
||||
val after = ReminderPlanner.afterSave(saved, dataSource.reminders(taskId), pastDefaults, settings, zone)
|
||||
val past = ReminderPlanner.pastOnSave(before, after, Clock.System.now().toEpochMilliseconds())
|
||||
if (past.isEmpty()) return@logFailure
|
||||
appScope.launch {
|
||||
logFailure("Ringing a reminder on save failed") { reminderScheduler.remindPastOnSave(taskId, past, pastDefaults) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private inline fun <T> logFailure(what: String, block: () -> T): T? =
|
||||
try {
|
||||
block()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, what, e)
|
||||
null
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private const val TAG = "TasksRepository"
|
||||
|
||||
/** Subtask levels a duplicate follows; deeper than any real list, short of a cycle. */
|
||||
private const val MAX_COPY_DEPTH = 8
|
||||
@@ -195,11 +195,18 @@ class RoomTasksDataSource @Inject constructor(
|
||||
tasks.exportTasks(listId).map(RoomTaskMapper::exportTask)
|
||||
|
||||
override fun reminders(): Map<Long, List<TaskReminder>> {
|
||||
val stored = alarms.all().groupBy({ it.taskId }) { it.asReminder().copy(acknowledgedAt = acknowledged(it)) }
|
||||
val stored = alarms.all().groupBy({ it.taskId }, ::reminderOf)
|
||||
// Turned off elsewhere: present and empty, so nothing falls back to a default.
|
||||
return stored + alarms.remindersOff().filterNot(stored::containsKey).associateWith { emptyList() }
|
||||
}
|
||||
|
||||
override fun reminders(taskId: Long): List<TaskReminder>? {
|
||||
val stored = alarms.forTask(taskId).map(::reminderOf)
|
||||
return stored.ifEmpty { if (alarms.remindersOff(taskId) == true) emptyList() else null }
|
||||
}
|
||||
|
||||
private fun reminderOf(row: TaskAlarmEntity): TaskReminder = row.asReminder().copy(acknowledgedAt = acknowledged(row))
|
||||
|
||||
/** `raw` → its `ACKNOWLEDGED`, so a scheduler pass does not re-parse every alarm. */
|
||||
private val acknowledgements = object : LinkedHashMap<String, Instant?>(64, 0.75f, true) {
|
||||
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, Instant?>) = size > ACK_CACHE_SIZE
|
||||
|
||||
@@ -48,6 +48,9 @@ interface TaskAlarmDao {
|
||||
@Query("SELECT id FROM tasks WHERE reminders_off = 1")
|
||||
fun remindersOff(): List<Long>
|
||||
|
||||
@Query("SELECT reminders_off FROM tasks WHERE id = :taskId")
|
||||
fun remindersOff(taskId: Long): Boolean?
|
||||
|
||||
/** Set the task's only reminder, or clear every one with `null`. */
|
||||
@Transaction
|
||||
fun replaceForTask(taskId: Long, alarm: TaskAlarmEntity?) {
|
||||
|
||||
@@ -22,6 +22,8 @@ data class TaskForm(
|
||||
val reminders: List<TaskReminder> = emptyList(),
|
||||
/** Whether [reminders] are exactly the task's, as the editor showed them: empty is then none. */
|
||||
val remindersChosen: Boolean = false,
|
||||
/** Defaults the editor left out of [reminders] as already past, for the save to ring (#106). */
|
||||
val pastReminders: List<TaskReminder> = emptyList(),
|
||||
val location: String? = null,
|
||||
val url: String? = null,
|
||||
val tags: List<String> = emptyList(),
|
||||
|
||||
@@ -84,6 +84,8 @@ data class TaskEditUiState(
|
||||
val remindersTouched: Boolean = false,
|
||||
/** Whether [reminders] are stored as they are — see [TaskForm.remindersChosen]. */
|
||||
val remindersChosen: Boolean = false,
|
||||
/** See [TaskForm.pastReminders]; gone once the user picks reminders. */
|
||||
val pastReminders: List<TaskReminder> = emptyList(),
|
||||
/** The time an all-day reminder without one of its own rings at. */
|
||||
val allDayMinuteOfDay: Int = DEFAULT_ALL_DAY_REMINDER_MINUTE,
|
||||
/** Set while the defaults being applied are the list's own rather than the general ones. */
|
||||
@@ -567,8 +569,18 @@ class TaskEditViewModel @Inject constructor(
|
||||
ZoneId.systemDefault(),
|
||||
loadedUntimed,
|
||||
).isNotEmpty()
|
||||
val past = StoredReminders.leftOutAsPast(
|
||||
toForm().copy(reminders = loadedReminders),
|
||||
loadedStart,
|
||||
loadedDue,
|
||||
loadedAllDay,
|
||||
settings,
|
||||
nowMillis(),
|
||||
ZoneId.systemDefault(),
|
||||
)
|
||||
return copy(
|
||||
reminders = reminders,
|
||||
pastReminders = past,
|
||||
// A new task's, or defaults added to the ones it had: stored as shown.
|
||||
remindersChosen = isNew || reminders.toSet() != storedReminders,
|
||||
visibleFields = visible,
|
||||
@@ -602,12 +614,19 @@ class TaskEditViewModel @Inject constructor(
|
||||
reminders = (it.reminders + reminder).distinct().sortedForDisplay(it),
|
||||
remindersTouched = true,
|
||||
remindersChosen = true,
|
||||
pastReminders = emptyList(),
|
||||
listDefaultsHint = null,
|
||||
errors = emptySet(),
|
||||
)
|
||||
}
|
||||
fun removeReminder(reminder: TaskReminder) = update {
|
||||
it.copy(reminders = it.reminders - reminder, remindersTouched = true, remindersChosen = true, listDefaultsHint = null)
|
||||
it.copy(
|
||||
reminders = it.reminders - reminder,
|
||||
remindersTouched = true,
|
||||
remindersChosen = true,
|
||||
pastReminders = emptyList(),
|
||||
listDefaultsHint = null,
|
||||
)
|
||||
}
|
||||
fun onLocationChange(value: String) = update { it.copy(location = value) }
|
||||
fun onUrlChange(value: String) = update { it.copy(url = value) }
|
||||
@@ -696,7 +715,7 @@ private val TaskEditUiState.hasDates: Boolean get() = start != null || due != nu
|
||||
|
||||
/** No reminders shown; saved, the task keeps none of its own without turning reminders off. */
|
||||
private fun TaskEditUiState.withoutReminders(): TaskEditUiState =
|
||||
copy(reminders = emptyList(), remindersChosen = false, listDefaultsHint = null)
|
||||
copy(reminders = emptyList(), remindersChosen = false, pastReminders = emptyList(), listDefaultsHint = null)
|
||||
|
||||
/** Reminders put away while the task has no date, as the kind they were picked in. */
|
||||
private class SetAside(val reminders: List<TaskReminder>, val allDay: Boolean)
|
||||
@@ -715,6 +734,7 @@ private fun TaskEditUiState.toForm(): TaskForm = TaskForm(
|
||||
percentComplete = percentComplete,
|
||||
reminders = reminders,
|
||||
remindersChosen = remindersChosen,
|
||||
pastReminders = pastReminders,
|
||||
location = location.ifBlank { null },
|
||||
url = url.ifBlank { null },
|
||||
tags = withDraft(tagDraft),
|
||||
|
||||
@@ -194,6 +194,13 @@ internal fun NotificationsScreen(
|
||||
position = Position.Middle,
|
||||
onClick = { showAllDayTime = true },
|
||||
)
|
||||
GroupedSwitchRow(
|
||||
title = stringResource(R.string.settings_remind_past_on_save),
|
||||
summary = stringResource(R.string.settings_remind_past_on_save_hint),
|
||||
checked = state.settings.remindPastOnSave,
|
||||
onCheckedChange = { viewModel.setRemindPastOnSave(it) },
|
||||
position = Position.Middle,
|
||||
)
|
||||
GroupedRow(
|
||||
title = stringResource(R.string.settings_reminder_description),
|
||||
summary = reminderDescriptionLabel(state.settings.reminderDescription),
|
||||
|
||||
@@ -290,6 +290,7 @@ class SettingsViewModel @Inject constructor(
|
||||
fun setBottomAddBar(enabled: Boolean) = viewModelScope.launch { prefs.setBottomAddBar(enabled) }
|
||||
fun setDefaultDueDate(due: DefaultDueDate) = viewModelScope.launch { prefs.setDefaultDueDate(due) }
|
||||
fun setDefaultStartDate(start: DefaultStartDate) = viewModelScope.launch { prefs.setDefaultStartDate(start) }
|
||||
fun setRemindPastOnSave(enabled: Boolean) = viewModelScope.launch { prefs.setRemindPastOnSave(enabled) }
|
||||
|
||||
/** Toggle whether [field] shows by default on a new task's edit form. */
|
||||
fun setFormFieldDefault(field: TaskFormField, enabled: Boolean) = viewModelScope.launch {
|
||||
|
||||
@@ -524,6 +524,8 @@
|
||||
<string name="settings_reliable_delivery_hint">Android may delay reminders to save battery. Exempt Agendula so they arrive on time.</string>
|
||||
<string name="settings_reliable_delivery_exempt">Exempt from battery optimisation — reminders arrive on time.</string>
|
||||
<string name="settings_reminder_description">Description in reminders</string>
|
||||
<string name="settings_remind_past_on_save">Remind right away when past</string>
|
||||
<string name="settings_remind_past_on_save_hint">Saving a task whose reminder time has already passed notifies at once instead of skipping it</string>
|
||||
<string name="settings_reminder_description_hidden">Hidden</string>
|
||||
<string name="settings_reminder_description_short">Short</string>
|
||||
<string name="settings_reminder_description_full">Full</string>
|
||||
|
||||
@@ -360,4 +360,42 @@ class ReminderPlannerTest {
|
||||
)
|
||||
assertThat(plan).containsExactly(ScheduledReminder(10, millis(date.atTime(8, 45), berlin)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a save rings the reminders it put in the past, not the ones the task had`() {
|
||||
val now = millis(date.atTime(12, 0), berlin)
|
||||
val overdue = ScheduledReminder(1, now - 3 * 24 * 3_600_000L)
|
||||
val justNow = ScheduledReminder(1, now - 60_000L)
|
||||
val atNow = ScheduledReminder(1, now)
|
||||
val later = ScheduledReminder(1, now + 60_000L)
|
||||
assertThat(ReminderPlanner.pastOnSave(emptyList(), listOf(overdue, atNow, later), now))
|
||||
.containsExactly(overdue, atNow)
|
||||
assertThat(ReminderPlanner.pastOnSave(listOf(overdue), listOf(overdue, justNow, later), now))
|
||||
.containsExactly(justNow)
|
||||
assertThat(ReminderPlanner.pastOnSave(listOf(overdue), listOf(overdue), now)).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `triggers reach past the window but not a closed or dateless task`() {
|
||||
val due = Instant.fromEpochMilliseconds(millis(date.atTime(12, 0), berlin))
|
||||
val own = listOf(TaskReminder(0), TaskReminder(30 * 24 * 60))
|
||||
val task = testTask(id = 4, due = due)
|
||||
assertThat(ReminderPlanner.triggers(task, own, Settings(), berlin)).containsExactly(
|
||||
ScheduledReminder(4, due.toEpochMilliseconds()),
|
||||
ScheduledReminder(4, due.toEpochMilliseconds() - 30L * 24 * 3_600_000L),
|
||||
)
|
||||
assertThat(ReminderPlanner.triggers(testTask(id = 4), own, Settings(), berlin)).isEmpty()
|
||||
val done = testTask(id = 4, due = due, status = de.jeanlucmakiola.agendula.domain.TaskStatus.COMPLETED)
|
||||
assertThat(ReminderPlanner.triggers(done, own, Settings(), berlin)).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a default from before the task existed counts only when asked to`() {
|
||||
val due = Instant.fromEpochMilliseconds(millis(date.atTime(12, 0), berlin))
|
||||
val task = testTask(id = 4, due = due, created = due)
|
||||
val settings = Settings(defaultReminders = listOf(60).asReminderLeads())
|
||||
assertThat(ReminderPlanner.triggers(task, null, settings, berlin)).isEmpty()
|
||||
assertThat(ReminderPlanner.triggers(task, null, settings, berlin, sinceCreated = false))
|
||||
.containsExactly(ScheduledReminder(4, due.toEpochMilliseconds() - 3_600_000L))
|
||||
}
|
||||
}
|
||||
@@ -77,6 +77,45 @@ class StoredRemindersTest {
|
||||
assertThat(stored(form)).containsExactly(dayBeforeDue, hourBeforeDue)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the defaults left out as past are the ones a save rings`() {
|
||||
val form = TaskForm(title = "t", listId = 1, start = now, due = now + 5.days)
|
||||
assertThat(pastDefaults(form)).containsExactly(dayBeforeStart)
|
||||
assertThat(pastDefaults(form.copy(rrule = "FREQ=DAILY"))).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the past defaults follow the ones a save stores`() {
|
||||
val current = testTask(due = now + 1.hours)
|
||||
val form = TaskForm(title = "t", listId = 1, start = now, due = now + 1.hours)
|
||||
assertThat(stored(form, current)).containsExactly(hourBeforeDue)
|
||||
assertThat(pastDefaults(form, current)).containsExactly(dayBeforeStart, dayBeforeDue)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a save rings no past default the stored ones would not take`() {
|
||||
val form = TaskForm(title = "t", listId = 1, start = now, due = now + 5.days, reminders = listOf(dayBeforeDue))
|
||||
assertThat(pastDefaults(form)).isEmpty()
|
||||
val current = testTask(due = now + 5.days)
|
||||
val cleared = TaskForm(title = "t", listId = 1, start = now, due = now + 5.days, remindersChosen = true)
|
||||
assertThat(pastDefaults(cleared, current)).isEmpty()
|
||||
val named = TaskForm(title = "t", listId = 1, start = now, due = now + 5.days, reminders = listOf(TaskReminder(0, fromStart = true)))
|
||||
assertThat(pastDefaults(named, current)).isEmpty()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a form from the editor rings the defaults it noted as past`() {
|
||||
val form = TaskForm(title = "t", listId = 1, start = now, due = now + 5.days)
|
||||
val past = StoredReminders.leftOutAsPast(form, null, null, false, settings, now.toEpochMilliseconds(), zone)
|
||||
assertThat(past).containsExactly(dayBeforeStart)
|
||||
val chosen = form.copy(reminders = listOf(dayBeforeDue, hourBeforeDue), remindersChosen = true)
|
||||
assertThat(pastDefaults(chosen.copy(pastReminders = past))).containsExactly(dayBeforeStart)
|
||||
assertThat(pastDefaults(chosen)).isEmpty()
|
||||
}
|
||||
|
||||
private fun pastDefaults(form: TaskForm, current: de.jeanlucmakiola.agendula.domain.Task? = null) =
|
||||
StoredReminders.pastDefaults(form, current, settings, now.toEpochMilliseconds(), zone)
|
||||
|
||||
@Test
|
||||
fun `a recurring task keeps it for the occurrences to come`() {
|
||||
val form = TaskForm(title = "t", listId = 1, start = now, due = now + 5.days, rrule = "FREQ=DAILY")
|
||||
|
||||
Reference in new issue
Block a user