Modern Apps git

← Modern-Apps.git

various fixes

Commit
1e4cf1f48b72eaf2e3b094517aa7ca4ecc1261d2
Author
vayun-mathur <[email protected]>
When
2026-08-18 23:10 UTC (3 months ago)
Parents
5882470

Diff

.github/workflows/issue_labeler.yml
diff --git a/.github/workflows/issue_labeler.yml b/.github/workflows/issue_labeler.ymlindex 1c240d0fd3..fee106cf3b 100644--- a/.github/workflows/issue_labeler.yml+++ b/.github/workflows/issue_labeler.yml@@ -21,7 +21,7 @@ jobs:              if (match && match[1]) {               const selectedApp = match[1].trim().toLowerCase();-              const validApps = ['alchemist', 'appstore', 'astronomy', 'calculator', 'calendar', 'camera', 'chess', 'clock', 'code', 'contacts', 'education', 'email', 'everysync', 'files', 'findfamily', 'fooddelivery', 'health', 'hub', 'keyboard', 'logicgate', 'maps', 'measure', 'messages', 'music', 'musicbrainz', 'notes', 'office', 'openassistant', 'passwords', 'pdf', 'photos', 'pipes', 'solitaire', 'speech', 'things', 'translate', 'travel', 'unblockjam', 'vpn', 'voxels', 'weather', 'web', 'wordmaker', 'youpipe'];+              const validApps = ['alchemist', 'appstore', 'astronomy', 'calculator', 'calendar', 'camera', 'chess', 'clock', 'code', 'contacts', 'education', 'email', 'everysync', 'files', 'findfamily', 'fooddelivery', 'health', 'hub', 'keyboard', 'launcher', 'logicgate', 'maps', 'measure', 'messages', 'music', 'musicbrainz', 'notes', 'office', 'openassistant', 'passwords', 'pdf', 'photos', 'pipes', 'solitaire', 'speech', 'things', 'translate', 'travel', 'unblockjam', 'vpn', 'voxels', 'weather', 'web', 'wordmaker', 'youpipe'];                if (validApps.includes(selectedApp)) {                 await github.rest.issues.addLabels({
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 f800ac3511..53129bddfb 100644--- a/keyboard/src/main/java/com/vayunmathur/keyboard/ime/KeyboardService.kt+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/ime/KeyboardService.kt@@ -100,6 +100,16 @@ class KeyboardService : InputMethodService(),     /** The word currently being composed (underlined) on the letters page. */     private val composing = StringBuilder() +    /**+     * What is in front of the cursor, mirrored locally rather than read back from the field+     * on every keystroke. Every edit below goes through [commit], [setComposing],+     * [finishComposing] or [deleteBackward] so it stays in step.+     */+    private val before = TextBeforeCursor()++    /** The composition currently shown, so finalizing it can be mirrored into [before]. */+    private var pendingComposition: CharSequence = ""+     /**      * The composition engine for the active layout, or null for layouts whose keys are      * already characters. Owns everything about Hangul/pinyin/kana input; the service only@@ -230,13 +240,13 @@ class KeyboardService : InputMethodService(),      * becomes final, then whatever is still being composed goes back under it.      */     private fun applyComposition(ic: InputConnection, engine: Composer, result: ComposeResult) {-        if (result.commit.isNotEmpty()) ic.commitText(result.commit, 1)+        if (result.commit.isNotEmpty()) commit(ic, result.commit)         if (result.composing.isNotEmpty()) {-            ic.setComposingText(result.composing, 1)+            setComposing(ic, result.composing)         } else if (result.commit.isEmpty()) {             // Nothing settled and nothing left: the last backspace emptied the composition.-            ic.setComposingText("", 1)-            ic.finishComposingText()+            setComposing(ic, "")+            finishComposing(ic)         }         kbState.suggestions = engine.candidates     }@@ -247,15 +257,55 @@ class KeyboardService : InputMethodService(),         if (engine.isComposing) {             val result = engine.finish()             if (result != null && result.commit.isNotEmpty()) {-                ic.commitText(result.commit, 1)+                commit(ic, result.commit)             } else {-                ic.finishComposingText()+                finishComposing(ic)             }         }         engine.reset()         kbState.suggestions = emptyList()     } +    // --- Edits ---++    /**+     * The four ways this service changes the field, each mirrored into [before]. Going+     * through these rather than touching the [InputConnection] directly is what lets+     * auto-capitalisation and the double-space period answer from memory instead of asking+     * the target app — see [TextBeforeCursor].+     */+    private fun commit(ic: InputConnection, text: CharSequence) {+        ic.commitText(text, 1)+        pendingComposition = ""+        before.committed(text)+    }++    private fun setComposing(ic: InputConnection, text: CharSequence) {+        ic.setComposingText(text, 1)+        pendingComposition = text.toString()+        before.composing(text)+    }++    private fun finishComposing(ic: InputConnection) {+        ic.finishComposingText()+        before.composingFinished(pendingComposition)+        pendingComposition = ""+    }++    private fun deleteBackward(ic: InputConnection) {+        ic.deleteSurroundingText(1, 0)+        before.deleted()+    }++    /** The text in front of the cursor, asking the field only when the mirror cannot say. */+    private fun textBeforeCursor(): CharSequence {+        before.peek()?.let { return it }+        val ic = currentInputConnection ?: return ""+        val text = ic.getTextBeforeCursor(TextBeforeCursor.WINDOW, 0) ?: return ""+        before.fill(text)+        return text+    }+     private inline fun update(transform: KeyboardSettings.() -> KeyboardSettings) {         kbState.settings = kbState.settings.transform()     }@@ -305,6 +355,8 @@ class KeyboardService : InputMethodService(),     override fun onStartInputView(info: EditorInfo, restarting: Boolean) {         super.onStartInputView(info, restarting)         composing.setLength(0)+        pendingComposition = ""+        before.onStartInput(info.initialSelStart, info.initialSelEnd)         // Open on whatever subtype the system currently has selected for us, so the app's         // active layout tracks the framework (e.g. after a system-level switch).         val current = getSystemService(InputMethodManager::class.java)?.currentInputMethodSubtype@@ -353,9 +405,25 @@ class KeyboardService : InputMethodService(),         lifecycleRegistry.currentState = Lifecycle.State.STARTED     } +    override fun onUpdateSelection(+        oldSelStart: Int,+        oldSelEnd: Int,+        newSelStart: Int,+        newSelEnd: Int,+        candidatesStart: Int,+        candidatesEnd: Int,+    ) {+        super.onUpdateSelection(+            oldSelStart, oldSelEnd, newSelStart, newSelEnd, candidatesStart, candidatesEnd,+        )+        before.onSelectionChanged(newSelStart, newSelEnd)+    }+     override fun onFinishInputView(finishingInput: Boolean) {         super.onFinishInputView(finishingInput)         composing.setLength(0)+        pendingComposition = ""+        before.invalidate()         composer?.reset()     } @@ -466,17 +534,17 @@ class KeyboardService : InputMethodService(),             }             // Punctuation, a symbol-page key: settle the composition and type it plainly.             finishComposition(ic)-            ic.commitText(text, 1)+            commit(ic, text)             consumeShift()             return         }         if (useComposing() && text.length == 1 && text[0].isLetter()) {             composing.append(text)-            ic.setComposingText(composing, 1)+            setComposing(ic, composing)             updateSuggestions()         } else {             commitCurrentWord(ic, autoCorrect = false)-            ic.commitText(text, 1)+            commit(ic, text)             kbState.suggestions = emptyList()         }         consumeShift()@@ -506,21 +574,20 @@ class KeyboardService : InputMethodService(),         if (composing.isNotEmpty()) {             composing.deleteCharAt(composing.length - 1)             if (composing.isEmpty()) {-                ic.setComposingText("", 1)-                ic.finishComposingText()+                setComposing(ic, "")+                finishComposing(ic)                 kbState.suggestions = emptyList()             } else {-                ic.setComposingText(composing, 1)+                setComposing(ic, composing)                 updateSuggestions()             }+        } else if (before.hasSelection) {+            // Deleting a selection leaves whatever preceded it in front of the cursor, which+            // is text we never saw, so the mirror has to start again.+            commit(ic, "")+            before.invalidate()         } else {-            // Delete a selection if there is one, else one char before the cursor.-            val selected = ic.getSelectedText(0)-            if (!selected.isNullOrEmpty()) {-                ic.commitText("", 1)-            } else {-                ic.deleteSurroundingText(1, 0)-            }+            deleteBackward(ic)         }         updateAutoCapShift()     }@@ -543,6 +610,9 @@ class KeyboardService : InputMethodService(),         if (!handled) {             sendDownUpKeyEvents(KeyEvent.KEYCODE_ENTER)         }+        // Either way the field is now the app's business — it may have inserted a newline,+        // moved focus or submitted and cleared itself.+        before.invalidate()         kbState.suggestions = emptyList()         updateAutoCapShift()     }@@ -561,20 +631,21 @@ class KeyboardService : InputMethodService(),                 return             }             finishComposition(ic)-            ic.commitText(" ", 1)+            commit(ic, " ")             lastSpaceTime = SystemClock.uptimeMillis()             return         }         commitCurrentWord(ic, autoCorrect = kbState.settings.autoCorrect)-        val before = ic.getTextBeforeCursor(2, 0)+        val text = textBeforeCursor()         val now = SystemClock.uptimeMillis()-        val doubleSpace = kbState.settings.doubleSpacePeriod && before != null && before.length == 2 &&-            before[1] == ' ' && before[0].isLetterOrDigit() && now - lastSpaceTime < 1000+        val doubleSpace = kbState.settings.doubleSpacePeriod && text.length >= 2 &&+            text[text.length - 1] == ' ' && text[text.length - 2].isLetterOrDigit() &&+            now - lastSpaceTime < 1000         if (doubleSpace) {-            ic.deleteSurroundingText(1, 0)-            ic.commitText(". ", 1)+            deleteBackward(ic)+            commit(ic, ". ")         } else {-            ic.commitText(" ", 1)+            commit(ic, " ")         }         lastSpaceTime = now         kbState.suggestions = emptyList()@@ -617,9 +688,9 @@ class KeyboardService : InputMethodService(),             applyComposition(ic, engine, engine.pick(word))             return         }-        ic.setComposingText(word, 1)-        ic.finishComposingText()-        ic.commitText(" ", 1)+        setComposing(ic, word)+        finishComposing(ic)+        commit(ic, " ")         composing.setLength(0)         lastSpaceTime = SystemClock.uptimeMillis()         kbState.suggestions = emptyList()@@ -700,6 +771,7 @@ class KeyboardService : InputMethodService(),             finishComposition(it)             commitCurrentWord(it, autoCorrect = false)         }+         kbState.settings = kbState.settings.copy(activeLayoutId = id)         kbState.shift = ShiftState.OFF         kbState.suggestions = emptyList()@@ -770,7 +842,7 @@ class KeyboardService : InputMethodService(),         } else {             finishComposition(ic)             commitCurrentWord(ic, autoCorrect = false)-            ic.commitText(item.text, 1)+            commit(ic, item.text)             kbState.suggestions = emptyList()         }         updateAutoCapShift()@@ -797,6 +869,8 @@ class KeyboardService : InputMethodService(),             InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION,             null,         )+        // How the field represents an image — if it takes it at all — is up to the app.+        before.invalidate()     }      /**@@ -884,15 +958,15 @@ class KeyboardService : InputMethodService(),     private fun commitCurrentWord(ic: InputConnection, autoCorrect: Boolean) {         if (composing.isEmpty()) return         if (autoCorrect) {+            // autocorrect already declines to rewrite a word it knows, so there is no need+            // to look the typed word up separately first.             val typed = composing.toString()-            if (!dictionary.contains(typed)) {-                val fix = dictionary.autocorrect(typed)-                if (fix != null && !fix.equals(typed, ignoreCase = true)) {-                    ic.setComposingText(fix, 1)-                }+            val fix = dictionary.autocorrect(typed)+            if (fix != null && !fix.equals(typed, ignoreCase = true)) {+                setComposing(ic, fix)             }         }-        ic.finishComposingText()+        finishComposing(ic)         composing.setLength(0)     } @@ -923,25 +997,31 @@ class KeyboardService : InputMethodService(),     }      private fun isAtSentenceStart(): Boolean {-        val ic = currentInputConnection ?: return true-        val before = ic.getTextBeforeCursor(2, 0) ?: return true-        if (before.isEmpty()) return true-        val last = before[before.length - 1]+        val text = textBeforeCursor()+        if (text.isEmpty()) return true+        val last = text[text.length - 1]         if (last == '\n') return true-        if (before.length < 2) return false-        val prev = before[before.length - 2]+        if (text.length < 2) return false+        val prev = text[text.length - 2]         return last == ' ' && (prev == '.' || prev == '?' || prev == '!')     }      // --- Feedback --- +    /**+     * A light key "tick" (like the stock keyboard), not a full-strength buzz. Built once:+     * this runs before the edit on every single keypress, and both the effect and the+     * service lookup were being redone each time.+     */+    private val keyTick by lazy { VibrationEffect.createPredefined(VibrationEffect.EFFECT_TICK) }+    private val audio by lazy { getSystemService(AudioManager::class.java) }+     private fun feedback() {         if (kbState.settings.haptic) {-            // A light key "tick" (like the stock keyboard), not a full-strength buzz.-            vibrator?.vibrate(VibrationEffect.createPredefined(VibrationEffect.EFFECT_TICK))+            vibrator?.vibrate(keyTick)         }         if (kbState.settings.sound) {-            getSystemService(AudioManager::class.java)?.playSoundEffect(AudioManager.FX_KEYPRESS_STANDARD)+            audio?.playSoundEffect(AudioManager.FX_KEYPRESS_STANDARD)         }     } }
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.ktnew file mode 100644index 0000000000..8a93679370--- /dev/null+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/ime/TextBeforeCursor.kt@@ -0,0 +1,143 @@+package com.vayunmathur.keyboard.ime++/**+ * A local mirror of the text immediately before the cursor, and of whether anything is+ * selected.+ *+ * Asking the field for either means a synchronous round-trip into the target app's process.+ * An IME that does that on every keystroke — which reading it for auto-capitalisation and+ * the double-space period amounts to — stalls for as long as that app's main thread is busy,+ * which is why a keyboard can feel fine in one app and stutter in another. So the service+ * reports its own edits here instead and reads the answer locally; the field is only+ * consulted when the mirror genuinely cannot answer.+ *+ * Telling our own edits from everyone else's is what the cursor arithmetic is for: each edit+ * says where it leaves the cursor, and a reported selection anywhere else came from outside+ * (a tap elsewhere in the field, the app rewriting it) and discards the mirror. Predicting+ * wrong therefore costs one reread and never a wrong answer.+ *+ * The mirror holds *final* text only. Callers must not read it while a composition is open,+ * which none do: auto-capitalisation gives up while a word is composing, and the space key+ * settles the composition before it looks behind the cursor.+ */+internal class TextBeforeCursor {++    private val window = StringBuilder()++    /** True when [window] is short because the field starts there, not because it was trimmed. */+    private var atStart = false++    private var known = false++    /** Where the cursor should now be, or -1 when that is anyone's guess. */+    private var cursor = -1++    /** Length of the composition sitting just before the cursor, which is not final yet. */+    private var composingLength = 0++    /** Whether the field has a non-empty selection, as last reported by the framework. */+    var hasSelection = false+        private set++    /** Start over on a new field, told where its cursor and selection are. */+    fun onStartInput(selStart: Int, selEnd: Int) {+        invalidate()+        cursor = selStart+        hasSelection = selStart != selEnd+    }++    /**+     * The text before the cursor, or null when the field has to be asked for it instead.+     * Only valid until the next edit: this is the live buffer, not a copy of it.+     */+    fun peek(): CharSequence? {+        if (!known) return null+        return if (atStart || window.length >= NEEDED) window else null+    }++    /** Take what the field answered, once [peek] has come back null. */+    fun fill(text: CharSequence) {+        window.setLength(0)+        window.append(text)+        atStart = text.length < WINDOW+        known = true+        trim()+    }++    /** Text committed as final, replacing any open composition. */+    fun committed(text: CharSequence) {+        moveCursor(text.length - composingLength)+        composingLength = 0+        append(text)+    }++    /** Text shown as an open composition, replacing any earlier one. */+    fun composing(text: CharSequence) {+        moveCursor(text.length - composingLength)+        composingLength = text.length+    }++    /** The open composition, [text], became final as it stands. */+    fun composingFinished(text: CharSequence) {+        composingLength = 0+        append(text)+    }++    /** One character deleted from in front of the cursor. */+    fun deleted() {+        moveCursor(-1)+        hasSelection = false+        if (!known) return+        when {+            window.isNotEmpty() -> window.deleteCharAt(window.length - 1)+            // 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+        }+    }++    /** An edit whose outcome we cannot predict; the field is the only authority now. */+    fun invalidate() {+        window.setLength(0)+        atStart = false+        known = false+        cursor = -1+        composingLength = 0+    }++    /** Where the framework says the cursor ended up. Anywhere unexpected discards the mirror. */+    fun onSelectionChanged(selStart: Int, selEnd: Int) {+        val ours = selStart == cursor && selStart == selEnd+        if (!ours) {+            invalidate()+            // Resynced, so the next run of our own edits can be followed again.+            cursor = selStart+        }+        hasSelection = selStart != selEnd+    }++    private fun append(text: CharSequence) {+        hasSelection = false+        if (!known) return+        window.append(text)+        trim()+    }++    private fun trim() {+        if (window.length <= WINDOW) return+        window.delete(0, window.length - WINDOW)+        atStart = false+    }++    private fun moveCursor(delta: Int) {+        if (cursor >= 0) cursor = (cursor + delta).coerceAtLeast(0)+    }++    companion object {+        /** How much text to keep, and to ask the field for when the mirror has run dry. */+        const val WINDOW = 16++        /** The furthest back any caller looks; below this the mirror cannot answer. */+        private const val NEEDED = 2+    }+}
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 4a8ac13511..46d5b6dfce 100644--- a/keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyButton.kt+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyButton.kt@@ -24,7 +24,6 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState@@ -113,8 +112,12 @@ fun RowScope.CharKey(     val pressed by interaction.collectIsPressedAsState()     // -1 while the popup is closed, otherwise the alternate under the finger.     var selected by remember { mutableIntStateOf(-1) }-    var keyLeft by remember { mutableFloatStateOf(0f) }-    var keyWidth by remember { mutableFloatStateOf(0f) }+    // Where the key sits, recorded on layout. Deliberately *not* snapshot state: writing+    // state from onGloballyPositioned that composition then reads schedules another+    // recomposition and another layout pass, and with every key on the keyboard doing it+    // that doubles the cost of every relayout. Nothing needs these until a long press has+    // opened the popup, by which point the key has long since been positioned.+    val bounds = remember { KeyBounds() }      val density = LocalDensity.current     val screenWidth = LocalWindowInfo.current.containerSize.width.toFloat()@@ -138,25 +141,13 @@ fun RowScope.CharKey(         if (options.isEmpty()) full else minOf(full, screenWidth / options.length)     } -    // Where the popup's left edge sits relative to the key's: centred on the key, then-    // nudged back inside the screen. The drag-to-select maths below uses the same number,-    // so what the finger is over is always what is highlighted.-    val popupOffset = remember(options, itemWidth, keyLeft, keyWidth) {-        val total = itemWidth * options.length-        val centred = keyLeft + (keyWidth - total) / 2f-        val clamped = centred.coerceIn(0f, (screenWidth - total).coerceAtLeast(0f))-        clamped - keyLeft-    }-     // The gesture below reads all of these through snapshots rather than capturing them, so it-    // never has to be restarted to pick up a new value — including popupOffset, which is still-    // 0 on the first composition and only gets its real value once the key has been positioned.-    // See the note on `pointerInput(Unit)`.+    // never has to be restarted to pick up a new value. See the note on `pointerInput(Unit)`.     val currentOnClick by rememberUpdatedState(onClick)     val currentOnAlternate by rememberUpdatedState(onAlternate)     val currentOptions by rememberUpdatedState(options)     val currentItemWidth by rememberUpdatedState(itemWidth)-    val currentPopupOffset by rememberUpdatedState(popupOffset)+    val currentScreenWidth by rememberUpdatedState(screenWidth)      Box(         modifier = Modifier@@ -166,8 +157,8 @@ fun RowScope.CharKey(             // down, but only for the visual (clip + background), never for hit-testing.             .height(height + KeyPadding * 2)             .onGloballyPositioned {-                keyLeft = it.positionInWindow().x-                keyWidth = it.size.width.toFloat()+                bounds.left = it.positionInWindow().x+                bounds.width = it.size.width.toFloat()             }             // Written out rather than assembled from detectTapGestures because tap and             // long-press are one continuous gesture here: the long press opens the popup@@ -201,12 +192,13 @@ fun RowScope.CharKey(                             continue                         }                         val picked = awaitPointerEventScope {-                            selected = indexAt(down.position.x, currentPopupOffset, currentItemWidth, opts.length)+                            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, currentPopupOffset, currentItemWidth, opts.length)+                                selected = indexAt(change.position.x, offset, currentItemWidth, opts.length)                             }                             selected                         }@@ -273,7 +265,7 @@ fun RowScope.CharKey(                 options = options,                 selected = selected,                 itemWidth = with(density) { itemWidth.toDp() },-                offsetX = popupOffset.toInt(),+                offsetX = alternatesOffset(bounds, itemWidth, options.length, screenWidth).toInt(),             )             // FUTO/AOSP-style preview: while held, balloon the character above the key so             // the finger doesn't hide it. clippingEnabled=false lets it float above the@@ -283,6 +275,24 @@ fun RowScope.CharKey(     } } +/** Where a key ended up on screen, as of the last layout pass. */+private class KeyBounds {+    var left = 0f+    var width = 0f+}++/**+ * Where the alternates row's left edge sits relative to the key's: centred on the key, then+ * nudged back inside the screen. The gesture that picks from the row uses the same number, so+ * what the finger is over is always what is highlighted.+ */+private fun alternatesOffset(bounds: KeyBounds, itemWidth: Float, count: Int, screenWidth: Float): Float {+    val total = itemWidth * count+    val centred = bounds.left + (bounds.width - total) / 2f+    val clamped = centred.coerceIn(0f, (screenWidth - total).coerceAtLeast(0f))+    return clamped - bounds.left+}+ /** True while the finger is still over the key it went down on. */ private fun Offset.isInside(size: IntSize): Boolean =     x >= 0f && y >= 0f && x <= size.width && y <= size.height
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 28a88c8a9d..4477ad8fa0 100644--- a/keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyboardScreen.kt+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyboardScreen.kt@@ -9,6 +9,9 @@ import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable+import androidx.compose.runtime.derivedStateOf+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Dp@@ -41,6 +44,10 @@ import com.vayunmathur.library.ui.Text  * Root of the keyboard view: a suggestion strip (when enabled) above whichever page of keys  * is active. All sizing is weight-based so it fills the width; key height scales with the  * user's height-scale setting.+ *+ * The pieces below are split into their own composables along the lines of what changes+ * while typing: a keystroke produces new suggestions and usually flips shift, and reading+ * either of those here would redraw every key on the keyboard twice per keypress.  */ @Composable fun KeyboardScreen(state: KeyboardState, actions: ImeActions) {@@ -52,94 +59,119 @@ fun KeyboardScreen(state: KeyboardState, actions: ImeActions) {     // with a floor so there's breathing room even when the inset reads small (gesture nav).     val bottomInset = with(LocalDensity.current) { state.bottomInsetPx.toDp() }     val bottomPad = (bottomInset + 18.dp).coerceAtLeast(30.dp)+    // Derived rather than read straight: the query changes on every keystroke of a search,+    // and only arriving at or leaving search should rearrange the keyboard.+    val searching by remember(state) { derivedStateOf { state.emojiQuery != null } }     Surface(color = MaterialTheme.colorScheme.surfaceContainer) {         Column(             modifier = Modifier                 .fillMaxWidth()                 .padding(bottom = bottomPad),         ) {-            val query = state.emojiQuery-            if (query != null) {+            if (searching) {                 // Search borrows the ordinary letter keys rather than shipping a second                 // keyboard: the query bar and the results sit on top of LettersPage, and the                 // service routes keystrokes into the query while this is showing.-                EmojiSearchBar(height = StripHeight, query = query, onClose = actions::endEmojiSearch)-                EmojiSearchResults(-                    height = StripHeight,-                    results = state.emojiResults,-                    onPick = actions::commitEmoji,-                )+                EmojiSearchStrip(state, actions)                 LettersPage(state, actions, keyHeight)-                return@Column-            }-            // The strip belongs to text entry only; numeric/phone/emoji pages never compose-            // words, so (like FUTO) they show no strip. Nor do layouts that have nothing to-            // put in it: the one dictionary we ship is English.-            val layout = state.settings.activeLayout-            val textPage = state.page == KeyboardPage.LETTERS ||-                state.page == KeyboardPage.SYMBOLS ||-                state.page == KeyboardPage.MORE_SYMBOLS-            val clip = state.clipSuggestion-            when {-                // 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.-                clip != null -> ClipboardStrip(-                    height = StripHeight,-                    item = clip,-                    onOpen = { actions.setPage(KeyboardPage.CLIPBOARD) },-                    onPaste = { actions.pasteClip(clip) },-                    onDelete = { actions.deleteClip(clip) },-                )-                // Candidates are not a suggestion the user can decline — on a Chinese layout-                // they are the only way a character gets typed — so the "show suggestions"-                // preference does not apply to them.-                textPage && layout.offersCandidates -> CandidateStrip(-                    height = StripHeight,-                    candidates = state.suggestions,-                    onPick = actions::commitSuggestion,-                )-                textPage && layout.englishDictionary && state.settings.showSuggestions ->-                    SuggestionStrip(-                        height = StripHeight,-                        suggestions = state.suggestions,-                        onPick = actions::commitSuggestion,-                    )-            }-            when (state.page) {-                KeyboardPage.LETTERS -> LettersPage(state, actions, keyHeight)-                KeyboardPage.SYMBOLS ->-                    SymbolPage(state, actions, keyHeight, Layouts.SYMBOL_ROWS, KeyboardPage.MORE_SYMBOLS, "=\\<")-                KeyboardPage.MORE_SYMBOLS ->-                    SymbolPage(state, actions, keyHeight, Layouts.MORE_SYMBOL_ROWS, KeyboardPage.SYMBOLS, "?123")-                KeyboardPage.NUMERIC -> NumericPage(state, actions, keyHeight)-                KeyboardPage.PHONE -> PhonePage(state, actions, keyHeight)-                KeyboardPage.PHONE_SYMBOLS -> PhoneSymbolsPage(state, actions, keyHeight)-                KeyboardPage.EMOJI -> EmojiPage(-                    data = state.emojiData,-                    recents = state.recentEmoji,-                    keyHeight = keyHeight,-                    rows = 4,-                    onEmoji = actions::commitEmoji,-                    onSearch = actions::startEmojiSearch,-                    onBackspace = actions::onBackspace,-                    onBack = { actions.setPage(state.basePage) },-                )-                KeyboardPage.CLIPBOARD -> ClipboardPage(-                    clips = state.clips,-                    keyHeight = keyHeight,-                    rows = 4,-                    onPaste = actions::pasteClip,-                    onDelete = actions::deleteClip,-                    onClearAll = actions::clearClips,-                    onBackspace = actions::onBackspace,-                    onBack = { actions.setPage(state.basePage) },-                )+            } else {+                Strip(state, actions)+                KeyPage(state, actions, keyHeight)             }         }     } } +/** The emoji-search query bar and its results, which change together on every keystroke. */+@Composable+private fun EmojiSearchStrip(state: KeyboardState, actions: ImeActions) {+    val query = state.emojiQuery ?: return+    EmojiSearchBar(height = StripHeight, query = query, onClose = actions::endEmojiSearch)+    EmojiSearchResults(+        height = StripHeight,+        results = state.emojiResults,+        onPick = actions::commitEmoji,+    )+}++/** Whatever occupies the strip above the keys, or nothing. */+@Composable+private fun Strip(state: KeyboardState, actions: ImeActions) {+    // 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.+    val clip = state.clipSuggestion+    if (clip != null) {+        ClipboardStrip(+            height = StripHeight,+            item = clip,+            onOpen = { actions.setPage(KeyboardPage.CLIPBOARD) },+            onPaste = { actions.pasteClip(clip) },+            onDelete = { actions.deleteClip(clip) },+        )+        return+    }+    // The strip belongs to text entry only; numeric/phone/emoji pages never compose words,+    // so (like FUTO) they show no strip.+    val page = state.page+    val textPage = page == KeyboardPage.LETTERS ||+        page == KeyboardPage.SYMBOLS ||+        page == KeyboardPage.MORE_SYMBOLS+    if (!textPage) return+    // Nor do layouts that have nothing to put in it: the one dictionary we ship is English.+    val layout = state.settings.activeLayout+    when {+        // Candidates are not a suggestion the user can decline — on a Chinese layout they+        // are the only way a character gets typed — so the "show suggestions" preference+        // does not apply to them.+        layout.offersCandidates -> CandidateStrip(+            height = StripHeight,+            candidates = state.suggestions,+            onPick = actions::commitSuggestion,+        )+        layout.englishDictionary && state.settings.showSuggestions -> SuggestionStrip(+            height = StripHeight,+            suggestions = state.suggestions,+            onPick = actions::commitSuggestion,+        )+    }+}++/** The active page of keys. */+@Composable+private fun KeyPage(state: KeyboardState, actions: ImeActions, keyHeight: Dp) {+    when (state.page) {+        KeyboardPage.LETTERS -> LettersPage(state, actions, keyHeight)+        KeyboardPage.SYMBOLS ->+            SymbolPage(state, actions, keyHeight, Layouts.SYMBOL_ROWS, KeyboardPage.MORE_SYMBOLS, "=\\<")+        KeyboardPage.MORE_SYMBOLS ->+            SymbolPage(state, actions, keyHeight, Layouts.MORE_SYMBOL_ROWS, KeyboardPage.SYMBOLS, "?123")+        KeyboardPage.NUMERIC -> NumericPage(state, actions, keyHeight)+        KeyboardPage.PHONE -> PhonePage(state, actions, keyHeight)+        KeyboardPage.PHONE_SYMBOLS -> PhoneSymbolsPage(state, actions, keyHeight)+        KeyboardPage.EMOJI -> EmojiPage(+            data = state.emojiData,+            recents = state.recentEmoji,+            keyHeight = keyHeight,+            rows = 4,+            onEmoji = actions::commitEmoji,+            onSearch = actions::startEmojiSearch,+            onBackspace = actions::onBackspace,+            onBack = { actions.setPage(state.basePage) },+        )+        KeyboardPage.CLIPBOARD -> ClipboardPage(+            clips = state.clips,+            keyHeight = keyHeight,+            rows = 4,+            onPaste = actions::pasteClip,+            onDelete = actions::deleteClip,+            onClearAll = actions::clearClips,+            onBackspace = actions::onBackspace,+            onBack = { actions.setPage(state.basePage) },+        )+    }+}+ /** Height of the strip above the keys, shared by everything that can occupy it. */ private val StripHeight = 44.dp @@ -156,8 +188,6 @@ private val StripHeight = 44.dp private fun LettersPage(state: KeyboardState, actions: ImeActions, keyHeight: Dp) {     val layout = state.settings.activeLayout     val rows = layout.rows-    val shift = state.shift-    val slack = { row: Int -> (layout.width - rows[row].length) / 2f }     if (state.settings.numberRow && rows.size < 4) {         Row(Modifier.fillMaxWidth()) {             DIGITS.forEach {@@ -169,6 +199,36 @@ private fun LettersPage(state: KeyboardState, actions: ImeActions, keyHeight: Dp     // The two are mutually exclusive so a digit is never reachable two ways at once, and     // layouts with four rows already spend that row on their own script.     val topRowDigits = !state.settings.numberRow && rows.size < 4+    LetterRows(state, layout, actions, keyHeight, topRowDigits)+    // Email/URL fields surface @ or / where the comma usually sits.+    val commaChar = when (state.textVariation) {+        TextVariation.EMAIL -> "@"+        TextVariation.URL -> "/"+        TextVariation.NORMAL -> layout.comma+    }+    BottomRow(+        state, actions, keyHeight,+        leftLabel = "?123", leftTarget = KeyboardPage.SYMBOLS,+        commaChar = commaChar, periodChar = layout.period,+    )+}++/**+ * The letter rows proper, which are the only part of the page whose labels depend on shift.+ * Separated from the rest so that a shift change — which auto-capitalisation makes on most+ * keystrokes — redraws these and leaves the number row and the bottom row alone.+ */+@Composable+private fun LetterRows(+    state: KeyboardState,+    layout: KeyboardLayout,+    actions: ImeActions,+    keyHeight: Dp,+    topRowDigits: Boolean,+) {+    val rows = layout.rows+    val shift = state.shift+    val slack = { row: Int -> (layout.width - rows[row].length) / 2f }     for (r in 0 until rows.size - 1) {         Row(Modifier.fillMaxWidth()) {             if (slack(r) > 0f) Spacer(Modifier.weight(slack(r)))@@ -196,17 +256,6 @@ private fun LettersPage(state: KeyboardState, actions: ImeActions, keyHeight: Dp         }         RepeatKey(keyHeight, edge, actions::onBackspace) { IconBackspace() }     }-    // Email/URL fields surface @ or / where the comma usually sits.-    val commaChar = when (state.textVariation) {-        TextVariation.EMAIL -> "@"-        TextVariation.URL -> "/"-        TextVariation.NORMAL -> layout.comma-    }-    BottomRow(-        state, actions, keyHeight,-        leftLabel = "?123", leftTarget = KeyboardPage.SYMBOLS,-        commaChar = commaChar, periodChar = layout.period,-    ) }  /**
keyboard/src/main/java/com/vayunmathur/keyboard/util/Dictionary.kt
diff --git a/keyboard/src/main/java/com/vayunmathur/keyboard/util/Dictionary.kt b/keyboard/src/main/java/com/vayunmathur/keyboard/util/Dictionary.ktindex 2de2a6584f..48b3cac2d6 100644--- a/keyboard/src/main/java/com/vayunmathur/keyboard/util/Dictionary.kt+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/util/Dictionary.kt@@ -22,11 +22,13 @@ class Dictionary private constructor(     private val words: List<String>,     private val freqs: IntArray,     /**-     * Indices into [words] bucketed by word length, so [autocorrect] can look at just the-     * three lengths that can be within one edit instead of scanning the whole list. Index-     * `n` holds every word of length `n`; short trailing lengths may be empty.+     * Indices into [words] bucketed by (word length, first character), and the same by+     * second character — the two indexes [autocorrect] intersects its candidates from.+     * Only offerable words (frequency > 0) are indexed, since the others can never be+     * produced as a correction anyway. Keyed by [bucketKey].      */-    private val byLength: Array<IntArray>,+    private val byFirst: Map<Int, IntArray>,+    private val bySecond: Map<Int, IntArray>, ) {     /** True if [word] (any case) is a known dictionary word. */     fun contains(word: String): Boolean {@@ -62,21 +64,54 @@ class Dictionary private constructor(     fun autocorrect(word: String): String? {         if (word.length < 2) return null         val lower = word.lowercase()-        if (contains(lower)) return null+        if (indexOf(lower) >= 0) return null++        val len = lower.length+        val first = lower[0]+        val second = lower[1]          var best = -1         var bestFreq = 0 // 0 also excludes never-offered words without a second check.-        // Edit distance 1 can only change the length by one, so these are the only three-        // buckets worth looking at — roughly 5% of the list rather than all of it.-        for (len in (lower.length - 1)..(lower.length + 1)) {-            if (len < 1 || len >= byLength.size) continue-            for (idx in byLength[len]) {+        fun scan(bucket: IntArray?) {+            if (bucket == null) return+            for (idx in bucket) {                 if (freqs[idx] <= bestFreq) continue // includes the freq == 0 exclusion                 if (!withinEditDistance1(lower, words[idx])) continue                 bestFreq = freqs[idx]                 best = idx             }         }++        // Bucketing by length alone meant reading the three fattest buckets in the list —+        // for a 7-letter word that is 17k of the 42k words, on the main thread, while the+        // user waits for the space they just pressed. Pinning a character position as well+        // cuts that by six to nine times (2.7k candidates for a 7-letter word, 300 for a+        // 3-letter one), and these seven buckets provably still contain every word within+        // one edit of `lower` (call it `w`, and note `len` >= 2 here):+        //+        //  - Same length: one substitution, or one transposition of adjacent characters.+        //    Either it leaves position 0 alone, so w[0] == first; or it is at position 0,+        //    where a substitution leaves w[1] == second and a transposition puts `second`+        //    itself at w[0].+        //  - One shorter (the typed word has the extra character): dropping that character+        //    leaves w[0] == first, unless what was dropped *was* the first, which leaves+        //    w[0] == second.+        //  - One longer (the candidate has the extra character): removing it leaves+        //    w[0] == first, unless it was the candidate's own first character, which+        //    leaves w[1] == first.+        //+        // Buckets overlap when first == second; re-scanning one is harmless (picking the+        // best is idempotent) but pointless, so those lookups are skipped.+        scan(byFirst[bucketKey(len, first)])+        scan(bySecond[bucketKey(len, second)])+        scan(byFirst[bucketKey(len - 1, first)])+        if (second != first) {+            scan(byFirst[bucketKey(len, second)])+            scan(byFirst[bucketKey(len - 1, second)])+        }+        scan(byFirst[bucketKey(len + 1, first)])+        scan(bySecond[bucketKey(len + 1, first)])+         return if (best >= 0) capitalizeLike(word, words[best]) else null     } @@ -128,7 +163,13 @@ class Dictionary private constructor(      companion object {         /** An empty dictionary used before loading completes. */-        val EMPTY = Dictionary(emptyList(), IntArray(0), emptyArray())+        val EMPTY = Dictionary(emptyList(), IntArray(0), emptyMap(), emptyMap())++        /**+         * Key for the [byFirst]/[bySecond] buckets: a word length paired with the+         * character at the position that index pins.+         */+        private fun bucketKey(length: Int, c: Char): Int = (length shl 16) or c.code          /** Load and index the bundled word list off the main thread. */         suspend fun load(context: Context): Dictionary = withContext(Dispatchers.IO) {@@ -175,20 +216,27 @@ class Dictionary private constructor(             val words = sorted.map { it.key }             val freqs = IntArray(sorted.size) { sorted[it].value } -            // Bucket indices by length in one pass: count, allocate exactly, then fill.-            val maxLen = words.maxOfOrNull { it.length } ?: 0-            val counts = IntArray(maxLen + 1)-            for (w in words) counts[w.length]++-            val byLength = Array(maxLen + 1) { IntArray(counts[it]) }-            val fill = IntArray(maxLen + 1)+            // Correction candidates, indexed on the two character positions autocorrect+            // pins. Words at frequency 0 are left out: they are never offered, so they can+            // never be the answer, and skipping them shrinks every bucket.+            val byFirst = HashMap<Int, MutableList<Int>>()+            val bySecond = HashMap<Int, MutableList<Int>>()             for (i in words.indices) {-                val len = words[i].length-                byLength[len][fill[len]++] = i+                if (freqs[i] <= 0) continue+                val w = words[i]+                byFirst.getOrPut(bucketKey(w.length, w[0])) { ArrayList() }.add(i)+                if (w.length > 1) {+                    bySecond.getOrPut(bucketKey(w.length, w[1])) { ArrayList() }.add(i)+                }             } -            return Dictionary(words, freqs, byLength)+            return Dictionary(words, freqs, byFirst.packed(), bySecond.packed())         } +        /** Collapse the index's per-bucket lists into arrays, which is how they are read. */+        private fun Map<Int, MutableList<Int>>.packed(): Map<Int, IntArray> =+            mapValues { (_, indices) -> indices.toIntArray() }+         /** Apply [sample]'s leading capitalization to [word]. */         private fun capitalizeLike(sample: String, word: String): String = when {             sample.isNotEmpty() && sample.all { it.isUpperCase() } && sample.length > 1 -> word.uppercase()
keyboard/src/main/java/com/vayunmathur/keyboard/util/Emojis.kt
diff --git a/keyboard/src/main/java/com/vayunmathur/keyboard/util/Emojis.kt b/keyboard/src/main/java/com/vayunmathur/keyboard/util/Emojis.ktindex 753e7b44cd..1439a54190 100644--- a/keyboard/src/main/java/com/vayunmathur/keyboard/util/Emojis.kt+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/util/Emojis.kt@@ -11,7 +11,17 @@ data class EmojiCategory(val label: String, val emojis: List<String>)  * One emoji plus the text search matches against: the CLDR short name ("grinning face")  * and its keywords ("happy", "smile", ...). Both are lowercase.  */-data class EmojiEntry(val char: String, val name: String, val keywords: List<String>)+data class EmojiEntry(val char: String, val name: String, val keywords: List<String>) {+    /**+     * The words of [name] after the first. Search runs over every entry on every keystroke,+     * so splitting the name there allocated a list per emoji per keypress; this does it once+     * when the palette is read instead.+     *+     * The first word is left out because it cannot add a match: a query that starts it also+     * starts the whole name, which search has already ranked higher.+     */+    val laterNameWords: List<String> = name.split(' ').drop(1)+}  /**  * The emoji the user picked most recently, newest first. Kept out of [KeyboardSettings]@@ -59,7 +69,7 @@ class EmojiData(         for (entry in entries) {             val bucket = when {                 entry.name.startsWith(q) -> name-                entry.name.split(' ').any { it.startsWith(q) } -> word+                entry.laterNameWords.any { it.startsWith(q) } -> word                 entry.keywords.any { it.startsWith(q) } -> keyword                 else -> continue             }
keyboard/src/test/java/com/vayunmathur/keyboard/util/DictionaryTest.kt
diff --git a/keyboard/src/test/java/com/vayunmathur/keyboard/util/DictionaryTest.kt b/keyboard/src/test/java/com/vayunmathur/keyboard/util/DictionaryTest.ktindex 2a3c3a9fdc..e16c9a652d 100644--- a/keyboard/src/test/java/com/vayunmathur/keyboard/util/DictionaryTest.kt+++ b/keyboard/src/test/java/com/vayunmathur/keyboard/util/DictionaryTest.kt@@ -144,6 +144,29 @@ class DictionaryTest {         assertNull(d.autocorrect("abc"))     } +    /**+     * The three cases below are the ones the candidate index is easiest to get wrong: each+     * one is a correction whose first character is not the first character the user typed,+     * so a naive "same length, same first letter" bucket would never find it.+     */+    @Test+    fun aTranspositionOfTheFirstTwoCharactersIsCorrected() {+        val d = Dictionary.fromEntries(listOf("you" to 100))+        assertEquals("you", d.autocorrect("oyu"))+    }++    @Test+    fun anExtraCharacterTypedBeforeTheWordIsCorrected() {+        val d = Dictionary.fromEntries(listOf("the" to 100))+        assertEquals("the", d.autocorrect("xthe"))+    }++    @Test+    fun aMissingFirstCharacterIsCorrected() {+        val d = Dictionary.fromEntries(listOf("the" to 100))+        assertEquals("the", d.autocorrect("he"))+    }+     @Test     fun twoEditsAwayIsNotCorrected() {         assertNull(editDict.autocorrect("xyzzy"))
library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt b/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.ktindex 12cd8113c0..ac56942f97 100644--- a/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt+++ b/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt@@ -18,6 +18,7 @@ import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.mapNotNull@@ -62,8 +63,12 @@ class DataStoreUtils private constructor(context: Context) {         return dataStore.data.first()[longPreferencesKey(name)]     } +    // `dataStore.data` re-emits the whole preference set on every write, so without this a+    // collector of one key wakes up for every change to any other. Anything watching a+    // handful of keys at once (the keyboard watches twelve) otherwise does that much+    // redundant work on each save.     fun booleanFlow(name: String): Flow<Boolean> {-        return dataStore.data.mapNotNull { it[booleanPreferencesKey(name)] }+        return dataStore.data.mapNotNull { it[booleanPreferencesKey(name)] }.distinctUntilChanged()     }      /** Suspend variant that awaits DataStore hydration. */@@ -78,11 +83,11 @@ class DataStoreUtils private constructor(context: Context) {     }      fun longFlow(s: String): Flow<Long> {-        return dataStore.data.mapNotNull { it[longPreferencesKey(s)] }+        return dataStore.data.mapNotNull { it[longPreferencesKey(s)] }.distinctUntilChanged()     }      fun longFlow(name: String, default: Long): Flow<Long> {-        return dataStore.data.map { it[longPreferencesKey(name)] ?: default }+        return dataStore.data.map { it[longPreferencesKey(name)] ?: default }.distinctUntilChanged()     }      suspend fun setLong(s: String, userid: Long, onlyIfAbsent: Boolean = false) {@@ -106,7 +111,7 @@ class DataStoreUtils private constructor(context: Context) {     }      fun doubleFlow(string: String): Flow<Double> {-        return dataStore.data.mapNotNull { it[doublePreferencesKey(string)] }+        return dataStore.data.mapNotNull { it[doublePreferencesKey(string)] }.distinctUntilChanged()     }      fun getDouble(name: String): Double? {@@ -136,11 +141,11 @@ class DataStoreUtils private constructor(context: Context) {     }      fun stringFlow(key: String): Flow<String> {-        return dataStore.data.mapNotNull { it[stringPreferencesKey(key)] }+        return dataStore.data.mapNotNull { it[stringPreferencesKey(key)] }.distinctUntilChanged()     }      fun stringSetFlow(key: String): Flow<Set<String>> {-        return dataStore.data.map { it[stringSetPreferencesKey(key)] ?: emptySet() }+        return dataStore.data.map { it[stringSetPreferencesKey(key)] ?: emptySet() }.distinctUntilChanged()     }      /**
metadata_data/launcher.md
diff --git a/metadata_data/launcher.md b/metadata_data/launcher.mdnew file mode 100644index 0000000000..b0ea5f1dff--- /dev/null+++ b/metadata_data/launcher.md@@ -0,0 +1,7 @@+A home screen++A home screen replacement with a paged icon grid, a hotseat, folders, a searchable app drawer, and real home screen widgets.++Widgets are hosted directly, so anything that works on your current launcher works here — including providers that need a configuration step before they appear. Icons, folders and widgets are laid out on a cell grid whose size you choose, and the layout is kept in an encrypted database on your device.++Nothing is collected, nothing is uploaded, and there is no account. Recents and the swipe-up gesture stay with the system launcher; those need signature-level access no third-party app can have.
metadata_data/photos/share/1.png
diff --git a/metadata_data/photos/share/1.png b/metadata_data/photos/share/1.pngnew file mode 100644index 0000000000..8f8083ba3fBinary files /dev/null and b/metadata_data/photos/share/1.png differ
metadata_data/photos/share/2.png
diff --git a/metadata_data/photos/share/2.png b/metadata_data/photos/share/2.pngnew file mode 100644index 0000000000..186bf97d28Binary files /dev/null and b/metadata_data/photos/share/2.png differ
metadata_data/photos/share/3.png
diff --git a/metadata_data/photos/share/3.png b/metadata_data/photos/share/3.pngnew file mode 100644index 0000000000..43b5b9872cBinary files /dev/null and b/metadata_data/photos/share/3.png differ
metadata_data/photos/share/4.png
diff --git a/metadata_data/photos/share/4.png b/metadata_data/photos/share/4.pngnew file mode 100644index 0000000000..4305a6584aBinary files /dev/null and b/metadata_data/photos/share/4.png differ
metadata_data/photos/share/5.png
diff --git a/metadata_data/photos/share/5.png b/metadata_data/photos/share/5.pngnew file mode 100644index 0000000000..732c911d61Binary files /dev/null and b/metadata_data/photos/share/5.png differ