Snapshot of the Umamo working tree as it is
Uploaded as-is from /home/litruv/dev/vtsmaker/umamo on 2026-11-03. 1347 files. Includes the uncommitted work in progress in :edit, :runtime, and :ui, and the untracked files under module/edit/src/jvmAndroidMain/. History is not carried over. The source repo is https://github.com/umamoorg/umamo.
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
// :settings — JSON settings engine over :storage: bundled defaults ← user overrides (← vendor later),
|
||||
// dotted-key get/set, persistence, and a change-event Flow. → :storage, kotlinx-serialization, coroutines.
|
||||
// :settings — :storage 上の JSON 設定エンジン。デフォルト←ユーザー設定の重ね合わせ、ドットキー get/set、変更通知。
|
||||
|
||||
plugins {
|
||||
alias(libs.plugins.kotlinMultiplatform)
|
||||
alias(libs.plugins.androidKmpLibrary)
|
||||
alias(libs.plugins.kotlinSerialization)
|
||||
}
|
||||
|
||||
kotlin {
|
||||
jvmToolchain(21)
|
||||
|
||||
jvm()
|
||||
|
||||
android {
|
||||
namespace = "org.umamo.settings"
|
||||
compileSdk = libs.versions.android.compileSdk.get().toInt()
|
||||
minSdk = libs.versions.android.minSdk.get().toInt()
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
commonMain {
|
||||
dependencies {
|
||||
// `api`: AppStorage + JsonElement appear in the Settings surface, so consumers see them.
|
||||
api(project(":storage"))
|
||||
api(libs.kotlinxSerializationJson)
|
||||
implementation(libs.kotlinxCoroutinesCore)
|
||||
}
|
||||
}
|
||||
commonTest {
|
||||
dependencies {
|
||||
implementation(kotlin("test"))
|
||||
// In-memory FileSystem so settings load/merge/persist is tested with no real disk.
|
||||
implementation(libs.okio.fakefilesystem)
|
||||
// runTest for the change-event Flow assertion.
|
||||
implementation(libs.kotlinxCoroutinesTest)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package org.umamo.settings
|
||||
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.SharedFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.booleanOrNull
|
||||
import kotlinx.serialization.json.doubleOrNull
|
||||
import kotlinx.serialization.json.intOrNull
|
||||
import org.umamo.storage.AppStorage
|
||||
|
||||
/**
|
||||
* The app's settings: a merged JSON tree of bundled defaults ← user overrides (← vendor extension
|
||||
* defaults, later), addressed by dotted keys (`getString("interface.theme")`). No caller ever passes a
|
||||
* default - `defaultSettings.json` is the single source of baseline values, so reads are
|
||||
* default-by-construction. Writes go to the user layer only, re-merge, persist via [AppStorage], and emit
|
||||
* the changed key on [changes] (the reactive spine the UI/keymap/History collect).
|
||||
*
|
||||
* Build it with [Settings.load]. The tree is held as a dynamic [JsonObject] (not typed `@Serializable`
|
||||
* classes) because settings are open-ended and merged; typed per-domain views can layer on top later.
|
||||
*
|
||||
* @property Boolean foundUserFile Whether a user settings file was on disk when these settings loaded - false
|
||||
* on a first launch. A fact about the load, so it stays false for this instance's whole life, even after
|
||||
* the first write creates the file. A file that exists but does not parse still counts as found.
|
||||
*/
|
||||
class Settings private constructor(
|
||||
private val storage: AppStorage,
|
||||
private val userFile: okio.Path,
|
||||
private val defaults: JsonObject,
|
||||
private var user: JsonObject,
|
||||
val foundUserFile: Boolean,
|
||||
) {
|
||||
private var merged: JsonObject = deepMerge(defaults, user)
|
||||
|
||||
private val mutableChanges = MutableSharedFlow<String>(extraBufferCapacity = 64)
|
||||
|
||||
/** Emits a setting's dotted key whenever it is written, so consumers re-read just what changed. */
|
||||
val changes: SharedFlow<String> = mutableChanges.asSharedFlow()
|
||||
|
||||
/**
|
||||
* Resolves a dotted [key] to its merged value.
|
||||
*
|
||||
* @param String key Dotted key, e.g. `"input.keybinding.preset"`.
|
||||
* @return JsonElement? The value (user override, else default), or null if absent.
|
||||
*/
|
||||
fun get(key: String): JsonElement? {
|
||||
var current: JsonElement = merged
|
||||
for (segment in key.split('.')) {
|
||||
current = (current as? JsonObject)?.get(segment) ?: return null
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
/** @return String? The [key]'s string value, or null if absent / not a string. */
|
||||
fun getString(key: String): String? = (get(key) as? JsonPrimitive)?.takeIf { it.isString }?.content
|
||||
|
||||
/** @return Boolean? The [key]'s boolean value, or null if absent / not a boolean. */
|
||||
fun getBoolean(key: String): Boolean? = (get(key) as? JsonPrimitive)?.booleanOrNull
|
||||
|
||||
/** @return Int? The [key]'s integer value, or null if absent / not an integer. */
|
||||
fun getInt(key: String): Int? = (get(key) as? JsonPrimitive)?.intOrNull
|
||||
|
||||
/** @return Double? The [key]'s number value, or null if absent / not a number. */
|
||||
fun getDouble(key: String): Double? = (get(key) as? JsonPrimitive)?.doubleOrNull
|
||||
|
||||
/** Sets a string value at [key]. */
|
||||
fun setString(key: String, value: String) = set(key, JsonPrimitive(value))
|
||||
|
||||
/** Sets a boolean value at [key]. */
|
||||
fun setBoolean(key: String, value: Boolean) = set(key, JsonPrimitive(value))
|
||||
|
||||
/** Sets an integer value at [key]. */
|
||||
fun setInt(key: String, value: Int) = set(key, JsonPrimitive(value))
|
||||
|
||||
/** Sets a number value at [key]. */
|
||||
fun setDouble(key: String, value: Double) = set(key, JsonPrimitive(value))
|
||||
|
||||
/**
|
||||
* Writes [value] into the user layer at dotted [key] (creating intermediate objects), re-merges over
|
||||
* the defaults, persists the user layer, and emits [key] on [changes].
|
||||
*
|
||||
* @param Path key Dotted key.
|
||||
* @param JsonElement value The value to store.
|
||||
*/
|
||||
fun set(key: String, value: JsonElement) {
|
||||
user = putAtPath(user, key.split('.'), value)
|
||||
merged = deepMerge(defaults, user)
|
||||
storage.writeText(userFile, JSON.encodeToString(JsonObject.serializer(), user))
|
||||
mutableChanges.tryEmit(key)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val JSON =
|
||||
Json {
|
||||
ignoreUnknownKeys = true
|
||||
prettyPrint = true
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads settings: parses bundled [defaultSettingsJson] as the baseline and overlays the user file
|
||||
* ([fileName] under [storage]'s config directory) if present and valid. A missing or corrupt user
|
||||
* file falls back to defaults-only (never throws).
|
||||
*
|
||||
* @param AppStorage storage Where the user file lives + IO.
|
||||
* @param String defaultSettingsJson The bundled `defaultSettings.json` contents.
|
||||
* @param String fileName The user settings file name under the config directory.
|
||||
* @return Settings The loaded settings.
|
||||
*/
|
||||
fun load(storage: AppStorage, defaultSettingsJson: String, fileName: String = "settings.json"): Settings {
|
||||
val defaults = parseObjectOrEmpty(defaultSettingsJson)
|
||||
val userFile = storage.configDirectory / fileName
|
||||
val userText = storage.readText(userFile)
|
||||
val user = userText?.let { parseObjectOrEmpty(it) } ?: JsonObject(emptyMap())
|
||||
return Settings(storage, userFile, defaults, user, foundUserFile = userText != null)
|
||||
}
|
||||
|
||||
/** Parses [text] to a [JsonObject], or an empty object when it is absent/blank/not an object/invalid. */
|
||||
private fun parseObjectOrEmpty(text: String): JsonObject =
|
||||
runCatching { JSON.parseToJsonElement(text) as? JsonObject }.getOrNull() ?: JsonObject(emptyMap())
|
||||
|
||||
/** Deep-merges [overlay] onto [base]: nested objects merge recursively; any other value is replaced. */
|
||||
private fun deepMerge(base: JsonObject, overlay: JsonObject): JsonObject {
|
||||
val result = base.toMutableMap()
|
||||
for ((key, overlayValue) in overlay) {
|
||||
val baseValue = result[key]
|
||||
result[key] =
|
||||
if (baseValue is JsonObject && overlayValue is JsonObject) {
|
||||
deepMerge(baseValue, overlayValue)
|
||||
} else {
|
||||
overlayValue
|
||||
}
|
||||
}
|
||||
return JsonObject(result)
|
||||
}
|
||||
|
||||
/** Returns a copy of [root] with [value] set at the dotted [path], creating intermediate objects. */
|
||||
private fun putAtPath(root: JsonObject, path: List<String>, value: JsonElement): JsonObject {
|
||||
if (path.isEmpty()) {
|
||||
return root
|
||||
}
|
||||
val head = path.first()
|
||||
val child =
|
||||
if (path.size == 1) {
|
||||
value
|
||||
} else {
|
||||
putAtPath(root[head] as? JsonObject ?: JsonObject(emptyMap()), path.drop(1), value)
|
||||
}
|
||||
return JsonObject(root.toMutableMap().apply { put(head, child) })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package org.umamo.settings
|
||||
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.test.runCurrent
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import okio.Path
|
||||
import okio.Path.Companion.toPath
|
||||
import okio.fakefilesystem.FakeFileSystem
|
||||
import org.umamo.storage.OkioAppStorage
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFalse
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
/** Settings load/merge/get/set/persist + change-event coverage, all on okio's in-memory FakeFileSystem. */
|
||||
class SettingsTest {
|
||||
private val configDir: Path = "/config".toPath()
|
||||
|
||||
/** A FakeFileSystem seeded with an optional user settings file, plus an [OkioAppStorage] over it. */
|
||||
private fun storageWith(userJson: String? = null): Pair<FakeFileSystem, OkioAppStorage> {
|
||||
val fileSystem = FakeFileSystem()
|
||||
fileSystem.createDirectories(configDir)
|
||||
if (userJson != null) {
|
||||
fileSystem.write(configDir / "settings.json") { writeUtf8(userJson) }
|
||||
}
|
||||
return fileSystem to OkioAppStorage(fileSystem, configDir, "/data".toPath())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun readsDefaultsWhenNoUserFile() {
|
||||
val (_, storage) = storageWith()
|
||||
val settings = Settings.load(storage, """{"interface":{"theme":"dark"},"localization":{"locale":"en"}}""")
|
||||
assertEquals("dark", settings.getString("interface.theme"))
|
||||
assertEquals("en", settings.getString("localization.locale"))
|
||||
assertNull(settings.getString("does.not.exist"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun userOverridesDefaultsButKeepsUnsetSiblings() {
|
||||
val (_, storage) = storageWith(userJson = """{"interface":{"theme":"light"}}""")
|
||||
val settings = Settings.load(storage, """{"interface":{"theme":"dark","fontSize":12}}""")
|
||||
assertEquals("light", settings.getString("interface.theme")) // overridden
|
||||
assertEquals(12, settings.getInt("interface.fontSize")) // default kept (deep merge, not replace)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun typedGettersParsePrimitives() {
|
||||
val (_, storage) = storageWith()
|
||||
val settings = Settings.load(storage, """{"a":{"flag":true,"count":7,"ratio":0.5,"name":"x"}}""")
|
||||
assertEquals(true, settings.getBoolean("a.flag"))
|
||||
assertEquals(7, settings.getInt("a.count"))
|
||||
assertEquals(0.5, settings.getDouble("a.ratio"))
|
||||
assertEquals("x", settings.getString("a.name"))
|
||||
assertNull(settings.getInt("a.name")) // wrong type → null, not a throw
|
||||
}
|
||||
|
||||
@Test
|
||||
fun setWritesUserLayerAndSurvivesReload() {
|
||||
val (fileSystem, storage) = storageWith()
|
||||
val settings = Settings.load(storage, """{"interface":{"theme":"dark","fontSize":12}}""")
|
||||
settings.setString("interface.theme", "light")
|
||||
settings.setInt("interface.fontSize", 16)
|
||||
|
||||
// A fresh load over the same filesystem sees the persisted user overrides on top of the defaults.
|
||||
val reloaded = Settings.load(OkioAppStorage(fileSystem, configDir, "/data".toPath()), """{"interface":{"theme":"dark","fontSize":12}}""")
|
||||
assertEquals("light", reloaded.getString("interface.theme"))
|
||||
assertEquals(16, reloaded.getInt("interface.fontSize"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun corruptUserFileFallsBackToDefaults() {
|
||||
val (_, storage) = storageWith(userJson = "{ this is not json")
|
||||
val settings = Settings.load(storage, """{"interface":{"theme":"dark"}}""")
|
||||
assertEquals("dark", settings.getString("interface.theme")) // no throw; defaults stand
|
||||
}
|
||||
|
||||
@Test
|
||||
fun foundUserFileIsFalseWithNoFile() {
|
||||
val (_, storage) = storageWith()
|
||||
assertFalse(Settings.load(storage, "{}").foundUserFile)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun foundUserFileIsTrueWithAValidFile() {
|
||||
val (_, storage) = storageWith(userJson = """{"interface":{"theme":"light"}}""")
|
||||
assertTrue(Settings.load(storage, "{}").foundUserFile)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun foundUserFileIsTrueWithACorruptFile() {
|
||||
// Present but unreadable is still found: the rigger's settings exist, they just did not parse.
|
||||
val (_, storage) = storageWith(userJson = "{ this is not json")
|
||||
assertTrue(Settings.load(storage, "{}").foundUserFile)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun foundUserFileStaysFalseAfterTheFirstWrite() {
|
||||
val (fileSystem, storage) = storageWith()
|
||||
val settings = Settings.load(storage, """{"a":{"b":1}}""")
|
||||
settings.setInt("a.b", 2)
|
||||
// The write created the file, but the flag describes the load, not the disk now.
|
||||
assertTrue(fileSystem.exists(configDir / "settings.json"))
|
||||
assertFalse(settings.foundUserFile)
|
||||
// The next load finds it.
|
||||
assertTrue(Settings.load(OkioAppStorage(fileSystem, configDir, "/data".toPath()), "{}").foundUserFile)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun setEmitsChangedKey() =
|
||||
runTest {
|
||||
val (_, storage) = storageWith()
|
||||
val settings = Settings.load(storage, """{"a":{"b":1}}""")
|
||||
val received = mutableListOf<String>()
|
||||
val collector = launch { settings.changes.collect { received.add(it) } }
|
||||
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||
runCurrent() // let the collector subscribe before we emit
|
||||
settings.setInt("a.b", 2)
|
||||
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||
runCurrent() // deliver the emission
|
||||
collector.cancel()
|
||||
assertEquals(listOf("a.b"), received)
|
||||
assertTrue(settings.getInt("a.b") == 2)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sequentialSetsEmitTheirKeysInOrder() =
|
||||
runTest {
|
||||
val (_, storage) = storageWith()
|
||||
val settings = Settings.load(storage, """{"a":{"b":1,"c":"x"},"d":{"e":true}}""")
|
||||
val received = mutableListOf<String>()
|
||||
val collector = launch { settings.changes.collect { received.add(it) } }
|
||||
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||
runCurrent()
|
||||
settings.setInt("a.b", 2)
|
||||
settings.setString("a.c", "y")
|
||||
settings.setBoolean("d.e", false)
|
||||
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||
runCurrent()
|
||||
collector.cancel()
|
||||
assertEquals(listOf("a.b", "a.c", "d.e"), received)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun lateSubscriberReceivesOnlySubsequentEvents() =
|
||||
runTest {
|
||||
val (_, storage) = storageWith()
|
||||
val settings = Settings.load(storage, """{"a":{"b":1,"c":"x"}}""")
|
||||
val earlyEvents = mutableListOf<String>()
|
||||
val earlyCollector = launch { settings.changes.collect { earlyEvents.add(it) } }
|
||||
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||
runCurrent()
|
||||
settings.setInt("a.b", 2)
|
||||
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||
runCurrent()
|
||||
|
||||
// The changes flow has no replay: a subscriber arriving after an event never sees it.
|
||||
val lateEvents = mutableListOf<String>()
|
||||
val lateCollector = launch { settings.changes.collect { lateEvents.add(it) } }
|
||||
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||
runCurrent()
|
||||
settings.setString("a.c", "y")
|
||||
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||
runCurrent()
|
||||
earlyCollector.cancel()
|
||||
lateCollector.cancel()
|
||||
assertEquals(listOf("a.b", "a.c"), earlyEvents)
|
||||
assertEquals(listOf("a.c"), lateEvents)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user