Cotton code
311 lines · 11.6 KB · KotlinRaw
package com.cottondb.android.keyboardimport android.content.Intentimport android.inputmethodservice.InputMethodServiceimport android.view.inputmethod.EditorInfoimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.WindowInsetsimport androidx.compose.foundation.layout.WindowInsetsSidesimport androidx.compose.foundation.layout.onlyimport androidx.compose.foundation.layout.systemBarsimport androidx.compose.foundation.layout.windowInsetsPaddingimport androidx.compose.ui.Modifierimport com.cottondb.android.generated.CottonPaletteimport androidx.compose.ui.platform.ViewCompositionStrategyimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.setValueimport androidx.compose.ui.platform.ComposeViewimport androidx.lifecycle.Lifecycleimport androidx.lifecycle.LifecycleOwnerimport androidx.lifecycle.LifecycleRegistryimport androidx.lifecycle.ViewModelStoreimport androidx.lifecycle.ViewModelStoreOwnerimport androidx.lifecycle.setViewTreeLifecycleOwnerimport androidx.lifecycle.setViewTreeViewModelStoreOwnerimport androidx.savedstate.SavedStateRegistryimport androidx.savedstate.SavedStateRegistryControllerimport androidx.savedstate.SavedStateRegistryOwnerimport androidx.savedstate.setViewTreeSavedStateRegistryOwnerimport com.cottondb.android.MainActivityimport com.cottondb.android.design.CottonThemeimport com.cottondb.android.ui.keyboard.KeyboardSurfaceimport java.time.Clockimport java.util.UUIDimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.cancelimport kotlinx.coroutines.launchimport kotlinx.serialization.json.JsonObject/** * The private-process IME host. * * It only owns an input connection, a compact credential-protected handback channel, and its own Compose * view. It deliberately has no Cotton core, runtime, or speech-recognition dependency; Speak * opens the primary activity, which owns capture after its normal unlock and permission checks. */class CottonInputMethodService : InputMethodService() {    private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)    private val channelScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)    private lateinit var coordinator: KeyboardInputSessionCoordinator    private var inputEpoch = 0L    private var inputActive = false    private var lastEditorInfo: EditorInfo? = null    private var startupFailure: Throwable? = null    private var renderedSnapshot by mutableStateOf<KeyboardSnapshot?>(null)    private var renderedProblem by mutableStateOf<String?>(null)    private var renderedInsertedWords by mutableStateOf<Long?>(null)    private var composeOwners: ImeViewTreeOwners? = null    override fun onCreate() {        super.onCreate()        val channel = try {            AndroidKeyboardChannelStore.open(this, channelScope)        } catch (failure: Throwable) {            startupFailure = failure            UnavailableKeyboardChannelStore(failure)        }        coordinator = KeyboardInputSessionCoordinator(            channel = channel,            clock = Clock.systemUTC(),            nextEventId = { UUID.randomUUID().toString() },        )    }    override fun onEvaluateFullscreenMode(): Boolean = false    override fun onCreateInputView(): ComposeView {        composeOwners?.destroy()        val owners = ImeViewTreeOwners().also {            it.create()            it.resume()        }        composeOwners = owners        return ComposeView(this).also { view ->            window?.window?.decorView?.setViewTreeLifecycleOwner(owners)            window?.window?.decorView?.setViewTreeViewModelStoreOwner(owners)            window?.window?.decorView?.setViewTreeSavedStateRegistryOwner(owners)            view.setViewTreeLifecycleOwner(owners)            view.setViewTreeViewModelStoreOwner(owners)            view.setViewTreeSavedStateRegistryOwner(owners)            view.setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)            view.setContent {                CottonTheme {                    // Include the IME caption bar as well as gesture navigation; both overlay this window.                    Box(Modifier.background(CottonPalette.graphiteGround).windowInsetsPadding(WindowInsets.systemBars.only(WindowInsetsSides.Bottom))) {                        KeyboardSurface(                            snapshot = renderedSnapshot,                            insertedWords = renderedInsertedWords,                            problem = renderedProblem,                            onType = ::type,                            onDelete = ::deleteBackward,                            onSpeak = ::openTakeCapture,                            onUseTake = { take ->                                val epoch = inputEpoch                                serviceScope.launch {                                    coordinator.useTake(take.takeId)                                    if (epoch == inputEpoch) publishCoordinatorState()                                }                            },                            onUndo = {                                coordinator.undoLastInsertion()                                publishCoordinatorState()                            },                            onSwitchKeyboard = { switchToNextInputMethod(false) },                            nowMillis = { android.os.SystemClock.elapsedRealtime() },                        )                    }                }            }        }    }    override fun onStartInput(attribute: EditorInfo?, restarting: Boolean) {        super.onStartInput(attribute, restarting)        beginInputSession(attribute)        renderedSnapshot = null        renderedInsertedWords = null        renderedProblem = startupFailure?.let { "Keyboard storage is unavailable." }    }    override fun onStartInputView(info: EditorInfo?, restarting: Boolean) {        super.onStartInputView(info, restarting)        composeOwners?.resume()        if (!inputActive) beginInputSession(info ?: lastEditorInfo)        reloadAndAutoInsert(inputEpoch)    }    override fun onUpdateSelection(        oldSelStart: Int,        oldSelEnd: Int,        newSelStart: Int,        newSelEnd: Int,        candidatesStart: Int,        candidatesEnd: Int,    ) {        super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd, candidatesStart, candidatesEnd)        coordinator.observeSelection(newSelStart, newSelEnd)    }    override fun onFinishInputView(finishingInput: Boolean) {        composeOwners?.stop()        endInputSession()        flushSealedInput()        super.onFinishInputView(finishingInput)    }    override fun onFinishInput() {        endInputSession()        flushSealedInput()        super.onFinishInput()    }    override fun onDestroy() {        composeOwners?.destroy()        composeOwners = null        serviceScope.cancel()        channelScope.cancel()        super.onDestroy()    }    private fun type(text: String) {        coordinator.type(text)        publishCoordinatorState()    }    private fun deleteBackward() {        coordinator.deleteBackward()        publishCoordinatorState()    }    private fun reloadAndAutoInsert(epoch: Long) {        serviceScope.launch {            coordinator.reload()            if (epoch != inputEpoch) return@launch            coordinator.autoInsertNewest()            if (epoch != inputEpoch) return@launch            publishCoordinatorState()        }    }    /**     * The lifecycle seals synchronously before this runs. This job only flushes already-sealed     * events, so a delayed old job cannot capture typing from a newer editor.     */    private fun flushSealedInput() {        val epoch = inputEpoch        serviceScope.launch {            coordinator.flushPendingTypedEvents()            if (epoch == inputEpoch) publishCoordinatorState()        }    }    private fun publishCoordinatorState() {        renderedSnapshot = (coordinator.lastSnapshotRead as? KeyboardSnapshotRead.Available)?.snapshot        renderedInsertedWords = coordinator.insertedWords        renderedProblem = startupFailure?.let { "Keyboard storage is unavailable." }            ?: keyboardVisibleProblem(coordinator.lastSnapshotRead, coordinator.lastError)    }    private fun openTakeCapture() {        try {            startActivity(                Intent(this, MainActivity::class.java)                    .setAction(ACTION_KEYBOARD_TAKE)                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),            )        } catch (_: RuntimeException) {            renderedProblem = "Cotton could not open Take."        }    }    private fun beginInputSession(editorInfo: EditorInfo?) {        inputEpoch += 1        lastEditorInfo = editorInfo        coordinator.beginInputSession(            inputConnection = currentInputConnection,            editorInfo = editorInfo,            selectionStart = editorInfo?.initialSelStart ?: -1,            selectionEnd = editorInfo?.initialSelEnd ?: -1,        )        inputActive = true    }    private fun endInputSession() {        inputEpoch += 1        if (!inputActive) return        // End seals this editor synchronously; the queued job only persists sealed events.        coordinator.endInputSession()        inputActive = false    }    private companion object {        const val ACTION_KEYBOARD_TAKE = "com.cottondb.android.KEYBOARD_TAKE"    }}private class UnavailableKeyboardChannelStore(    private val failure: Throwable,) : KeyboardChannelStore {    override suspend fun read(): JsonObject = throw failure    override suspend fun update(transform: (JsonObject) -> JsonObject): JsonObject = throw failure}internal fun keyboardVisibleProblem(    snapshotRead: KeyboardSnapshotRead,    error: KeyboardInputSessionError?,): String? = when (error) {    is KeyboardInputSessionError.Storage -> "Keyboard storage is unavailable."    is KeyboardInputSessionError.InputConnectionGone -> "The app stopped accepting input."    KeyboardInputSessionError.ChannelChanged -> "Cotton changed databases. Reopen the keyboard."    null -> when (snapshotRead) {        is KeyboardSnapshotRead.Malformed -> "Recent takes could not be read."        KeyboardSnapshotRead.Missing, is KeyboardSnapshotRead.Available -> null    }}/** * InputMethodService is not a ComponentActivity. Compose therefore needs explicit owners for each * IME view, including saved state. They are owned only by the IME view, never by app runtime. */private class ImeViewTreeOwners :    LifecycleOwner,    ViewModelStoreOwner,    SavedStateRegistryOwner {    private val lifecycleRegistry = LifecycleRegistry(this)    private val savedStateController = SavedStateRegistryController.create(this)    override val lifecycle: Lifecycle        get() = lifecycleRegistry    override val viewModelStore = ViewModelStore()    override val savedStateRegistry: SavedStateRegistry        get() = savedStateController.savedStateRegistry    fun create() {        savedStateController.performAttach()        savedStateController.performRestore(null)        lifecycleRegistry.currentState = Lifecycle.State.CREATED    }    fun resume() {        lifecycleRegistry.currentState = Lifecycle.State.RESUMED    }    fun stop() {        lifecycleRegistry.currentState = Lifecycle.State.CREATED    }    fun destroy() {        lifecycleRegistry.currentState = Lifecycle.State.DESTROYED        viewModelStore.clear()    }}