package com.cottondb.android.keyboard import android.content.Context import androidx.datastore.core.CorruptionException import androidx.datastore.core.DataStore import androidx.datastore.core.MultiProcessDataStoreFactory import androidx.datastore.core.Serializer import java.io.File import java.io.InputStream import java.io.OutputStream import java.nio.ByteBuffer import java.nio.charset.CharacterCodingException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.flow.first import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject /** * A KeyboardChannelStore backed by one multiprocess DataStore per canonical file in this process. * The app's normal no-backup directory is credential encrypted; callers must not pass a * device-protected context because the channel can contain pending capture text. */ class AndroidKeyboardChannelStore private constructor( private val dataStore: DataStore, ) : KeyboardChannelStore { override suspend fun read(): JsonObject = dataStore.data.first() override suspend fun update(transform: (JsonObject) -> JsonObject): JsonObject = dataStore.updateData { current -> immutableJsonObject(transform(current)) } companion object { const val FILE_NAME = "keyboard-channel-v1.json" private val lock = Any() private val activeStores = mutableMapOf() /** * Opens the canonical credential-encrypted, no-backup channel. Repeated calls while the * supplied scope is active receive the same DataStore, as required by DataStore. */ fun open(context: Context, scope: CoroutineScope): KeyboardChannelStore { require(!context.isDeviceProtectedStorage) { "Keyboard channel must use credential-encrypted storage." } val applicationContext = context.applicationContext require(!applicationContext.isDeviceProtectedStorage) { "Keyboard channel application context must use credential-encrypted storage." } requireActiveScope(scope) val directory = applicationContext.noBackupFilesDir.canonicalFile val file = File(directory, FILE_NAME).canonicalFile check(file.parentFile == directory) { "Keyboard channel must remain directly inside the no-backup directory." } return synchronized(lock) { activeStores[file.path]?.takeIf { it.scope.coroutineContext[Job]?.isActive != false } ?.store ?: createCanonicalStore(file, scope).also { created -> activeStores[file.path] = ActiveStore(scope, created) scope.coroutineContext[Job]?.invokeOnCompletion { synchronized(lock) { if (activeStores[file.path]?.store === created) { activeStores.remove(file.path) } } } } } } /** * Injection seam for device tests. A test must use a unique file and cancel its scope * before opening that file again, matching DataStore's one-active-instance rule. */ internal fun openForTest( file: File, scope: CoroutineScope, factory: KeyboardChannelDataStoreFactory = MultiProcessKeyboardChannelDataStoreFactory, ): KeyboardChannelStore { requireActiveScope(scope) return AndroidKeyboardChannelStore(factory.create(file.canonicalFile, scope)) } private fun createCanonicalStore(file: File, scope: CoroutineScope): KeyboardChannelStore = AndroidKeyboardChannelStore(MultiProcessKeyboardChannelDataStoreFactory.create(file, scope)) private fun requireActiveScope(scope: CoroutineScope) { val job = requireNotNull(scope.coroutineContext[Job]) { "Keyboard channel scope must own a Job." } require(job.isActive) { "Keyboard channel scope must be active." } } } private data class ActiveStore( val scope: CoroutineScope, val store: KeyboardChannelStore, ) } internal fun interface KeyboardChannelDataStoreFactory { fun create(file: File, scope: CoroutineScope): DataStore } internal object MultiProcessKeyboardChannelDataStoreFactory : KeyboardChannelDataStoreFactory { override fun create(file: File, scope: CoroutineScope): DataStore = MultiProcessDataStoreFactory.create( serializer = RawKeyboardChannelSerializer, scope = scope, produceFile = { file }, ) } /** * JSON storage with no replacement corruption handler. An unreadable existing file is therefore * reported to the caller; it is never deleted or replaced with an empty outbox. */ internal object RawKeyboardChannelSerializer : Serializer { override val defaultValue: JsonObject = JsonObject(emptyMap()) override suspend fun readFrom(input: InputStream): JsonObject { val bytes = input.readBytes() if (bytes.isEmpty()) { throw CorruptionException("Keyboard channel is empty.") } val text = try { Charsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString() } catch (failure: CharacterCodingException) { throw CorruptionException("Keyboard channel is not UTF-8.", failure) } val element = try { Json.parseToJsonElement(text) } catch (failure: Exception) { throw CorruptionException("Keyboard channel is malformed JSON.", failure) } return (element as? JsonObject)?.let(::immutableJsonObject) ?: throw CorruptionException("Keyboard channel root must be an object.") } override suspend fun writeTo(t: JsonObject, output: OutputStream) { output.write(immutableJsonObject(t).toString().toByteArray(Charsets.UTF_8)) } } private fun immutableJsonObject(value: JsonObject): JsonObject = JsonObject(value.mapValues { (_, element) -> immutableJsonElement(element) }) private fun immutableJsonElement(value: JsonElement): JsonElement = when (value) { is JsonObject -> immutableJsonObject(value) is JsonArray -> JsonArray(value.map(::immutableJsonElement)) else -> value }