Read saved filters with one clock per load, week start from one place (#172)

This commit is contained in:
makiolaj committed 2026-11-26 17:22:50 +01:00
1 parent 1ad7ed6fe3
commit 5390cb8882
10 files changed
+47 -45

No files matched your search

@@ -98,10 +98,11 @@ class AgendulaApp : Application(), Configuration.Provider {
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
super.onConfigurationChanged(newConfig)
refreshNotificationChannels()
runCatching { EntryPointAccessors.fromApplication(this, AppEntryPoint::class.java).settingsPrefs().onLocaleChanged() }
// Language or dark mode changed: the widget's strings and list colours follow.
// Language or dark mode changed: week starts, the widget's strings and list colours follow.
runCatching {
EntryPointAccessors.fromApplication(this, AppEntryPoint::class.java).taskWidgetUpdater().requestRefresh()
val entryPoint = EntryPointAccessors.fromApplication(this, AppEntryPoint::class.java)
entryPoint.settingsPrefs().onLocaleChanged()
entryPoint.taskWidgetUpdater().requestRefresh()
}
}
@@ -57,6 +57,8 @@ internal object SavedFilterCodec {
*/
fun withoutLists(raw: String?, mode: String, gone: (Long) -> Boolean): String =
lines(raw).joinToString("\n") { line ->
// Most filters hold none of this store's lists; only those need reading.
if ("$mode:" !in line && encode("$mode:") !in line) return@joinToString line
val filter = runCatching { decodeLine(line, mode) }.getOrNull() ?: return@joinToString line
val pruned = filter.copy(rule = filter.rule.withoutLists(gone))
if (pruned == filter) line else encodeLine(pruned, mode)
@@ -317,7 +317,7 @@ class SettingsPrefs @Inject constructor(
?: TimeFormatPref.AUTO,
autofocusTitle = p[AUTOFOCUS_TITLE] ?: true,
syncIntervalMinutes = p[SYNC_INTERVAL]?.takeIf { it == 0 || it >= 15 } ?: DEFAULT_SYNC_INTERVAL_MINUTES,
weekStart = p[WEEK_START]?.let { runCatching { DayOfWeek.valueOf(it) }.getOrNull() },
weekStart = storedWeekStart(p),
pushEnabled = p[PUSH_ENABLED] ?: true,
hiddenFromSmartLists = scope.let { mode ->
p[SMART_LIST_HIDDEN].orEmpty()
@@ -339,6 +339,8 @@ class SettingsPrefs @Inject constructor(
private val locale = MutableStateFlow(Locale.getDefault())
private fun storedWeekStart(p: Preferences): DayOfWeek? = p[WEEK_START]?.let { runCatching { DayOfWeek.valueOf(it) }.getOrNull() }
/** Call when the device language changes: a week start left on automatic follows it. */
fun onLocaleChanged() {
locale.value = Locale.getDefault()
@@ -346,7 +348,7 @@ class SettingsPrefs @Inject constructor(
/** The first day of the week: the setting, or the current locale's when none is set. */
val firstDayOfWeek: Flow<DayOfWeek> =
combine(settings.map { it.weekStart }.distinctUntilChanged(), locale) { set, locale -> set ?: localeWeekStart(locale) }
combine(dataStore.data.map { storedWeekStart(it) }.distinctUntilChanged(), locale) { set, locale -> set ?: localeWeekStart(locale) }
.distinctUntilChanged()
/** Folds or unfolds the group with [id]; day groups that have passed are dropped on the way. */
@@ -21,7 +21,7 @@ import de.jeanlucmakiola.agendula.domain.TaskForm
import de.jeanlucmakiola.agendula.domain.TaskList
import de.jeanlucmakiola.agendula.domain.TaskSorting
import de.jeanlucmakiola.agendula.domain.TaskStatus
import de.jeanlucmakiola.agendula.domain.localeWeekStart
import de.jeanlucmakiola.agendula.domain.RuleClock
import de.jeanlucmakiola.agendula.domain.readsWeekStart
import de.jeanlucmakiola.agendula.domain.recurrence.RecurringScope
import kotlinx.coroutines.CancellationException
@@ -89,13 +89,13 @@ class TasksRepositoryImpl @Inject constructor(
is TaskFilter.Saved -> settingsPrefs.savedFilter(filter.id)
.flatMapLatest { saved ->
if (saved == null) return@flatMapLatest flowOf(FilteredTasks(emptyList()))
// Only a rule with weeks in it reloads when the week start moves.
val weekStarts = if (saved.rule.readsWeekStart) settingsPrefs.firstDayOfWeek else flowOf(null)
// Only a rule with weeks in it reloads when the week start moves; others never read it.
val weekStarts = if (saved.rule.readsWeekStart) settingsPrefs.firstDayOfWeek else flowOf(DayOfWeek.MONDAY)
weekStarts.flatMapLatest { weekStart ->
observing {
// A deleted list's id would otherwise leave the filter quietly empty.
val current = saved.withListsIn(dataSource.taskLists().mapTo(HashSet()) { it.id })
FilteredTasks(loadTasks(filter, current, weekStart ?: localeWeekStart()), current)
FilteredTasks(loadTasks(filter, current, weekStart), current)
}
}
}
@@ -121,7 +121,7 @@ class TasksRepositoryImpl @Inject constructor(
}
/** [weekStart] is where [saved]'s weeks begin. */
private fun loadTasks(filter: TaskFilter, saved: SavedFilter? = null, weekStart: DayOfWeek? = null): List<Task> {
private fun loadTasks(filter: TaskFilter, saved: SavedFilter? = null, weekStart: DayOfWeek = DayOfWeek.MONDAY): List<Task> {
val query = when (filter) {
is TaskFilter.OfList -> TaskQuery(listId = filter.listId, includeCompleted = true)
// Read completed tasks too, then let [TaskFiltering.matches] enforce each
@@ -137,6 +137,7 @@ class TasksRepositoryImpl @Inject constructor(
}
val zone = ZoneId.systemDefault()
val (todayStart, todayEnd) = DayWindow.today(Clock.System.now(), zone)
val clock = saved?.let { RuleClock(todayStart, todayEnd, zone, weekStart) }
val all = SeriesCollapse.visible(dataSource.tasks(query))
// (done, total) of direct children per parent, over the unfiltered set.
val progress: Map<Long, Pair<Int, Int>> = all
@@ -146,7 +147,7 @@ class TasksRepositoryImpl @Inject constructor(
(if (t.isCompleted) done + 1 else done) to (total + 1)
}
return all
.filter { TaskFiltering.matches(it, filter, todayStart, todayEnd, saved, weekStart = weekStart) }
.filter { TaskFiltering.matches(it, filter, todayStart, todayEnd, saved, ruleClock = clock) }
.map { task ->
progress[task.taskId]?.let { (done, total) ->
task.copy(subtaskDone = done, subtaskTotal = total)
@@ -1,8 +1,6 @@
package de.jeanlucmakiola.agendula.domain
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.ZoneId
import kotlin.time.Instant
/** The due date a new task starts with, counted from the day it is created. */
@@ -72,20 +70,20 @@ fun newTaskDates(
/**
* Whether an open task with these dates shows in [smartList], Upcoming reaching
* up to [upcomingEnd], or passes [savedFilter]'s due conditions, its weeks
* starting on [weekStart]; with neither it shows anywhere.
* up to [upcomingEnd], or passes [savedFilter]'s due conditions read with
* [ruleClock]; with neither it shows anywhere, as does a saved filter without a clock.
*/
fun NewTaskDates.showsIn(
smartList: SmartList?,
savedFilter: SavedFilter?,
todayStart: Instant,
todayEnd: Instant,
weekStart: DayOfWeek,
upcomingEnd: Instant? = null,
ruleClock: RuleClock? = null,
): Boolean {
val probe = openTaskDated(start, due, isAllDay)
return when {
savedFilter != null -> savedFilter.admitsDueOf(probe, RuleClock(todayStart, todayEnd, ZoneId.systemDefault(), weekStart))
savedFilter != null -> ruleClock == null || savedFilter.admitsDueOf(probe, ruleClock)
smartList != null -> TaskFiltering.matches(probe, TaskFilter.Smart(smartList), todayStart, todayEnd, upcomingEnd = upcomingEnd)
else -> true
}
@@ -1,6 +1,5 @@
package de.jeanlucmakiola.agendula.domain
import java.time.DayOfWeek
import java.time.ZoneId
import kotlin.time.Instant
@@ -36,7 +35,7 @@ object TaskFiltering {
/**
* [saved] is the definition behind a [TaskFilter.Saved]; without one it matches nothing.
* [upcomingEnd] caps Upcoming to dues before it (see [UpcomingRange.end]); `null` = no cap.
* [weekStart] is where a saved filter's weeks begin, and required with [saved].
* [ruleClock] reads [saved]'s rule; a saved filter without either matches nothing.
*/
fun matches(
task: Task,
@@ -45,17 +44,15 @@ object TaskFiltering {
todayEnd: Instant,
saved: SavedFilter? = null,
upcomingEnd: Instant? = null,
weekStart: DayOfWeek? = null,
ruleClock: RuleClock? = null,
): Boolean =
when (filter) {
is TaskFilter.OfList -> task.listId == filter.listId
is TaskFilter.OfLists -> task.listId in filter.listIds
is TaskFilter.Smart -> matchesSmart(task, filter.list, todayStart, todayEnd, upcomingEnd)
is TaskFilter.Tagged -> filter.tag in task.tags
is TaskFilter.Saved -> saved?.takeIf { it.id == filter.id }?.let { s ->
requireNotNull(weekStart) { "A saved filter needs its week start" }
s.matches(task, RuleClock(todayStart, todayEnd, ZoneId.systemDefault(), weekStart))
} ?: false
is TaskFilter.Saved -> ruleClock != null &&
saved?.takeIf { it.id == filter.id }?.matches(task, ruleClock) == true
}
/**
@@ -32,6 +32,7 @@ import de.jeanlucmakiola.agendula.domain.populatedFields
import de.jeanlucmakiola.agendula.domain.htmlToPlainText
import de.jeanlucmakiola.agendula.domain.looksLikeHtml
import de.jeanlucmakiola.agendula.domain.DefaultStartDate
import de.jeanlucmakiola.agendula.domain.RuleClock
import de.jeanlucmakiola.agendula.domain.dueWindows
import de.jeanlucmakiola.agendula.domain.showsIn
import de.jeanlucmakiola.floret.time.DayWindow
@@ -245,9 +246,10 @@ class TaskEditViewModel @Inject constructor(
val zone = ZoneId.systemDefault()
val (todayStart, todayEnd) = DayWindow.today(now, zone)
val upcomingEnd = settings.upcomingRange.end(now, zone)
val ruleClock = RuleClock(todayStart, todayEnd, zone, settingsPrefs.firstDayOfWeek.first())
val presetDue = preset?.dueDate ?: presetSmartList?.dueWindows?.presetDue(today)
val dates = settings.defaultNewTaskDates(today, now, presetDue, subtask = parentId != null) {
it.showsIn(presetSmartList, filter, todayStart, todayEnd, settings.effectiveWeekStart, upcomingEnd)
it.showsIn(presetSmartList, filter, todayStart, todayEnd, upcomingEnd, ruleClock)
}
// A read-only or vanished default — or a widget's preset list, if it was
// since deleted or turned read-only — would give the task a list it
@@ -86,12 +86,11 @@ fun FilterEditScreen(
)
// A rule the flat sections can't show is kept as it is: only the name changes here.
val flat = criteria
if (flat == null) {
if (criteria == null) {
Spacer(Modifier.height(16.dp))
GroupedRow(title = stringResource(R.string.filter_rules_not_editable), position = Position.Alone)
} else {
CriteriaSections(flat, lists, tagsInUse, viewModel, onChoosePriority = { choosingPriority = true })
CriteriaSections(criteria, lists, tagsInUse, viewModel, onChoosePriority = { choosingPriority = true })
}
if (filter.id > 0) {
@@ -107,12 +106,11 @@ fun FilterEditScreen(
Spacer(Modifier.height(24.dp))
}
val flat = criteria
if (choosingPriority && flat != null) {
if (choosingPriority && criteria != null) {
OptionPicker(
title = stringResource(R.string.filter_section_priority),
options = Priority.entries,
selected = flat.minPriority,
selected = criteria.minPriority,
label = { minPriorityLabel(it) },
onSelect = { priority -> viewModel.updateCriteria { it.copy(minPriority = priority) } },
onDismiss = { choosingPriority = false },
@@ -64,11 +64,11 @@ class NewTaskDefaultsTest {
val upcomingEnd = UpcomingRange.WEEK.end(now, zone)
val preset = SmartList.UPCOMING.dueWindows.presetDue(localToday)
val dates = newTaskDates(DefaultDueDate.NEXT_MONTH, DefaultStartDate.NONE, preset, localToday, now) {
it.showsIn(SmartList.UPCOMING, null, start, end, DayOfWeek.MONDAY, upcomingEnd)
it.showsIn(SmartList.UPCOMING, null, start, end, upcomingEnd)
}
assertThat(dates.due).isEqualTo(allDayInstantOf(localToday.plusDays(1)))
val unlimited = newTaskDates(DefaultDueDate.NEXT_MONTH, DefaultStartDate.NONE, preset, localToday, now) {
it.showsIn(SmartList.UPCOMING, null, start, end, DayOfWeek.MONDAY)
it.showsIn(SmartList.UPCOMING, null, start, end)
}
assertThat(unlimited.due).isEqualTo(allDayInstantOf(localToday.plusMonths(1)))
}
@@ -78,13 +78,13 @@ class NewTaskDefaultsTest {
val (start, end) = DayWindow.today(now, zone)
val upcoming = SmartList.UPCOMING.dueWindows.presetDue(localToday)
fun inUpcoming(due: DefaultDueDate) = newTaskDates(due, DefaultStartDate.NONE, upcoming, localToday, now) {
it.showsIn(SmartList.UPCOMING, null, start, end, DayOfWeek.MONDAY)
it.showsIn(SmartList.UPCOMING, null, start, end)
}.due
assertThat(inUpcoming(DefaultDueDate.NEXT_WEEK)).isEqualTo(allDayInstantOf(localToday.plusWeeks(1)))
assertThat(inUpcoming(DefaultDueDate.TODAY)).isEqualTo(allDayInstantOf(localToday.plusDays(1)))
assertThat(inUpcoming(DefaultDueDate.NONE)).isEqualTo(allDayInstantOf(localToday.plusDays(1)))
val noDate = newTaskDates(DefaultDueDate.TOMORROW, DefaultStartDate.NONE, null, localToday, now) {
it.showsIn(SmartList.NO_DATE, null, start, end, DayOfWeek.MONDAY)
it.showsIn(SmartList.NO_DATE, null, start, end)
}
assertThat(noDate.due).isNull()
}
@@ -94,7 +94,7 @@ class NewTaskDefaultsTest {
val (start, end) = DayWindow.today(now, zone)
fun inToday(startDefault: DefaultStartDate) =
newTaskDates(DefaultDueDate.NEXT_WEEK, startDefault, localToday, localToday, now) {
it.showsIn(SmartList.TODAY, null, start, end, DayOfWeek.MONDAY)
it.showsIn(SmartList.TODAY, null, start, end)
}.due
assertThat(inToday(DefaultStartDate.TODAY)).isEqualTo(allDayInstantOf(localToday.plusWeeks(1)))
assertThat(inToday(DefaultStartDate.NONE)).isEqualTo(allDayInstantOf(localToday))
@@ -103,18 +103,19 @@ class NewTaskDefaultsTest {
@Test
fun `a saved filter checks only its due windows`() {
val (start, end) = DayWindow.today(now, zone)
val clock = RuleClock(start, end, zone, DayOfWeek.MONDAY)
val filter = SavedFilter(id = 1L, name = "Soon", criteria = FilterCriteria(due = setOf(DueWindow.TODAY), listIds = setOf(9L)))
val dates = newTaskDates(DefaultDueDate.TODAY, DefaultStartDate.NONE, localToday, localToday, now)
assertThat(dates.showsIn(null, filter, start, end, DayOfWeek.MONDAY)).isTrue()
assertThat(dates.showsIn(null, filter, start, end, ruleClock = clock)).isTrue()
val later = newTaskDates(DefaultDueDate.TOMORROW, DefaultStartDate.NONE, localToday, localToday, now)
assertThat(later.showsIn(null, filter, start, end, DayOfWeek.MONDAY)).isFalse()
assertThat(later.showsIn(null, filter, start, end, ruleClock = clock)).isFalse()
}
@Test
fun `a view no new task shows in keeps the default due`() {
val (start, end) = DayWindow.today(now, zone)
val dates = newTaskDates(DefaultDueDate.TOMORROW, DefaultStartDate.NONE, null, localToday, now) {
it.showsIn(SmartList.OVERDUE, null, start, end, DayOfWeek.MONDAY)
it.showsIn(SmartList.OVERDUE, null, start, end)
}
assertThat(dates.due).isEqualTo(allDayInstantOf(localToday.plusDays(1)))
}
@@ -194,15 +194,15 @@ class RuleTest {
}
@Test
fun `a saved filter needs its week start`() {
fun `a saved filter is read with its clock`() {
val day = LocalDate.of(2026, 11, 26)
val filter = SavedFilter(1, "f", Rule.Due(DueSpec.ThisWeek))
val clock = clockOn(day)
assertThat(TaskFiltering.matches(dueOn(day), TaskFilter.Saved(1), clock.todayStart, clock.todayEnd, filter, weekStart = DayOfWeek.MONDAY))
.isTrue()
org.junit.jupiter.api.assertThrows<IllegalArgumentException> {
TaskFiltering.matches(dueOn(day), TaskFilter.Saved(1), clock.todayStart, clock.todayEnd, filter)
}
fun matches(task: Task, ruleClock: RuleClock?) =
TaskFiltering.matches(task, TaskFilter.Saved(1), clock.todayStart, clock.todayEnd, filter, ruleClock = ruleClock)
assertThat(matches(dueOn(day), clock)).isTrue()
assertThat(matches(dueOn(day.plusDays(7)), clock)).isFalse()
assertThat(matches(dueOn(day), null)).isFalse()
}
@Test