package com.cottondb.android.keyboard import android.content.Intent import android.os.ParcelFileDescriptor import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.By import androidx.test.uiautomator.BySelector import androidx.test.uiautomator.UiDevice import androidx.test.uiautomator.UiObject2 import androidx.test.uiautomator.Until import com.cottondb.android.ScreenEvidence import java.util.UUID import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.runBlocking import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith /** * One emulator-only integration scenario. It changes the device default IME and restores both that * setting and the full raw keyboard channel in finally; do not run it in parallel with another IME * test or a second emulator. */ @RunWith(AndroidJUnit4::class) class CottonInputMethodServiceTest { 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" @After fun closeScope() { scope.cancel() } @Test fun realImeTypesAndAcknowledgesOneSyntheticPendingTake() = runBlocking { org.junit.Assume.assumeTrue(InstrumentationRegistry.getArguments().getString("cotton.ime") == "true") val priorIme = shell("settings get secure default_input_method").trim() val priorHardwareSetting = shell("settings get secure show_ime_with_hard_keyboard").trim() val wasEnabled = shell("ime list -s").lineSequence().any { it.trim() == imeId } val store = AndroidKeyboardChannelStore.open(context, scope) val originalChannel = store.read() try { shell("settings put secure show_ime_with_hard_keyboard 1") shell("ime enable $imeId") shell("ime set $imeId") launchHarness() awaitObject(By.desc("Keyboard editor")) click(By.text("Show keyboard")) awaitObject(By.desc("Speak")) captureSystemKeyboard("ime-speak") click(By.desc("abc")) click(By.desc("h")) click(By.desc("i")) click(By.desc("Return")) click(By.desc("Delete")) waitForEditor("Acornhi") val takeId = "ime-test-${UUID.randomUUID()}" val pending = pendingSnapshot(takeId) // Prime after the primary-process harness and its foreground work have settled. store.update { current -> JsonObject( current + mapOf( KeyboardChannelKeys.SNAPSHOT to pending, KeyboardChannelKeys.OUTBOX to JsonArray(emptyList()), ), ) } // The letter layer survives this edit sequence. Return to Speak, then insert this // deliberately old fixture explicitly from the tray; auto-insert timing is // covered by the coordinator's fixed-clock tests. device.pressBack() click(By.text("Show keyboard")) click(By.desc("Back")) click(By.desc("Tray 1")) awaitObject(By.text("Recent takes")) captureSystemKeyboard("ime-before-tray-insertion") click(By.text("synthetic pending take")) val expected = "Acornhi synthetic pending take" waitForEditor(expected) awaitObject(By.text("Inserted 3 words")) captureSystemKeyboard("ime-after-tray-insertion") val acknowledged = store.read() val take = ((acknowledged[KeyboardChannelKeys.SNAPSHOT] as JsonObject)["takes"] as JsonArray) .single() as JsonObject assertFalse((take["pending"] as JsonPrimitive).content.toBoolean()) val events = acknowledged[KeyboardChannelKeys.OUTBOX] as JsonArray assertEquals(1, events.size) assertEquals("takeInserted", ((events.single() as JsonObject)["kind"] as JsonPrimitive).content) assertEquals(takeId, ((events.single() as JsonObject)["takeId"] as JsonPrimitive).content) } finally { try { closeHarness() device.wait(Until.gone(By.desc("Speak")), UI_TIMEOUT_MILLIS) } finally { if (priorIme.isNotBlank() && priorIme != "null") shell("ime set $priorIme") if (!wasEnabled) shell("ime disable $imeId") if (priorHardwareSetting == "null") shell("settings delete secure show_ime_with_hard_keyboard") else shell("settings put secure show_ime_with_hard_keyboard $priorHardwareSetting") store.update { originalChannel } } } } private fun launchHarness() { context.startActivity( Intent(context, KeyboardEditorHarnessActivity::class.java) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP), ) } private fun closeHarness() { device.pressBack() if (device.wait(Until.hasObject(By.desc("Keyboard editor")), SHORT_UI_TIMEOUT_MILLIS)) { device.pressBack() } assertTrue( "Harness activity did not close.", device.wait(Until.gone(By.desc("Keyboard editor")), UI_TIMEOUT_MILLIS), ) } private fun pendingSnapshot(id: String): JsonObject = JsonObject( mapOf( "asOf" to JsonPrimitive("2000-01-01T00:00:00Z"), "takes" to JsonArray( listOf( JsonObject( mapOf( "id" to JsonPrimitive(id), "text" to JsonPrimitive("synthetic pending take"), "words" to JsonPrimitive(3), "createdAt" to JsonPrimitive("2000-01-01T00:00:00Z"), "pending" to JsonPrimitive(true), ), ), ), ), ), ) private fun click(selector: BySelector) { device.waitForIdle() val target = awaitObject(selector) println("IME tap $selector at ${target.visibleBounds}") target.click() device.waitForIdle() } private fun awaitObject(selector: BySelector): UiObject2 { val present = device.wait(object : androidx.test.uiautomator.Condition { override fun apply(root: UiDevice): Boolean { // UiAutomator 2.3 can retain the previous Compose IME layer after its window // redraws. Read a fresh tree, as newer UiAutomator root waits do by default. if (android.os.Build.VERSION.SDK_INT >= 34) instrumentation.uiAutomation.clearCache() return root.hasObject(selector) } }, UI_TIMEOUT_MILLIS) if (!present) { captureSystemKeyboard("ime-timeout") device.dumpWindowHierarchy(java.io.File(context.filesDir, "ime-timeout.xml")) } assertTrue("Timed out waiting for $selector", present) val found = device.findObject(selector) assertNotNull(found) return found!! } private fun waitForEditor(expected: String) { assertTrue("Expected editor text: $expected", awaitObject(By.desc("Keyboard editor")).wait(Until.textEquals(expected), UI_TIMEOUT_MILLIS)) } private fun editorText(): String? = device.findObject(By.desc("Keyboard editor"))?.text private fun captureSystemKeyboard(name: String) { ScreenEvidence.capture(name) { instrumentation.uiAutomation.takeScreenshot() ?: error("UiAutomation did not provide a screenshot.") } } private fun shell(command: String): String = ParcelFileDescriptor.AutoCloseInputStream( instrumentation.uiAutomation.executeShellCommand(command), ).bufferedReader().use { it.readText() } private companion object { const val SHORT_UI_TIMEOUT_MILLIS = 500L const val UI_TIMEOUT_MILLIS = 8_000L } }