diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/di/DataModule.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/di/DataModule.kt index d8010a6..a3db30a 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/di/DataModule.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/di/DataModule.kt @@ -13,6 +13,7 @@ import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import de.jeanlucmakiola.agendula.data.prefs.SavedFilterMigration +import de.jeanlucmakiola.agendula.data.prefs.ViewsMigration import de.jeanlucmakiola.agendula.data.tasks.AndroidProviderEnvironment import de.jeanlucmakiola.agendula.data.tasks.AndroidTasksDataSource import de.jeanlucmakiola.agendula.data.tasks.ModeRoutingTasksDataSource @@ -49,7 +50,7 @@ internal fun replaceCorrupted() = ReplaceFileCorruptionHandler { emptyPreference private val Context.agendulaDataStore: DataStore by preferencesDataStore( name = "agendula_prefs", corruptionHandler = replaceCorrupted(), - produceMigrations = { listOf(SavedFilterMigration) }, + produceMigrations = { listOf(SavedFilterMigration, ViewsMigration) }, ) @Module diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/SettingsPrefs.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/SettingsPrefs.kt index b09dc92..eaf4a13 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/SettingsPrefs.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/SettingsPrefs.kt @@ -32,6 +32,7 @@ import de.jeanlucmakiola.agendula.domain.asReminderLead import de.jeanlucmakiola.agendula.domain.TaskSortOrder import de.jeanlucmakiola.agendula.domain.SmartList import de.jeanlucmakiola.agendula.domain.UpcomingRange +import de.jeanlucmakiola.agendula.domain.View import de.jeanlucmakiola.agendula.domain.withinUpcoming import de.jeanlucmakiola.floret.reminders.ReminderLead import de.jeanlucmakiola.floret.reminders.ReminderOverride @@ -618,6 +619,17 @@ class SettingsPrefs @Inject constructor( p[GROUPINGS] = p[GROUPINGS].orEmpty().filterTo(HashSet()) { it.substringAfter(GROUPING_SEPARATOR) != key } } + /** + * The views in order, with the list ids of the current store. Home stands in + * for a stored layout that doesn't read, so there is always one. + */ + val views: Flow> = + dataStore.data.map { p -> p[VIEWS] to p[STORAGE_MODE] } + .distinctUntilChanged() + .map { (raw, mode) -> ViewCodec.decode(raw, (storedMode(mode) ?: resolver.autoMode()).name) } + .map { it.ifEmpty { listOf(View.home()) } } + .distinctUntilChanged() + suspend fun setDefaultEditFields(fields: Set) = dataStore.edit { it[DEFAULT_EDIT_FIELDS] = fields.mapTo(mutableSetOf()) { field -> field.name } } @@ -661,6 +673,7 @@ class SettingsPrefs @Inject constructor( val GROUPINGS = stringSetPreferencesKey("task_groupings") val SAVED_FILTERS = SavedFilterMigration.KEY val SAVED_FILTER_NEXT_ID = longPreferencesKey("saved_filter_next_id") + val VIEWS = ViewsMigration.KEY } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/ViewCodec.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/ViewCodec.kt new file mode 100644 index 0000000..3faacdc --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/ViewCodec.kt @@ -0,0 +1,225 @@ +package de.jeanlucmakiola.agendula.data.prefs + +import de.jeanlucmakiola.agendula.domain.Block +import de.jeanlucmakiola.agendula.domain.BlockOptions +import de.jeanlucmakiola.agendula.domain.BlockSource +import de.jeanlucmakiola.agendula.domain.BlockType +import de.jeanlucmakiola.agendula.domain.BlockWidth +import de.jeanlucmakiola.agendula.domain.Rule +import de.jeanlucmakiola.agendula.domain.SavedFilter +import de.jeanlucmakiola.agendula.domain.SmartList +import de.jeanlucmakiola.agendula.domain.TaskSortOrder +import de.jeanlucmakiola.agendula.domain.TileColor +import de.jeanlucmakiola.agendula.domain.View +import de.jeanlucmakiola.agendula.domain.ViewIcon +import de.jeanlucmakiola.agendula.domain.normalized +import java.net.URLDecoder +import java.net.URLEncoder + +/** + * Stored form of the views, in order. A `v1` line comes first, then each view + * as a `view|id|name|icon|quickAdd|scope` line followed by its blocks as + * `block|id|type|width|ignoreScope|source|options` lines. + * + * Rules (a scope, a `rules:` source) are written by [SavedFilterCodec], so list + * ids are qualified by their store (`OWN:3`) here too. Sources read `smart:TODAY`, + * `list:OWN%3A3`, `tag:…`, `filter:4` or `rules:…`; options are `key=value` + * pairs joined by `;`. Text is URL-encoded and booleans are `1` / `0`. + * + * Fixed once released — don't change without a data migration. + */ +internal object ViewCodec { + + const val VERSION = "v1" + + /** + * The views in [raw], with only the list ids of [mode]'s store. Lines that + * don't read are skipped, and a stored layout of another version reads as none. + */ + fun decode(raw: String?, mode: String): List { + val lines = raw.orEmpty().split('\n').filter { it.isNotBlank() } + if (lines.firstOrNull() != VERSION) return emptyList() + val views = mutableListOf() + // A block line belongs to the view above it; those under an unreadable view go with it. + var current: View? = null + var readable = false + fun close() { + current?.let { views += it.copy(blocks = it.blocks.normalized()) } + current = null + } + lines.drop(1).forEach { line -> + val f = line.split('|') + when (f.firstOrNull()) { + "view" -> { + close() + current = runCatching { decodeView(f, mode) }.getOrNull() + readable = current != null + } + "block" -> if (readable) { + runCatching { decodeBlock(f, mode) }.getOrNull()?.let { block -> + current = current?.let { it.copy(blocks = it.blocks + block) } + } + } + } + } + close() + return views.distinctBy { it.id } + } + + fun encode(views: List, mode: String): String = buildList { + add(VERSION) + views.forEach { view -> + add( + listOf( + "view", + view.id.toString(), + encode(view.name), + view.icon.name, + flag(view.quickAdd), + view.scope?.let { encodeRule(it, mode) }.orEmpty(), + ).joinToString("|"), + ) + view.blocks.forEach { add(encodeBlock(it, mode)) } + } + }.joinToString("\n") + + private fun decodeView(f: List, mode: String): View? { + if (f.size != 6) return null + return View( + id = f[1].toLongOrNull() ?: return null, + name = decode(f[2]), + icon = enumOr(f[3], ViewIcon.HOME), + quickAdd = f[4] != "0", + scope = f[5].takeIf { it.isNotEmpty() }?.let { decodeRule(it, mode) }, + blocks = emptyList(), + ) + } + + private fun encodeBlock(block: Block, mode: String): String = listOf( + "block", + block.id.toString(), + block.type.name, + block.width.name, + flag(block.ignoreScope), + block.source?.let { encodeSource(it, mode) }.orEmpty(), + encodeOptions(block.options), + ).joinToString("|") + + private fun decodeBlock(f: List, mode: String): Block? { + if (f.size != 7) return null + val type = BlockType.valueOf(f[2]) + return Block( + id = f[1].toLongOrNull() ?: return null, + type = type, + width = enumOr(f[3], type.widths.first()), + ignoreScope = f[4] == "1", + source = f[5].takeIf { it.isNotEmpty() }?.let { decodeSource(it, mode) ?: return null }, + options = decodeOptions(type, pairs(f[6])), + ) + } + + private fun encodeSource(source: BlockSource, mode: String): String = when (source) { + is BlockSource.Smart -> "smart:${source.smart.name}" + is BlockSource.List -> "list:${encode("$mode:${source.listId}")}" + is BlockSource.Tag -> "tag:${encode(source.tag)}" + is BlockSource.Filter -> "filter:${source.filterId}" + is BlockSource.Rules -> "rules:${encodeRule(source.rule, mode)}" + } + + /** The source [text] names; `null` for a list of another store, which no block here can show. */ + private fun decodeSource(text: String, mode: String): BlockSource? { + val kind = text.substringBefore(':') + val value = text.substringAfter(':') + return when (kind) { + "smart" -> BlockSource.Smart(SmartList.valueOf(value)) + "list" -> decode(value).let { ref -> ref.removePrefix("$mode:").takeIf { it != ref } } + ?.toLong()?.let(BlockSource::List) + "tag" -> BlockSource.Tag(decode(value)) + "filter" -> BlockSource.Filter(value.toLong()) + "rules" -> BlockSource.Rules(decodeRule(value, mode)) + else -> throw IllegalArgumentException("Unknown source $kind") + } + } + + private fun encodeOptions(options: BlockOptions): String = when (options) { + is BlockOptions.Progress -> listOf("wave" to flag(options.wave), "title" to options.title?.let(::encode)) + is BlockOptions.CountTile -> listOf( + "title" to options.title?.let(::encode), + "color" to options.color?.name, + "icon" to options.icon?.name, + ) + is BlockOptions.Preview -> listOf( + "count" to options.count.toString(), + "showAll" to flag(options.showAll), + "inlineDone" to flag(options.inlineDone), + ) + is BlockOptions.TaskList -> listOf( + "sort" to options.sort?.name, + "completed" to flag(options.showCompleted), + "inlineDone" to flag(options.inlineDone), + ) + is BlockOptions.Lists -> listOf( + "accounts" to options.accounts?.sorted()?.joinToString(",") { encode(it) }, + "counts" to flag(options.counts), + ) + is BlockOptions.SectionHeading -> listOf("text" to encode(options.text)) + is BlockOptions.RecentlyCompleted -> listOf("count" to options.count.toString()) + BlockOptions.Tags, BlockOptions.Filters, BlockOptions.WeekStrip -> emptyList() + }.mapNotNull { (key, value) -> value?.let { "$key=$it" } }.joinToString(";") + + /** [type]'s options from [p]; a key missing or not reading keeps its default. */ + private fun decodeOptions(type: BlockType, p: Map): BlockOptions = when (type) { + BlockType.PROGRESS -> BlockOptions.Progress( + wave = p["wave"] != "0", + title = p["title"]?.let(::decode), + ) + BlockType.COUNT_TILE -> BlockOptions.CountTile( + title = p["title"]?.let(::decode), + color = p["color"]?.let { enumOrNull(it) }, + icon = p["icon"]?.let { enumOrNull(it) }, + ) + BlockType.PREVIEW -> BlockOptions.Preview( + count = previewCount(p["count"]), + showAll = p["showAll"] != "0", + inlineDone = p["inlineDone"] == "1", + ) + BlockType.TASK_LIST -> BlockOptions.TaskList( + sort = p["sort"]?.let { enumOrNull(it) }, + showCompleted = p["completed"] != "0", + inlineDone = p["inlineDone"] != "0", + ) + BlockType.LISTS -> BlockOptions.Lists( + accounts = p["accounts"]?.split(',')?.filter { it.isNotEmpty() }?.mapTo(HashSet(), ::decode), + counts = p["counts"] != "0", + ) + BlockType.TAGS -> BlockOptions.Tags + BlockType.FILTERS -> BlockOptions.Filters + BlockType.SECTION_HEADING -> BlockOptions.SectionHeading(p["text"]?.let(::decode).orEmpty()) + BlockType.WEEK_STRIP -> BlockOptions.WeekStrip + BlockType.RECENTLY_COMPLETED -> BlockOptions.RecentlyCompleted(previewCount(p["count"])) + } + + private fun previewCount(value: String?): Int = + value?.toIntOrNull()?.takeIf { it in BlockOptions.PREVIEW_COUNTS } ?: BlockOptions.PREVIEW_COUNTS.first() + + private fun pairs(text: String): Map = text.split(';').filter { '=' in it } + .associate { it.substringBefore('=') to it.substringAfter('=') } + + // The rule grammar is the saved filters': written and read through their codec, as the rule of a line. + private fun encodeRule(rule: Rule, mode: String): String = + SavedFilterCodec.upsert(null, SavedFilter(0, "", rule), mode).split('|', limit = 4)[3] + + private fun decodeRule(text: String, mode: String): Rule = + SavedFilterCodec.decode("v2|0||$text", mode).single().rule + + private fun flag(value: Boolean): String = if (value) "1" else "0" + + private inline fun > enumOrNull(name: String): E? = + enumValues().firstOrNull { it.name == name } + + private inline fun > enumOr(name: String, default: E): E = enumOrNull(name) ?: default + + private fun encode(value: String): String = URLEncoder.encode(value, Charsets.UTF_8.name()) + + private fun decode(value: String): String = URLDecoder.decode(value, Charsets.UTF_8.name()) +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/ViewsMigration.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/ViewsMigration.kt new file mode 100644 index 0000000..0602eb2 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/ViewsMigration.kt @@ -0,0 +1,25 @@ +package de.jeanlucmakiola.agendula.data.prefs + +import androidx.datastore.core.DataMigration +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.stringPreferencesKey +import de.jeanlucmakiola.agendula.domain.View + +/** + * Stores the [View.home] layout once, when there are no views yet: on the + * upgrade from 1.4 and on a fresh install alike. + */ +internal object ViewsMigration : DataMigration { + + val KEY = stringPreferencesKey("views") + + // Home names no list, so the store its ids would be qualified by doesn't matter. + private const val ANY_STORE = "OWN" + + override suspend fun shouldMigrate(currentData: Preferences): Boolean = currentData[KEY] == null + + override suspend fun migrate(currentData: Preferences): Preferences = + currentData.toMutablePreferences().apply { this[KEY] = ViewCodec.encode(listOf(View.home()), ANY_STORE) } + + override suspend fun cleanUp() = Unit +} diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/ViewCodecTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/ViewCodecTest.kt new file mode 100644 index 0000000..ea8b82b --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/ViewCodecTest.kt @@ -0,0 +1,132 @@ +package de.jeanlucmakiola.agendula.data.prefs + +import androidx.datastore.preferences.core.preferencesOf +import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.agendula.domain.Block +import de.jeanlucmakiola.agendula.domain.BlockOptions +import de.jeanlucmakiola.agendula.domain.BlockSource +import de.jeanlucmakiola.agendula.domain.BlockType +import de.jeanlucmakiola.agendula.domain.BlockWidth +import de.jeanlucmakiola.agendula.domain.DueSpec +import de.jeanlucmakiola.agendula.domain.DueWindow +import de.jeanlucmakiola.agendula.domain.Priority +import de.jeanlucmakiola.agendula.domain.Rule +import de.jeanlucmakiola.agendula.domain.SmartList +import de.jeanlucmakiola.agendula.domain.TaskSortOrder +import de.jeanlucmakiola.agendula.domain.TileColor +import de.jeanlucmakiola.agendula.domain.View +import de.jeanlucmakiola.agendula.domain.ViewIcon +import kotlinx.coroutines.runBlocking +import org.junit.jupiter.api.Test + +class ViewCodecTest { + + private val rule = Rule.All( + listOf( + Rule.Any(listOf(Rule.InList(setOf(2L), setOf("EXTERNAL:7")), Rule.HasTag("next, action|(x)"))), + Rule.Not(Rule.Due(DueSpec.Window(DueWindow.NO_DATE))), + Rule.MinPriority(Priority.HIGH), + Rule.Due(DueSpec.NextDays(7)), + ), + ) + + private val everyBlock = listOf( + Block(1, BlockType.PROGRESS, BlockSource.Smart(SmartList.TODAY), BlockWidth.HALF, options = BlockOptions.Progress(wave = false, title = "Mine | today; a=b")), + Block(2, BlockType.COUNT_TILE, BlockSource.List(9), BlockWidth.HALF, ignoreScope = true, options = BlockOptions.CountTile("Tile", TileColor.TERTIARY, ViewIcon.BOLT)), + Block(3, BlockType.COUNT_TILE, BlockSource.Tag("größe,x"), BlockWidth.FULL), + Block(4, BlockType.PREVIEW, BlockSource.Filter(12), options = BlockOptions.Preview(count = 10, showAll = false, inlineDone = true)), + Block(5, BlockType.LISTS, options = BlockOptions.Lists(accounts = setOf("me@example.org", "a,b;c"), counts = false)), + Block(6, BlockType.TAGS), + Block(7, BlockType.FILTERS), + Block(8, BlockType.SECTION_HEADING, options = BlockOptions.SectionHeading("Work = 100%")), + Block(9, BlockType.WEEK_STRIP, ignoreScope = true), + Block(10, BlockType.RECENTLY_COMPLETED, options = BlockOptions.RecentlyCompleted(5)), + Block(11, BlockType.TASK_LIST, BlockSource.Rules(rule), options = BlockOptions.TaskList(TaskSortOrder.PRIORITY, showCompleted = false, inlineDone = false)), + ) + + private val views = listOf( + View.home(), + View(id = 2, name = "Work | stuff\nmore", icon = ViewIcon.WORK, scope = rule, blocks = everyBlock, quickAdd = false), + View(id = 3, name = "Empty", icon = ViewIcon.STAR, scope = Rule.Everything, blocks = emptyList()), + ) + + @Test + fun `views round-trip with every block, source and option`() { + val raw = ViewCodec.encode(views, "OWN") + assertThat(raw.lines().first()).isEqualTo("v1") + assertThat(ViewCodec.decode(raw, "OWN")).isEqualTo(views) + } + + @Test + fun `default options round-trip for every type`() { + val blocks = BlockType.entries.mapIndexed { i, type -> + Block(i + 1L, type, if (type.takesSource) BlockSource.Smart(SmartList.ALL) else null, type.widths.first()) + }.let { it.filterNot { b -> b.type == BlockType.TASK_LIST } + it.single { b -> b.type == BlockType.TASK_LIST } } + val view = View(1, "x", ViewIcon.HOME, null, blocks) + assertThat(ViewCodec.decode(ViewCodec.encode(listOf(view), "OWN"), "OWN")).containsExactly(view) + } + + @Test + fun `another store's lists read as theirs only`() { + val raw = ViewCodec.encode(views, "OWN") + val external = ViewCodec.decode(raw, "EXTERNAL")[1] + // The list source of another store can't show here, so its block drops out. + assertThat(external.blocks.map { it.id }).doesNotContain(2L) + val scope = external.scope as Rule.All + assertThat((scope.children[0] as Rule.Any).children[0]).isEqualTo(Rule.InList(setOf(7L), setOf("OWN:2"))) + } + + @Test + fun `nothing stored, or another version, reads as no views`() { + assertThat(ViewCodec.decode(null, "OWN")).isEmpty() + assertThat(ViewCodec.decode("", "OWN")).isEmpty() + assertThat(ViewCodec.decode("v2\nview|1|x|HOME|1|", "OWN")).isEmpty() + assertThat(ViewCodec.decode("view|1|x|HOME|1|", "OWN")).isEmpty() + } + + @Test + fun `lines that don't read are skipped, with their blocks`() { + val raw = listOf( + "v1", + "view|1|Home|HOME|1|", + "block|1|TAGS|FULL|0||", + "block|2|NOPE|FULL|0||", + "block|3|PREVIEW|FULL|0|smart:NOPE|", + "block|4|PREVIEW|FULL|0|rules:and(|", + "block|x|FILTERS|FULL|0||", + "garbage", + "block|5|FILTERS|FULL|0||", + "view|x|Broken|HOME|1|", + "block|6|TAGS|FULL|0||", + "view|2|Odd|NOPE|0|and(", + "view|3|Fine|NOPE|0|", + "block|7|COUNT_TILE|WIDE|0|smart:ALL|count=x;color=PINK", + "block|8|PREVIEW|HALF|0|smart:UPCOMING|count=4;showAll=0", + "block|9|LISTS|FULL|0|smart:ALL|", + "view|1|Again|HOME|1|", + ).joinToString("\n") + val decoded = ViewCodec.decode(raw, "OWN") + assertThat(decoded.map { it.id }).containsExactly(1L, 3L).inOrder() + assertThat(decoded[0].blocks.map { it.id }).containsExactly(1L, 5L).inOrder() + val fine = decoded[1] + assertThat(fine.icon).isEqualTo(ViewIcon.HOME) + assertThat(fine.quickAdd).isFalse() + // An unknown width or value falls back; a block with a source its type doesn't take drops out. + assertThat(fine.blocks).containsExactly( + Block(7, BlockType.COUNT_TILE, BlockSource.Smart(SmartList.ALL), BlockWidth.HALF), + Block(8, BlockType.PREVIEW, BlockSource.Smart(SmartList.UPCOMING), options = BlockOptions.Preview(showAll = false)), + ).inOrder() + } + + @Test + fun `the migration stores Home once, and only when there are no views`() = runBlocking { + assertThat(ViewsMigration.shouldMigrate(preferencesOf())).isTrue() + val migrated = ViewsMigration.migrate(preferencesOf()) + assertThat(ViewCodec.decode(migrated[ViewsMigration.KEY], "OWN")).containsExactly(View.home()) + assertThat(ViewsMigration.shouldMigrate(migrated)).isFalse() + assertThat(ViewsMigration.migrate(preferencesOf())).isEqualTo(migrated) + + val stored = preferencesOf(ViewsMigration.KEY to ViewCodec.encode(views.drop(1), "OWN")) + assertThat(ViewsMigration.shouldMigrate(stored)).isFalse() + } +}