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 990a03b..f55aa9e 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,8 @@ 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.DefaultStartDestination +import de.jeanlucmakiola.agendula.domain.StartDestination import de.jeanlucmakiola.agendula.domain.View import de.jeanlucmakiola.agendula.domain.withHomeFirst import de.jeanlucmakiola.agendula.domain.withinUpcoming @@ -634,6 +636,50 @@ class SettingsPrefs @Inject constructor( .distinctUntilChanged() .flowOn(Dispatchers.Default) + /** + * Stores [view] in place of the one with its id, or after the others; an id of + * 0 makes a new one. Returns the view's id. Ids are never handed out twice, so + * a launcher shortcut to a deleted view can't open a newer one. + */ + suspend fun saveView(view: View): Long { + var id = view.id + dataStore.edit { p -> + if (id <= 0) { + val taken = ViewCodec.decode(p[VIEWS], modeOf(p).name).maxOfOrNull { it.id } ?: View.HOME_ID + id = maxOf(p[VIEW_NEXT_ID] ?: 0L, taken + 1) + p[VIEW_NEXT_ID] = id + 1 + } + p[VIEWS] = ViewCodec.upsert(p[VIEWS], view.copy(id = id), modeOf(p).name) + } + return id + } + + /** Deletes view [id], never Home; the last used view and the start destination fall back to Home. */ + suspend fun deleteView(id: Long) { + if (id == View.HOME_ID) return + dataStore.edit { p -> + p[VIEWS] = ViewCodec.remove(p[VIEWS], id) + if (p[ACTIVE_VIEW] == id) p.remove(ACTIVE_VIEW) + if (decodeStart(p[START_DESTINATION], modeOf(p).name) == StartDestination.View(id)) p.remove(START_DESTINATION) + } + } + + /** Puts the views in the order of [ids]; Home stays first, as [views] reads it. */ + suspend fun reorderViews(ids: List) = dataStore.edit { p -> p[VIEWS] = ViewCodec.reorder(p[VIEWS], ids) } + + /** The view last shown; Home until another is. */ + val activeViewId: Flow = dataStore.data.map { it[ACTIVE_VIEW] ?: View.HOME_ID }.distinctUntilChanged() + + suspend fun setActiveView(id: Long) = dataStore.edit { it[ACTIVE_VIEW] = id } + + /** Where the app opens (#141); Home until chosen. A list of another store reads as the default. */ + val startDestination: Flow = + dataStore.data.map { p -> decodeStart(p[START_DESTINATION], modeOf(p).name) }.distinctUntilChanged() + + suspend fun setStartDestination(destination: StartDestination) = dataStore.edit { p -> + p[START_DESTINATION] = encodeStart(destination, modeOf(p).name) + } + suspend fun setDefaultEditFields(fields: Set) = dataStore.edit { it[DEFAULT_EDIT_FIELDS] = fields.mapTo(mutableSetOf()) { field -> field.name } } @@ -678,6 +724,9 @@ class SettingsPrefs @Inject constructor( val SAVED_FILTERS = SavedFilterMigration.KEY val SAVED_FILTER_NEXT_ID = longPreferencesKey("saved_filter_next_id") val VIEWS = ViewsMigration.KEY + val VIEW_NEXT_ID = longPreferencesKey("view_next_id") + val ACTIVE_VIEW = longPreferencesKey("active_view") + val START_DESTINATION = stringPreferencesKey("start_destination") } } @@ -688,6 +737,30 @@ class SettingsPrefs @Inject constructor( */ private val reminderCodec = ReminderOverrideCodec.DEFAULT +/** + * A start destination as stored: `last`, `view:3`, `filter:4`, or `list:OWN:5` + * with the list qualified by its store, as the views' are. + */ +internal fun encodeStart(destination: StartDestination, mode: String): String = when (destination) { + StartDestination.LastUsed -> "last" + is StartDestination.View -> "view:${destination.id}" + is StartDestination.List -> "list:$mode:${destination.id}" + is StartDestination.Filter -> "filter:${destination.id}" +} + +/** The start destination [stored] names; nothing, or a list of another store than [mode]'s, reads as the default. */ +internal fun decodeStart(stored: String?, mode: String): StartDestination { + val value = stored?.substringAfter(':') + return when (stored?.substringBefore(':')) { + "last" -> StartDestination.LastUsed + "view" -> value?.toLongOrNull()?.let { StartDestination.View(it) } + "filter" -> value?.toLongOrNull()?.let { StartDestination.Filter(it) } + "list" -> value?.takeIf { it.startsWith("$mode:") }?.substringAfter(':')?.toLongOrNull() + ?.let { StartDestination.List(it) } + else -> null + } ?: DefaultStartDestination +} + private fun listPersistencePrefix(mode: String, listId: Long) = "$mode:$listId=" /** `MODE:listId=ALWAYS|NEVER` entries, [mode]'s only. */ 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 index 715095c..0596f6e 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/ViewCodec.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/ViewCodec.kt @@ -83,6 +83,66 @@ internal object ViewCodec { } }.joinToString("\n") + /** + * [raw] with [view] written in place of the stored view with its id, or added + * at the end. Lines that don't read stay, those of [view] after its blocks. A + * layout of another version is returned as it is: writing over it would lose it. + */ + fun upsert(raw: String?, view: View, mode: String): String { + val layout = Layout.of(raw) ?: return raw.orEmpty() + val chunk = layout.chunks.firstOrNull { it.id == view.id } + val encoded = encode(listOf(view), mode).lines().drop(1) + val written = if (chunk == null) { + layout.chunks + Chunk(encoded) + } else { + val unread = chunk.lines.drop(1).filter { runCatching { decodeBlock(it.split('|'), mode) }.getOrNull() == null } + layout.chunks.map { if (it === chunk) Chunk(encoded + unread) else it } + } + return layout.copy(chunks = written).text() + } + + /** [raw] without the view [id]; another version's layout is returned as it is. */ + fun remove(raw: String?, id: Long): String { + val layout = Layout.of(raw) ?: return raw.orEmpty() + return layout.copy(chunks = layout.chunks.filterNot { it.id == id }).text() + } + + /** + * [raw] with its views in the order of [ids]. A view [ids] leaves out, and one + * that doesn't read, keeps its slot. + */ + fun reorder(raw: String?, ids: List): String { + val layout = Layout.of(raw) ?: return raw.orEmpty() + val named = layout.chunks.filter { it.id in ids } + val ordered = named.sortedBy { ids.indexOf(it.id) }.iterator() + return layout.copy(chunks = layout.chunks.map { if (it.id in ids) ordered.next() else it }).text() + } + + /** One view's lines: its `view` line and the block lines under it. */ + private class Chunk(val lines: List) { + val id: Long? = lines.first().split('|').getOrNull(1)?.toLongOrNull() + } + + /** A stored layout of this version: lines before the first view, then each view's. */ + private data class Layout(val head: List, val chunks: List) { + fun text(): String = (listOf(VERSION) + head + chunks.flatMap { it.lines }).joinToString("\n") + + companion object { + /** [raw] in chunks; nothing stored reads as an empty layout, another version as `null`. */ + fun of(raw: String?): Layout? { + val lines = raw.orEmpty().split('\n').filter { it.isNotBlank() } + if (lines.isEmpty()) return Layout(emptyList(), emptyList()) + if (lines.first() != VERSION) return null + val head = lines.drop(1).takeWhile { !it.startsWith("view|") } + val chunks = mutableListOf>() + lines.drop(1 + head.size).forEach { line -> + if (line.startsWith("view|")) chunks += mutableListOf(line) else chunks.last() += line + } + return Layout(head, chunks.map { Chunk(it) }) + } + } + } + private fun decodeView(f: List, mode: String): View? { if (f.size != 6) return null return View( 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 index 29c8770..9e1f2c2 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/ViewCodecTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/ViewCodecTest.kt @@ -164,4 +164,61 @@ class ViewCodecTest { val stored = preferencesOf(ViewsMigration.KEY to ViewCodec.encode(views.drop(1), "OWN")) assertThat(ViewsMigration.shouldMigrate(stored)).isFalse() } + @Test + fun `a view is written in its place, or after the others`() { + val raw = ViewCodec.encode(views, "OWN") + val renamed = views[1].copy(name = "Job", scope = null) + val replaced = ViewCodec.upsert(raw, renamed, "OWN") + assertThat(ViewCodec.decode(replaced, "OWN")).containsExactly(views[0], renamed, views[2]).inOrder() + + val added = View(9, "New", ViewIcon.STAR, null, View.home().blocks) + assertThat(ViewCodec.decode(ViewCodec.upsert(raw, added, "OWN"), "OWN").map { it.id }) + .containsExactly(1L, 2L, 3L, 9L).inOrder() + assertThat(ViewCodec.decode(ViewCodec.upsert(null, added, "OWN"), "OWN")).containsExactly(added) + } + + @Test + fun `writing a view keeps the lines that don't read`() { + val raw = listOf( + "v1", + "garbage", + "view|1|Home|HOME|1|", + "block|1|TAGS|FULL|0||", + "block|2|NOPE|FULL|0||", + "view|x|Broken|HOME|1|", + "block|6|TAGS|FULL|0||", + "view|3|Fine|STAR|1|", + ).joinToString("\n") + val home = ViewCodec.decode(raw, "OWN").first().copy(name = "Mine") + val written = ViewCodec.upsert(raw, home, "OWN") + assertThat(written.lines()).containsExactly( + "v1", + "garbage", + "view|1|Mine|HOME|1|", + "block|1|TAGS|FULL|0||", + "block|2|NOPE|FULL|0||", + "view|x|Broken|HOME|1|", + "block|6|TAGS|FULL|0||", + "view|3|Fine|STAR|1|", + ).inOrder() + assertThat(ViewCodec.remove(written, 3).lines()).doesNotContain("view|3|Fine|STAR|1|") + assertThat(ViewCodec.remove(written, 3).lines()).contains("view|x|Broken|HOME|1|") + } + + @Test + fun `views reorder by id, those not named keeping their slot`() { + val raw = ViewCodec.encode(views + View(4, "Four", ViewIcon.BOLT, null, emptyList()), "OWN") + val reordered = ViewCodec.reorder(raw, listOf(1L, 4L, 2L)) + assertThat(ViewCodec.decode(reordered, "OWN").map { it.id }).containsExactly(1L, 4L, 3L, 2L).inOrder() + assertThat(ViewCodec.decode(reordered, "OWN").single { it.id == 2L }).isEqualTo(views[1]) + } + + @Test + fun `another version's layout is never written over`() { + val newer = "v2\nview|1|x|HOME|1|" + val view = View(5, "x", ViewIcon.HOME, null, emptyList()) + assertThat(ViewCodec.upsert(newer, view, "OWN")).isEqualTo(newer) + assertThat(ViewCodec.remove(newer, 1)).isEqualTo(newer) + assertThat(ViewCodec.reorder(newer, listOf(1L))).isEqualTo(newer) + } } diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/ViewPrefsTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/ViewPrefsTest.kt new file mode 100644 index 0000000..015c8f9 --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/ViewPrefsTest.kt @@ -0,0 +1,103 @@ +package de.jeanlucmakiola.agendula.data.prefs + +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.emptyPreferences +import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.agendula.data.tasks.ProviderEnvironment +import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver +import de.jeanlucmakiola.agendula.data.tasks.StorageMode +import de.jeanlucmakiola.agendula.domain.DefaultStartDestination +import de.jeanlucmakiola.agendula.domain.Rule +import de.jeanlucmakiola.agendula.domain.StartDestination +import de.jeanlucmakiola.agendula.domain.View +import de.jeanlucmakiola.agendula.domain.newView +import de.jeanlucmakiola.agendula.domain.pinnedView +import de.jeanlucmakiola.agendula.domain.ViewIcon +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import org.junit.jupiter.api.Test + +class ViewPrefsTest { + + private class MemoryDataStore : DataStore { + override val data = MutableStateFlow(emptyPreferences()) + override suspend fun updateData(transform: suspend (t: Preferences) -> Preferences) = + transform(data.value).also { data.value = it } + } + + private object NoProviders : ProviderEnvironment { + override fun packageDeclaring(authority: String): String? = null + override fun isGranted(permission: String) = false + override fun appLabel(packageName: String): String? = null + } + + private val prefs = SettingsPrefs(MemoryDataStore(), ProviderResolver(NoProviders)) + + @Test + fun `a new view gets an id never handed out before`() = runBlocking { + prefs.setStorageMode(StorageMode.OWN) + val first = prefs.saveView(newView(0, "A")) + val second = prefs.saveView(pinnedView(0, "B", ViewIcon.LIST, Rule.InList(setOf(3L)))) + assertThat(first).isEqualTo(2L) + assertThat(second).isEqualTo(3L) + prefs.deleteView(second) + assertThat(prefs.saveView(newView(0, "C"))).isEqualTo(4L) + assertThat(prefs.views.first().map { it.name }).containsExactly("", "A", "C").inOrder() + assertThat(prefs.views.first()[1]).isEqualTo(newView(2, "A")) + } + + @Test + fun `saving a view replaces it in place`() = runBlocking { + val id = prefs.saveView(newView(0, "A")) + prefs.saveView(newView(0, "B")) + prefs.saveView(newView(id, "Renamed")) + assertThat(prefs.views.first().map { it.name }).containsExactly("", "Renamed", "B").inOrder() + } + + @Test + fun `Home stays first and can't be deleted`() = runBlocking { + val a = prefs.saveView(newView(0, "A")) + val b = prefs.saveView(newView(0, "B")) + prefs.reorderViews(listOf(b, a, View.HOME_ID)) + assertThat(prefs.views.first().map { it.id }).containsExactly(View.HOME_ID, b, a).inOrder() + prefs.deleteView(View.HOME_ID) + assertThat(prefs.views.first().first().id).isEqualTo(View.HOME_ID) + prefs.saveView(View.home().copy(name = "Mine")) + assertThat(prefs.views.first().first().name).isEqualTo("Mine") + } + + @Test + fun `deleting the last used or start view falls back to Home`() = runBlocking { + val id = prefs.saveView(newView(0, "A")) + prefs.setActiveView(id) + prefs.setStartDestination(StartDestination.View(id)) + assertThat(prefs.activeViewId.first()).isEqualTo(id) + prefs.deleteView(id) + assertThat(prefs.activeViewId.first()).isEqualTo(View.HOME_ID) + assertThat(prefs.startDestination.first()).isEqualTo(DefaultStartDestination) + } + + @Test + fun `the start destination round-trips, a list only in its own store`() = runBlocking { + assertThat(prefs.startDestination.first()).isEqualTo(StartDestination.View(View.HOME_ID)) + prefs.setStorageMode(StorageMode.OWN) + listOf(StartDestination.LastUsed, StartDestination.View(3), StartDestination.Filter(4), StartDestination.List(5)) + .forEach { destination -> + prefs.setStartDestination(destination) + assertThat(prefs.startDestination.first()).isEqualTo(destination) + } + prefs.setStorageMode(StorageMode.EXTERNAL) + assertThat(prefs.startDestination.first()).isEqualTo(DefaultStartDestination) + } + + @Test + fun `a stored start destination that doesn't read is the default`() { + assertThat(decodeStart(null, "OWN")).isEqualTo(DefaultStartDestination) + assertThat(decodeStart("view:x", "OWN")).isEqualTo(DefaultStartDestination) + assertThat(decodeStart("nope", "OWN")).isEqualTo(DefaultStartDestination) + assertThat(decodeStart(encodeStart(StartDestination.List(5), "OWN"), "OWN")).isEqualTo(StartDestination.List(5)) + assertThat(encodeStart(StartDestination.List(5), "OWN")).isEqualTo("list:OWN:5") + } +}