Keep nested rules intact when pruning lists, keep the old filters key (#172)

This commit is contained in:
makiolaj committed 2026-11-26 16:32:44 +01:00
1 parent 9dd8660571
commit bfbe7398d4
18 files changed
+168 -100

No files matched your search

@@ -20,7 +20,6 @@ import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.agendula.data.prefs.is24Hour
import de.jeanlucmakiola.agendula.ui.common.LocalFirstDayOfWeek
import de.jeanlucmakiola.agendula.ui.common.LocalUse24HourFormat
import de.jeanlucmakiola.agendula.ui.common.localeFirstDayOfWeek
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.lifecycleScope
@@ -104,7 +103,7 @@ class MainActivity : ComponentActivity() {
val darkTheme = ui.settings.themeMode.isDark(isSystemInDarkTheme())
val context = LocalContext.current
val use24Hour = ui.settings.timeFormat.is24Hour(DateFormat.is24HourFormat(context))
val firstDayOfWeek = ui.settings.weekStart ?: localeFirstDayOfWeek()
val firstDayOfWeek = ui.settings.effectiveWeekStart
AgendulaTheme(
darkTheme = darkTheme,
dynamicColor = ui.settings.dynamicColor,
@@ -20,7 +20,7 @@ import java.net.URLEncoder
* (`OWN:3`), since each store numbers its lists on its own.
*
* Lines without the `v2` mark are the flat format of 1.4 and earlier,
* `id|name|due|lists|tags|match|priority`; [migrate] rewrites them once.
* `id|name|due|lists|tags|match|priority`, still read; [migrate] rewrites them.
*
* Fixed once released — don't change without a data migration.
*/
@@ -42,21 +42,17 @@ internal object SavedFilterCodec {
}
/**
* [raw] without the lists of [mode]'s store [gone] names. A list condition
* left without lists drops out, as a read of it already did with them gone.
* [raw] without the lists of [mode]'s store [gone] names (see [Rule.withoutLists]).
*/
fun withoutLists(raw: String?, mode: String, gone: (Long) -> Boolean): String =
lines(raw).joinToString("\n") { line ->
val filter = runCatching { decodeLine(line, mode) }.getOrNull() ?: return@joinToString line
val pruned = filter.copy(rule = filter.rule.withoutLists(gone) ?: Rule.Everything)
val pruned = filter.copy(rule = filter.rule.withoutLists(gone))
if (pruned == filter) line else encodeLine(pruned, mode)
}
fun remove(raw: String?, id: Long): String = lines(raw).filterNot { idOf(it) == id }.joinToString("\n")
/** Whether [raw] still holds lines of the flat format. */
fun needsMigration(raw: String?): Boolean = lines(raw).any { !isV2(it) }
/**
* [raw] with every flat line rewritten as a rule, lists of every store kept
* as they are. Lines that never read as a filter are dropped.
@@ -87,8 +83,8 @@ internal object SavedFilterCodec {
val f = fields(line)
if (f.size != 4) return null
val id = f[1].toLongOrNull() ?: return null
// A list condition with none of its lists readable drops out, as a flat filter's did.
val rule = RuleParser(f[3], mode).parse().withoutLists { false } ?: Rule.Everything
// A top-level list condition with none of its lists readable drops out, as a flat filter's did.
val rule = RuleParser(f[3], mode).parse().withoutLists { false }
return SavedFilter(id = id, name = decode(f[2]), rule = rule)
}
@@ -4,16 +4,21 @@ import androidx.datastore.core.DataMigration
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.stringPreferencesKey
/** Rewrites the saved filters of 1.4 and earlier as rules, once (see [SavedFilterCodec.migrate]). */
/**
* Copies the saved filters of 1.4 and earlier into [KEY] as rules, once (see
* [SavedFilterCodec.migrate]). The old key is left as it was, so going back to
* an older version still finds the filters it knew.
*/
internal object SavedFilterMigration : DataMigration<Preferences> {
val KEY = stringPreferencesKey("saved_filters")
val KEY = stringPreferencesKey("saved_filters_v2")
val LEGACY_KEY = stringPreferencesKey("saved_filters")
override suspend fun shouldMigrate(currentData: Preferences): Boolean =
SavedFilterCodec.needsMigration(currentData[KEY])
currentData[KEY] == null && currentData[LEGACY_KEY] != null
override suspend fun migrate(currentData: Preferences): Preferences =
currentData.toMutablePreferences().apply { this[KEY] = SavedFilterCodec.migrate(this[KEY]) }
currentData.toMutablePreferences().apply { this[KEY] = SavedFilterCodec.migrate(this[LEGACY_KEY]) }
override suspend fun cleanUp() = Unit
}
@@ -15,6 +15,7 @@ import de.jeanlucmakiola.agendula.domain.DefaultDueDate
import de.jeanlucmakiola.agendula.domain.DefaultStartDate
import de.jeanlucmakiola.agendula.domain.NewTaskDates
import de.jeanlucmakiola.agendula.domain.SavedFilter
import de.jeanlucmakiola.agendula.domain.localeWeekStart
import de.jeanlucmakiola.agendula.domain.newTaskDates
import de.jeanlucmakiola.agendula.domain.Task
import de.jeanlucmakiola.agendula.domain.TaskFilter
@@ -160,6 +161,9 @@ data class Settings(
/** How far ahead the Upcoming smart list reaches. */
val upcomingRange: UpcomingRange = UpcomingRange.ALL,
) {
/** The first day of the week, the locale's when none is set. */
val effectiveWeekStart: DayOfWeek get() = weekStart ?: localeWeekStart()
/** Whether a save rings the reminders it puts in the past (#106). */
val ringsPastOnSave: Boolean get() = remindersEnabled && remindPastOnSave
@@ -10,6 +10,7 @@ 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.RuleClock
import de.jeanlucmakiola.agendula.domain.SavedFilter
import de.jeanlucmakiola.agendula.domain.SeriesCollapse
import de.jeanlucmakiola.agendula.domain.Task
@@ -89,7 +90,7 @@ class TasksRepositoryImpl @Inject constructor(
override fun filteredTasks(filter: TaskFilter): Flow<FilteredTasks> = when (filter) {
// A deleted filter shows nothing rather than failing the screen or widget on it.
is TaskFilter.Saved -> settingsPrefs.savedFilter(filter.id)
.combine(settingsPrefs.settings.map { it.weekStart ?: localeWeekStart() }.distinctUntilChanged(), ::Pair)
.combine(settingsPrefs.settings.map { it.effectiveWeekStart }.distinctUntilChanged(), ::Pair)
.flatMapLatest { (saved, weekStart) ->
if (saved == null) flowOf(FilteredTasks(emptyList()))
else observing {
@@ -133,7 +134,9 @@ class TasksRepositoryImpl @Inject constructor(
is TaskFilter.Tagged -> TaskQuery(includeCompleted = true)
is TaskFilter.Saved -> TaskQuery(includeCompleted = true)
}
val (todayStart, todayEnd) = DayWindow.today(Clock.System.now(), ZoneId.systemDefault())
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
@@ -143,7 +146,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)
@@ -58,9 +58,11 @@ data class FilterCriteria(
if (!claim("priority")) return null
criteria.copy(minPriority = part.priority)
}
// Tags straight under the top read as all of them.
part is Rule.HasTag -> {
if (!claim("tags")) return null
criteria.copy(tags = setOf(part.tag), tagMatch = TagMatch.ALL)
if ("tag group" in seen) return null
seen = seen + "tags"
criteria.copy(tags = criteria.tags + part.tag, tagMatch = TagMatch.ALL)
}
else -> {
val group = groupOf(part) ?: return null
@@ -72,7 +74,7 @@ data class FilterCriteria(
criteria.copy(due = windows.toSet())
}
tags.size == group.size -> {
if (!claim("tags")) return null
if (!claim("tags") || !claim("tag group")) return null
criteria.copy(tags = tags.toSet(), tagMatch = if (part is Rule.All) TagMatch.ALL else TagMatch.ANY)
}
else -> return null
@@ -1,5 +1,6 @@
package de.jeanlucmakiola.agendula.domain
import java.time.DayOfWeek
import java.time.LocalDate
import kotlin.time.Instant
@@ -70,8 +71,8 @@ fun newTaskDates(
/**
* Whether an open task with these dates shows in [smartList], Upcoming reaching
* up to [upcomingEnd], or passes [savedFilter]'s due windows; with neither it
* shows anywhere.
* up to [upcomingEnd], or passes [savedFilter]'s due conditions, its weeks
* starting on [weekStart]; with neither it shows anywhere.
*/
fun NewTaskDates.showsIn(
smartList: SmartList?,
@@ -79,10 +80,11 @@ fun NewTaskDates.showsIn(
todayStart: Instant,
todayEnd: Instant,
upcomingEnd: Instant? = null,
weekStart: DayOfWeek = localeWeekStart(),
): Boolean {
val probe = openTaskDated(start, due, isAllDay)
return when {
savedFilter != null -> savedFilter.admitsDueOf(probe, todayStart, todayEnd)
savedFilter != null -> savedFilter.admitsDueOf(probe, todayStart, todayEnd, weekStart)
smartList != null -> TaskFiltering.matches(probe, TaskFilter.Smart(smartList), todayStart, todayEnd, upcomingEnd = upcomingEnd)
else -> true
}
@@ -89,7 +89,7 @@ data class RuleClock(
val zone: ZoneId = ZoneId.systemDefault(),
val weekStart: DayOfWeek = localeWeekStart(),
) {
val today: LocalDate get() = todayStart.calendarDate(allDay = false, zone = zone)
val today: LocalDate = todayStart.calendarDate(allDay = false, zone = zone)
}
/** The first day of the week in [locale]; what an unset week start means. */
@@ -106,6 +106,22 @@ fun Rule.matches(task: Task, clock: RuleClock): Boolean = when (this) {
is Rule.Due -> window.matches(task, clock)
}
/**
* Whether [task]'s due date alone settles this rule: `true` or `false` when it
* does, `null` when the rule's other conditions decide.
*/
fun Rule.dueVerdict(task: Task, clock: RuleClock): Boolean? = when (this) {
is Rule.Due -> window.matches(task, clock)
is Rule.Not -> child.dueVerdict(task, clock)?.not()
is Rule.All -> children.map { it.dueVerdict(task, clock) }.let { v ->
if (false in v) false else if (null in v) null else true
}
is Rule.Any -> children.map { it.dueVerdict(task, clock) }.let { v ->
if (true in v) true else if (null in v) null else false
}
is Rule.InList, is Rule.HasTag, is Rule.MinPriority -> null
}
/** Whether [task]'s due falls in this spec. */
fun DueSpec.matches(task: Task, clock: RuleClock): Boolean = when (this) {
is DueSpec.Window -> dueWindowOf(task, clock.todayStart, clock.todayEnd, clock.zone) == window
@@ -118,29 +134,26 @@ fun DueSpec.matches(task: Task, clock: RuleClock): Boolean = when (this) {
/**
* This rule without the lists [gone] names, e.g. lists since deleted. A list
* condition left without lists, or that never had any, drops out, as do groups it leaves empty, so the
* rule reads as if it had never been there; `null` when nothing is left.
* condition left without lists matches nothing, as it did with them gone, so a
* nested rule reads the same. Only at the top, where a flat filter keeps its
* criteria, does it drop out instead, so the filter goes back to any list.
*/
fun Rule.withoutLists(gone: (Long) -> Boolean): Rule? = when (this) {
is Rule.InList -> {
val kept = listIds.filterNotTo(HashSet(), gone)
when {
kept.isEmpty() && elsewhere.isEmpty() -> null
kept.size == listIds.size -> this
else -> copy(listIds = kept)
}
fun Rule.withoutLists(gone: (Long) -> Boolean): Rule {
val pruned = withoutListIds(gone)
return when {
pruned.isEmptyList() -> Rule.Everything
pruned is Rule.All -> pruned.children.filterNot { it.isEmptyList() }
.let { if (it.size == pruned.children.size) pruned else Rule.All(it) }
else -> pruned
}
is Rule.All -> prunedGroup(children, gone)?.let(Rule::All)
is Rule.Any -> prunedGroup(children, gone)?.let(Rule::Any)
is Rule.Not -> child.withoutLists(gone)?.let { if (it === child) this else Rule.Not(it) }
is Rule.HasTag, is Rule.MinPriority, is Rule.Due -> this
}
private fun prunedGroup(children: List<Rule>, gone: (Long) -> Boolean): List<Rule>? {
val kept = children.mapNotNull { it.withoutLists(gone) }
return when {
kept.isEmpty() && children.isNotEmpty() -> null
kept == children -> children
else -> kept
}
private fun Rule.isEmptyList(): Boolean = this is Rule.InList && listIds.isEmpty() && elsewhere.isEmpty()
private fun Rule.withoutListIds(gone: (Long) -> Boolean): Rule = when (this) {
is Rule.InList -> listIds.filterNotTo(HashSet(), gone).let { if (it.size == listIds.size) this else copy(listIds = it) }
is Rule.All -> children.map { it.withoutListIds(gone) }.let { if (it == children) this else Rule.All(it) }
is Rule.Any -> children.map { it.withoutListIds(gone) }.let { if (it == children) this else Rule.Any(it) }
is Rule.Not -> child.withoutListIds(gone).let { if (it == child) this else Rule.Not(it) }
is Rule.HasTag, is Rule.MinPriority, is Rule.Due -> this
}
@@ -24,7 +24,7 @@ data class SavedFilter(
/** This filter without the list ids missing from [existing], e.g. lists since deleted. */
fun withListsIn(existing: Set<Long>): SavedFilter =
copy(rule = rule.withoutLists { it !in existing } ?: Rule.Everything)
copy(rule = rule.withoutLists { it !in existing })
fun matches(task: Task, clock: RuleClock): Boolean = !task.isClosed && rule.matches(task, clock)
@@ -35,14 +35,13 @@ data class SavedFilter(
weekStart: DayOfWeek = localeWeekStart(),
): Boolean = matches(task, RuleClock(todayStart, todayEnd, weekStart = weekStart))
/**
* Whether an open task dated like [probe] passes this filter's due windows.
* A filter without a flat form isn't read this way and lets any date through.
*/
fun admitsDueOf(probe: Task, todayStart: Instant, todayEnd: Instant): Boolean {
val due = criteria?.due.orEmpty()
return due.isEmpty() || dueWindowOf(probe, todayStart, todayEnd) in due
}
/** Whether an open task dated like [probe] can pass this filter, going by its due conditions only. */
fun admitsDueOf(
probe: Task,
todayStart: Instant,
todayEnd: Instant,
weekStart: DayOfWeek = localeWeekStart(),
): Boolean = rule.dueVerdict(probe, RuleClock(todayStart, todayEnd, weekStart = weekStart)) != false
}
/**
@@ -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.
* [ruleClock] reads a saved filter's rule; without one it is today with the locale's weeks.
*/
fun matches(
task: Task,
@@ -45,14 +44,14 @@ object TaskFiltering {
todayEnd: Instant,
saved: SavedFilter? = null,
upcomingEnd: Instant? = null,
weekStart: DayOfWeek = localeWeekStart(),
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 }?.matches(task, todayStart, todayEnd, weekStart) ?: false
is TaskFilter.Saved -> saved?.takeIf { it.id == filter.id }?.matches(task, ruleClock ?: RuleClock(todayStart, todayEnd)) ?: false
}
/**
@@ -5,7 +5,6 @@ import de.jeanlucmakiola.agendula.domain.localeWeekStart
import java.time.DayOfWeek
import java.time.LocalTime
import java.time.format.DateTimeFormatter
import java.time.temporal.WeekFields
import java.util.Locale
/**
@@ -15,12 +14,9 @@ import java.util.Locale
val LocalUse24HourFormat = staticCompositionLocalOf { true }
/** The resolved first day of the week, provided at the app root from the week-start setting. */
val LocalFirstDayOfWeek = staticCompositionLocalOf { WeekFields.of(Locale.getDefault()).firstDayOfWeek }
val LocalFirstDayOfWeek = staticCompositionLocalOf { localeWeekStart() }
/** A minute-of-day as a clock time: "14:00" or "2:00 PM". */
fun formatMinuteOfDay(minuteOfDay: Int, is24Hour: Boolean, locale: Locale = Locale.getDefault()): String =
LocalTime.of(minuteOfDay / 60 % 24, minuteOfDay % 60)
.format(DateTimeFormatter.ofPattern(if (is24Hour) "HH:mm" else "h:mm a", locale))
/** The locale's first day of the week, for a week start left on automatic. */
fun localeFirstDayOfWeek(locale: Locale = Locale.getDefault()): DayOfWeek = localeWeekStart(locale)
@@ -247,7 +247,7 @@ class TaskEditViewModel @Inject constructor(
val upcomingEnd = settings.upcomingRange.end(now, zone)
val presetDue = preset?.dueDate ?: presetSmartList?.dueWindows?.presetDue(today)
val dates = settings.defaultNewTaskDates(today, now, presetDue, subtask = parentId != null) {
it.showsIn(presetSmartList, filter, todayStart, todayEnd, upcomingEnd)
it.showsIn(presetSmartList, filter, todayStart, todayEnd, upcomingEnd, settings.effectiveWeekStart)
}
// 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
@@ -33,12 +33,15 @@ class FilterEditViewModel @Inject constructor(
private val _draft = MutableStateFlow<SavedFilter?>(null)
/** `null` until [bind] has loaded the filter. An id of 0 is a new one. */
/**
* `null` until [bind] has loaded the filter. An id of 0 is a new one. Its
* rule is the one loaded; [criteria] holds the edits and replaces it on save.
*/
val draft: StateFlow<SavedFilter?> = _draft.asStateFlow()
private val _criteria = MutableStateFlow<FilterCriteria?>(null)
/** The draft in the flat form the editor shows; `null` while loading, or when its rule has none. */
/** The criteria being edited; `null` while loading, or when the rule has no flat form. */
val criteria: StateFlow<FilterCriteria?> = _criteria.asStateFlow()
val lists: StateFlow<List<TaskList>> = repository.taskLists()
@@ -64,7 +67,9 @@ class FilterEditViewModel @Inject constructor(
viewModelScope.launch {
val saved = settingsPrefs.savedFilter(filterId).first()
// Show it as it matches: lists deleted since drop out, as they do in the repository.
// A read finding no list proves nothing, so it prunes nothing.
val existing = runCatching { repository.taskLists().first().mapTo(HashSet()) { it.id } }.getOrNull()
?.takeIf { it.isNotEmpty() }
load(saved?.let { if (existing == null) it else it.withListsIn(existing) } ?: SavedFilter(id = 0, name = ""))
}
}
@@ -73,11 +78,9 @@ class FilterEditViewModel @Inject constructor(
_draft.value = _draft.value?.copy(name = name)
}
/** Changes the draft's flat criteria; a draft without a flat form keeps its rule as it is. */
/** Changes the criteria; a filter without a flat form keeps its rule as it is. */
fun updateCriteria(transform: (FilterCriteria) -> FilterCriteria) {
val next = _criteria.value?.let(transform) ?: return
_criteria.value = next
_draft.value = _draft.value?.copy(rule = next.toRule())
_criteria.value = _criteria.value?.let(transform)
}
private fun load(filter: SavedFilter) {
@@ -89,8 +92,9 @@ class FilterEditViewModel @Inject constructor(
val filter = _draft.value ?: return
if (filter.name.isBlank() || saving) return
saving = true
val rule = _criteria.value?.toRule() ?: filter.rule
viewModelScope.launch {
val id = settingsPrefs.saveFilter(filter.copy(name = filter.name.trim()))
val id = settingsPrefs.saveFilter(filter.copy(name = filter.name.trim(), rule = rule))
// A widget showing this filter doesn't watch the prefs.
widgetUpdater.requestRefresh()
onSaved(id)
@@ -9,6 +9,7 @@ import de.jeanlucmakiola.agendula.data.sync.RemoteLists
import de.jeanlucmakiola.agendula.data.tasks.TasksRepository
import de.jeanlucmakiola.agendula.data.tasks.recoveringFromProviderFailure
import de.jeanlucmakiola.floret.time.DayWindow
import de.jeanlucmakiola.agendula.domain.RuleClock
import de.jeanlucmakiola.agendula.domain.SavedFilter
import de.jeanlucmakiola.agendula.domain.SmartList
import de.jeanlucmakiola.agendula.domain.Task
@@ -16,7 +17,6 @@ import de.jeanlucmakiola.agendula.domain.TaskFilter
import de.jeanlucmakiola.agendula.domain.TaskFiltering
import de.jeanlucmakiola.agendula.domain.TaskList
import de.jeanlucmakiola.agendula.domain.UpcomingRange
import de.jeanlucmakiola.agendula.domain.localeWeekStart
import de.jeanlucmakiola.agendula.domain.tagsInUse
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
@@ -148,10 +148,10 @@ class ListsViewModel @Inject constructor(
// Open smart lists drop completed tasks, but the Today ring needs the
// ones already ticked off to show "x of y done", so read them too.
repository.tasks(TaskFilter.Smart(SmartList.COMPLETED)),
settingsPrefs.settings.map { Triple(it.hiddenFromSmartLists, it.upcomingRange, it.weekStart) }.distinctUntilChanged(),
settingsPrefs.settings.map { Triple(it.hiddenFromSmartLists, it.upcomingRange, it.effectiveWeekStart) }.distinctUntilChanged(),
settingsPrefs.savedFilters,
) { lists, openTasks, completedTasks, (hidden, upcomingRange, weekStart), filters ->
buildContent(lists, openTasks, completedTasks, hidden, upcomingRange, filters, weekStart ?: localeWeekStart()) as ListsUiState
buildContent(lists, openTasks, completedTasks, hidden, upcomingRange, filters, weekStart) as ListsUiState
}.recoveringFromProviderFailure { ListsUiState.Failure }
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ListsUiState.Loading)
@@ -215,11 +215,15 @@ class ListsViewModel @Inject constructor(
val ids = tagged.mapTo(HashSet()) { it.taskId }
TagOverview(tag, tagged.count { !it.isClosed && (!it.isSubtask || it.parentId !in ids) })
}
val clock = RuleClock(todayStart, todayEnd, zone, weekStart)
// Lists deleted since drop out, as they do when the filter is opened.
val listIds = lists.mapTo(HashSet()) { it.id }
// Same folding as the tags: a subtask counts only when its parent isn't in the filter too.
val filters = savedFilters.map { filter ->
val matching = openTasks.filter { filter.matches(it, todayStart, todayEnd, weekStart) }
val filters = savedFilters.map { saved ->
val filter = if (listIds.isEmpty()) saved else saved.withListsIn(listIds)
val matching = openTasks.filter { filter.matches(it, clock) }
val ids = matching.mapTo(HashSet()) { it.taskId }
FilterOverview(filter, matching.count { !it.isSubtask || it.parentId !in ids })
FilterOverview(saved, matching.count { !it.isSubtask || it.parentId !in ids })
}
return ListsUiState.Content(
smartCounts = smartCounts,
@@ -23,7 +23,7 @@ import de.jeanlucmakiola.agendula.data.prefs.ThemeMode
import de.jeanlucmakiola.agendula.data.prefs.TimeFormatPref
import de.jeanlucmakiola.agendula.data.prefs.is24Hour
import de.jeanlucmakiola.agendula.ui.common.formatMinuteOfDay
import de.jeanlucmakiola.agendula.ui.common.localeFirstDayOfWeek
import de.jeanlucmakiola.agendula.domain.localeWeekStart
import de.jeanlucmakiola.floret.components.CollapsingScaffold
import de.jeanlucmakiola.floret.components.FullScreenPicker
import de.jeanlucmakiola.floret.components.GroupedRow
@@ -162,7 +162,7 @@ internal fun AppearanceScreen(
if (day == null) {
stringResource(
R.string.settings_week_start_auto_summary,
localeFirstDayOfWeek(locale).getDisplayName(TextStyle.FULL, locale),
localeWeekStart(locale).getDisplayName(TextStyle.FULL, locale),
)
} else {
null
@@ -30,6 +30,7 @@ import de.jeanlucmakiola.agendula.domain.TaskFormField
import de.jeanlucmakiola.agendula.domain.TaskList
import de.jeanlucmakiola.floret.reminders.ReminderLead
import de.jeanlucmakiola.floret.reminders.ReminderOverride
import de.jeanlucmakiola.agendula.widget.TaskWidgetUpdater
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
@@ -111,6 +112,7 @@ class SettingsViewModel @Inject constructor(
private val taskNotifier: TaskNotifier,
private val launcherNameManager: LauncherNameManager,
@IoDispatcher private val io: CoroutineDispatcher,
private val widgetUpdater: TaskWidgetUpdater,
repository: TasksRepository,
) : ViewModel() {
@@ -265,7 +267,11 @@ class SettingsViewModel @Inject constructor(
prefs.setTimeFormat(pref)
refreshShownReminders()
}
fun setWeekStart(day: DayOfWeek?) = viewModelScope.launch { prefs.setWeekStart(day) }
fun setWeekStart(day: DayOfWeek?) = viewModelScope.launch {
prefs.setWeekStart(day)
// A widget on a saved filter reads weeks from it, and doesn't watch the prefs.
widgetUpdater.requestRefresh()
}
fun setSnoozeMinutes(minutes: Int) = viewModelScope.launch {
prefs.setSnoozeMinutes(minutes)
refreshShownReminders()
@@ -174,9 +174,7 @@ class SavedFilterCodecTest {
"garbage",
legacyLine(id = 2, refs = listOf("OWN:nope")),
).joinToString("\n")
assertThat(SavedFilterCodec.needsMigration(raw)).isTrue()
val migrated = SavedFilterCodec.migrate(raw)
assertThat(SavedFilterCodec.needsMigration(migrated)).isFalse()
assertThat(migrated.lines()).hasSize(3)
assertThat(migrated.lines().all { it.startsWith("v2|") }).isTrue()
assertThat(SavedFilterCodec.migrate(migrated)).isEqualTo(migrated)
@@ -188,11 +186,13 @@ class SavedFilterCodecTest {
}
@Test
fun `the datastore migration runs only while flat lines are left`() = runBlocking<Unit> {
val prefs = preferencesOf(SavedFilterMigration.KEY to legacyLine(id = 1, refs = listOf("OWN:1")))
fun `the datastore migration runs once and keeps the old filters for older versions`() = runBlocking<Unit> {
val legacy = legacyLine(id = 1, refs = listOf("OWN:1"))
val prefs = preferencesOf(SavedFilterMigration.LEGACY_KEY to legacy)
assertThat(SavedFilterMigration.shouldMigrate(prefs)).isTrue()
val migrated = SavedFilterMigration.migrate(prefs)
assertThat(migrated[SavedFilterMigration.KEY]).startsWith("v2|1|")
assertThat(migrated[SavedFilterMigration.LEGACY_KEY]).isEqualTo(legacy)
assertThat(SavedFilterMigration.shouldMigrate(migrated)).isFalse()
assertThat(SavedFilterMigration.shouldMigrate(preferencesOf())).isFalse()
}
@@ -206,7 +206,7 @@ class SavedFilterCodecTest {
)
val raw = SavedFilterCodec.upsert(null, nested, "OWN") + "\n" + legacyLine(id = 6, refs = listOf("OWN:1", "OWN:3"))
val pruned = SavedFilterCodec.decode(SavedFilterCodec.withoutLists(raw, "OWN") { it == 1L }, "OWN")
assertThat(pruned[0].rule).isEqualTo(Rule.Any(listOf(Rule.Not(Rule.InList(setOf(2L))))))
assertThat(pruned[0].rule).isEqualTo(Rule.Any(listOf(Rule.InList(emptySet()), Rule.Not(Rule.InList(setOf(2L))))))
assertThat(pruned[1].flat().listIds).containsExactly(3L)
assertThat(SavedFilterCodec.withoutLists(raw, "OWN") { it == 99L }).isEqualTo(raw)
}
@@ -153,24 +153,57 @@ class RuleTest {
}
@Test
fun `a list condition losing its lists drops out`() {
fun `a top-level list condition losing its lists drops out`() {
val gone: (Long) -> Boolean = { it == 1L }
assertThat(Rule.InList(setOf(1L, 2L)).withoutLists(gone)).isEqualTo(Rule.InList(setOf(2L)))
assertThat(Rule.InList(setOf(1L)).withoutLists(gone)).isNull()
assertThat(Rule.InList(setOf(1L)).withoutLists(gone)).isEqualTo(Rule.Everything)
assertThat(Rule.InList(setOf(1L), setOf("EXTERNAL:1")).withoutLists(gone))
.isEqualTo(Rule.InList(emptySet(), setOf("EXTERNAL:1")))
val rule = Rule.All(
listOf(
Rule.HasTag("a"),
Rule.Not(Rule.InList(setOf(1L))),
Rule.Any(listOf(Rule.InList(setOf(1L)), Rule.HasTag("b"))),
Rule.Any(listOf(Rule.InList(setOf(1L)))),
),
)
assertThat(rule.withoutLists(gone)).isEqualTo(Rule.All(listOf(Rule.HasTag("a"), Rule.Any(listOf(Rule.HasTag("b"))))))
assertThat(Rule.All(listOf(Rule.InList(setOf(1L)))).withoutLists(gone)).isNull()
assertThat(Rule.All(listOf(Rule.InList(setOf(1L)), Rule.HasTag("a"))).withoutLists(gone))
.isEqualTo(Rule.All(listOf(Rule.HasTag("a"))))
assertThat(Rule.Everything.withoutLists(gone)).isEqualTo(Rule.Everything)
assertThat(rule.withoutLists { false }).isEqualTo(rule)
}
@Test
fun `a nested list condition losing its lists still matches the same tasks`() {
val gone: (Long) -> Boolean = { it == 1L }
val day = LocalDate.of(2026, 11, 26)
val rules = listOf(
Rule.Not(Rule.All(listOf(Rule.InList(setOf(1L)), Rule.HasTag("x")))),
Rule.Any(listOf(Rule.All(listOf(Rule.InList(setOf(1L)), Rule.HasTag("a"))), Rule.HasTag("b"))),
Rule.Any(listOf(Rule.Not(Rule.InList(setOf(1L))), Rule.HasTag("x"))),
Rule.All(listOf(Rule.HasTag("a"), Rule.Not(Rule.InList(setOf(1L, 2L))))),
)
val tasks = listOf(2L, 3L).flatMap { list ->
listOf(emptyList(), listOf("a"), listOf("b"), listOf("x")).map { testTask(listId = list, tags = it) }
}
for (rule in rules) {
val pruned = rule.withoutLists(gone)
assertThat(pruned).isNotEqualTo(rule)
for (task in tasks) assertThat(pruned.matches(task, day)).isEqualTo(rule.matches(task, day))
}
assertThat(rules[0].withoutLists(gone))
.isEqualTo(Rule.Not(Rule.All(listOf(Rule.InList(emptySet()), Rule.HasTag("x")))))
assertThat(rules[0].withoutLists { false }).isEqualTo(rules[0])
}
@Test
fun `the due date settles a rule only where nothing else decides`() {
val day = LocalDate.of(2026, 11, 26)
val clock = clockOn(day)
val thisWeek = Rule.Due(DueSpec.ThisWeek)
val inWeek = dueOn(day)
val later = dueOn(day.plusDays(30))
val rule = Rule.All(listOf(thisWeek, Rule.Not(Rule.MinPriority(Priority.HIGH))))
assertThat(rule.dueVerdict(inWeek, clock)).isNull()
assertThat(rule.dueVerdict(later, clock)).isFalse()
assertThat(Rule.Any(listOf(thisWeek, Rule.HasTag("a"))).dueVerdict(inWeek, clock)).isTrue()
assertThat(Rule.Any(listOf(thisWeek, Rule.HasTag("a"))).dueVerdict(later, clock)).isNull()
assertThat(Rule.Not(thisWeek).dueVerdict(later, clock)).isTrue()
assertThat(Rule.Everything.dueVerdict(later, clock)).isTrue()
val filter = SavedFilter(1, "f", rule)
assertThat(filter.admitsDueOf(inWeek, clock.todayStart, clock.todayEnd, DayOfWeek.MONDAY)).isTrue()
assertThat(filter.admitsDueOf(later, clock.todayStart, clock.todayEnd, DayOfWeek.MONDAY)).isFalse()
}
@Test
@@ -200,6 +233,8 @@ class RuleTest {
assertThat(FilterCriteria.of(Rule.Due(DueSpec.Window(DueWindow.TODAY)))).isEqualTo(FilterCriteria(due = setOf(DueWindow.TODAY)))
assertThat(FilterCriteria.of(Rule.Any(listOf(Rule.HasTag("a"), Rule.HasTag("b")))))
.isEqualTo(FilterCriteria(tags = setOf("a", "b")))
assertThat(FilterCriteria.of(Rule.All(listOf(Rule.HasTag("a"), Rule.InList(setOf(1L)), Rule.HasTag("b")))))
.isEqualTo(FilterCriteria(listIds = setOf(1L), tags = setOf("a", "b"), tagMatch = TagMatch.ALL))
}
@Test
@@ -213,6 +248,7 @@ class RuleTest {
Rule.All(listOf(Rule.Any(emptyList()))),
Rule.InList(emptySet()),
Rule.All(listOf(Rule.All(listOf(Rule.Due(DueSpec.Window(DueWindow.TODAY)))))),
Rule.All(listOf(Rule.HasTag("a"), Rule.Any(listOf(Rule.HasTag("b"))))),
)
for (rule in notFlat) assertThat(FilterCriteria.of(rule)).isNull()
}
@@ -221,6 +257,6 @@ class RuleTest {
fun `a filter without a flat form presets nothing`() {
val filter = SavedFilter(1, "f", Rule.Not(Rule.InList(setOf(1L))))
assertThat(filter.newTaskPreset(LocalDate.of(2026, 11, 26))).isEqualTo(NewTaskPreset())
assertThat(filter.withListsIn(setOf(2L)).rule).isEqualTo(Rule.Everything)
assertThat(filter.withListsIn(setOf(2L)).rule).isEqualTo(Rule.Not(Rule.InList(emptySet())))
}
}