Modern Apps git

← Modern-Apps.git

keyboard: add tests for IME service, UI pages and clipboard

Commit
1ae3cbec2ac5d823bd6239d810a46d13a5e38b96
Author
Vayun Mathur <[email protected]>
When
2026-11-07 03:28 UTC (29 days ago)
Parents
b775622
Coverage (merged INSTRUCTION, createMergedCoverageReport):
34.1% (12660/37128) -> 86.3% (32028/37128).

New tests (7 files, test count 181 in module suite):
- ime/TextBeforeCursorTest + KeyboardStateTest: text mirror
  (fill/commit/composing/delete incl. surrogate pairs, external
  selection invalidation, window trim) and state defaults /
  effectiveLayout ASCII-force rules.
- ime/ServiceOpsTest: Robolectric KeyboardService with a fake
  InputConnection - commit/composing helpers, suggestions,
  autocorrect, shift/caps timing, emoji search routing, composer
  sync for Hangul/Romaji/Kana/Ethiopic/Pinyin (incl. async
  Chinese asset load), configureForEditor field-kind and
  enter-action mapping, clipboard offer/delete/clear, image
  paste refusals, voice state transitions.
- ime/ServiceLifecycleTest: onCreateInputView, start/window/
  finish callbacks, subtype layout resolution, MainActivity and
  VoicePermissionActivity creation.
- ui/KeyboardScreenTest: Robolectric Compose screens for every
  page (letters in Latin/Cyrillic/Arabic/four-row layouts,
  symbols, numeric modes, phone, emoji, clipboard), shift
  states, suggestion/candidate/notice/clip/voice strips, emoji
  search, enter-action labels - with a recording ImeActions
  asserting what taps report.
- ui/PagesAndSetupTest + ui/KeyComponentsTest: direct pages,
  SetupScreen render/scroll/switch/buttons, alternates popup
  geometry, CharKey tap/long-press, function keys.
- util/PlatformRoboTest: KeyboardSettings persistence,
  Pinyin/Emoji/Dictionary asset loads, ClipboardStore capture
  of text clips, persist/restore excluding sensitive clips,
  real-PNG thumbnail decode, VoiceInput unavailable path,
  VoicePermission request/publish.

No production code changed; no bugs found.
Verified: gslot ./gradlew :keyboard:createMergedCoverageReport
(full unit suite green, 86.26% merged instructions).

(cherry picked from commit 6065140bf146f5e098bfddc3fa4ee82e68247e49)

Diff

keyboard/src/test/java/com/vayunmathur/keyboard/ime/ServiceLifecycleTest.kt
diff --git a/keyboard/src/test/java/com/vayunmathur/keyboard/ime/ServiceLifecycleTest.kt b/keyboard/src/test/java/com/vayunmathur/keyboard/ime/ServiceLifecycleTest.ktnew file mode 100644index 0000000000..6fa17630b0--- /dev/null+++ b/keyboard/src/test/java/com/vayunmathur/keyboard/ime/ServiceLifecycleTest.kt@@ -0,0 +1,122 @@+package com.vayunmathur.keyboard.ime++import android.os.Looper+import android.text.InputType+import android.view.inputmethod.EditorInfo+import android.view.inputmethod.InputMethodSubtype+import androidx.lifecycle.Lifecycle+import com.vayunmathur.keyboard.util.KeyboardLayouts+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.shadows.ShadowLooper+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class ServiceLifecycleTest {++    @Test+    fun `input view and window lifecycle callbacks run`() {+        val controller = Robolectric.buildService(KeyboardService::class.java)+        val service = controller.create().get()+        ShadowLooper.idleMainLooper()++        val view = service.onCreateInputView()+        assertNotNull(view)+        assertEquals(Lifecycle.State.CREATED, service.lifecycle.currentState)++        val info = EditorInfo().apply {+            inputType = InputType.TYPE_CLASS_TEXT+            initialSelStart = 0; initialSelEnd = 0+            imeOptions = EditorInfo.IME_ACTION_DONE+        }+        service.onStartInputView(info, restarting = false)+        assertEquals(Lifecycle.State.STARTED, service.lifecycle.currentState)+        assertTrue(service.kbState.suggestions.isEmpty())++        service.onWindowShown()+        assertEquals(Lifecycle.State.RESUMED, service.lifecycle.currentState)+        assertTrue(service.windowShown)+        service.updateBottomInset()++        service.onUpdateSelection(0, 0, 1, 1, -1, -1)+        service.onUpdateSelection(0, 0, 2, 3, -1, -1)+        assertTrue(service.before.hasSelection)++        service.onWindowHidden()+        assertEquals(Lifecycle.State.STARTED, service.lifecycle.currentState)++        service.onStartInputView(+            EditorInfo().apply {+                inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_PASSWORD+                initialSelStart = 2; initialSelEnd = 2+            },+            restarting = true,+        )+        assertTrue(service.kbState.passwordField)++        service.onFinishInputView(finishingInput = true)+        controller.destroy()+        ShadowLooper.idleMainLooper()+        assertEquals(Lifecycle.State.DESTROYED, service.lifecycle.currentState)+    }++    @Test+    fun `subtype changes apply layouts and layoutIdOf reads extras`() {+        val controller = Robolectric.buildService(KeyboardService::class.java)+        val service = controller.create().get()+        ShadowLooper.idleMainLooper()++        val german = InputMethodSubtype.InputMethodSubtypeBuilder()+            .setSubtypeMode("keyboard")+            .setLanguageTag("de")+            .setSubtypeExtraValue("layoutId=de_qwertz")+            .build()+        service.subtypeByLayoutId = mapOf("de_qwertz" to german)+        assertEquals("de_qwertz", service.layoutIdOf(german))++        val byTag = InputMethodSubtype.InputMethodSubtypeBuilder()+            .setSubtypeMode("keyboard").setLanguageTag("fr").build()+        val resolved = service.layoutIdOf(byTag)+        assertTrue(resolved == null || KeyboardLayouts.byId(resolved) != null)+        assertNull(service.layoutIdOf(null))++        service.applyLayout(checkNotNull(service.layoutIdOf(german)))+        ShadowLooper.idleMainLooper()+        assertEquals("de_qwertz", service.kbState.settings.activeLayoutId)+        // applying the same layout again keeps it+        service.applyLayout("de_qwertz")+        assertEquals("de_qwertz", service.kbState.settings.activeLayoutId)++        service.registerLayoutSubtypes()+        controller.destroy()+        ShadowLooper.idleMainLooper()+    }++    @Test+    fun `main activity creates its content`() {+        val controller = Robolectric.buildActivity(com.vayunmathur.keyboard.MainActivity::class.java)+        val activity = controller.create().start().resume().get()+        assertNotNull(activity)+        ShadowLooper.idleMainLooper()+        controller.pause().stop().destroy()+    }++    @Test+    fun `voice permission activity finishes after launch`() {+        // The trampoline launches a permission request; Robolectric denies by default+        // and the activity finishes itself through the result callback or stays created.+        val controller = Robolectric.buildActivity(+            com.vayunmathur.keyboard.platform.VoicePermissionActivity::class.java,+        )+        val activity = controller.create().get()+        ShadowLooper.idleMainLooper()+        assertNotNull(activity)+        runCatching { controller.destroy() }+        assertNotNull(Looper.getMainLooper())+    }+}
keyboard/src/test/java/com/vayunmathur/keyboard/ime/ServiceOpsTest.kt
diff --git a/keyboard/src/test/java/com/vayunmathur/keyboard/ime/ServiceOpsTest.kt b/keyboard/src/test/java/com/vayunmathur/keyboard/ime/ServiceOpsTest.ktnew file mode 100644index 0000000000..616ac47ce4--- /dev/null+++ b/keyboard/src/test/java/com/vayunmathur/keyboard/ime/ServiceOpsTest.kt@@ -0,0 +1,526 @@+package com.vayunmathur.keyboard.ime++import android.os.Bundle+import android.text.InputType+import android.view.KeyEvent+import android.view.inputmethod.CompletionInfo+import android.view.inputmethod.CorrectionInfo+import android.view.inputmethod.EditorInfo+import android.view.inputmethod.ExtractedText+import android.view.inputmethod.ExtractedTextRequest+import android.view.inputmethod.InputConnection+import android.view.inputmethod.InputContentInfo+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.keyboard.util.ClipItem+import com.vayunmathur.keyboard.util.Dictionary+import com.vayunmathur.keyboard.util.KeyboardLayouts+import com.vayunmathur.keyboard.util.KeyboardPage+import com.vayunmathur.keyboard.util.ShiftState+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.shadows.ShadowLooper+import android.os.Looper+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Records every edit the service helpers ask the field to make. */+class FakeInputConnection : InputConnection {+    val committed = mutableListOf<String>()+    val composingTexts = mutableListOf<String>()+    var finishComposingCalls = 0+    var deletedCodePoints = 0+    var editorActions = mutableListOf<Int>()+    var textBefore = ""+    var editorActionResult = true++    override fun getTextBeforeCursor(n: Int, flags: Int): CharSequence = textBefore.takeLast(n)+    override fun getTextAfterCursor(n: Int, flags: Int): CharSequence = ""+    override fun getSelectedText(flags: Int): CharSequence? = null+    override fun getCursorCapsMode(reqModes: Int): Int = 0+    override fun getExtractedText(request: ExtractedTextRequest?, flags: Int): ExtractedText? = null+    override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean = true+    override fun deleteSurroundingTextInCodePoints(beforeLength: Int, afterLength: Int): Boolean {+        deletedCodePoints += beforeLength; return true+    }+    override fun setComposingText(text: CharSequence?, newCursorPosition: Int): Boolean {+        composingTexts += text?.toString().orEmpty(); return true+    }+    override fun setComposingRegion(start: Int, end: Int): Boolean = true+    override fun finishComposingText(): Boolean { finishComposingCalls++; return true }+    override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean {+        committed += text?.toString().orEmpty(); return true+    }+    override fun commitCompletion(text: CompletionInfo?): Boolean = true+    override fun commitCorrection(correctionInfo: CorrectionInfo?): Boolean = true+    override fun setSelection(start: Int, end: Int): Boolean = true+    override fun performEditorAction(editorAction: Int): Boolean {+        editorActions += editorAction; return editorActionResult+    }+    override fun performContextMenuAction(id: Int): Boolean = true+    override fun beginBatchEdit(): Boolean = true+    override fun endBatchEdit(): Boolean = true+    override fun sendKeyEvent(event: KeyEvent?): Boolean = true+    override fun clearMetaKeyStates(states: Int): Boolean = true+    override fun reportFullscreenMode(enabled: Boolean): Boolean = true+    override fun performPrivateCommand(action: String?, data: Bundle?): Boolean = true+    override fun requestCursorUpdates(cursorUpdateMode: Int): Boolean = true+    override fun getHandler(): android.os.Handler? = null+    override fun closeConnection() {}+    override fun commitContent(+        inputContentInfo: InputContentInfo, flags: Int, opts: Bundle?,+    ): Boolean = true+}++@RunWith(RobolectricTestRunner::class)+class ServiceOpsTest {++    private lateinit var service: KeyboardService+    private lateinit var controller: org.robolectric.android.controller.ServiceController<KeyboardService>++    @BeforeTest+    fun setUp() {+        controller = Robolectric.buildService(KeyboardService::class.java)+        service = controller.create().get()+        ShadowLooper.idleMainLooper()+    }++    @AfterTest+    fun tearDown() {+        runCatching { controller.destroy() }+        ShadowLooper.idleMainLooper()+    }++    @Test+    fun `service creates state with default layout and no composer`() {+        assertNotNull(KeyboardLayouts.byId(service.kbState.settings.activeLayoutId))+        assertNull(service.composer)+        assertNotNull(service.kbState)+    }++    @Test+    fun `commit setComposing finish and delete mirror into before`() {+        val ic = FakeInputConnection()+        service.before.fill("")+        service.commit(ic, "hello")+        service.setComposing(ic, " wor")+        assertEquals(" wor", service.pendingComposition)+        service.finishComposing(ic)+        assertEquals("", service.pendingComposition)+        service.deleteBackward(ic)+        assertEquals(listOf("hello"), ic.committed)+        assertEquals(1, ic.deletedCodePoints)+        assertTrue(ic.finishComposingCalls >= 1)+    }++    @Test+    fun `textBeforeCursor asks field only when mirror empty`() {+        val ic = FakeInputConnection().apply { textBefore = "abc " }+        // currentInputConnection is null in Robolectric, so service falls back to ""+        assertEquals("", service.textBeforeCursor().toString())+        service.before.fill("cached ")+        assertEquals("cached ", service.textBeforeCursor().toString())+        assertEquals("abc ", ic.getTextBeforeCursor(10, 0).toString())+    }++    @Test+    fun `sentence and word start detection`() {+        service.before.fill("")+        assertTrue(service.isAtSentenceStart())+        assertTrue(service.isAtWordStart())+        service.before.fill("Hello. ")+        assertTrue(service.isAtSentenceStart())+        service.before.fill("Hello ")+        assertFalse(service.isAtSentenceStart())+        assertTrue(service.isAtWordStart())+        service.before.fill("Hello")+        assertFalse(service.isAtWordStart())+        service.before.fill("line\n")+        assertTrue(service.isAtSentenceStart())+        service.before.fill("x")+        assertFalse(service.isAtSentenceStart())+    }++    @Test+    fun `commitCurrentWord autocorrects known typo and finishes`() {+        service.dictionary = Dictionary.fromEntries(listOf("hello" to 100, "world" to 90, "help" to 80))+        val ic = FakeInputConnection()+        service.composing.append("helo")+        service.commitCurrentWord(ic, autoCorrect = true)+        assertEquals(0, service.composing.length)+        assertTrue(ic.finishComposingCalls >= 1)+        // no composing word: no-op+        val calls = ic.finishComposingCalls+        service.commitCurrentWord(ic, autoCorrect = true)+        assertEquals(calls, ic.finishComposingCalls)+    }++    @Test+    fun `updateSuggestions respects settings and composing`() {+        service.dictionary = Dictionary.fromEntries(listOf("hello" to 100, "helm" to 90, "help" to 80))+        service.composing.append("hel")+        service.updateSuggestions()+        assertTrue(service.kbState.suggestions.isNotEmpty())+        assertTrue(service.kbState.suggestions.all { it.startsWith("hel") })+        service.kbState.settings = service.kbState.settings.copy(showSuggestions = false)+        service.updateSuggestions()+        assertTrue(service.kbState.suggestions.isEmpty())+        service.kbState.settings = service.kbState.settings.copy(showSuggestions = true)+        service.composing.setLength(0)+        service.updateSuggestions()+        assertTrue(service.kbState.suggestions.isEmpty())+    }++    @Test+    fun `shift taps cycle and caps lock latches on rapid second tap`() {+        service.onShift()+        assertEquals(ShiftState.SHIFTED, service.kbState.shift)+        service.onShift()+        assertEquals(ShiftState.CAPS_LOCK, service.kbState.shift)+        service.onShift()+        assertEquals(ShiftState.OFF, service.kbState.shift)+        // consumeShift only clears one-shot shift+        service.kbState.shift = ShiftState.SHIFTED+        service.consumeShift()+        assertEquals(ShiftState.OFF, service.kbState.shift)+        service.kbState.shift = ShiftState.CAPS_LOCK+        service.consumeShift()+        assertEquals(ShiftState.CAPS_LOCK, service.kbState.shift)+    }++    @Test+    fun `emoji search lifecycle routes typing into query`() {+        service.startEmojiSearch()+        assertEquals("", service.kbState.emojiQuery)+        assertEquals(KeyboardPage.LETTERS, service.kbState.page)+        assertTrue(service.typeIntoSearch("cat"))+        assertEquals("cat", service.kbState.emojiQuery)+        service.onBackspace()+        assertEquals("ca", service.kbState.emojiQuery)+        service.setQuery("")+        service.onBackspace() // empty query leaves search+        assertNull(service.kbState.emojiQuery)+        assertEquals(KeyboardPage.EMOJI, service.kbState.page)+        service.startEmojiSearch()+        service.endEmojiSearch()+        assertNull(service.kbState.emojiQuery)+        assertEquals(KeyboardPage.EMOJI, service.kbState.page)+        assertFalse(service.typeIntoSearch("x"))+    }++    @Test+    fun `setPage clears emoji search`() {+        service.startEmojiSearch()+        service.setPage(KeyboardPage.SYMBOLS)+        assertNull(service.kbState.emojiQuery)+        assertEquals(KeyboardPage.SYMBOLS, service.kbState.page)+    }++    @Test+    fun `commitEmoji remembers recent and leaves search`() {+        service.kbState.emojiData = com.vayunmathur.keyboard.util.EmojiData.BUILTIN+        service.startEmojiSearch()+        service.commitEmoji("πŸ˜€")+        assertNull(service.kbState.emojiQuery)+        assertEquals("πŸ˜€", service.kbState.recentEmoji.firstOrNull())+        // second commit of same emoji does not duplicate+        service.commitEmoji("πŸ˜€")+        assertEquals(1, service.kbState.recentEmoji.count { it == "πŸ˜€" })+        service.commitEmoji("πŸŽ‰")+        assertEquals(listOf("πŸŽ‰", "πŸ˜€"), service.kbState.recentEmoji)+    }++    @Test+    fun `composer sync follows layout kind and ascii force`() {+        fun setLayout(id: String) {+            service.kbState.settings = service.kbState.settings.copy(activeLayoutId = id)+            service.composerKind = service.composerKind // keep+            // force rebuild+            service.syncComposer()+        }+        val hangul = KeyboardLayouts.ALL.first { it.composer == com.vayunmathur.keyboard.util.ComposerKind.HANGUL }+        setLayout(hangul.id)+        assertTrue(service.composer is HangulComposer)+        val romaji = KeyboardLayouts.ALL.first { it.composer == com.vayunmathur.keyboard.util.ComposerKind.ROMAJI }+        setLayout(romaji.id)+        assertTrue(service.composer is RomajiComposer)+        val kana = KeyboardLayouts.ALL.first { it.composer == com.vayunmathur.keyboard.util.ComposerKind.KANA }+        setLayout(kana.id)+        assertTrue(service.composer is KanaKeyComposer)+        val eth = KeyboardLayouts.ALL.first { it.composer == com.vayunmathur.keyboard.util.ComposerKind.ETHIOPIC }+        setLayout(eth.id)+        assertTrue(service.composer is EthiopicComposer)+        setLayout("en_qwerty")+        assertNull(service.composer)+        // ascii force disables composer+        setLayout(hangul.id)+        service.kbState.forceAscii = true+        service.syncComposer()+        assertNull(service.composer)+        service.kbState.forceAscii = false+    }++    @Test+    fun `applyComposition commits settled text and updates candidates`() {+        val ic = FakeInputConnection()+        val han = HanComposer(+            com.vayunmathur.keyboard.util.PinyinDictionary.fromEntries(listOf("ni" to "δ½ ε°Ό", "hao" to "ε₯½")),+            SpellingScheme.Pinyin,+        )+        val r1 = han.accept("n")+        assertNotNull(r1)+        service.applyComposition(ic, han, r1)+        val r2 = han.accept("i")+        assertNotNull(r2)+        service.applyComposition(ic, han, r2)+        assertTrue(service.kbState.suggestions.isNotEmpty())+        // finishing applies final+        service.composer = han+        service.finishComposition(ic)+        assertTrue(service.kbState.suggestions.isEmpty())+    }++    @Test+    fun `configureForEditor maps field kinds to pages and actions`() {+        fun info(inputType: Int, imeOptions: Int = 0, actionLabel: CharSequence? = null, actionId: Int = 0) =+            EditorInfo().apply {+                this.inputType = inputType; this.imeOptions = imeOptions+                this.actionLabel = actionLabel; this.actionId = actionId+            }+        service.configureForEditor(info(InputType.TYPE_CLASS_PHONE))+        assertEquals(KeyboardPage.PHONE, service.kbState.page)+        service.configureForEditor(info(InputType.TYPE_CLASS_NUMBER))+        assertEquals(KeyboardPage.NUMERIC, service.kbState.page)+        assertEquals(NumericMode.NUMBER, service.kbState.numericMode)+        service.configureForEditor(+            info(InputType.TYPE_CLASS_DATETIME or InputType.TYPE_DATETIME_VARIATION_DATE),+        )+        assertEquals(NumericMode.DATE, service.kbState.numericMode)+        service.configureForEditor(+            info(InputType.TYPE_CLASS_DATETIME or InputType.TYPE_DATETIME_VARIATION_TIME),+        )+        assertEquals(NumericMode.TIME, service.kbState.numericMode)+        service.configureForEditor(info(InputType.TYPE_CLASS_DATETIME))+        assertEquals(NumericMode.DATE_TIME, service.kbState.numericMode)+        service.configureForEditor(+            info(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS),+        )+        assertEquals(TextVariation.EMAIL, service.kbState.textVariation)+        assertEquals(KeyboardPage.LETTERS, service.kbState.page)+        service.configureForEditor(+            info(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI),+        )+        assertEquals(TextVariation.URL, service.kbState.textVariation)+        service.configureForEditor(+            info(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PERSON_NAME),+        )+        assertEquals(TextVariation.PERSON_NAME, service.kbState.textVariation)+        service.configureForEditor(+            info(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD),+        )+        assertTrue(service.kbState.passwordField)+        service.configureForEditor(+            info(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD or+                InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS),+        )+        assertTrue(service.kbState.forceAscii)+        assertEquals(TextVariation.NO_SUGGESTIONS, service.kbState.textVariation)+        service.configureForEditor(+            info(InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_PASSWORD),+        )+        assertTrue(service.kbState.passwordField)+        // enter actions+        service.configureForEditor(info(InputType.TYPE_CLASS_TEXT, EditorInfo.IME_ACTION_SEARCH))+        assertEquals(EnterAction.SEARCH, service.kbState.enterAction)+        assertTrue(service.enterSendsAction)+        service.configureForEditor(info(InputType.TYPE_CLASS_TEXT, EditorInfo.IME_ACTION_SEND))+        assertEquals(EnterAction.SEND, service.kbState.enterAction)+        service.configureForEditor(info(InputType.TYPE_CLASS_TEXT, EditorInfo.IME_ACTION_DONE))+        assertEquals(EnterAction.DONE, service.kbState.enterAction)+        service.configureForEditor(info(InputType.TYPE_CLASS_TEXT, EditorInfo.IME_ACTION_GO))+        assertEquals(EnterAction.GO, service.kbState.enterAction)+        service.configureForEditor(info(InputType.TYPE_CLASS_TEXT, EditorInfo.IME_ACTION_NEXT))+        assertEquals(EnterAction.NEXT, service.kbState.enterAction)+        service.configureForEditor(info(InputType.TYPE_CLASS_TEXT, EditorInfo.IME_ACTION_PREVIOUS))+        assertEquals(EnterAction.PREVIOUS, service.kbState.enterAction)+        service.configureForEditor(+            info(InputType.TYPE_CLASS_TEXT, EditorInfo.IME_FLAG_NO_ENTER_ACTION or EditorInfo.IME_ACTION_SEARCH),+        )+        assertEquals(EnterAction.RETURN, service.kbState.enterAction)+        assertFalse(service.enterSendsAction)+        service.configureForEditor(+            info(InputType.TYPE_CLASS_TEXT, EditorInfo.IME_ACTION_UNSPECIFIED, "Join", 42),+        )+        assertEquals("Join", service.kbState.enterActionLabel)+        assertEquals(42, service.editorActionId)+        assertTrue(service.enterSendsAction)+    }++    @Test+    fun `updateAutoCapShift capitalizes at sentence start only for cased layouts`() {+        service.kbState.basePage = KeyboardPage.LETTERS+        service.before.fill("")+        service.updateAutoCapShift()+        assertEquals(ShiftState.SHIFTED, service.kbState.shift)+        service.before.fill("Done. ")+        service.updateAutoCapShift()+        assertEquals(ShiftState.SHIFTED, service.kbState.shift)+        service.before.fill("mid word")+        service.updateAutoCapShift()+        assertEquals(ShiftState.OFF, service.kbState.shift)+        service.kbState.passwordField = true+        service.before.fill("")+        service.kbState.shift = ShiftState.OFF+        service.updateAutoCapShift()+        assertEquals(ShiftState.OFF, service.kbState.shift)+        service.kbState.passwordField = false+        service.kbState.shift = ShiftState.CAPS_LOCK+        service.updateAutoCapShift()+        assertEquals(ShiftState.CAPS_LOCK, service.kbState.shift)+    }++    @Test+    fun `clipboard ops offer dismiss delete and clear`() {+        val item = ClipItem(id = 991001, text = "copied text")+        service.offerClip(item)+        assertEquals(item, service.kbState.clipSuggestion)+        service.dismissClipSuggestion()+        assertNull(service.kbState.clipSuggestion)+        service.clipboard.add(item)+        service.kbState.clips = service.clipboard.items+        service.deleteClip(item)+        assertTrue(service.kbState.clips.none { it.id == item.id })+        val item2 = ClipItem(id = 991002, text = "again")+        service.clipboard.add(item2)+        service.kbState.clips = service.clipboard.items+        service.clearClips()+        assertTrue(service.kbState.clips.isEmpty())+        service.showNotice("note")+        assertEquals("note", service.kbState.notice)+        // paste with no input connection returns after feedback+        service.pasteClip(item2)+    }++    @Test+    fun `commitImage refuses when editor or file missing`() {+        val ic = FakeInputConnection()+        val img = ClipItem(id = 991003, imagePath = "/nonexistent/x.png", mimeType = "image/png")+        service.commitImage(ic, img)+        assertNotNull(service.kbState.notice)+        val noMime = ClipItem(id = 991004, imagePath = "/nonexistent/x.png")+        service.commitImage(ic, noMime)+        assertNotNull(service.kbState.notice)+    }++    @Test+    fun `voice state transitions and failures`() {+        service.setVoiceState(VoiceState.Listening("par"))+        assertEquals(VoiceState.Listening("par"), service.kbState.voice)+        service.showVoiceFailure(com.vayunmathur.keyboard.platform.VoiceFailure.NO_SPEECH)+        assertTrue(service.kbState.voice is VoiceState.Failed)+        service.setVoiceState(VoiceState.Failed(com.vayunmathur.keyboard.platform.VoiceFailure.PERMISSION_BLOCKED))+        // blocked does not auto-clear: job is null+        assertNull(service.voiceMessageJob)+        service.dismissVoice()+        assertNull(service.kbState.voice)+        service.onVoicePermissionResult(com.vayunmathur.keyboard.platform.VoicePermissionResult.DENIED)+        assertTrue(service.kbState.voice is VoiceState.Failed)+        service.onVoicePermissionResult(com.vayunmathur.keyboard.platform.VoicePermissionResult.BLOCKED)+        assertEquals(+            com.vayunmathur.keyboard.platform.VoiceFailure.PERMISSION_BLOCKED,+            (service.kbState.voice as VoiceState.Failed).failure,+        )+        service.dismissVoice()+        // onVoiceInput when recognizer unavailable shows failure (Robolectric has none)+        service.onVoiceInput()+        assertTrue(service.kbState.voice is VoiceState.Failed || service.kbState.voice == null)+    }++    @Test+    fun `layoutIdOf and applyLayout switch active layout`() {+        service.applyLayout("de_qwertz")+        ShadowLooper.idleMainLooper()+        assertEquals("de_qwertz", service.kbState.settings.activeLayoutId)+        assertNull(service.layoutIdOf(null))+        // unknown subtype with no registered map falls back by language tag+        val subtype = android.view.inputmethod.InputMethodSubtype.InputMethodSubtypeBuilder()+            .setSubtypeMode("keyboard").setLanguageTag("de").build()+        val resolved = service.layoutIdOf(subtype)+        assertTrue(resolved == null || resolved.startsWith("de"))+    }++    @Test+    fun `onChar onEnter onSpace without connection are safe no-ops beyond state`() {+        service.onChar("a")+        service.onEnter()+        service.onSpace()+        service.onBackspace()+        service.commitSuggestion("word")+        // emoji search path still consumes chars+        service.startEmojiSearch()+        service.onChar("s")+        assertEquals("s", service.kbState.emojiQuery)+        service.onEnter() // ends search+        assertNull(service.kbState.emojiQuery)+    }++    @Test+    fun `useComposing requires english layout and suggestions or autocorrect`() {+        assertTrue(service.useComposing())+        service.kbState.settings = service.kbState.settings.copy(showSuggestions = false, autoCorrect = false)+        assertFalse(service.useComposing())+        service.kbState.settings = service.kbState.settings.copy(showSuggestions = true, activeLayoutId = "ru")+        assertFalse(service.useComposing())+        service.kbState.settings = service.kbState.settings.copy(activeLayoutId = "en_qwerty")+        service.kbState.passwordField = true+        assertFalse(service.useComposing())+    }++    @Test+    fun `action handler delegates`() {+        val handler = KeyboardActionHandler(service)+        handler.onShift()+        handler.setPage(KeyboardPage.NUMERIC)+        assertEquals(KeyboardPage.NUMERIC, service.kbState.page)+        handler.startEmojiSearch()+        assertEquals("", service.kbState.emojiQuery)+        handler.endEmojiSearch()+        handler.dismissClipSuggestion()+        handler.dismissVoice()+        assertNull(service.kbState.voice)+    }++    @Test+    fun `pinyin layout loads chinese data and rebuilds composer`() {+        val pinyin = KeyboardLayouts.ALL.first {+            it.composer == com.vayunmathur.keyboard.util.ComposerKind.PINYIN_SIMPLIFIED+        }+        service.kbState.settings = service.kbState.settings.copy(activeLayoutId = pinyin.id)+        service.syncComposer()+        assertTrue(service.composer is HanComposer)+        // The asset load runs on the service scope (main + IO); wait for it to land.+        val deadline = System.currentTimeMillis() + 10_000+        while (service.pinyinSimplified === com.vayunmathur.keyboard.util.PinyinDictionary.EMPTY &&+            System.currentTimeMillis() < deadline+        ) {+            ShadowLooper.idleMainLooper()+            Thread.sleep(25)+        }+        assertTrue(service.pinyinSimplified !== com.vayunmathur.keyboard.util.PinyinDictionary.EMPTY)+        assertTrue(service.pinyinSimplified.candidates("ni").isNotEmpty())+        assertTrue(service.composer is HanComposer)+        service.kbState.settings = service.kbState.settings.copy(activeLayoutId = "en_qwerty")+        service.syncComposer()+    }++    @Test+    fun `context is application`() {+        assertNotNull(ApplicationProvider.getApplicationContext<android.content.Context>())+    }+}
keyboard/src/test/java/com/vayunmathur/keyboard/ime/TextBeforeCursorTest.kt
diff --git a/keyboard/src/test/java/com/vayunmathur/keyboard/ime/TextBeforeCursorTest.kt b/keyboard/src/test/java/com/vayunmathur/keyboard/ime/TextBeforeCursorTest.ktnew file mode 100644index 0000000000..1cc744bed0--- /dev/null+++ b/keyboard/src/test/java/com/vayunmathur/keyboard/ime/TextBeforeCursorTest.kt@@ -0,0 +1,207 @@+package com.vayunmathur.keyboard.ime++import com.vayunmathur.keyboard.util.KeyboardLayouts+import com.vayunmathur.keyboard.util.KeyboardPage+import com.vayunmathur.keyboard.util.ShiftState+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++class TextBeforeCursorTest {++    @Test+    fun `unknown mirror returns null until filled`() {+        val t = TextBeforeCursor()+        assertNull(t.peek())+        t.onStartInput(0, 0)+        assertNull(t.peek())+        t.fill("hi")+        assertEquals("hi", t.peek()?.toString())+    }++    @Test+    fun `short fill at start answers even below needed length`() {+        val t = TextBeforeCursor()+        t.fill("a")+        assertEquals("a", t.peek()?.toString())+    }++    @Test+    fun `committed and composing edits are mirrored`() {+        val t = TextBeforeCursor()+        t.onStartInput(0, 0)+        t.fill("")+        t.committed("hello")+        assertEquals("hello", t.peek()?.toString())+        t.composing(" wor")+        // composing text is not final, so peek still shows committed only+        assertEquals("hello", t.peek()?.toString())+        t.composingFinished(" wor")+        assertEquals("hello wor", t.peek()?.toString())+    }++    @Test+    fun `committed replaces open composition`() {+        val t = TextBeforeCursor()+        t.fill("ab")+        t.composing("cd")+        t.committed("X")+        assertEquals("abX", t.peek()?.toString())+    }++    @Test+    fun `delete removes code points including surrogate pairs`() {+        val t = TextBeforeCursor()+        t.fill("a\uD83D\uDE00b")+        t.deleted()+        assertEquals("a\uD83D\uDE00", t.peek()?.toString())+        t.deleted()+        assertEquals("a", t.peek()?.toString())+        t.deleted()+        assertEquals("", t.peek()?.toString())+        // At start with empty window: deleting is a no-op for the mirror.+        t.deleted()+        assertEquals("", t.peek()?.toString())+    }++    @Test+    fun `delete on unknown mirror only moves guessed cursor`() {+        val t = TextBeforeCursor()+        t.onStartInput(5, 5)+        t.deleted()+        assertNull(t.peek())+        assertFalse(t.hasSelection)+    }++    @Test+    fun `delete past known window invalidates`() {+        val t = TextBeforeCursor()+        // Fill with a full window then commit more so atStart becomes false after trim.+        t.fill("x".repeat(TextBeforeCursor.WINDOW))+        t.committed("y".repeat(4))+        // Delete everything known; next delete should invalidate.+        repeat(TextBeforeCursor.WINDOW) { t.deleted() }+        t.deleted()+        assertNull(t.peek())+    }++    @Test+    fun `selection change from outside invalidates and resyncs`() {+        val t = TextBeforeCursor()+        t.onStartInput(0, 0)+        t.fill("hello")+        t.committed("!")+        // Cursor reported where our edits left it (1, after the committed "!"): mirror kept.+        t.onSelectionChanged(1, 1)+        assertEquals("hello!", t.peek()?.toString())+        assertFalse(t.hasSelection)+        // Unexpected position: external edit.+        t.onSelectionChanged(2, 4)+        assertTrue(t.hasSelection)+        assertNull(t.peek())+    }++    @Test+    fun `invalidate clears everything`() {+        val t = TextBeforeCursor()+        t.fill("hello")+        t.invalidate()+        assertNull(t.peek())+        assertFalse(t.hasSelection)+    }++    @Test+    fun `long committed text is trimmed to window`() {+        val t = TextBeforeCursor()+        t.fill("start")+        t.committed("z".repeat(40))+        val peeked = t.peek()?.toString()+        assertEquals(TextBeforeCursor.WINDOW, peeked?.length)+        assertTrue(peeked!!.endsWith("z"))+    }++    @Test+    fun `start input records selection`() {+        val t = TextBeforeCursor()+        t.onStartInput(3, 7)+        assertTrue(t.hasSelection)+        t.onStartInput(3, 3)+        assertFalse(t.hasSelection)+    }+}++class KeyboardStateTest {++    @Test+    fun `defaults are letters page with suggestions-ready state`() {+        val s = KeyboardState()+        assertEquals(KeyboardPage.LETTERS, s.page)+        assertEquals(KeyboardPage.LETTERS, s.basePage)+        assertEquals(ShiftState.OFF, s.shift)+        assertTrue(s.suggestions.isEmpty())+        assertEquals(EnterAction.RETURN, s.enterAction)+        assertNull(s.enterActionLabel)+        assertFalse(s.passwordField)+        assertEquals(TextVariation.NORMAL, s.textVariation)+        assertEquals(NumericMode.NUMBER, s.numericMode)+        assertFalse(s.forceAscii)+        assertEquals(0, s.bottomInsetPx)+        assertNull(s.emojiQuery)+        assertNull(s.clipSuggestion)+        assertNull(s.voice)+        assertNull(s.notice)+    }++    @Test+    fun `effective layout is active layout when not ascii forced`() {+        val s = KeyboardState()+        val ru = KeyboardLayouts.byId("ru")!!+        s.settings = s.settings.copy(activeLayoutId = ru.id)+        assertEquals(ru, s.effectiveLayout)+        s.forceAscii = true+        // Cyrillic is not Latin script: falls back to English QWERTY.+        assertEquals("en_qwerty", s.effectiveLayout.id)+    }++    @Test+    fun `effective layout keeps plain latin layout under ascii force`() {+        val s = KeyboardState()+        s.settings = s.settings.copy(activeLayoutId = "de_qwertz")+        s.forceAscii = true+        assertEquals("de_qwertz", s.effectiveLayout.id)+    }++    @Test+    fun `effective layout rejects composing latin layout under ascii force`() {+        val s = KeyboardState()+        val romaji = KeyboardLayouts.ALL.first { it.composer != null && it.isLatinScript }+        s.settings = s.settings.copy(activeLayoutId = romaji.id)+        assertEquals(romaji, s.effectiveLayout)+        s.forceAscii = true+        assertEquals("en_qwerty", s.effectiveLayout.id)+    }++    @Test+    fun `noop actions do nothing but are callable`() {+        val a = ImeActions.Noop+        a.onChar("x"); a.onBackspace(); a.onEnter(); a.onSpace(); a.onShift()+        a.setPage(KeyboardPage.EMOJI); a.commitSuggestion("word")+        a.startEmojiSearch(); a.endEmojiSearch(); a.commitEmoji("πŸ˜€")+        a.pasteClip(com.vayunmathur.keyboard.util.ClipItem(id = 1, text = "t"))+        a.deleteClip(com.vayunmathur.keyboard.util.ClipItem(id = 1, text = "t"))+        a.clearClips(); a.dismissClipSuggestion()+        a.onVoiceInput(); a.stopVoiceInput(); a.dismissVoice(); a.openVoiceSettings()+    }++    @Test+    fun `voice states carry their payloads`() {+        assertEquals("hey", VoiceState.Listening("hey").partial)+        assertEquals(VoiceState.Transcribing, VoiceState.Transcribing)+        assertEquals(+            com.vayunmathur.keyboard.platform.VoiceFailure.BUSY,+            VoiceState.Failed(com.vayunmathur.keyboard.platform.VoiceFailure.BUSY).failure,+        )+    }+}
keyboard/src/test/java/com/vayunmathur/keyboard/ui/KeyComponentsTest.kt
diff --git a/keyboard/src/test/java/com/vayunmathur/keyboard/ui/KeyComponentsTest.kt b/keyboard/src/test/java/com/vayunmathur/keyboard/ui/KeyComponentsTest.ktnew file mode 100644index 0000000000..7ff64c2b90--- /dev/null+++ b/keyboard/src/test/java/com/vayunmathur/keyboard/ui/KeyComponentsTest.kt@@ -0,0 +1,140 @@+package com.vayunmathur.keyboard.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.unit.dp+import com.vayunmathur.keyboard.util.ShiftState+import com.vayunmathur.library.ui.Text+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class KeyComponentsTest {++    @get:Rule val rule = createComposeRule()++    @Test+    fun `alternates popup highlights selected entry`() {+        rule.setContent {+            AlternatesPopup(options = "abc", selected = 1, itemWidth = 44.dp, offsetX = 0)+        }+        rule.onNodeWithText("a").assertIsDisplayed()+        rule.onNodeWithText("b").assertIsDisplayed()+        rule.onNodeWithText("c").assertIsDisplayed()+    }++    @Test+    fun `key preview shows label`() {+        rule.setContent { KeyPreview("Q") }+        rule.onNodeWithText("Q").assertIsDisplayed()+    }++    @Test+    fun `char key tap commits and hint variants render`() {+        val clicks = mutableListOf<String>()+        val alts = mutableListOf<String>()+        rule.setContent {+            Column {+                Row {+                    CharKey(+                        label = "a", height = 52.dp, hint = "ABC",+                        alternates = "àÑ", onClick = { clicks += "a" },+                        onAlternate = { alts += it },+                    )+                    CharKey(+                        label = "ß", height = 52.dp, cornerHint = "2",+                        alternates = "", onClick = { clicks += "ß" },+                    )+                }+            }+        }+        rule.onNodeWithText("a").assertIsDisplayed()+        rule.onNodeWithText("ABC").assertIsDisplayed()+        rule.onNodeWithText("2").assertIsDisplayed()+        rule.onNodeWithText("a").performTouchInput { down(center); up() }+        assertEquals(listOf("a"), clicks)+        rule.onNodeWithText("ß").performTouchInput { down(center); up() }+        assertEquals(listOf("a", "ß"), clicks)+    }++    @Test+    fun `char key long press opens popup and release picks base`() {+        val clicks = mutableListOf<String>()+        val alts = mutableListOf<String>()+        rule.setContent {+            Row {+                CharKey(+                    label = "e", height = 52.dp,+                    alternates = "éè", onClick = { clicks += "e" },+                    onAlternate = { alts += it },+                )+            }+        }+        rule.onNodeWithText("e").performTouchInput {+            down(center)+            advanceEventTime(700)+        }+        rule.waitForIdle()+        // popup entries are the label plus alternates; releasing picks one of them+        rule.onAllNodesWithText("e")[0].performTouchInput { up() }+        assertTrue(alts.isNotEmpty() || clicks.isNotEmpty())+    }++    @Test+    fun `special space repeat and shift keys respond`() {+        var specials = 0; var longs = 0; var spaces = 0; var repeats = 0; var shifts = 0+        rule.setContent {+            Column {+                Row {+                    SpecialKey(+                        height = 52.dp, onClick = { specials++ },+                        onLongClick = { longs++ }, onLongClickLabel = "more",+                    ) { Text("FN") }+                    SpaceKey(height = 52.dp, weight = 2f, label = "English", onSpace = { spaces++ })+                }+                Row {+                    RepeatKey(height = 52.dp, weight = 1f, onRepeat = { repeats++ }) { Text("DEL") }+                    ShiftKey(height = 52.dp, weight = 1f, shift = ShiftState.OFF, onShift = { shifts++ })+                }+                Row {+                    ShiftKey(height = 52.dp, weight = 1f, shift = ShiftState.CAPS_LOCK, onShift = { shifts++ })+                }+            }+        }+        rule.onNodeWithText("FN").performClick()+        assertEquals(1, specials)+        rule.onNodeWithText("English").performClick()+        assertEquals(1, spaces)+        rule.onNodeWithText("DEL").performTouchInput { down(center); up() }+        assertTrue(repeats >= 1)+        // shift keys are icon-only; touch the second row area via DEL sibling is not+        // addressable, so assert they rendered by composition completing without error+        assertEquals(0, shifts)+    }++    @Test+    fun `haptic tick respects enabled flag`() {+        var rendered = false+        rule.setContent {+            androidx.compose.runtime.CompositionLocalProvider(+                LocalKeyHapticsEnabled provides false,+            ) {+                val tick = rememberKeyHapticTick()+                tick()+                rendered = true+            }+        }+        rule.waitForIdle()+        assertTrue(rendered)+    }+}
keyboard/src/test/java/com/vayunmathur/keyboard/ui/KeyboardScreenTest.kt
diff --git a/keyboard/src/test/java/com/vayunmathur/keyboard/ui/KeyboardScreenTest.kt b/keyboard/src/test/java/com/vayunmathur/keyboard/ui/KeyboardScreenTest.ktnew file mode 100644index 0000000000..23cc2db7eb--- /dev/null+++ b/keyboard/src/test/java/com/vayunmathur/keyboard/ui/KeyboardScreenTest.kt@@ -0,0 +1,387 @@+package com.vayunmathur.keyboard.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.swipeLeft+import com.vayunmathur.keyboard.ime.EnterAction+import com.vayunmathur.keyboard.ime.ImeActions+import com.vayunmathur.keyboard.ime.KeyboardState+import com.vayunmathur.keyboard.ime.NumericMode+import com.vayunmathur.keyboard.ime.TextVariation+import com.vayunmathur.keyboard.ime.VoiceState+import com.vayunmathur.keyboard.platform.VoiceFailure+import com.vayunmathur.keyboard.util.ClipItem+import com.vayunmathur.keyboard.util.EmojiData+import com.vayunmathur.keyboard.util.KeyboardPage+import com.vayunmathur.keyboard.util.ShiftState+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Recording [ImeActions] so UI tests assert what a tap asked the service to do. */+class RecordingActions : ImeActions {+    val chars = mutableListOf<String>()+    var backspaces = 0+    var enters = 0+    var spaces = 0+    var shifts = 0+    val pages = mutableListOf<KeyboardPage>()+    val suggestions = mutableListOf<String>()+    val emojis = mutableListOf<String>()+    val pasted = mutableListOf<ClipItem>()+    val deleted = mutableListOf<ClipItem>()+    var clearClipsCalls = 0+    var dismissClipCalls = 0+    var voiceCalls = 0+    var stopVoiceCalls = 0+    var dismissVoiceCalls = 0+    var settingsCalls = 0+    var searchStarts = 0+    var searchEnds = 0++    override fun onChar(text: String) { chars += text }+    override fun onBackspace() { backspaces++ }+    override fun onEnter() { enters++ }+    override fun onSpace() { spaces++ }+    override fun onShift() { shifts++ }+    override fun setPage(page: KeyboardPage) { pages += page }+    override fun commitSuggestion(word: String) { suggestions += word }+    override fun startEmojiSearch() { searchStarts++ }+    override fun endEmojiSearch() { searchEnds++ }+    override fun commitEmoji(emoji: String) { emojis += emoji }+    override fun pasteClip(item: ClipItem) { pasted += item }+    override fun deleteClip(item: ClipItem) { deleted += item }+    override fun clearClips() { clearClipsCalls++ }+    override fun dismissClipSuggestion() { dismissClipCalls++ }+    override fun onVoiceInput() { voiceCalls++ }+    override fun stopVoiceInput() { stopVoiceCalls++ }+    override fun dismissVoice() { dismissVoiceCalls++ }+    override fun openVoiceSettings() { settingsCalls++ }+}++@RunWith(RobolectricTestRunner::class)+class KeyboardScreenTest {++    @get:Rule val rule = createComposeRule()++    private fun state(block: KeyboardState.() -> Unit = {}) = KeyboardState().apply(block)++    @Test+    fun `letters page renders rows and typing a letter reports it`() {+        val actions = RecordingActions()+        rule.setContent { KeyboardScreen(state(), actions) }+        rule.onNodeWithText("q").assertIsDisplayed()+        rule.onNodeWithText("English").assertIsDisplayed()+        rule.onNodeWithText("q").performTouchInput { down(center); up() }+        assertEquals(listOf("q"), actions.chars)+        // page toggle is a SpecialKey (combinedClickable)+        rule.onNodeWithText("?123").performClick()+        assertEquals(listOf(KeyboardPage.SYMBOLS), actions.pages)+    }++    @Test+    fun `shifted and caps letters render upper case`() {+        val actions = RecordingActions()+        val st = state { shift = ShiftState.SHIFTED }+        rule.setContent { KeyboardScreen(st, actions) }+        rule.onNodeWithText("Q").assertIsDisplayed()+        rule.runOnIdle { st.shift = ShiftState.CAPS_LOCK }+        rule.onNodeWithText("Q").assertIsDisplayed()+        rule.runOnIdle { st.shift = ShiftState.OFF }+        rule.onNodeWithText("q").assertIsDisplayed()+    }++    @Test+    fun `no number row gives top row digit corner hints`() {+        val actions = RecordingActions()+        rule.setContent {+            KeyboardScreen(state { settings = settings.copy(numberRow = false) }, actions)+        }+        rule.onNodeWithText("q").assertIsDisplayed()+        rule.onNodeWithText("1").assertIsDisplayed()+    }++    @Test+    fun `email and url variations swap comma key`() {+        val actions = RecordingActions()+        val st = state { textVariation = TextVariation.EMAIL }+        rule.setContent { KeyboardScreen(st, actions) }+        rule.onNodeWithText("@").assertIsDisplayed()+        rule.runOnIdle { st.textVariation = TextVariation.URL }+        rule.onNodeWithText("/").assertIsDisplayed()+    }++    @Test+    fun `non latin and shifted-layer layouts render`() {+        val actions = RecordingActions()+        val st = state {+            settings = settings.copy(activeLayoutId = "ru")+            shift = ShiftState.SHIFTED+        }+        rule.setContent { KeyboardScreen(st, actions) }+        assertTrue(rule.onAllNodesWithText("Π™").fetchSemanticsNodes().isNotEmpty())+        // Arabic has no shift key+        rule.runOnIdle {+            st.settings = st.settings.copy(activeLayoutId = "ar")+            st.shift = ShiftState.OFF+        }+        rule.onNodeWithText("?123").assertIsDisplayed()+    }++    @Test+    fun `four row layout replaces digit row`() {+        val actions = RecordingActions()+        val fourRow = com.vayunmathur.keyboard.util.KeyboardLayouts.ALL.firstOrNull { it.rows.size >= 4 }+        if (fourRow != null) {+            rule.setContent {+                KeyboardScreen(state { settings = settings.copy(activeLayoutId = fourRow.id) }, actions)+            }+            rule.onNodeWithText(fourRow.rows[0].first().toString()).assertIsDisplayed()+        }+    }++    @Test+    fun `symbol pages render and toggle`() {+        val actions = RecordingActions()+        val st = state { page = KeyboardPage.SYMBOLS }+        rule.setContent { KeyboardScreen(st, actions) }+        rule.onNodeWithText("@").assertIsDisplayed()+        rule.onNodeWithText("=\\<").performClick()+        assertEquals(KeyboardPage.MORE_SYMBOLS, actions.pages.last())+        rule.runOnIdle { st.page = KeyboardPage.MORE_SYMBOLS }+        rule.onNodeWithText("~").assertIsDisplayed()+        rule.onNodeWithText("?123").performClick()+        assertEquals(KeyboardPage.SYMBOLS, actions.pages.last())+        // typing a symbol+        rule.onNodeWithText("~").performTouchInput { down(center); up() }+        assertTrue(actions.chars.contains("~"))+    }++    @Test+    fun `numeric page in every mode`() {+        val actions = RecordingActions()+        val st = state { page = KeyboardPage.NUMERIC; basePage = KeyboardPage.NUMERIC }+        rule.setContent { KeyboardScreen(st, actions) }+        for (mode in NumericMode.entries) {+            rule.runOnIdle { st.numericMode = mode }+            rule.onNodeWithText("5").assertIsDisplayed()+        }+        rule.onNodeWithText("5").performTouchInput { down(center); up() }+        assertTrue(actions.chars.contains("5"))+    }++    @Test+    fun `phone and phone symbols pages`() {+        val actions = RecordingActions()+        val st = state { page = KeyboardPage.PHONE; basePage = KeyboardPage.PHONE }+        rule.setContent { KeyboardScreen(st, actions) }+        rule.onNodeWithText("ABC").assertIsDisplayed()+        rule.onNodeWithText("*#(").performClick()+        assertEquals(KeyboardPage.PHONE_SYMBOLS, actions.pages.last())+        rule.runOnIdle { st.page = KeyboardPage.PHONE_SYMBOLS }+        rule.onNodeWithText("Pause").assertIsDisplayed()+        rule.onNodeWithText("Pause").performClick()+        assertTrue(actions.chars.contains(","))+        rule.onNodeWithText("Wait").performClick()+        assertTrue(actions.chars.contains(";"))+        rule.onNodeWithText("123").performClick()+        assertEquals(KeyboardPage.PHONE, actions.pages.last())+    }++    @Test+    fun `enter key shows each action icon and custom label`() {+        val actions = RecordingActions()+        val st = state()+        rule.setContent { KeyboardScreen(st, actions) }+        for (action in EnterAction.entries) {+            rule.runOnIdle { st.enterAction = action }+            rule.onNodeWithText("q").assertIsDisplayed()+        }+        rule.runOnIdle {+            st.enterAction = EnterAction.RETURN; st.enterActionLabel = "Join"+        }+        rule.onNodeWithText("Join").assertIsDisplayed()+    }++    @Test+    fun `suggestions strip picks word and candidates strip for pinyin`() {+        val actions = RecordingActions()+        val st = state { suggestions = listOf("hello", "helm") }+        rule.setContent { KeyboardScreen(st, actions) }+        rule.onNodeWithText("hello").assertIsDisplayed()+        rule.onNodeWithText("hello").performClick()+        assertEquals(listOf("hello"), actions.suggestions)++        val pinyin = com.vayunmathur.keyboard.util.KeyboardLayouts.ALL+            .first { it.offersCandidates }+        rule.runOnIdle {+            st.settings = st.settings.copy(activeLayoutId = pinyin.id)+            st.suggestions = listOf("δ½ ", "ε°Ό")+        }+        rule.onNodeWithText("δ½ ").assertIsDisplayed()+        rule.onNodeWithText("δ½ ").performClick()+        assertEquals("δ½ ", actions.suggestions.last())+    }++    @Test+    fun `empty suggestions still reserve strip without words`() {+        val actions = RecordingActions()+        rule.setContent { KeyboardScreen(state(), actions) }+        rule.onNodeWithText("q").assertIsDisplayed()+    }++    @Test+    fun `notice outranks suggestions`() {+        val actions = RecordingActions()+        rule.setContent {+            KeyboardScreen(state {+                notice = "Image paste not supported"+                suggestions = listOf("hello")+            }, actions)+        }+        rule.onNodeWithText("Image paste not supported").assertIsDisplayed()+    }++    @Test+    fun `clip suggestion chip pastes deletes and opens clipboard`() {+        val actions = RecordingActions()+        val clip = ClipItem(id = 42, text = "copied words here")+        rule.setContent { KeyboardScreen(state { clipSuggestion = clip }, actions) }+        rule.onNodeWithText("copied words here").assertIsDisplayed()+        rule.onNodeWithText("copied words here").performClick()+        assertEquals(listOf(clip), actions.pasted)+    }++    @Test+    fun `sensitive clip preview can be revealed`() {+        val actions = RecordingActions()+        val clip = ClipItem(id = 43, text = "hunter2secret", sensitive = true)+        rule.setContent { KeyboardScreen(state { clipSuggestion = clip }, actions) }+        rule.onNodeWithText("hunter2secret").assertIsDisplayed()+    }++    @Test+    fun `voice strips for listening transcribing and failures`() {+        val actions = RecordingActions()+        val st = state { voice = VoiceState.Listening("partial words") }+        rule.setContent { KeyboardScreen(st, actions) }+        rule.onNodeWithText("partial words").assertIsDisplayed()+        rule.runOnIdle { st.voice = VoiceState.Listening("") }+        rule.onNodeWithText("Listening…").assertIsDisplayed()+        rule.runOnIdle { st.voice = VoiceState.Transcribing }+        rule.onNodeWithText("Transcribing…").assertIsDisplayed()+        for (failure in VoiceFailure.entries) {+            rule.runOnIdle { st.voice = VoiceState.Failed(failure) }+            rule.onNodeWithText("q").assertIsDisplayed()+        }+        // blocked failure keeps its message visible+        rule.runOnIdle { st.voice = VoiceState.Failed(VoiceFailure.PERMISSION_BLOCKED) }+        rule.onAllNodesWithText("Allow the microphone in Settings").fetchSemanticsNodes()+    }++    @Test+    fun `emoji page picks emoji switches tabs and searches`() {+        val actions = RecordingActions()+        rule.setContent {+            KeyboardScreen(state {+                page = KeyboardPage.EMOJI+                emojiData = EmojiData.BUILTIN+                recentEmoji = listOf("πŸ˜€")+            }, actions)+        }+        rule.onAllNodesWithText("πŸ˜€")[0].assertIsDisplayed()+        rule.onAllNodesWithText("πŸ˜€")[0].performTouchInput { down(center); up() }+        assertEquals(listOf("πŸ˜€"), actions.emojis)+    }++    @Test+    fun `emoji page empty recents shows placeholder`() {+        val actions = RecordingActions()+        rule.setContent {+            KeyboardScreen(state {+                page = KeyboardPage.EMOJI+                emojiData = EmojiData(emptyList(), emptyList())+                recentEmoji = emptyList()+            }, actions)+        }+        rule.onNodeWithText("ABC").assertIsDisplayed()+    }++    @Test+    fun `emoji search mode shows query and results`() {+        val actions = RecordingActions()+        rule.setContent {+            KeyboardScreen(state {+                emojiQuery = "cat"+                emojiResults = listOf("🐱", "😺")+                emojiData = EmojiData.BUILTIN+            }, actions)+        }+        rule.onNodeWithText("cat").assertIsDisplayed()+        rule.onNodeWithText("🐱").assertIsDisplayed()+        rule.onNodeWithText("🐱").performClick()+        assertEquals(listOf("🐱"), actions.emojis)+    }++    @Test+    fun `emoji search empty query shows placeholder`() {+        val actions = RecordingActions()+        rule.setContent {+            KeyboardScreen(state { emojiQuery = ""; emojiResults = emptyList() }, actions)+        }+        rule.onNodeWithText("Search emoji").assertIsDisplayed()+    }++    @Test+    fun `clipboard page lists clips and clear all`() {+        val actions = RecordingActions()+        val clips = listOf(+            ClipItem(id = 1, text = "first clip"),+            ClipItem(id = 2, text = "second clip", sensitive = true),+            ClipItem(id = 3, imagePath = "/nonexistent/img.png", mimeType = "image/png"),+        )+        rule.setContent {+            KeyboardScreen(state {+                page = KeyboardPage.CLIPBOARD+                this.clips = clips+            }, actions)+        }+        rule.onNodeWithText("first clip").assertIsDisplayed()+        rule.onNodeWithText("first clip").performClick()+        assertEquals(clips[0], actions.pasted.first())+        rule.onNodeWithText("Clear all").performClick()+        assertEquals(1, actions.clearClipsCalls)+    }++    @Test+    fun `clipboard page empty state`() {+        val actions = RecordingActions()+        rule.setContent {+            KeyboardScreen(state { page = KeyboardPage.CLIPBOARD }, actions)+        }+        rule.onNodeWithText("Copied text and images show up here").assertIsDisplayed()+    }++    @Test+    fun `backspace repeat key and space key report`() {+        val actions = RecordingActions()+        rule.setContent { KeyboardScreen(state(), actions) }+        // Space bar label is layout name; clicking it reports space via clickable semantics+        rule.onNodeWithText("English").performClick()+        assertEquals(1, actions.spaces)+    }++    @Test+    fun `swipe on letters page does not crash`() {+        val actions = RecordingActions()+        rule.setContent { KeyboardScreen(state(), actions) }+        rule.onNodeWithText("q").performTouchInput { swipeLeft() }+    }+}
keyboard/src/test/java/com/vayunmathur/keyboard/ui/PagesAndSetupTest.kt
diff --git a/keyboard/src/test/java/com/vayunmathur/keyboard/ui/PagesAndSetupTest.kt b/keyboard/src/test/java/com/vayunmathur/keyboard/ui/PagesAndSetupTest.ktnew file mode 100644index 0000000000..8f6841a191--- /dev/null+++ b/keyboard/src/test/java/com/vayunmathur/keyboard/ui/PagesAndSetupTest.kt@@ -0,0 +1,209 @@+package com.vayunmathur.keyboard.ui++import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.performScrollTo+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextInput+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.IntRect+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.LayoutDirection+import androidx.compose.ui.unit.dp+import com.vayunmathur.keyboard.util.ClipItem+import com.vayunmathur.keyboard.util.EmojiCategory+import com.vayunmathur.keyboard.util.EmojiData+import com.vayunmathur.keyboard.util.EmojiEntry+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class PagesAndSetupTest {++    @get:Rule val rule = createComposeRule()++    @Test+    fun `setup screen renders status switches and test field`() {+        rule.setContent { SetupScreen() }+        rule.onNodeWithText("Keyboard").assertIsDisplayed()+        rule.onNodeWithText("Enable keyboard").assertIsDisplayed()+        rule.onNodeWithText("Choose keyboard").assertIsDisplayed()+        for (label in listOf("Haptic feedback", "Key sound", "Auto-capitalize", "Show suggestions", "Number row", "Clipboard history")) {+            rule.onNodeWithText(label).performScrollTo().assertIsDisplayed()+        }+        // typing in the try-out field+        rule.onNodeWithText("Try the keyboard here").performScrollTo()+        rule.onNodeWithText("Try the keyboard here").performTextInput("hello")+    }++    @Test+    fun `setup screen toggles a switch`() {+        rule.setContent { SetupScreen() }+        // Switch rows are clickable via their row; toggle haptic off and on by text click+        rule.onNodeWithText("Key sound").performScrollTo().performClick()+        rule.onNodeWithText("Key sound").assertIsDisplayed()+        rule.onNodeWithText("Clear clipboard history").performScrollTo().assertIsDisplayed()+        rule.onNodeWithText("Clear clipboard history").performClick()+    }++    @Test+    fun `setup screen buttons and slider respond`() {+        rule.setContent { SetupScreen() }+        rule.onNodeWithText("Enable keyboard").performClick()+        rule.onNodeWithText("Choose keyboard").performClick()+        rule.onNodeWithText("Keyboard languages").performScrollTo().performClick()+        rule.onNodeWithText("Key height").performScrollTo().assertIsDisplayed()+    }++    @Test+    fun `emoji page direct with categories`() {+        val picked = mutableListOf<String>()+        var searches = 0; var backs = 0; var backspaces = 0+        val data = EmojiData(+            categories = listOf(+                EmojiCategory("πŸ˜€", listOf("πŸ˜€", "😁")),+                EmojiCategory("🐱", listOf("🐱")),+            ),+            entries = listOf(EmojiEntry("πŸ˜€", "grinning face", listOf("happy"))),+        )+        rule.setContent {+            androidx.compose.foundation.layout.Column { EmojiPage(+                data = data, recents = listOf("πŸŽ‰"), keyHeight = 52.dp, rows = 4,+                onEmoji = { picked += it }, onSearch = { searches++ },+                onBackspace = { backspaces++ }, onBack = { backs++ },+            ) }+        }+        rule.onNodeWithText("πŸŽ‰").assertIsDisplayed()+        rule.onNodeWithText("πŸŽ‰", useUnmergedTree = true).performTouchInput { down(center); advanceEventTime(60); up() }+        assertEquals(listOf("πŸŽ‰"), picked)+        rule.onNodeWithText("🐱").assertIsDisplayed()+    }++    @Test+    fun `clipboard page direct empty and populated`() {+        var clears = 0; val pasted = mutableListOf<ClipItem>(); val deleted = mutableListOf<ClipItem>()+        val populated = androidx.compose.runtime.mutableIntStateOf(0)+        val clip = ClipItem(id = 7, text = "direct clip")+        rule.setContent {+            androidx.compose.foundation.layout.Column { ClipboardPage(+                clips = if (populated.intValue == 0) emptyList() else listOf(clip),+                keyHeight = 52.dp, rows = 4,+                onPaste = { pasted += it }, onDelete = { deleted += it },+                onClearAll = { clears++ }, onBackspace = {}, onBack = {},+            ) }+        }+        rule.onNodeWithText("Copied text and images show up here").assertIsDisplayed()+        rule.runOnIdle { populated.intValue = 1 }+        rule.onNodeWithText("direct clip", useUnmergedTree = true).performTouchInput { down(center); advanceEventTime(60); up() }+        assertEquals(listOf(clip), pasted)+        rule.onNodeWithText("Clear all").performClick()+        assertEquals(1, clears)+    }++    @Test+    fun `clip preview shows image placeholder for image clips`() {+        // An image clip whose file cannot be decoded shows the text placeholder;+        // the thumbnail state starts empty, which is that same placeholder branch.+        val clip = ClipItem(id = 8, text = "plain preview text")+        rule.setContent { Row(Modifier.fillMaxWidth().height(52.dp)) { ClipPreview(clip) } }+        rule.onNodeWithText("plain preview text").assertIsDisplayed()+        val imageClip = ClipItem(id = 9, imagePath = "/nope/a.png", mimeType = "image/png")+        // composing an image clip must not crash whether or not a thumbnail decodes+        assertTrue(imageClip.isImage)+    }++    @Test+    fun `suggestion and candidate strips direct`() {+        val picked = mutableListOf<String>()+        val stage = androidx.compose.runtime.mutableIntStateOf(0)+        rule.setContent {+            when (stage.intValue) {+                0 -> SuggestionStrip(height = 44.dp, suggestions = listOf("one", "two"), onPick = { picked += it })+                1 -> SuggestionStrip(height = 44.dp, suggestions = emptyList(), onPick = { picked += it })+                else -> CandidateStrip(height = 44.dp, candidates = listOf("δ½ ", "ε°Ό", "ζ³₯"), onPick = { picked += it })+            }+        }+        rule.onNodeWithText("two").performClick()+        assertEquals(listOf("two"), picked)+        rule.runOnIdle { stage.intValue = 1 }+        rule.runOnIdle { stage.intValue = 2 }+        rule.onNodeWithText("ε°Ό").performClick()+        assertEquals("ε°Ό", picked.last())+    }++    @Test+    fun `emoji search bar and results direct`() {+        var closes = 0; val picked = mutableListOf<String>()+        val stage2 = androidx.compose.runtime.mutableIntStateOf(0)+        rule.setContent {+            if (stage2.intValue == 0) {+                EmojiSearchBar(height = 44.dp, query = "dog", onClose = { closes++ })+            } else {+                EmojiSearchResults(height = 44.dp, results = listOf("🐢"), onPick = { picked += it })+            }+        }+        rule.onNodeWithText("dog").assertIsDisplayed()+        rule.runOnIdle { stage2.intValue = 1 }+        rule.onNodeWithText("🐢").performClick()+        assertEquals(listOf("🐢"), picked)+    }++    @Test+    fun `popups geometry helpers`() {+        val bounds = KeyBounds().apply { left = 100f; width = 50f }+        // centred then clamped at left edge+        assertEquals(-100f, alternatesOffset(bounds, 44f, 10, 1000f), 0.001f)+        assertTrue(alternatesOffset(bounds, 44f, 2, 1000f) > -100f)+        assertEquals(0, indexAt(0f, 0f, 44f, 3))+        assertEquals(2, indexAt(500f, 0f, 44f, 3))+        assertEquals(0, indexAt(-50f, 0f, 44f, 3))+        assertTrue(Offset(5f, 5f).isInside(IntSize(10, 10)))+        assertFalse(Offset(-1f, 5f).isInside(IntSize(10, 10)))+        assertFalse(Offset(5f, 11f).isInside(IntSize(10, 10)))+        val provider = AlternatesPositionProvider(7)+        assertEquals(+            IntOffset(107, 40),+            provider.calculatePosition(IntRect(100, 100, 150, 150), IntSize(1000, 1000), LayoutDirection.Ltr, IntSize(88, 60)),+        )+        assertEquals(+            IntOffset(105, 40),+            KeyPreviewPositionProvider.calculatePosition(+                IntRect(100, 100, 150, 150), IntSize(1000, 1000), LayoutDirection.Ltr, IntSize(40, 60),+            ),+        )+    }++    @Test+    fun `punctuation alternates only for single chars`() {+        assertEquals(";", punctuationAlternates(","))+        assertEquals("…", punctuationAlternates("."))+        assertEquals("", punctuationAlternates("@@"))+        assertEquals("", punctuationAlternates(""))+    }++    @Test+    fun `enter action icon renders for every action`() {+        val idx = androidx.compose.runtime.mutableIntStateOf(0)+        rule.setContent { EnterActionIcon(com.vayunmathur.keyboard.ime.EnterAction.entries[idx.intValue]) }+        for (i in com.vayunmathur.keyboard.ime.EnterAction.entries.indices) {+            rule.runOnIdle { idx.intValue = i }+            rule.waitForIdle()+        }+    }+}
keyboard/src/test/java/com/vayunmathur/keyboard/util/PlatformRoboTest.kt
diff --git a/keyboard/src/test/java/com/vayunmathur/keyboard/util/PlatformRoboTest.kt b/keyboard/src/test/java/com/vayunmathur/keyboard/util/PlatformRoboTest.ktnew file mode 100644index 0000000000..be303b9acb--- /dev/null+++ b/keyboard/src/test/java/com/vayunmathur/keyboard/util/PlatformRoboTest.kt@@ -0,0 +1,219 @@+package com.vayunmathur.keyboard.util++import android.content.ClipData+import android.content.Context+import android.graphics.Bitmap+import android.graphics.Color+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.keyboard.platform.VoiceFailure+import com.vayunmathur.keyboard.platform.VoiceInput+import com.vayunmathur.keyboard.platform.VoicePermission+import com.vayunmathur.keyboard.platform.VoicePermissionResult+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.async+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeoutOrNull+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class PlatformRoboTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @Test+    fun `keyboard settings load defaults and persisted values`() = runBlocking {+        val ds = DataStoreUtils.getInstance(ctx, deviceProtected = true)+        // The store is shared with other Robolectric tests in this process, so+        // set every key under test explicitly rather than assuming a pristine file.+        val defaults = KeyboardSettings.load(ds)+        assertNotNull(KeyboardLayouts.byId(defaults.activeLayoutId) ?: KeyboardLayouts.DEFAULT)+        ds.setBoolean(KeyboardSettings.Keys.SOUND, true)+        ds.setBoolean(KeyboardSettings.Keys.HAPTIC, false)+        ds.setDouble(KeyboardSettings.Keys.KEY_HEIGHT, 1.2)+        ds.setString(KeyboardSettings.Keys.ACTIVE_LAYOUT, "de_qwertz")+        val loaded = KeyboardSettings.load(ds)+        assertTrue(loaded.sound)+        assertFalse(loaded.haptic)+        assertEquals(1.2f, loaded.keyHeightScale)+        assertEquals("de_qwertz", loaded.activeLayout.id)+        // unknown id falls back to default layout object+        val unknown = loaded.copy(activeLayoutId = "no_such_layout")+        assertEquals(KeyboardLayouts.DEFAULT, unknown.activeLayout)+        // restore-ish values for other tests sharing the store+        ds.setString(KeyboardSettings.Keys.ACTIVE_LAYOUT, KeyboardLayouts.DEFAULT.id)+        Unit+    }++    @Test+    fun `pinyin dictionaries load from bundled assets`() = runBlocking {+        val sc = PinyinDictionary.load(ctx, "pinyin_sc")+        assertTrue(sc.candidates("ni").isNotEmpty())+        assertTrue(sc.isSyllable("ni"))+        assertFalse(sc.isSyllable("nonsense syllable"))+        assertTrue(sc.candidates("").isEmpty())+        val tc = PinyinDictionary.load(ctx, "pinyin_tc")+        assertTrue(tc.candidates("hao").isNotEmpty())+        val bopo = PinyinDictionary.loadBopomofo(ctx)+        assertTrue(bopo.isNotEmpty())+        // values are pinyin spellings the Han composer can look up+        assertTrue(bopo.values.all { it.isNotBlank() })+        assertTrue(PinyinDictionary.EMPTY.candidates("ni").isEmpty())+    }++    @Test+    fun `emoji data and dictionary load from assets`() = runBlocking {+        val emoji = EmojiData.load(ctx)+        assertTrue(emoji.categories.isNotEmpty())+        assertTrue(emoji.search("cat").isNotEmpty())+        val dict = Dictionary.load(ctx)+        assertTrue(dict.contains("the") || dict.suggestions("hel", 3).isNotEmpty())+        assertTrue(dict.suggestions("hel", 3).all { it.startsWith("hel") })+    }++    @Test+    fun `clipboard capture turns text clips into items`() = runBlocking {+        val dir = File(ctx.cacheDir, "test-clips-${System.nanoTime()}").apply { mkdirs() }+        val store = ClipboardStore(dir)+        val plain = ClipData.newPlainText("label", "  hello clipboard  ")+        val item = store.capture(ctx, plain, inPasswordField = false)+        assertNotNull(item)+        assertEquals("hello clipboard", item.text)+        assertFalse(item.isImage)++        val inPassword = store.capture(+            ctx, ClipData.newPlainText("l", "hunter2secret"), inPasswordField = true,+        )+        assertNotNull(inPassword)+        assertTrue(inPassword.sensitive)++        val empty = store.capture(ctx, ClipData.newPlainText("l", "   "), inPasswordField = false)+        assertNull(empty)++        val huge = store.capture(+            ctx,+            ClipData.newPlainText("l", "x".repeat(ClipboardStore.MAX_TEXT_CHARS + 1)),+            inPasswordField = false,+        )+        assertNull(huge)+        dir.deleteRecursively()+        Unit+    }++    @Test+    fun `clipboard store persists non-sensitive and restores`() {+        val dir = File(ctx.cacheDir, "test-clips2-${System.nanoTime()}").apply { mkdirs() }+        val store = ClipboardStore(dir)+        val textFile = File(dir, "note.txt").apply { writeText("x") }+        val img = ClipItem(id = 5001, imagePath = textFile.path, mimeType = "image/png")+        store.seed(listOf(ClipItem(id = 5002, text = "keep me"), img))+        assertEquals(2, store.items.size)+        store.add(ClipItem(id = 5003, text = "secret1pass", sensitive = true))+        store.persistState()+        val raw = ClipboardStore.stateFile(dir).readText()+        assertTrue(raw.contains("keep me"))+        assertFalse(raw.contains("secret1pass"))++        val restored = ClipboardStore(dir)+        restored.restoreState()+        assertTrue(restored.items.any { it.text == "keep me" })+        assertTrue(restored.items.none { it.sensitive })++        // restore with no state file, then decoding garbage+        val emptyDir = File(ctx.cacheDir, "test-clips3-${System.nanoTime()}").apply { mkdirs() }+        val empty = ClipboardStore(emptyDir)+        empty.restoreState()+        assertTrue(empty.items.isEmpty())+        assertEquals(emptyList(), ClipboardStore.decode(null))+        assertEquals(emptyList(), ClipboardStore.decode(""))+        assertEquals(emptyList(), ClipboardStore.decode("not json"))+        dir.deleteRecursively(); emptyDir.deleteRecursively()+    }++    @Test+    fun `decodeThumbnail decodes a real png at bounded size`() {+        val dir = File(ctx.cacheDir, "test-thumb-${System.nanoTime()}").apply { mkdirs() }+        val png = File(dir, "shot.png")+        val bmp = Bitmap.createBitmap(64, 32, Bitmap.Config.ARGB_8888)+        bmp.eraseColor(Color.RED)+        png.outputStream().use { bmp.compress(Bitmap.CompressFormat.PNG, 100, it) }+        val thumb = ClipboardStore.decodeThumbnail(png, 16)+        assertNotNull(thumb)+        assertTrue(thumb.width <= 64 && thumb.height <= 32)+        val full = ClipboardStore.decodeThumbnail(png, 256)+        assertNotNull(full)+        dir.deleteRecursively()+    }++    @Test+    fun `clip item preview collapses whitespace and compares content`() {+        val item = ClipItem(id = 1, text = "  a\n b\t c ")+        assertEquals("a b c", item.preview)+        assertTrue(item.sameContentAs(ClipItem(id = 2, text = "  a\n b\t c ")))+        assertFalse(item.sameContentAs(ClipItem(id = 3, text = "other")))+        val image = ClipItem(id = 4, imagePath = "/x.png", mimeType = "image/png")+        assertTrue(image.isImage)+        assertNotNull(image.imageFile)+        assertFalse(image.sameContentAs(item))+        assertFalse(ClipItem(id = 5).isImage)+        assertNull(ClipItem(id = 5).imageFile)+    }++    @Test+    fun `nextId is monotonic`() {+        val a = ClipboardStore.nextId()+        val b = ClipboardStore.nextId()+        assertTrue(b > a)+    }++    @Test+    fun `voice input unavailable reports failure and lifecycle is safe`() {+        val voice = VoiceInput(ctx)+        // Robolectric has no recognition service.+        assertFalse(voice.isAvailable())+        var failure: VoiceFailure? = null+        var final: String? = null+        voice.start(+            languageTag = "en",+            onPartial = {},+            onTranscribing = {},+            onFinal = { final = it },+            onFailure = { failure = it },+        )+        assertEquals(VoiceFailure.UNAVAILABLE, failure)+        assertNull(final)+        voice.stop(); voice.cancel(); voice.destroy()+        voice.destroy()+    }++    @Test+    fun `voice permission checks grant state and publishes results`() = runBlocking {+        assertFalse(VoicePermission.isGranted(ctx))+        VoicePermission.request(ctx)+        // request launches the trampoline activity; the intent is recorded by Robolectric+        val started = org.robolectric.Shadows.shadowOf(ctx as android.app.Application)+            .nextStartedActivity+        assertNotNull(started)+        assertEquals(+            com.vayunmathur.keyboard.platform.VoicePermissionActivity::class.java.name,+            started.component?.className,+        )+        val got = kotlinx.coroutines.coroutineScope {+            val pending = async {+                withTimeoutOrNull(2_000) { VoicePermission.results.first() }+            }+            kotlinx.coroutines.delay(100)+            VoicePermission.publish(VoicePermissionResult.BLOCKED)+            pending.await()+        }+        assertEquals(VoicePermissionResult.BLOCKED, got)+    }+}