Modern Apps git

← Modern-Apps.git

keyboard: several bug fixes

Commit
27abf4ced1ddb5e5ca27e35f93ef03883828ba1a
Author
vayun-mathur <[email protected]>
When
2026-09-25 17:29 UTC (2 months ago)
Parents
d798001

Diff

keyboard/src/main/AndroidManifest.xml
diff --git a/keyboard/src/main/AndroidManifest.xml b/keyboard/src/main/AndroidManifest.xmlindex 3de0a89551..4b2f86be1b 100644--- a/keyboard/src/main/AndroidManifest.xml+++ b/keyboard/src/main/AndroidManifest.xml@@ -60,7 +60,7 @@          <provider             android:name="androidx.core.content.FileProvider"-            android:authorities="com.vayunmathur.keyboard.fileprovider"+            android:authorities="${applicationId}.fileprovider"             android:exported="false"             android:grantUriPermissions="true">             <meta-data
keyboard/src/main/java/com/vayunmathur/keyboard/ime/KeyboardService.kt
diff --git a/keyboard/src/main/java/com/vayunmathur/keyboard/ime/KeyboardService.kt b/keyboard/src/main/java/com/vayunmathur/keyboard/ime/KeyboardService.ktindex 954494c253..cf9ae852ed 100644--- a/keyboard/src/main/java/com/vayunmathur/keyboard/ime/KeyboardService.kt+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/ime/KeyboardService.kt@@ -45,6 +45,7 @@ import com.vayunmathur.keyboard.platform.VoiceInput import com.vayunmathur.keyboard.platform.VoicePermission import com.vayunmathur.keyboard.platform.VoicePermissionResult import com.vayunmathur.keyboard.ui.KeyboardScreen+import com.vayunmathur.keyboard.R import com.vayunmathur.keyboard.util.ClipItem import com.vayunmathur.keyboard.util.ClipboardStore import com.vayunmathur.keyboard.util.ComposerKind@@ -66,6 +67,7 @@ import kotlinx.coroutines.cancel import kotlinx.coroutines.delay import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext import java.io.File  /**@@ -88,6 +90,18 @@ private const val VOICE_MESSAGE_MS = 6_000L /** How long a granted microphone still counts as "the user just asked for dictation". */ private const val VOICE_GRANT_MS = 30_000L +/** How long a strip notice (e.g. image paste refused) stays up before clearing itself. */+private const val NOTICE_MS = 4_000L++/**+ * Layouts that stay registered as framework subtypes on platforms below API 34 even when+ * they share a language prefix with another layout. Same-language *arrangements* (QWERTY+ * vs Dvorak) collapse to one entry there because the platform cannot label them apart, but+ * these are different inputs, not different arrangements: hiding one would remove a script+ * the user cannot reach any other way.+ */+private val PRE34_DISTINCT_LAYOUTS = setOf("zh_pinyin", "zh_pinyin_tc", "ja_romaji", "ja_kana", "tr_q", "tr_f")+ class KeyboardService : InputMethodService(),     LifecycleOwner, ViewModelStoreOwner, SavedStateRegistryOwner, ImeActions { @@ -105,9 +119,15 @@ class KeyboardService : InputMethodService(),     private val kbState = KeyboardState()     private var dictionary: Dictionary = Dictionary.EMPTY +    // Credential-encrypted cache, like before: pre-unlock the files are unreadable rather+    // than readable-without-a-passcode, so clipboard I/O below tolerates failure and the+    // history is simply unavailable until first unlock (see onCreate/restoreState).     private val clipboard by lazy { ClipboardStore(File(cacheDir, "clips")) }     private var clipListener: ClipboardManager.OnPrimaryClipChangedListener? = null +    /** Clears a strip notice after a while; cancelled by the next notice. */+    private var noticeJob: Job? = null+     /** Id of the clip the chip is currently offering, so a stale timeout can't clear a newer one. */     private var chipClipId = 0L @@ -179,9 +199,13 @@ class KeyboardService : InputMethodService(),         scope.launch { dictionary = Dictionary.load(this@KeyboardService) }         scope.launch { kbState.emojiData = EmojiData.load(this@KeyboardService) }         kbState.recentEmoji = RecentEmoji.decode(ds.getString(KeyboardSettings.Keys.EMOJI_RECENTS))-        scope.launch {-            clipboard.restore(ds.getString(KeyboardSettings.Keys.CLIPS))-            kbState.clips = clipboard.items+        scope.launch(Dispatchers.IO) {+            migrateLegacyClips()+            // Pre-unlock (direct boot) credential-encrypted storage is unreadable;+            // the history then stays empty until the next start rather than crashing.+            runCatching { clipboard.restoreState() }+            val items = clipboard.items+            withContext(Dispatchers.Main) { kbState.clips = items }         }         observeClipboard()         syncComposer()@@ -206,10 +230,23 @@ class KeyboardService : InputMethodService(),                 if (!it) forgetClips()             }         }-        // Settings can wipe the history while the keyboard is running; an empty stored value-        // is that request. Nothing here writes a blank string back, so this cannot loop.+        // Settings wipes the history by bumping the wipe counter; a counter (not a blank+        // string) means the one-time legacy migration below can clear the old key without+        // looking like a wipe request. The first emission is the stored value, not a request.         scope.launch {-            ds.stringFlow(keys.CLIPS).collectLatest { if (it.isBlank()) forgetClips() }+            var first = true+            var seen = 0L+            ds.longFlow(keys.CLIPS_WIPE, 0L).collectLatest {+                if (first) {+                    seen = it+                    first = false+                    return@collectLatest+                }+                if (it > seen) {+                    seen = it+                    forgetClips()+                }+            }         }         scope.launch { ds.doubleFlow(keys.KEY_HEIGHT).collectLatest { update { copy(keyHeightScale = it.toFloat()) } } }         scope.launch {@@ -322,7 +359,9 @@ class KeyboardService : InputMethodService(),     }      private fun deleteBackward(ic: InputConnection) {-        ic.deleteSurroundingText(1, 0)+        // Code points, not Java chars: a single emoji is two UTF-16 units, and+        // deleting one unit leaves a lone surrogate (�) in the field.+        ic.deleteSurroundingTextInCodePoints(1, 0)         before.deleted()     } @@ -699,20 +738,19 @@ class KeyboardService : InputMethodService(),         feedback()         // Apply shift immediately on every tap; a quick second tap (while already shifted)         // latches caps-lock. No waiting for a double-tap, so shift feels instant.+        // A rapid tap while latched unlatches: without it the third tap of a+        // triple-tap re-latched and caps-lock had no quick exit.         val now = SystemClock.uptimeMillis()+        val rapid = now - lastShiftTime < DOUBLE_TAP_MS         kbState.shift = when {-            now - lastShiftTime < DOUBLE_TAP_MS && kbState.shift != ShiftState.OFF -> ShiftState.CAPS_LOCK+            kbState.shift == ShiftState.CAPS_LOCK && rapid -> ShiftState.OFF+            rapid && kbState.shift != ShiftState.OFF -> ShiftState.CAPS_LOCK             kbState.shift == ShiftState.OFF -> ShiftState.SHIFTED             else -> ShiftState.OFF         }         lastShiftTime = now     } -    override fun onCapsLock() {-        feedback()-        kbState.shift = ShiftState.CAPS_LOCK-    }-     override fun setPage(page: KeyboardPage) {         feedback()         if (kbState.emojiQuery != null) {@@ -750,9 +788,11 @@ class KeyboardService : InputMethodService(),      * Several layouts can share a language (English alone has QWERTY, Dvorak, Colemak…), so      * each subtype needs a distinct name to be tellable apart in the enabler. Naming a      * subtype requires [InputMethodSubtypeBuilder.setSubtypeNameOverride], added in API 34;-     * below that the extra same-language variants are not registered at all (rather than-     * showing several indistinguishable "English" entries), so each language appears once-     * via its primary variant.+     * below that the extra same-language *arrangements* are not registered (rather than+     * showing several indistinguishable "English" entries), but layouts that are different+     * inputs rather than different arrangements — simplified vs traditional, romaji vs kana,+     * Q vs F — are kept, via [PRE34_DISTINCT_LAYOUTS]. The fallback name resource keeps+     * the entry labelled on old platforms instead of rendering blank.      */     private fun registerLayoutSubtypes() {         val imm = getSystemService(InputMethodManager::class.java) ?: return@@ -764,8 +804,10 @@ class KeyboardService : InputMethodService(),         val layouts = if (nameable) {             KeyboardLayouts.ALL         } else {-            // One layout per language code (first = primary variant, e.g. en_qwerty, tr_q).-            KeyboardLayouts.ALL.groupBy { it.id.substringBefore('_') }.map { it.value.first() }+            val seen = HashSet<String>()+            KeyboardLayouts.ALL.filter { layout ->+                layout.id in PRE34_DISTINCT_LAYOUTS || seen.add(layout.id.substringBefore('_'))+            }         }         val map = LinkedHashMap<String, InputMethodSubtype>()         for (layout in layouts) {@@ -774,7 +816,7 @@ class KeyboardService : InputMethodService(),                 .setLanguageTag(layout.id.substringBefore('_'))                 .setSubtypeExtraValue("layoutId=${layout.id}")                 .setSubtypeId(layout.id.hashCode())-                .setSubtypeNameResId(0)+                .setSubtypeNameResId(R.string.subtype_keyboard)             if (nameable) {                 builder.setSubtypeNameOverride(layout.description)             }@@ -825,6 +867,32 @@ class KeyboardService : InputMethodService(),      // --- Clipboard --- +    /**+     * One-time move off the old DataStore-backed history (see [KeyboardSettings.Keys.CLIPS]):+     * decode the legacy string into the file store, persist it, then blank the key. The+     * wipe watcher keys off CLIPS_WIPE, so blanking here is not mistaken for a request.+     * Runs on IO from onCreate.+     */+    private suspend fun migrateLegacyClips() {+        // Await, not snapshot-read: the DataStore mirror may not be hydrated yet this+        // early in onCreate, and a null here would skip the one-time migration forever.+        val stored = ds.getStringAwait(KeyboardSettings.Keys.CLIPS) ?: return+        if (stored.isBlank()) return+        clipboard.seed(ClipboardStore.decode(stored))+        clipboard.persistState()+        ds.setString(KeyboardSettings.Keys.CLIPS, "")+    }++    /** A short-lived strip notice; the IME has no snackbar host, so the strip is the channel. */+    private fun showNotice(text: String) {+        noticeJob?.cancel()+        kbState.notice = text+        noticeJob = scope.launch {+            delay(NOTICE_MS)+            if (kbState.notice == text) kbState.notice = null+        }+    }+     /**      * Watch the system clipboard. An IME may read it while it is the active input method,      * which is what makes this possible on Android 10+ — but the callback only fires while@@ -864,8 +932,8 @@ class KeyboardService : InputMethodService(),     }      private fun persistClips() {-        val encoded = clipboard.serialize()-        scope.launch { ds.setString(KeyboardSettings.Keys.CLIPS, encoded) }+        // File I/O, never on the main thread; encode() already excludes sensitive clips.+        scope.launch(Dispatchers.IO) { runCatching { clipboard.persistState() } }     }      /** Drop everything, in memory and on disk — what turning the setting off has to mean. */@@ -893,17 +961,29 @@ class KeyboardService : InputMethodService(),      /**      * Hand an image clip to the field via `commitContent`. Most fields cannot take one, so-     * the editor's accepted MIME types are checked first rather than committing into the void.+     * the editor's accepted MIME types are checked first; every refusal explains itself in+     * the strip rather than leaving the tap visibly dead.      */     private fun commitImage(ic: InputConnection, item: ClipItem) {-        val file = item.imageFile ?: return-        val mime = item.mimeType ?: return-        val editor = currentInputEditorInfo ?: return+        val file = item.imageFile+        val mime = item.mimeType+        val editor = currentInputEditorInfo+        if (file == null || mime == null || editor == null || !file.exists()) {+            showNotice(getString(R.string.clipboard_image_unavailable))+            return+        }         val accepted = EditorInfoCompat.getContentMimeTypes(editor)-        if (accepted.none { ClipDescription.compareMimeTypes(mime, it) }) return+        if (accepted.none { ClipDescription.compareMimeTypes(mime, it) }) {+            showNotice(getString(R.string.clipboard_image_not_supported))+            return+        }         val uri = runCatching {             FileProvider.getUriForFile(this, "$packageName.fileprovider", file)-        }.getOrNull() ?: return+        }.getOrNull()+        if (uri == null) {+            showNotice(getString(R.string.clipboard_image_unavailable))+            return+        }         val content = InputContentInfoCompat(uri, ClipDescription(item.preview, arrayOf(mime)), null)         InputConnectionCompat.commitContent(             ic,
keyboard/src/main/java/com/vayunmathur/keyboard/ime/KeyboardState.kt
diff --git a/keyboard/src/main/java/com/vayunmathur/keyboard/ime/KeyboardState.kt b/keyboard/src/main/java/com/vayunmathur/keyboard/ime/KeyboardState.ktindex c03a1e8427..34de44a4d6 100644--- a/keyboard/src/main/java/com/vayunmathur/keyboard/ime/KeyboardState.kt+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/ime/KeyboardState.kt@@ -104,6 +104,13 @@ class KeyboardState {      /** Dictation progress or its last failure, shown in place of the strip. Null when idle. */     var voice by mutableStateOf<VoiceState?>(null)++    /**+     * A short-lived strip notice (e.g. image paste refused), shown in place of the+     * strip. An IME has no scaffold for a snackbar and a Toast is banned repo-wide,+     * so the strip is the channel; the service clears this after a few seconds.+     */+    var notice by mutableStateOf<String?>(null) }  /**@@ -116,7 +123,6 @@ interface ImeActions {     fun onEnter()     fun onSpace()     fun onShift()-    fun onCapsLock()     fun setPage(page: KeyboardPage)     fun commitSuggestion(word: String) @@ -158,7 +164,6 @@ interface ImeActions {             override fun onEnter() {}             override fun onSpace() {}             override fun onShift() {}-            override fun onCapsLock() {}             override fun setPage(page: KeyboardPage) {}             override fun commitSuggestion(word: String) {}             override fun startEmojiSearch() {}
keyboard/src/main/java/com/vayunmathur/keyboard/ime/TextBeforeCursor.kt
diff --git a/keyboard/src/main/java/com/vayunmathur/keyboard/ime/TextBeforeCursor.kt b/keyboard/src/main/java/com/vayunmathur/keyboard/ime/TextBeforeCursor.ktindex 8a93679370..9403fc92b2 100644--- a/keyboard/src/main/java/com/vayunmathur/keyboard/ime/TextBeforeCursor.kt+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/ime/TextBeforeCursor.kt@@ -83,16 +83,32 @@ internal class TextBeforeCursor {         append(text)     } -    /** One character deleted from in front of the cursor. */+    /** One code point deleted from in front of the cursor (an emoji is two UTF-16 units). */     fun deleted() {-        moveCursor(-1)         hasSelection = false-        if (!known) return+        if (!known) {+            // Guessing one unit; a wrong guess only costs a reread (see class docs).+            moveCursor(-1)+            return+        }         when {-            window.isNotEmpty() -> window.deleteCharAt(window.length - 1)+            window.isNotEmpty() -> {+                var units = 1+                if (window.last().isLowSurrogate() && window.length >= 2 &&+                    window[window.length - 2].isHighSurrogate()+                ) {+                    units = 2+                }+                window.delete(window.length - units, window.length)+                moveCursor(-units)+            }             // The window was already empty and the field did not start there, so what is             // left in front of the cursor now is something we never saw.-            !atStart -> known = false+            !atStart -> {+                known = false+                moveCursor(-1)+            }+            // Otherwise the field starts here and there was nothing to delete.         }     } 
keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyButton.kt
diff --git a/keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyButton.kt b/keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyButton.ktindex 06e099d83b..0974b73500 100644--- a/keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyButton.kt+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyButton.kt@@ -2,9 +2,10 @@  package com.vayunmathur.keyboard.ui +import android.os.SystemClock import androidx.compose.foundation.background+import androidx.compose.foundation.gestures.awaitEachGesture import androidx.compose.foundation.gestures.awaitFirstDown-import androidx.compose.foundation.gestures.waitForUpOrCancellation import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.PressInteraction import androidx.compose.foundation.interaction.collectIsPressedAsState@@ -26,6 +27,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color+import androidx.compose.ui.input.pointer.PointerInputChange import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.positionInWindow@@ -152,41 +154,76 @@ fun RowScope.CharKey(             // emitting, all of which happen mid-keypress — the Press interaction is never             // released and the key stays lit with its preview stuck above it until it             // leaves composition (i.e. until the user switches to another page).+            //+            // One gesture per awaitEachGesture iteration, deliberately. The previous code+            // waited out the long-press timeout and then started a *second* wait for the+            // lift; an up landing in between left the second wait holding a stale+            // still-pressed snapshot, so it hung until the next touch on the same key —+            // the stuck popup — and that next touch was then consumed as the old+            // gesture's release position, committing a phantom variant. A tap whose up+            // arrived as a cancellation (second thumb down mid-tap) also read as a+            // timeout and opened the menu. Bounding each down→up to one iteration+            // removes all three.             .pointerInput(Unit) {-                while (true) {-                    val down = awaitPointerEventScope { awaitFirstDown(requireUnconsumed = false) }+                awaitEachGesture {+                    val down = awaitFirstDown(requireUnconsumed = false)                     val press = PressInteraction.Press(down.position)                     try {-                        interaction.emit(press)-                        val lifted = withTimeoutOrNull(viewConfiguration.longPressTimeoutMillis) {-                            awaitPointerEventScope { waitForUpOrCancellation() }+                        // tryEmit, not emit: awaitEachGesture's block is a restricted+                        // suspend scope, so member suspend calls on other objects+                        // (like emit) do not compile here.+                        interaction.tryEmit(press)+                        val timeout = viewConfiguration.longPressTimeoutMillis+                        val start = SystemClock.uptimeMillis()+                        var up: PointerInputChange? = null+                        var lastX = down.position.x+                        while (up == null && SystemClock.uptimeMillis() - start < timeout) {+                            val remaining = timeout - (SystemClock.uptimeMillis() - start)+                            val event = withTimeoutOrNull(remaining.coerceAtLeast(0L)) {+                                awaitPointerEvent()+                            } ?: break+                            val change = event.changes.firstOrNull { it.id == down.id } ?: continue+                            lastX = change.position.x+                            if (!change.pressed) up = change                         }-                        if (lifted != null) {-                            if (lifted.position.isInside(size)) currentOnClick()-                            continue+                        if (up != null) {+                            if (up.position.isInside(size)) currentOnClick()+                            return@awaitEachGesture                         }                         val opts = currentOptions                         val onAlt = currentOnAlternate                         if (opts.isEmpty() || onAlt == null) {-                            awaitPointerEventScope { waitForUpOrCancellation() }-                            continue+                            // A hold with nothing to offer still types the key; the old+                            // code waited for the lift and then committed nothing.+                            currentOnClick()+                            return@awaitEachGesture                         }-                        val picked = awaitPointerEventScope {-                            val offset = alternatesOffset(bounds, currentItemWidth, opts.length, currentScreenWidth)-                            selected = indexAt(down.position.x, offset, currentItemWidth, opts.length)-                            var change = down-                            while (change.pressed) {-                                change = awaitPointerEvent().changes-                                    .firstOrNull { it.id == down.id } ?: break-                                selected = indexAt(change.position.x, offset, currentItemWidth, opts.length)+                        val offset = alternatesOffset(bounds, currentItemWidth, opts.length, currentScreenWidth)+                        var picked = indexAt(lastX, offset, currentItemWidth, opts.length)+                        selected = picked+                        while (true) {+                            val event = awaitPointerEvent()+                            val change = event.changes.firstOrNull { it.id == down.id }+                            if (change == null) {+                                // Only other pointers speaking. A fresh down here means+                                // our own up was lost in the timeout race; abandon rather+                                // than hang on a gesture that is already over.+                                if (event.changes.any { it.pressed && !it.previousPressed }) {+                                    return@awaitEachGesture+                                }+                                continue+                            }+                            if (!change.pressed) {+                                onAlt(opts[picked].toString())+                                break                             }-                            selected+                            picked = indexAt(change.position.x, offset, currentItemWidth, opts.length)+                            selected = picked                         }-                        onAlt(opts[picked].toString())                     } finally {                         // tryEmit, not emit: this also has to run on the cancellation path,                         // where a suspending emit would itself be cancelled and leave the-                        // key stuck. `continue` runs it too, so every exit clears the press.+                        // key stuck.                         selected = -1                         interaction.tryEmit(PressInteraction.Release(press))                     }
keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyboardScreen.kt
diff --git a/keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyboardScreen.kt b/keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyboardScreen.ktindex 7365bab491..971546c644 100644--- a/keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyboardScreen.kt+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyboardScreen.kt@@ -18,8 +18,10 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp import com.vayunmathur.keyboard.ime.ImeActions import com.vayunmathur.keyboard.ime.KeyboardState import com.vayunmathur.keyboard.util.KeyboardPage@@ -27,6 +29,7 @@ import com.vayunmathur.keyboard.util.Layouts import com.vayunmathur.library.ui.IconPaste import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Surface+import com.vayunmathur.library.ui.Text  /**  * Root of the keyboard view: a suggestion strip (when enabled) above whichever page of keys@@ -101,6 +104,12 @@ private fun EmojiSearchStrip(state: KeyboardState, actions: ImeActions) { /** Whatever occupies the strip above the keys, or nothing. */ @Composable private fun Strip(state: KeyboardState, actions: ImeActions) {+    // A paste refusal explains itself here: the strip is the IME's only channel —+    // there is no scaffold for a snackbar and Toast is banned repo-wide.+    state.notice?.let {+        NoticeStrip(text = it)+        return+    }     // A fresh clip outranks suggestions because the two never really compete: the chip is     // offered before anything has been typed and the service drops it on the first keypress,     // which is exactly when suggestions appear. The chip carries its own open button, so it@@ -168,6 +177,24 @@ private fun Strip(state: KeyboardState, actions: ImeActions) {     } } +/** One line of strip text for paste refusals and other notices the IME must surface inline. */+@Composable+private fun NoticeStrip(text: String) {+    Box(+        modifier = Modifier.fillMaxWidth().height(StripHeight),+        contentAlignment = Alignment.Center,+    ) {+        Text(+            text = text,+            color = MaterialTheme.colorScheme.onSurfaceVariant,+            fontSize = 14.sp,+            maxLines = 1,+            overflow = TextOverflow.Ellipsis,+            modifier = Modifier.padding(horizontal = 16.dp),+        )+    }+}+ /** The active page of keys. */ @Composable private fun KeyPage(state: KeyboardState, actions: ImeActions, keyHeight: Dp) {
keyboard/src/main/java/com/vayunmathur/keyboard/ui/SetupScreen.kt
diff --git a/keyboard/src/main/java/com/vayunmathur/keyboard/ui/SetupScreen.kt b/keyboard/src/main/java/com/vayunmathur/keyboard/ui/SetupScreen.ktindex 380fad2be8..07110dbf27 100644--- a/keyboard/src/main/java/com/vayunmathur/keyboard/ui/SetupScreen.kt+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/ui/SetupScreen.kt@@ -142,16 +142,16 @@ fun SetupScreen() {              Text(stringResource(UiR.string.settings), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.primary) -            SettingSwitch("Haptic feedback", haptic) {+            SettingSwitch(stringResource(R.string.setting_haptic_feedback), haptic) {                 haptic = it; scope.launch { ds.setBoolean(keys.HAPTIC, it) }             }-            SettingSwitch("Key sound", sound) {+            SettingSwitch(stringResource(R.string.setting_key_sound), sound) {                 sound = it; scope.launch { ds.setBoolean(keys.SOUND, it) }             }-            SettingSwitch("Auto-capitalize", autoCap) {+            SettingSwitch(stringResource(R.string.setting_auto_capitalize), autoCap) {                 autoCap = it; scope.launch { ds.setBoolean(keys.AUTO_CAP, it) }             }-            SettingSwitch("Double-space inserts period", doubleSpace) {+            SettingSwitch(stringResource(R.string.setting_double_space_period), doubleSpace) {                 doubleSpace = it; scope.launch { ds.setBoolean(keys.DOUBLE_SPACE_PERIOD, it) }             }             // The word list we ship is English, so say so rather than let these two look@@ -159,30 +159,36 @@ fun SetupScreen() {             val englishOnly = KeyboardLayouts.byId(activeLayoutId)?.englishDictionary == false             val englishNote =                 if (englishOnly) stringResource(R.string.available_for_english_layouts_only) else null-            SettingSwitch("Show suggestions", showSuggestions, englishNote) {+            SettingSwitch(stringResource(R.string.setting_show_suggestions), showSuggestions, englishNote) {                 showSuggestions = it; scope.launch { ds.setBoolean(keys.SHOW_SUGGESTIONS, it) }             }-            SettingSwitch("Auto-correct", autoCorrect, englishNote) {+            SettingSwitch(stringResource(R.string.setting_auto_correct), autoCorrect, englishNote) {                 autoCorrect = it; scope.launch { ds.setBoolean(keys.AUTO_CORRECT, it) }             }-            SettingSwitch("Number row", numberRow) {+            SettingSwitch(stringResource(R.string.setting_number_row), numberRow) {                 numberRow = it; scope.launch { ds.setBoolean(keys.NUMBER_ROW, it) }             }             SettingSwitch(-                "Clipboard history",+                stringResource(R.string.setting_clipboard_history),                 clipboardEnabled,-                "Remember what you copy and offer it back above the keys",+                stringResource(R.string.setting_clipboard_history_desc),             ) {                 clipboardEnabled = it                 scope.launch { ds.setBoolean(keys.CLIPBOARD, it) }             }             if (clipboardEnabled) {-                // Blanking the stored value is the signal the running IME watches for; it+                // Bumping the wipe counter is the signal the running IME watches for; it                 // wipes its in-memory history (including the sensitive clips that never-                // reached disk) rather than letting this write be overwritten.+                // reached disk) rather than letting this write be overwritten. A counter+                // rather than a blanked clips string, so the startup migration clearing+                // the legacy key cannot be mistaken for a wipe request.                 SettingsRow(                     title = stringResource(R.string.clear_clipboard_history),-                    onClick = { scope.launch { ds.setString(keys.CLIPS, "") } },+                    onClick = {+                        scope.launch {+                            ds.setLong(keys.CLIPS_WIPE, (ds.getLong(keys.CLIPS_WIPE) ?: 0L) + 1)+                        }+                    },                     leadingContent = { IconDelete() },                 )             }@@ -224,8 +230,8 @@ private fun StatusCard(enabled: Boolean, selected: Boolean) {             modifier = Modifier.padding(16.dp),             verticalArrangement = Arrangement.spacedBy(8.dp),         ) {-            StatusRow("Enabled in system settings", enabled)-            StatusRow("Selected as active keyboard", selected)+            StatusRow(stringResource(R.string.status_enabled), enabled)+            StatusRow(stringResource(R.string.status_selected), selected)         }     } }
keyboard/src/main/java/com/vayunmathur/keyboard/util/Clipboard.kt
diff --git a/keyboard/src/main/java/com/vayunmathur/keyboard/util/Clipboard.kt b/keyboard/src/main/java/com/vayunmathur/keyboard/util/Clipboard.ktindex fab3ee7793..f5d0427724 100644--- a/keyboard/src/main/java/com/vayunmathur/keyboard/util/Clipboard.kt+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/util/Clipboard.kt@@ -12,10 +12,11 @@ import kotlinx.coroutines.withContext import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import java.io.File+import java.util.concurrent.atomic.AtomicLong  /**- * One thing the user copied. [id] is the capture time in milliseconds, which is also what- * orders the history and names the cached image file.+ * One thing the user copied. [id] is unique and monotonic (see [nextId]), which is also+ * what orders the history and names the cached image file.  *  * A clip is either text or an image, never both: [imagePath] points at the keyboard's own  * copy of the image bytes (see [ClipboardStore.capture]) and is null for text clips.@@ -51,18 +52,41 @@ data class ClipItem(  * app's clip, so a reference would paste fine for a minute and then silently fail — which  * is exactly when a clipboard history is worth having.  *- * Sensitive clips (see [looksSensitive]) live in memory for the session only; [serialize]- * leaves them out, so a password never reaches disk.+ * Sensitive clips (see [looksSensitive]) live in memory for the session only; [persistState]+ * writes through [encode], which leaves them out, so a password never reaches disk.+ * Sensitive images are refused at capture instead, so no bytes are written either.  */ class ClipboardStore(private val imageDir: File) {      var items: List<ClipItem> = emptyList()         private set -    fun restore(stored: String?) {-        items = decode(stored).filter { it.imageFile?.exists() != false }+    fun restoreState() {+        val file = stateFile()+        if (!file.exists()) {+            items = emptyList()+            return+        }+        items = decode(runCatching { file.readText() }.getOrNull())+            .filter { it.imageFile?.exists() != false }+    }++    /** Write the history to [stateFile]; sensitive clips are excluded by [encode]. Must be called off the main thread. */+    fun persistState() {+        runCatching {+            imageDir.mkdirs()+            stateFile().writeText(encode(items))+        }+    }++    /** Replace the history wholesale (startup migration); trims to the caps like [add] does. */+    fun seed(history: List<ClipItem>) {+        items = cap(history.filter { it.imageFile?.exists() != false }, ::discardImage)     } +    /** The history file inside [imageDir]. Cache is excluded from backup rules, so clips never leave the device. */+    fun stateFile(): File = stateFile(imageDir)+     /**      * Record [item]. Returns it when it is genuinely new; re-copying something already in      * the history just moves it back to the front and returns null, so the strip does not@@ -89,43 +113,68 @@ class ClipboardStore(private val imageDir: File) {         items = emptyList()     } -    fun serialize(): String = encode(items)-     /**      * Turn the system's primary clip into a [ClipItem], copying image bytes into the cache      * on the way. Returns null for a clip with nothing usable in it.      */     suspend fun capture(context: Context, clip: ClipData, inPasswordField: Boolean): ClipItem? {         val entry = (if (clip.itemCount > 0) clip.getItemAt(0) else null) ?: return null-        val id = System.currentTimeMillis()         val flagged = inPasswordField || clip.description.isMarkedSensitive()          val uri = entry.uri         val mime = uri?.let { context.contentResolver.getType(it) }         if (uri != null && mime != null && mime.startsWith("image/")) {+            // Sensitive images are not recorded at all: bytes on disk would outlive+            // the session while the history entry (excluded from serialization)+            // does not, leaving orphaned credential-adjacent files.+            if (flagged) return null+            val id = nextId()             val file = withContext(Dispatchers.IO) { copyImage(context, uri, id, mime) }                 ?: return null-            return ClipItem(id, imagePath = file.path, mimeType = mime, sensitive = flagged)+            return ClipItem(+                id = id,+                imagePath = file.path,+                mimeType = mime,+                sensitive = false,+            )         }          val text = entry.coerceToText(context).toString().trim()-        if (text.isEmpty()) return null+        // Beyond this a copy is an accident (select-all of a document), not a clip;+        // a multi-megabyte string does not belong in DataStore-shaped persistence.+        if (text.isEmpty() || text.length > MAX_TEXT_CHARS) return null         return ClipItem(-            id = id,+            id = nextId(),             text = text,             mimeType = ClipDescription.MIMETYPE_TEXT_PLAIN,             sensitive = flagged || looksSensitive(text),         )     } -    private fun copyImage(context: Context, uri: Uri, id: Long, mime: String): File? = runCatching {-        imageDir.mkdirs()+    private fun copyImage(context: Context, uri: Uri, id: Long, mime: String): File? {         val file = File(imageDir, "$id.${mime.substringAfterLast('/', "png")}")-        context.contentResolver.openInputStream(uri)?.use { input ->-            file.outputStream().use(input::copyTo)-        } ?: return null-        file-    }.getOrNull()+        val ok = runCatching {+            imageDir.mkdirs()+            context.contentResolver.openInputStream(uri)?.use { input ->+                file.outputStream().use { out ->+                    val buf = ByteArray(DEFAULT_BUFFER_SIZE)+                    var total = 0L+                    while (true) {+                        val n = input.read(buf)+                        if (n < 0) break+                        total += n+                        // Refuse rather than half-keep: a truncated image pastes as+                        // a corrupt file, which is worse than no history entry.+                        if (total > MAX_IMAGE_BYTES) return@runCatching false+                        out.write(buf, 0, n)+                    }+                    true+                }+            } == true+        }.getOrDefault(false)+        if (!ok) runCatching { file.delete() }+        return if (ok) file else null+    }      private fun discardImage(item: ClipItem) {         runCatching { item.imageFile?.delete() }@@ -138,6 +187,32 @@ class ClipboardStore(private val imageDir: File) {         /** Images are cached as real files, so far fewer of them are kept. */         const val MAX_IMAGES = 10 +        /** Longest single text clip kept; beyond this a copy is an accident, not a clip. */+        const val MAX_TEXT_CHARS = 50_000++        /** Largest single image cached; bigger copies are refused rather than half-kept. */+        const val MAX_IMAGE_BYTES = 10_000_000L++        /** History file inside a clips dir; cache is excluded from backup rules. */+        fun stateFile(clipsDir: File): File = File(clipsDir, "clips.json")++        /**+         * Unique, monotonic ids. Wall-clock millis plus a sequence, so two copies in+         * the same millisecond — or a backwards clock step — never share an id.+         * Ids are LazyColumn keys and image filenames, so a collision is a crash+         * plus one image overwriting the other.+         */+        private val lastClipId = AtomicLong(0)++        fun nextId(): Long {+            val now = System.currentTimeMillis() * 1_000L+            while (true) {+                val last = lastClipId.get()+                val next = maxOf(now, last + 1)+                if (lastClipId.compareAndSet(last, next)) return next+            }+        }+         private val json = Json { ignoreUnknownKeys = true }          /**@@ -171,6 +246,13 @@ class ClipboardStore(private val imageDir: File) {          * mistake shows someone's password on screen.          */         fun looksSensitive(text: String): Boolean {+            // PINs, 2FA codes and card numbers: short digit runs, often grouped with+            // spaces or dashes ("1234", "4111 1111 1111 1111"). Over-blurs an+            // occasional year or score, which costs one eye-tap; the opposite mistake+            // shows a credential in the clear.+            val digits = text.count { it.isDigit() }+            val rest = text.filterNot { it.isDigit() || it.isWhitespace() || it == '-' || it == '+' }+            if (rest.isEmpty() && digits in 4..24) return true             if (text.length !in 6..64) return false             if (text.any { it.isWhitespace() }) return false             if (text.contains("://") || EMAIL.matches(text)) return false
keyboard/src/main/java/com/vayunmathur/keyboard/util/KeyboardLayoutsLatin.kt
diff --git a/keyboard/src/main/java/com/vayunmathur/keyboard/util/KeyboardLayoutsLatin.kt b/keyboard/src/main/java/com/vayunmathur/keyboard/util/KeyboardLayoutsLatin.ktindex 7332ef993c..eab035ecae 100644--- a/keyboard/src/main/java/com/vayunmathur/keyboard/util/KeyboardLayoutsLatin.kt+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/util/KeyboardLayoutsLatin.kt@@ -167,7 +167,10 @@ internal val latinKeyboardLayouts: List<KeyboardLayout> by lazy {             description = "Azerbaijani · QWERTY",             rows = listOf("qüertyuiopöğ", "asdfghjklıə", "zxcvbnmçş"),             shiftedRows = listOf("QÜERTYUİOPÖĞ", "ASDFGHJKLIƏ", "ZXCVBNMÇŞ"),-            alternates = mapOf('a' to "â", 'i' to "ı", 'u' to "ü", 'o' to "ö", 'e' to "ə"),+            alternates = latinExtra(+                listOf("qüertyuiopöğ", "asdfghjklıə", "zxcvbnmçş"),+                'a' to "â", 'i' to "ı", 'u' to "ü", 'o' to "ö", 'e' to "ə",+            ),         ),         KeyboardLayout(             id = "et_qwerty",@@ -404,3 +407,13 @@ internal val latinKeyboardLayouts: List<KeyboardLayout> by lazy { /** Latin alternates plus this language's own, which take precedence. */ private fun latinExtra(vararg extra: Pair<Char, String>): Map<Char, String> =     Layouts.LATIN_ALTERNATES + extra.toMap()++/**+ * Same, but only for keys the layout actually has. Long-pressing a key that isn't on the+ * layout can never fire (see the layout tests), so unfiltered defaults would add dead+ * entries — Azerbaijani has no `w`, for example, and no `i` either (it has `ı`).+ */+private fun latinExtra(rows: List<String>, vararg extra: Pair<Char, String>): Map<Char, String> {+    val chars = rows.joinToString("").toSet()+    return (Layouts.LATIN_ALTERNATES + extra.toMap()).filterKeys { it in chars }+}
keyboard/src/main/java/com/vayunmathur/keyboard/util/KeyboardPrefs.kt
diff --git a/keyboard/src/main/java/com/vayunmathur/keyboard/util/KeyboardPrefs.kt b/keyboard/src/main/java/com/vayunmathur/keyboard/util/KeyboardPrefs.ktindex e5ef49743d..b308e84228 100644--- a/keyboard/src/main/java/com/vayunmathur/keyboard/util/KeyboardPrefs.kt+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/util/KeyboardPrefs.kt@@ -37,6 +37,12 @@ data class KeyboardSettings(         const val NUMBER_ROW = "kb_number_row"         const val CLIPBOARD = "kb_clipboard"         const val CLIPS = "kb_clips"+        /**+         * Bumped whenever the history must be forgotten (settings "clear"). A counter, not+         * a blanked string: blanking the stored clips as the wipe signal meant the+         * startup migration clearing the legacy key looked like a wipe request.+         */+        const val CLIPS_WIPE = "kb_clips_wipe"         const val EMOJI_RECENTS = "kb_emoji_recents"         const val KEY_HEIGHT = "kb_key_height"         const val ACTIVE_LAYOUT = "kb_active_layout"
keyboard/src/main/res/values/strings.xml
diff --git a/keyboard/src/main/res/values/strings.xml b/keyboard/src/main/res/values/strings.xmlindex 9315576703..c78119a181 100644--- a/keyboard/src/main/res/values/strings.xml+++ b/keyboard/src/main/res/values/strings.xml@@ -17,6 +17,24 @@     <string name="clear_clipboard">Clear all</string>     <string name="clear_clipboard_history">Clear clipboard history</string>     <string name="copied_text_shows_up_here">Copied text and images show up here</string>+    <!-- Fallback label for a framework input-method subtype on platforms below API 34, where per-subtype names are unavailable. -->+    <string name="subtype_keyboard">Keyboard</string>+    <!-- Keyboard: shown in the strip above the keys when an image clip cannot be pasted because the cached file is gone. -->+    <string name="clipboard_image_unavailable">Image is no longer available</string>+    <!-- Keyboard: shown in the strip above the keys when an image clip cannot be pasted because the field only accepts text. -->+    <string name="clipboard_image_not_supported">This field doesn\'t accept images</string>+    <!-- Keyboard setup screen. -->+    <string name="setting_haptic_feedback">Haptic feedback</string>+    <string name="setting_key_sound">Key sound</string>+    <string name="setting_auto_capitalize">Auto-capitalize</string>+    <string name="setting_double_space_period">Double-space inserts period</string>+    <string name="setting_show_suggestions">Show suggestions</string>+    <string name="setting_auto_correct">Auto-correct</string>+    <string name="setting_number_row">Number row</string>+    <string name="setting_clipboard_history">Clipboard history</string>+    <string name="setting_clipboard_history_desc">Remember what you copy and offer it back above the keys</string>+    <string name="status_enabled">Enabled in system settings</string>+    <string name="status_selected">Selected as active keyboard</string>      <!-- Accessibility label for the long-press action on the keyboard's enter key, which starts dictation. -->     <string name="voice_input">Voice input</string>
keyboard/src/main/res/xml/data_extraction_rules.xml
diff --git a/keyboard/src/main/res/xml/data_extraction_rules.xml b/keyboard/src/main/res/xml/data_extraction_rules.xmlindex 51a3db4312..3fe9e5f460 100644--- a/keyboard/src/main/res/xml/data_extraction_rules.xml+++ b/keyboard/src/main/res/xml/data_extraction_rules.xml@@ -1,22 +1,24 @@ <?xml version="1.0" encoding="utf-8"?> <!---  Keyboard. Audited state: ten settings persisted through DataStoreUtils into+  Keyboard. Audited state: settings persist through DataStoreUtils into   filesDir/datastore_default.preferences_pb — haptics, sound, auto-capitalise,   double-space-period, suggestions, autocorrect, number row, key height, the-  enabled layout list and the active layout (KeyboardSettings.Keys).+  active layout (KeyboardSettings.Keys) and a clipboard-wipe counter.    Checked specifically for a learned-words / user dictionary, since an IME that   records what the user types would be sensitive regardless of this app's   general risk level. There is none. Dictionary.load() and   PinyinDictionary.load() read fixed APK assets (dict/words_en.txt,-  dict/bopomofo.txt, emoji.txt) and are never written back; the only writes-  anywhere in the module are the ds.setBoolean/setString calls in SetupScreen-  and the active-layout write in KeyboardService. There is also no persisted-  clipboard history — the clipboard page is UI-only.+  dict/bopomofo.txt, emoji.txt) and are never written back. -  So nothing the user has typed is stored on disk, and there is nothing to hold-  back from cloud backup. Settings back up in full; restoring them is the whole-  point, since reconfiguring layouts by hand on a new phone is tedious.+  Clipboard history lives in the app cache (cacheDir/clips/clips.json plus cached+  image files), never in DataStore, and cache/ is never backed up — so clips never+  leave the device. Sensitive clips never reach disk at all (memory only), and+  sensitive images are refused at capture. The legacy kb_clips DataStore key is+  migrated to the cache file on first start and then blanked.++  Settings back up in full; restoring them is the whole point, since+  reconfiguring layouts by hand on a new phone is tedious. --> <data-extraction-rules>     <cloud-backup>
keyboard/src/test/java/com/vayunmathur/keyboard/util/ClipboardTest.kt
diff --git a/keyboard/src/test/java/com/vayunmathur/keyboard/util/ClipboardTest.kt b/keyboard/src/test/java/com/vayunmathur/keyboard/util/ClipboardTest.ktindex 04af97110d..9497438c39 100644--- a/keyboard/src/test/java/com/vayunmathur/keyboard/util/ClipboardTest.kt+++ b/keyboard/src/test/java/com/vayunmathur/keyboard/util/ClipboardTest.kt@@ -47,6 +47,21 @@ class ClipboardTest {         assertFalse(ClipboardStore.looksSensitive("a1" + "x".repeat(80)))     } +    /** PINs, 2FA codes and card numbers are digit runs, often grouped with spaces/dashes. */+    @Test+    fun `pins and card numbers are flagged`() {+        assertTrue(ClipboardStore.looksSensitive("123456"))+        assertTrue(ClipboardStore.looksSensitive("1234"))+        assertTrue(ClipboardStore.looksSensitive("4111 1111 1111 1111"))+        assertTrue(ClipboardStore.looksSensitive("123-456"))+    }++    @Test+    fun `short digit runs that are clearly not pins are not`() {+        assertFalse(ClipboardStore.looksSensitive("123"))+        assertFalse(ClipboardStore.looksSensitive("1".repeat(25)))+    }+     // --- history ---      @Test@@ -78,6 +93,13 @@ class ClipboardTest {         assertEquals(listOf("one", "two"), store.items.map { it.text })     } +    @Test+    fun `ids are unique and monotonic even within one millisecond`() {+        val ids = (1..1000).map { ClipboardStore.nextId() }+        assertEquals(ids.size, ids.toSet().size, "duplicate clip id")+        assertTrue(ids.zipWithNext().all { (a, b) -> b > a }, "ids must be monotonic")+    }+     // --- persistence ---      @Test@@ -87,6 +109,29 @@ class ClipboardTest {         assertEquals(items, restored)     } +    @Test+    fun `the history persists to its state file and restores from it`() {+        val dir = kotlin.io.path.createTempDirectory("clips").toFile()+        try {+            val store = ClipboardStore(dir)+            store.add(text(1, "hello"))+            store.add(text(2, "world"))+            store.persistState()+            val restored = ClipboardStore(dir)+            restored.restoreState()+            assertEquals(listOf("world", "hello"), restored.items.map { it.text })+        } finally {+            dir.deleteRecursively()+        }+    }++    @Test+    fun `a missing state file restores to an empty history rather than throwing`() {+        val store = ClipboardStore(java.io.File("/tmp/clip-test-does-not-exist"))+        store.restoreState()+        assertEquals(emptyList(), store.items)+    }+     @Test     fun `sensitive clips never reach the serialized form`() {         val items = listOf(text(1, "hunter2", sensitive = true), text(2, "plain"))