package com.cottondb.android.keyboard import android.content.Intent import android.inputmethodservice.InputMethodService import android.view.inputmethod.EditorInfo import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.WindowInsetsSides import androidx.compose.foundation.layout.only import androidx.compose.foundation.layout.systemBars import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.ui.Modifier import com.cottondb.android.generated.CottonPalette import androidx.compose.ui.platform.ViewCompositionStrategy import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.platform.ComposeView import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry import androidx.lifecycle.ViewModelStore import androidx.lifecycle.ViewModelStoreOwner import androidx.lifecycle.setViewTreeLifecycleOwner import androidx.lifecycle.setViewTreeViewModelStoreOwner import androidx.savedstate.SavedStateRegistry import androidx.savedstate.SavedStateRegistryController import androidx.savedstate.SavedStateRegistryOwner import androidx.savedstate.setViewTreeSavedStateRegistryOwner import com.cottondb.android.MainActivity import com.cottondb.android.design.CottonTheme import com.cottondb.android.ui.keyboard.KeyboardSurface import java.time.Clock import java.util.UUID import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import 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(null) private var renderedProblem by mutableStateOf(null) private var renderedInsertedWords by mutableStateOf(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() } }