package com.cottondb.android.keyboard import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.os.ParcelFileDescriptor import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.By import androidx.test.uiautomator.UiDevice import androidx.test.uiautomator.Until import com.cottondb.android.CottonApplication import com.cottondb.android.MainActivity import com.cottondb.android.RuntimeState import com.cottondb.android.boot.BootState import java.util.concurrent.TimeUnit import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.delay import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.boolean import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive /** * Serial emulator fixture for real-IME scenarios. * * It owns every device-wide setting it changes, restores the complete raw channel rather than * reconstructing it, and uses the production boot gate to create a local synthetic workspace. */ class ImeTestFixture { private val instrumentation = InstrumentationRegistry.getInstrumentation() private val context = instrumentation.targetContext private val device = UiDevice.getInstance(instrumentation) private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) private val imeId = "${context.packageName}/com.cottondb.android.keyboard.CottonInputMethodService" private val priorIme = shell("settings get secure default_input_method").trim() private val priorHardware = shell("settings get secure show_ime_with_hard_keyboard").trim() private val wasEnabled = shell("ime list -s").lineSequence().any { it.trim() == imeId } private val hadMicrophone = context.checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED private val store = AndroidKeyboardChannelStore.open(context, scope) private val original: JsonObject = runBlocking { store.read() } fun enableCottonImeAndMicrophone() { shell("settings put secure show_ime_with_hard_keyboard 1") shell("ime enable $imeId") shell("ime set $imeId") shell("pm grant ${context.packageName} ${Manifest.permission.RECORD_AUDIO}") } /** Starts the actual application and, on a fresh test install, starts its local workspace. */ fun bootReadySyntheticWorkspace() { context.startActivity( Intent(context, MainActivity::class.java) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP), ) val runtime = context.applicationContext as CottonApplication val ready = runBlocking { withTimeout(UI_TIMEOUT_MILLIS) { runtime.runtime.state.first { it is RuntimeState.Ready || it is RuntimeState.Error } } } check(ready is RuntimeState.Ready) { "Cotton did not open for the IME handback test: ${(ready as RuntimeState.Error).message}" } val boot = runBlocking { withTimeout(UI_TIMEOUT_MILLIS) { ready.boot.state.first { it is BootState.Start || it is BootState.Ready || it is BootState.Error } } } if (boot is BootState.Start) { check(device.wait(Until.hasObject(By.desc("Start a new database")), UI_TIMEOUT_MILLIS)) { "The app reported a fresh workspace but did not show the production start control." } device.findObject(By.desc("Start a new database")).click() } val settled = runBlocking { withTimeout(UI_TIMEOUT_MILLIS) { ready.boot.state.first { it is BootState.Ready || it is BootState.Error } } } check(settled is BootState.Ready) { "The synthetic local workspace did not become ready: ${(settled as BootState.Error).message}" } } suspend fun readChannel(): JsonObject = store.read() suspend fun updateChannel(transform: (JsonObject) -> JsonObject): JsonObject = store.update(transform) fun launchExternalEditor() { context.startActivity( Intent(context, ExternalEditorHarnessActivity::class.java) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP), ) check(device.wait(Until.hasObject(By.desc("External keyboard editor")), UI_TIMEOUT_MILLIS)) { "The external editor did not open." } device.findObject(By.text("Show keyboard")).click() } /** The bridge can consume the receipt immediately, so no assertion inspects the outbox. */ fun awaitTakeAcknowledgement(text: String) = runBlocking { withTimeout(UI_TIMEOUT_MILLIS) { while (true) { val snapshot = store.read()[KeyboardChannelKeys.SNAPSHOT] as? JsonObject val received = snapshot?.get("takes")?.jsonArray ?.map { it.jsonObject } ?.firstOrNull { it["text"]?.jsonPrimitive?.content == text } if (received != null && received["pending"]?.jsonPrimitive?.boolean == false) return@withTimeout delay(POLL_MILLIS) } } } fun closeExternalEditorIfOpen() { if (!device.hasObject(By.desc("External keyboard editor"))) return device.pressBack() if (device.wait(Until.hasObject(By.desc("External keyboard editor")), SHORT_UI_TIMEOUT_MILLIS)) { device.pressBack() } } fun restore() = runBlocking { try { if (priorIme.isNotBlank() && priorIme != "null") shell("ime set $priorIme") if (!wasEnabled) shell("ime disable $imeId") if (priorHardware == "null") shell("settings delete secure show_ime_with_hard_keyboard") else shell("settings put secure show_ime_with_hard_keyboard $priorHardware") store.update { original } if (!hadMicrophone) shell("pm revoke ${context.packageName} ${Manifest.permission.RECORD_AUDIO}") } finally { scope.cancel() } } private fun shell(command: String): String = ParcelFileDescriptor.AutoCloseInputStream(instrumentation.uiAutomation.executeShellCommand(command)) .bufferedReader() .use { it.readText() } private companion object { const val POLL_MILLIS = 100L val SHORT_UI_TIMEOUT_MILLIS = TimeUnit.MILLISECONDS.toMillis(500L) val UI_TIMEOUT_MILLIS = TimeUnit.SECONDS.toMillis(12L) } }