Modern Apps git

← Modern-Apps.git

new app: keyboard

Commit
7d9347cd90b31870eeace7760cffa28ca0145018
Author
Vayun Mathur <[email protected]>
When
2026-07-30 20:55 UTC (4 months ago)
Parents
a4403c8

Diff

keyboard/build.gradle.kts
diff --git a/keyboard/build.gradle.kts b/keyboard/build.gradle.ktsnew file mode 100644index 0000000000..81dff28af6--- /dev/null+++ b/keyboard/build.gradle.kts@@ -0,0 +1,19 @@+plugins {+    id("common-conventions-app")+    id("common-conventions-metadata")+    alias(libs.plugins.ksp)+}++launcherIcon {+    symbol = "keyboard"+}++android {+    defaultConfig {+        applicationId = "com.vayunmathur.keyboard"+    }+}++dependencies {+    implementation(libs.androidx.datastore.preferences)+}
keyboard/src/main/AndroidManifest.xml
diff --git a/keyboard/src/main/AndroidManifest.xml b/keyboard/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..7c36a638e4--- /dev/null+++ b/keyboard/src/main/AndroidManifest.xml@@ -0,0 +1,42 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++    <uses-permission android:name="android.permission.VIBRATE" />++    <application+        android:allowBackup="true"+        android:dataExtractionRules="@xml/data_extraction_rules"+        android:icon="@mipmap/ic_launcher"+        android:label="@string/app_name"+        android:roundIcon="@mipmap/ic_launcher"+        android:supportsRtl="true"+        android:theme="@style/Theme.General">++        <!-- Setup / settings launcher activity. -->+        <activity+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:name=".MainActivity"+            android:exported="true"+            android:theme="@style/Theme.General">+            <intent-filter>+                <action android:name="android.intent.action.MAIN" />+                <category android:name="android.intent.category.LAUNCHER" />+            </intent-filter>+        </activity>++        <!-- The input method (IME) service the system binds to. -->+        <service+            android:name=".ime.KeyboardService"+            android:label="@string/app_name"+            android:permission="android.permission.BIND_INPUT_METHOD"+            android:exported="true">+            <intent-filter>+                <action android:name="android.view.InputMethod" />+            </intent-filter>+            <meta-data+                android:name="android.view.im"+                android:resource="@xml/method" />+        </service>+    </application>++</manifest>
keyboard/src/main/assets/dict/words_en.txt
diff --git a/keyboard/src/main/assets/dict/words_en.txt b/keyboard/src/main/assets/dict/words_en.txtnew file mode 100644index 0000000000..280a2e4924--- /dev/null+++ b/keyboard/src/main/assets/dict/words_en.txt@@ -0,0 +1,330 @@+# Starter English word list for the offline keyboard.+# Format: one entry per line, either "word" or "word<TAB>frequency".+# When no frequency column is present, words are ranked by position (most common first).+# This is a small curated starter set (~350 of the most common English words) meant to+# demonstrate suggestions/autocorrect. Replace with a much larger frequency list+# (e.g. a public unigram frequency dump) for production quality; the loader in+# Dictionary.kt already handles a large "word<TAB>freq" file dropped in here.+the+be+to+of+and+a+in+that+have+i+it+for+not+on+with+he+as+you+do+at+this+but+his+by+from+they+we+say+her+she+or+an+will+my+one+all+would+there+their+what+so+up+out+if+about+who+get+which+go+me+when+make+can+like+time+no+just+him+know+take+people+into+year+your+good+some+could+them+see+other+than+then+now+look+only+come+its+over+think+also+back+after+use+two+how+our+work+first+well+way+even+new+want+because+any+these+give+day+most+us+is+was+are+been+has+had+were+said+did+getting+made+find+where+much+too+very+still+being+going+why+before+never+here+more+something+nothing+another+while+last+might+great+old+right+big+high+small+large+next+early+young+important+few+public+bad+same+able+country+world+school+state+family+student+group+problem+hand+part+place+case+week+company+system+program+question+government+number+night+point+home+water+room+mother+area+money+story+fact+month+lot+study+book+eye+job+word+business+issue+side+kind+head+house+service+friend+father+power+hour+game+line+end+member+law+car+city+community+name+president+team+minute+idea+kid+body+information+nothing+parent+face+level+office+door+health+person+art+war+history+party+result+change+morning+reason+research+girl+guy+moment+air+teacher+force+education+love+hello+please+thanks+thank+sorry+yes+yeah+okay+maybe+today+tomorrow+tonight+always+around+together+sometimes+everything+everyone+someone+anyone+myself+yourself+himself+herself+message+phone+email+text+call+send+type+keyboard+computer+internet+online+password+account+address+number+morning+afternoon+evening+weekend+holiday+birthday+happy+better+best+sure+really+actually+probably+definitely+absolutely+awesome+amazing+beautiful+wonderful+perfect+great+excited+tired+hungry+ready+finished+started+working+talking+looking+coming+going+making+taking+thinking+feeling+trying+using+playing+reading+writing+running+walking+eating+sleeping+watching+listening+learning+teaching+building
keyboard/src/main/java/com/vayunmathur/keyboard/MainActivity.kt
diff --git a/keyboard/src/main/java/com/vayunmathur/keyboard/MainActivity.kt b/keyboard/src/main/java/com/vayunmathur/keyboard/MainActivity.ktnew file mode 100644index 0000000000..9f1596f504--- /dev/null+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/MainActivity.kt@@ -0,0 +1,24 @@+package com.vayunmathur.keyboard++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import com.vayunmathur.keyboard.ui.SetupScreen+import com.vayunmathur.library.ui.DynamicTheme++/**+ * Setup + settings entry point. The IME itself lives in [com.vayunmathur.keyboard.ime.KeyboardService];+ * this activity only helps the user enable/select the keyboard and tune its preferences.+ */+class MainActivity : ComponentActivity() {+    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        enableEdgeToEdge()+        setContent {+            DynamicTheme {+                SetupScreen()+            }+        }+    }+}
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.ktnew file mode 100644index 0000000000..f4613de752--- /dev/null+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/ime/KeyboardService.kt@@ -0,0 +1,438 @@+package com.vayunmathur.keyboard.ime++import android.inputmethodservice.InputMethodService+import android.media.AudioManager+import android.os.SystemClock+import android.os.VibrationEffect+import android.os.Vibrator+import android.os.VibratorManager+import android.text.InputType+import android.view.KeyEvent+import android.view.View+import android.view.inputmethod.EditorInfo+import android.view.inputmethod.InputConnection+import android.view.inputmethod.InputMethodManager+import androidx.compose.ui.platform.ComposeView+import androidx.compose.ui.platform.ViewCompositionStrategy+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleOwner+import androidx.lifecycle.LifecycleRegistry+import androidx.lifecycle.ViewModelStore+import androidx.lifecycle.ViewModelStoreOwner+import androidx.lifecycle.setViewTreeLifecycleOwner+import androidx.lifecycle.setViewTreeViewModelStoreOwner+import androidx.savedstate.SavedStateRegistry+import androidx.savedstate.SavedStateRegistryController+import androidx.savedstate.SavedStateRegistryOwner+import androidx.savedstate.setViewTreeSavedStateRegistryOwner+import com.vayunmathur.keyboard.ui.KeyboardScreen+import com.vayunmathur.keyboard.util.Dictionary+import com.vayunmathur.keyboard.util.KeyboardPage+import com.vayunmathur.keyboard.util.KeyboardSettings+import com.vayunmathur.keyboard.util.Layouts+import com.vayunmathur.keyboard.util.ShiftState+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.flow.collectLatest+import kotlinx.coroutines.launch++/**+ * The input method (IME). Renders the keyboard with Compose and turns key actions into edits+ * on the target field's [InputConnection].+ *+ * Compose views need a [LifecycleOwner], [ViewModelStoreOwner] and [SavedStateRegistryOwner]+ * in their view tree; an [InputMethodService] provides none, so this service implements all+ * three and drives the lifecycle from the IME window callbacks.+ */+/** Max gap between two shift taps to latch caps-lock. */+private const val DOUBLE_TAP_MS = 300L++class KeyboardService : InputMethodService(),+    LifecycleOwner, ViewModelStoreOwner, SavedStateRegistryOwner, ImeActions {++    private val lifecycleRegistry = LifecycleRegistry(this)+    private val store = ViewModelStore()+    private val savedStateRegistryController = SavedStateRegistryController.create(this)++    override val lifecycle: Lifecycle get() = lifecycleRegistry+    override val viewModelStore: ViewModelStore get() = store+    override val savedStateRegistry: SavedStateRegistry get() = savedStateRegistryController.savedStateRegistry++    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)++    private lateinit var ds: DataStoreUtils+    private val kbState = KeyboardState()+    private var dictionary: Dictionary = Dictionary.EMPTY++    /** The word currently being composed (underlined) on the letters page. */+    private val composing = StringBuilder()+    private var lastSpaceTime = 0L+    private var lastShiftTime = 0L++    /** Enter behaviour derived from the current field. */+    private var editorActionId = EditorInfo.IME_ACTION_UNSPECIFIED+    private var enterSendsAction = false++    private var vibrator: Vibrator? = null++    override fun onCreate() {+        super.onCreate()+        savedStateRegistryController.performAttach()+        savedStateRegistryController.performRestore(null)+        lifecycleRegistry.currentState = Lifecycle.State.CREATED++        ds = DataStoreUtils.getInstance(this)+        kbState.settings = KeyboardSettings.load(ds)+        vibrator = getSystemService(VibratorManager::class.java)?.defaultVibrator++        // Load the dictionary off the main thread; suggestions stay empty until it is ready.+        scope.launch { dictionary = Dictionary.load(this@KeyboardService) }+        observeSettings()+    }++    /** Keep [KeyboardState.settings] in sync with DataStore so changes apply live. */+    private fun observeSettings() {+        val keys = KeyboardSettings.Keys+        scope.launch { ds.booleanFlow(keys.HAPTIC).collectLatest { update { copy(haptic = it) } } }+        scope.launch { ds.booleanFlow(keys.SOUND).collectLatest { update { copy(sound = it) } } }+        scope.launch { ds.booleanFlow(keys.AUTO_CAP).collectLatest { update { copy(autoCapitalize = it) } } }+        scope.launch { ds.booleanFlow(keys.DOUBLE_SPACE_PERIOD).collectLatest { update { copy(doubleSpacePeriod = it) } } }+        scope.launch { ds.booleanFlow(keys.SHOW_SUGGESTIONS).collectLatest { update { copy(showSuggestions = it) } } }+        scope.launch { ds.booleanFlow(keys.AUTO_CORRECT).collectLatest { update { copy(autoCorrect = it) } } }+        scope.launch { ds.booleanFlow(keys.NUMBER_ROW).collectLatest { update { copy(numberRow = it) } } }+        scope.launch { ds.doubleFlow(keys.KEY_HEIGHT).collectLatest { update { copy(keyHeightScale = it.toFloat()) } } }+    }++    private inline fun update(transform: KeyboardSettings.() -> KeyboardSettings) {+        kbState.settings = kbState.settings.transform()+    }++    override fun onCreateInputView(): View {+        // Compose resolves its per-window recomposer from the IME window's decor view+        // (the ancestor of the framework's `parentPanel`), NOT from our ComposeView.+        // Setting the ViewTree owners only on the ComposeView therefore crashes with+        // "ViewTreeLifecycleOwner not found"; they must live on the window decor view.+        window?.window?.decorView?.let { decor ->+            decor.setViewTreeLifecycleOwner(this)+            decor.setViewTreeViewModelStoreOwner(this)+            decor.setViewTreeSavedStateRegistryOwner(this)+        }+        return ComposeView(this).apply {+            setViewTreeLifecycleOwner(this@KeyboardService)+            setViewTreeViewModelStoreOwner(this@KeyboardService)+            setViewTreeSavedStateRegistryOwner(this@KeyboardService)+            setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)+            // Some devices dispatch window insets to the input view; capture them when+            // they do (complements the decor-view read in updateBottomInset()).+            setOnApplyWindowInsetsListener { _, insets ->+                kbState.bottomInsetPx = insets.getInsets(+                    android.view.WindowInsets.Type.navigationBars(),+                ).bottom+                insets+            }+            setContent {+                DynamicTheme {+                    KeyboardScreen(kbState, this@KeyboardService)+                }+            }+        }+    }++    override fun onStartInputView(info: EditorInfo, restarting: Boolean) {+        super.onStartInputView(info, restarting)+        composing.setLength(0)+        configureForEditor(info)+        kbState.suggestions = emptyList()+        lifecycleRegistry.currentState = Lifecycle.State.STARTED+        updateAutoCapShift()+    }++    override fun onWindowShown() {+        super.onWindowShown()+        lifecycleRegistry.currentState = Lifecycle.State.RESUMED+        updateBottomInset()+    }++    /**+     * Read the navigation-bar height from the window so the keyboard can pad clear of+     * it. Reads immediately and again after the next layout pass (rootWindowInsets is+     * often not populated yet when onWindowShown/onStartInputView first run).+     */+    private fun updateBottomInset() {+        val decor = window?.window?.decorView ?: return+        val read = {+            decor.rootWindowInsets?.let {+                kbState.bottomInsetPx = it.getInsets(android.view.WindowInsets.Type.navigationBars()).bottom+            }+        }+        read()+        decor.post { read() }+    }++    override fun onWindowHidden() {+        super.onWindowHidden()+        // Keep the composition alive (STARTED, not DESTROYED) so re-showing is instant.+        lifecycleRegistry.currentState = Lifecycle.State.STARTED+    }++    override fun onFinishInputView(finishingInput: Boolean) {+        super.onFinishInputView(finishingInput)+        composing.setLength(0)+    }++    override fun onDestroy() {+        lifecycleRegistry.currentState = Lifecycle.State.DESTROYED+        store.clear()+        scope.cancel()+        super.onDestroy()+    }++    // --- Editor configuration ---++    private fun configureForEditor(info: EditorInfo) {+        val cls = info.inputType and InputType.TYPE_MASK_CLASS+        val variation = info.inputType and InputType.TYPE_MASK_VARIATION+        val isPassword = (cls == InputType.TYPE_CLASS_TEXT &&+            (variation == InputType.TYPE_TEXT_VARIATION_PASSWORD ||+                variation == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD ||+                variation == InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD)) ||+            (cls == InputType.TYPE_CLASS_NUMBER && variation == InputType.TYPE_NUMBER_VARIATION_PASSWORD)+        val isNumeric = cls == InputType.TYPE_CLASS_NUMBER ||+            cls == InputType.TYPE_CLASS_PHONE ||+            cls == InputType.TYPE_CLASS_DATETIME++        kbState.passwordField = isPassword+        kbState.textVariation = when {+            cls == InputType.TYPE_CLASS_TEXT &&+                (variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS ||+                    variation == InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS) -> TextVariation.EMAIL+            cls == InputType.TYPE_CLASS_TEXT &&+                variation == InputType.TYPE_TEXT_VARIATION_URI -> TextVariation.URL+            else -> TextVariation.NORMAL+        }+        kbState.basePage = if (isNumeric) KeyboardPage.NUMERIC else KeyboardPage.LETTERS+        kbState.page = kbState.basePage+        kbState.shift = ShiftState.OFF++        val action = info.imeOptions and EditorInfo.IME_MASK_ACTION+        val noAction = (info.imeOptions and EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0+        editorActionId = action+        enterSendsAction = !noAction && action != EditorInfo.IME_ACTION_NONE &&+            action != EditorInfo.IME_ACTION_UNSPECIFIED+        kbState.enterAction = if (!enterSendsAction) EnterAction.RETURN else when (action) {+            EditorInfo.IME_ACTION_GO -> EnterAction.GO+            EditorInfo.IME_ACTION_SEARCH -> EnterAction.SEARCH+            EditorInfo.IME_ACTION_SEND -> EnterAction.SEND+            EditorInfo.IME_ACTION_NEXT -> EnterAction.NEXT+            EditorInfo.IME_ACTION_DONE -> EnterAction.DONE+            EditorInfo.IME_ACTION_PREVIOUS -> EnterAction.PREVIOUS+            else -> EnterAction.RETURN+        }+    }++    /**+     * Composing (word tracking) is needed for either suggestions or autocorrect, and only+     * makes sense for plain text fields (never passwords or the numeric layout).+     */+    private fun useComposing(): Boolean =+        (kbState.settings.showSuggestions || kbState.settings.autoCorrect) &&+            !kbState.passwordField && kbState.basePage == KeyboardPage.LETTERS++    // --- ImeActions ---++    override fun onChar(text: String) {+        feedback()+        val ic = currentInputConnection ?: return+        if (useComposing() && text.length == 1 && text[0].isLetter()) {+            composing.append(text)+            ic.setComposingText(composing, 1)+            updateSuggestions()+        } else {+            commitCurrentWord(ic, autoCorrect = false)+            ic.commitText(text, 1)+            kbState.suggestions = emptyList()+        }+        consumeShift()+        updateAutoCapShift()+    }++    override fun onCharLongPress(base: Char) {+        val alts = Layouts.LETTER_ALTERNATES[base] ?: return+        if (alts.isEmpty()) return+        feedback()+        val ic = currentInputConnection ?: return+        commitCurrentWord(ic, autoCorrect = false)+        ic.commitText(alts[0].toString(), 1)+        kbState.suggestions = emptyList()+        consumeShift()+        updateAutoCapShift()+    }++    override fun onBackspace() {+        feedback()+        val ic = currentInputConnection ?: return+        if (composing.isNotEmpty()) {+            composing.deleteCharAt(composing.length - 1)+            if (composing.isEmpty()) {+                ic.setComposingText("", 1)+                ic.finishComposingText()+                kbState.suggestions = emptyList()+            } else {+                ic.setComposingText(composing, 1)+                updateSuggestions()+            }+        } 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)+            }+        }+        updateAutoCapShift()+    }++    override fun onEnter() {+        feedback()+        val ic = currentInputConnection ?: return+        commitCurrentWord(ic, autoCorrect = false)+        if (enterSendsAction) {+            ic.performEditorAction(editorActionId)+        } else {+            sendDownUpKeyEvents(KeyEvent.KEYCODE_ENTER)+        }+        kbState.suggestions = emptyList()+        updateAutoCapShift()+    }++    override fun onSpace() {+        feedback()+        val ic = currentInputConnection ?: return+        commitCurrentWord(ic, autoCorrect = kbState.settings.autoCorrect)+        val before = ic.getTextBeforeCursor(2, 0)+        val now = SystemClock.uptimeMillis()+        val doubleSpace = kbState.settings.doubleSpacePeriod && before != null && before.length == 2 &&+            before[1] == ' ' && before[0].isLetterOrDigit() && now - lastSpaceTime < 1000+        if (doubleSpace) {+            ic.deleteSurroundingText(1, 0)+            ic.commitText(". ", 1)+        } else {+            ic.commitText(" ", 1)+        }+        lastSpaceTime = now+        kbState.suggestions = emptyList()+        updateAutoCapShift()+    }++    override fun onShift() {+        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.+        val now = SystemClock.uptimeMillis()+        kbState.shift = when {+            now - lastShiftTime < DOUBLE_TAP_MS && 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()+        kbState.page = page+    }++    override fun commitSuggestion(word: String) {+        feedback()+        val ic = currentInputConnection ?: return+        ic.setComposingText(word, 1)+        ic.finishComposingText()+        ic.commitText(" ", 1)+        composing.setLength(0)+        lastSpaceTime = SystemClock.uptimeMillis()+        kbState.suggestions = emptyList()+        updateAutoCapShift()+    }++    override fun switchToNextIme() {+        feedback()+        val switched = switchToNextInputMethod(false)+        if (!switched) {+            getSystemService(InputMethodManager::class.java)?.showInputMethodPicker()+        }+    }++    // --- Editing helpers ---++    /** Finish the composing word, optionally replacing it with an autocorrect suggestion. */+    private fun commitCurrentWord(ic: InputConnection, autoCorrect: Boolean) {+        if (composing.isEmpty()) return+        if (autoCorrect) {+            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)+                }+            }+        }+        ic.finishComposingText()+        composing.setLength(0)+    }++    private fun updateSuggestions() {+        if (!kbState.settings.showSuggestions || !useComposing()) {+            kbState.suggestions = emptyList()+            return+        }+        val prefix = composing.toString()+        kbState.suggestions = if (prefix.isBlank()) emptyList() else dictionary.suggestions(prefix, 3)+    }++    private fun consumeShift() {+        if (kbState.shift == ShiftState.SHIFTED) kbState.shift = ShiftState.OFF+    }++    /** Auto-capitalize the shift key when the cursor sits at the start of a sentence. */+    private fun updateAutoCapShift() {+        if (kbState.basePage != KeyboardPage.LETTERS) return+        if (kbState.passwordField || kbState.textVariation != TextVariation.NORMAL) return+        if (kbState.shift == ShiftState.CAPS_LOCK) return+        if (!kbState.settings.autoCapitalize) return+        if (composing.isNotEmpty()) return+        kbState.shift = if (isAtSentenceStart()) ShiftState.SHIFTED else ShiftState.OFF+    }++    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]+        if (last == '\n') return true+        if (before.length < 2) return false+        val prev = before[before.length - 2]+        return last == ' ' && (prev == '.' || prev == '?' || prev == '!')+    }++    // --- Feedback ---++    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))+        }+        if (kbState.settings.sound) {+            getSystemService(AudioManager::class.java)?.playSoundEffect(AudioManager.FX_KEYPRESS_STANDARD)+        }+    }+}
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.ktnew file mode 100644index 0000000000..446e54c73b--- /dev/null+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/ime/KeyboardState.kt@@ -0,0 +1,71 @@+package com.vayunmathur.keyboard.ime++import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import com.vayunmathur.keyboard.util.KeyboardPage+import com.vayunmathur.keyboard.util.KeyboardSettings+import com.vayunmathur.keyboard.util.ShiftState++/** What the Enter key should do, derived from the target field's [android.view.inputmethod.EditorInfo]. */+enum class EnterAction { RETURN, GO, SEARCH, SEND, NEXT, DONE, PREVIOUS }++/**+ * Text-field flavour that tweaks the letters layout: EMAIL surfaces `@`, URL surfaces+ * `/` (both in place of the comma key), NORMAL keeps punctuation. Number/phone fields+ * use the dedicated numeric page instead (see [KeyboardState.basePage]).+ */+enum class TextVariation { NORMAL, EMAIL, URL }++/**+ * Compose-observable UI state owned by the IME service. The service mutates these fields in+ * response to key actions and editor changes; [com.vayunmathur.keyboard.ui.KeyboardScreen]+ * reads them to render. Kept as a plain holder (not a ViewModel) since the service owns its+ * whole lifetime.+ */+class KeyboardState {+    /** Currently visible page of keys. */+    var page by mutableStateOf(KeyboardPage.LETTERS)++    /** The non-emoji page to return to (letters normally, numeric for number fields). */+    var basePage by mutableStateOf(KeyboardPage.LETTERS)++    var shift by mutableStateOf(ShiftState.OFF)++    /** Up to three completion/correction candidates for the word being typed. */+    var suggestions by mutableStateOf<List<String>>(emptyList())++    var settings by mutableStateOf(KeyboardSettings())++    var enterAction by mutableStateOf(EnterAction.RETURN)++    /** True when the target field is a password field (disables suggestions/composing). */+    var passwordField by mutableStateOf(false)++    /** Field flavour that adapts the letters layout (email/url punctuation). */+    var textVariation by mutableStateOf(TextVariation.NORMAL)++    /**+     * Navigation-bar height in pixels, read from the window by the service. In an IME+     * the window insets are not reliably dispatched to Compose, so we pad the keyboard+     * bottom by this value ourselves to keep the last row clear of the system bar.+     */+    var bottomInsetPx by mutableStateOf(0)+}++/**+ * Callbacks the keyboard UI invokes; implemented by the service, which owns the+ * [android.view.inputmethod.InputConnection] and applies the edits.+ */+interface ImeActions {+    fun onChar(text: String)+    fun onCharLongPress(base: Char)+    fun onBackspace()+    fun onEnter()+    fun onSpace()+    fun onShift()+    fun onCapsLock()+    fun setPage(page: KeyboardPage)+    fun commitSuggestion(word: String)+    fun switchToNextIme()+}
keyboard/src/main/java/com/vayunmathur/keyboard/ui/EmojiPage.kt
diff --git a/keyboard/src/main/java/com/vayunmathur/keyboard/ui/EmojiPage.kt b/keyboard/src/main/java/com/vayunmathur/keyboard/ui/EmojiPage.ktnew file mode 100644index 0000000000..c1ebe78d74--- /dev/null+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/ui/EmojiPage.kt@@ -0,0 +1,92 @@+package com.vayunmathur.keyboard.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.RowScope+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.lazy.grid.GridCells+import androidx.compose.foundation.lazy.grid.LazyVerticalGrid+import androidx.compose.foundation.lazy.grid.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.keyboard.util.Emojis+import com.vayunmathur.library.ui.IconBackspace+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text++/**+ * The emoji page: a scrollable grid of the selected category plus a bottom bar with the+ * category tabs, an "ABC" return key and a backspace. Emoji are committed as plain text.+ */+@Composable+fun EmojiPage(+    keyHeight: Dp,+    rows: Int,+    onEmoji: (String) -> Unit,+    onBackspace: () -> Unit,+    onBack: () -> Unit,+) {+    var category by remember { mutableIntStateOf(0) }+    LazyVerticalGrid(+        columns = GridCells.Fixed(8),+        modifier = Modifier+            .fillMaxWidth()+            .height(keyHeight * rows),+    ) {+        items(Emojis.CATEGORIES[category].emojis) { emoji ->+            Box(+                modifier = Modifier+                    .aspectRatio(1f)+                    .clickable { onEmoji(emoji) },+                contentAlignment = Alignment.Center,+            ) {+                Text(text = emoji, fontSize = 24.sp)+            }+        }+    }+    Row(+        modifier = Modifier.fillMaxWidth(),+        verticalAlignment = Alignment.CenterVertically,+    ) {+        SpecialKey(height = keyHeight, weight = 1.4f, onClick = onBack) {+            Text("ABC", color = MaterialTheme.colorScheme.onSurface, fontSize = 15.sp)+        }+        Emojis.CATEGORIES.forEachIndexed { index, cat ->+            CategoryTab(+                label = cat.label,+                selected = index == category,+                onClick = { category = index },+            )+        }+        RepeatKey(height = keyHeight, weight = 1.4f, onRepeat = onBackspace) {+            IconBackspace()+        }+    }+}++@Composable+private fun RowScope.CategoryTab(label: String, selected: Boolean, onClick: () -> Unit) {+    val bg = if (selected) MaterialTheme.colorScheme.secondaryContainer else MaterialTheme.colorScheme.surfaceContainer+    Box(+        modifier = Modifier+            .weight(1f)+            .height(44.dp)+            .background(bg)+            .clickable(onClick = onClick),+        contentAlignment = Alignment.Center,+    ) {+        Text(text = label, fontSize = 18.sp)+    }+}
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.ktnew file mode 100644index 0000000000..f68adbca1c--- /dev/null+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyButton.kt@@ -0,0 +1,303 @@+@file:OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)++package com.vayunmathur.keyboard.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.combinedClickable+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.interaction.MutableInteractionSource+import androidx.compose.foundation.interaction.PressInteraction+import androidx.compose.foundation.interaction.collectIsPressedAsState+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.RowScope+import androidx.compose.foundation.layout.defaultMinSize+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+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.remember+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.pointerInput+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.IntRect+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.LayoutDirection+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.compose.ui.window.Popup+import androidx.compose.ui.window.PopupPositionProvider+import androidx.compose.ui.window.PopupProperties+import com.vayunmathur.keyboard.util.ShiftState+import com.vayunmathur.library.ui.IconShift+import com.vayunmathur.library.ui.LocalContentColor+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch++/**+ * Key composables shared by every page. Keys are rounded, weight-sized tiles (so a row+ * always fills the width). On press the *whole* key fills with the brightest surface+ * colour ([pressedColor]) โ€” a clear, gboard-style highlight rather than a ripple splash.+ * Colours are all Material tokens so light/dark + dynamic colour just work.+ */++private val KeyPadding = 3.dp+private val KeyShape = RoundedCornerShape(11.dp)++/** Resting colour for letter/symbol keys (slightly raised above the keyboard surface). */+@Composable+fun charKeyColor(): Color = MaterialTheme.colorScheme.surfaceContainerHigh++/** Resting colour for function keys (dimmer, so they read as secondary). */+@Composable+fun specialKeyColor(): Color = MaterialTheme.colorScheme.surfaceContainer++/** The whole-key highlight shown while a key is held down. */+@Composable+fun pressedKeyColor(): Color = MaterialTheme.colorScheme.surfaceBright++/** A letter/symbol key: tap commits, optional long-press commits an alternate. */+@Composable+fun RowScope.CharKey(+    label: String,+    height: Dp,+    weight: Float = 1f,+    onClick: () -> Unit,+    onLongClick: (() -> Unit)? = null,+) {+    val interaction = remember { MutableInteractionSource() }+    val pressed by interaction.collectIsPressedAsState()+    Box(+        modifier = Modifier+            .weight(weight)+            .padding(KeyPadding)+            .height(height)+            .clip(KeyShape)+            .background(if (pressed) pressedKeyColor() else charKeyColor())+            .combinedClickable(+                interactionSource = interaction,+                indication = null,+                onClick = onClick,+                onLongClick = onLongClick,+            ),+        contentAlignment = Alignment.Center,+    ) {+        Text(text = label, color = MaterialTheme.colorScheme.onSurface, fontSize = 20.sp)+        // 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+        // top row (outside the keyboard bounds).+        if (pressed) KeyPreview(label)+    }+}++/** The pop-up character preview shown above a held key. */+@Composable+private fun KeyPreview(label: String) {+    Popup(+        popupPositionProvider = KeyPreviewPositionProvider,+        properties = PopupProperties(focusable = false, clippingEnabled = false),+    ) {+        Box(+            modifier = Modifier+                .padding(horizontal = 2.dp, vertical = 4.dp)+                .defaultMinSize(minWidth = 46.dp, minHeight = 50.dp)+                .clip(RoundedCornerShape(12.dp))+                .background(MaterialTheme.colorScheme.primaryContainer)+                .padding(horizontal = 12.dp, vertical = 6.dp),+            contentAlignment = Alignment.Center,+        ) {+            Text(+                text = label,+                color = MaterialTheme.colorScheme.onPrimaryContainer,+                fontSize = 30.sp,+            )+        }+    }+}++/** Positions the preview centred horizontally over the key and directly above it. */+private object KeyPreviewPositionProvider : PopupPositionProvider {+    override fun calculatePosition(+        anchorBounds: IntRect,+        windowSize: IntSize,+        layoutDirection: LayoutDirection,+        popupContentSize: IntSize,+    ): IntOffset {+        val x = anchorBounds.left + (anchorBounds.width - popupContentSize.width) / 2+        val y = anchorBounds.top - popupContentSize.height+        return IntOffset(x, y)+    }+}++/** A functional key that only needs a tap (page toggles, comma/period, emoji, enter). */+@Composable+fun RowScope.SpecialKey(+    height: Dp,+    weight: Float = 1f,+    containerColor: Color = specialKeyColor(),+    contentColor: Color = MaterialTheme.colorScheme.onSurface,+    pressedContainerColor: Color = pressedKeyColor(),+    pressedContentColor: Color = MaterialTheme.colorScheme.onSurface,+    onClick: () -> Unit,+    content: @Composable () -> Unit,+) {+    val interaction = remember { MutableInteractionSource() }+    val pressed by interaction.collectIsPressedAsState()+    Box(+        modifier = Modifier+            .weight(weight)+            .padding(KeyPadding)+            .height(height)+            .clip(KeyShape)+            .background(if (pressed) pressedContainerColor else containerColor)+            .clickable(interactionSource = interaction, indication = null, onClick = onClick),+        contentAlignment = Alignment.Center,+    ) {+        CompositionLocalProvider(+            LocalContentColor provides if (pressed) pressedContentColor else contentColor,+        ) { content() }+    }+}++/** Space bar: tap inserts a space, long-press switches to the next IME. */+@Composable+fun RowScope.SpaceKey(+    height: Dp,+    weight: Float,+    onSpace: () -> Unit,+    onLongPress: () -> Unit,+) {+    val interaction = remember { MutableInteractionSource() }+    val pressed by interaction.collectIsPressedAsState()+    Box(+        modifier = Modifier+            .weight(weight)+            .padding(KeyPadding)+            .height(height)+            .clip(KeyShape)+            .background(if (pressed) pressedKeyColor() else charKeyColor())+            .combinedClickable(+                interactionSource = interaction,+                indication = null,+                onClick = onSpace,+                onLongClick = onLongPress,+            ),+        contentAlignment = Alignment.Center,+    ) {+        Text(+            text = "English",+            color = MaterialTheme.colorScheme.onSurfaceVariant,+            fontSize = 14.sp,+        )+    }+}++/** Backspace with press-and-hold repeat delete. */+@Composable+fun RowScope.RepeatKey(+    height: Dp,+    weight: Float,+    onRepeat: () -> Unit,+    content: @Composable () -> Unit,+) {+    val interaction = remember { MutableInteractionSource() }+    val pressed by interaction.collectIsPressedAsState()+    val scope = androidx.compose.runtime.rememberCoroutineScope()+    Box(+        modifier = Modifier+            .weight(weight)+            .padding(KeyPadding)+            .height(height)+            .clip(KeyShape)+            .background(if (pressed) pressedKeyColor() else specialKeyColor())+            .pointerInput(Unit) {+                detectTapGestures(onPress = { offset ->+                    val press = PressInteraction.Press(offset)+                    interaction.emit(press)+                    onRepeat()+                    val job = scope.launch {+                        delay(350)+                        while (true) {+                            onRepeat()+                            delay(45)+                        }+                    }+                    val released = tryAwaitRelease()+                    job.cancel()+                    interaction.emit(+                        if (released) PressInteraction.Release(press) else PressInteraction.Cancel(press),+                    )+                })+            },+        contentAlignment = Alignment.Center,+    ) {+        CompositionLocalProvider(LocalContentColor provides MaterialTheme.colorScheme.onSurface) { content() }+    }+}++/** Shift key: single tap toggles shift, double tap latches caps-lock. */+@Composable+fun RowScope.ShiftKey(+    height: Dp,+    weight: Float,+    shift: ShiftState,+    onShift: () -> Unit,+) {+    val active = shift != ShiftState.OFF+    val interaction = remember { MutableInteractionSource() }+    val pressed by interaction.collectIsPressedAsState()+    val container = when {+        pressed -> pressedKeyColor()+        active -> MaterialTheme.colorScheme.primaryContainer+        else -> specialKeyColor()+    }+    val content = when {+        pressed -> MaterialTheme.colorScheme.onSurface+        active -> MaterialTheme.colorScheme.onPrimaryContainer+        else -> MaterialTheme.colorScheme.onSurface+    }+    Box(+        modifier = Modifier+            .weight(weight)+            .padding(KeyPadding)+            .height(height)+            .clip(KeyShape)+            .background(container)+            .pointerInput(Unit) {+                // Fire on press-up immediately (no double-tap wait). Caps-lock is detected+                // from tap timing in the service, so shift responds instantly.+                detectTapGestures(+                    onPress = { offset ->+                        val press = PressInteraction.Press(offset)+                        interaction.emit(press)+                        val released = tryAwaitRelease()+                        interaction.emit(+                            if (released) PressInteraction.Release(press) else PressInteraction.Cancel(press),+                        )+                        if (released) onShift()+                    },+                )+            },+        contentAlignment = Alignment.Center,+    ) {+        IconShift(tint = content)+        if (shift == ShiftState.CAPS_LOCK) {+            Box(+                Modifier+                    .align(Alignment.BottomCenter)+                    .padding(bottom = 7.dp)+                    .size(width = 14.dp, height = 2.dp)+                    .background(content),+            )+        }+    }+}
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.ktnew file mode 100644index 0000000000..d485ca42ff--- /dev/null+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyboardScreen.kt@@ -0,0 +1,232 @@+package com.vayunmathur.keyboard.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.RowScope+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.ui.Modifier+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.keyboard.ime.EnterAction+import com.vayunmathur.keyboard.ime.ImeActions+import com.vayunmathur.keyboard.ime.KeyboardState+import com.vayunmathur.keyboard.ime.TextVariation+import com.vayunmathur.keyboard.util.KeyboardPage+import com.vayunmathur.keyboard.util.Layouts+import com.vayunmathur.keyboard.util.ShiftState+import com.vayunmathur.library.ui.IconBackspace+import com.vayunmathur.library.ui.IconEmoji+import com.vayunmathur.library.ui.IconReturn+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+ * is active. All sizing is weight-based so it fills the width; key height scales with the+ * user's height-scale setting.+ */+@Composable+fun KeyboardScreen(state: KeyboardState, actions: ImeActions) {+    val scale = state.settings.keyHeightScale.coerceIn(0.8f, 1.4f)+    val keyHeight = (52 * scale).dp+    // The IME window doesn't reliably deliver insets to Compose, so pad the bottom by+    // the navigation-bar height the service measured from the window.+    // Clear the system nav bar / gesture area: measured inset plus a comfortable margin,+    // 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)+    Surface(color = MaterialTheme.colorScheme.surfaceContainer) {+        Column(+            modifier = Modifier+                .fillMaxWidth()+                .padding(bottom = bottomPad),+        ) {+            if (state.settings.showSuggestions && state.page != KeyboardPage.EMOJI) {+                SuggestionStrip(+                    height = 44.dp,+                    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.EMOJI -> EmojiPage(+                    keyHeight = keyHeight,+                    rows = 4,+                    onEmoji = { actions.onChar(it) },+                    onBackspace = actions::onBackspace,+                    onBack = { actions.setPage(state.basePage) },+                )+            }+        }+    }+}++@Composable+private fun LettersPage(state: KeyboardState, actions: ImeActions, keyHeight: Dp) {+    val rows = Layouts.LETTER_ROWS+    val shift = state.shift+    if (state.settings.numberRow) {+        Row(Modifier.fillMaxWidth()) {+            "1234567890".forEach { SymbolKey(it, keyHeight, actions) }+        }+    }+    Row(Modifier.fillMaxWidth()) {+        rows[0].forEach { LetterKey(it, shift, keyHeight, actions) }+    }+    Row(Modifier.fillMaxWidth()) {+        Spacer(Modifier.weight(0.5f))+        rows[1].forEach { LetterKey(it, shift, keyHeight, actions) }+        Spacer(Modifier.weight(0.5f))+    }+    Row(Modifier.fillMaxWidth()) {+        ShiftKey(keyHeight, 1.5f, shift, actions::onShift)+        rows[2].forEach { LetterKey(it, shift, keyHeight, actions) }+        RepeatKey(keyHeight, 1.5f, actions::onBackspace) { IconBackspace() }+    }+    // Email/URL fields surface @ or / where the comma usually sits.+    val commaChar = when (state.textVariation) {+        TextVariation.EMAIL -> "@"+        TextVariation.URL -> "/"+        TextVariation.NORMAL -> ","+    }+    BottomRow(+        state, actions, keyHeight,+        leftLabel = "?123", leftTarget = KeyboardPage.SYMBOLS, commaChar = commaChar,+    )+}++@Composable+private fun RowScope.LetterKey(c: Char, shift: ShiftState, keyHeight: Dp, actions: ImeActions) {+    val display = if (shift != ShiftState.OFF) c.uppercaseChar().toString() else c.toString()+    CharKey(+        label = display,+        height = keyHeight,+        onClick = { actions.onChar(display) },+        onLongClick = { actions.onCharLongPress(c) },+    )+}++@Composable+private fun SymbolPage(+    state: KeyboardState,+    actions: ImeActions,+    keyHeight: Dp,+    rows: List<String>,+    otherPage: KeyboardPage,+    toggleLabel: String,+) {+    Row(Modifier.fillMaxWidth()) {+        rows[0].forEach { SymbolKey(it, keyHeight, actions) }+    }+    Row(Modifier.fillMaxWidth()) {+        rows[1].forEach { SymbolKey(it, keyHeight, actions) }+    }+    Row(Modifier.fillMaxWidth()) {+        SpecialKey(keyHeight, 1.5f, onClick = { actions.setPage(otherPage) }) {+            Text(toggleLabel, fontSize = 14.sp)+        }+        rows[2].forEach { SymbolKey(it, keyHeight, actions) }+        RepeatKey(keyHeight, 1.5f, actions::onBackspace) { IconBackspace() }+    }+    BottomRow(state, actions, keyHeight, leftLabel = "ABC", leftTarget = state.basePage)+}++@Composable+private fun RowScope.SymbolKey(c: Char, keyHeight: Dp, actions: ImeActions) {+    CharKey(label = c.toString(), height = keyHeight, onClick = { actions.onChar(c.toString()) })+}++@Composable+private fun NumericPage(state: KeyboardState, actions: ImeActions, keyHeight: Dp) {+    Row(Modifier.fillMaxWidth()) {+        SymbolKey('1', keyHeight, actions)+        SymbolKey('2', keyHeight, actions)+        SymbolKey('3', keyHeight, actions)+        RepeatKey(keyHeight, 1f, actions::onBackspace) { IconBackspace() }+    }+    Row(Modifier.fillMaxWidth()) {+        SymbolKey('4', keyHeight, actions)+        SymbolKey('5', keyHeight, actions)+        SymbolKey('6', keyHeight, actions)+        SymbolKey('+', keyHeight, actions)+    }+    Row(Modifier.fillMaxWidth()) {+        SymbolKey('7', keyHeight, actions)+        SymbolKey('8', keyHeight, actions)+        SymbolKey('9', keyHeight, actions)+        SymbolKey('-', keyHeight, actions)+    }+    Row(Modifier.fillMaxWidth()) {+        SpecialKey(keyHeight, 1f, onClick = { actions.setPage(KeyboardPage.LETTERS) }) {+            Text("ABC", fontSize = 14.sp)+        }+        SymbolKey('*', keyHeight, actions)+        SymbolKey('0', keyHeight, actions)+        SymbolKey('#', keyHeight, actions)+        EnterKey(state, actions, keyHeight, 1f)+    }+}++@Composable+private fun BottomRow(+    state: KeyboardState,+    actions: ImeActions,+    keyHeight: Dp,+    leftLabel: String,+    leftTarget: KeyboardPage,+    commaChar: String = ",",+    periodChar: String = ".",+) {+    Row(Modifier.fillMaxWidth()) {+        SpecialKey(keyHeight, 1.5f, onClick = { actions.setPage(leftTarget) }) {+            Text(leftLabel, fontSize = 14.sp)+        }+        SpecialKey(keyHeight, 1f, onClick = { actions.setPage(KeyboardPage.EMOJI) }) { IconEmoji() }+        CharKey(commaChar, keyHeight, 1f, onClick = { actions.onChar(commaChar) })+        SpaceKey(keyHeight, 4f, actions::onSpace, actions::switchToNextIme)+        CharKey(periodChar, keyHeight, 1f, onClick = { actions.onChar(periodChar) })+        EnterKey(state, actions, keyHeight, 1.5f)+    }+}++@Composable+private fun RowScope.EnterKey(state: KeyboardState, actions: ImeActions, keyHeight: Dp, weight: Float) {+    SpecialKey(+        height = keyHeight,+        weight = weight,+        containerColor = MaterialTheme.colorScheme.primary,+        contentColor = MaterialTheme.colorScheme.onPrimary,+        pressedContainerColor = MaterialTheme.colorScheme.primaryContainer,+        pressedContentColor = MaterialTheme.colorScheme.onPrimaryContainer,+        onClick = actions::onEnter,+    ) {+        val label = enterLabel(state.enterAction)+        if (label != null) {+            Text(label, fontSize = 14.sp)+        } else {+            IconReturn()+        }+    }+}++private fun enterLabel(action: EnterAction): String? = when (action) {+    EnterAction.GO -> "Go"+    EnterAction.SEARCH -> "Search"+    EnterAction.SEND -> "Send"+    EnterAction.NEXT -> "Next"+    EnterAction.DONE -> "Done"+    EnterAction.PREVIOUS -> "Prev"+    EnterAction.RETURN -> null+}
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.ktnew file mode 100644index 0000000000..68d3b158aa--- /dev/null+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/ui/SetupScreen.kt@@ -0,0 +1,204 @@+package com.vayunmathur.keyboard.ui++import android.content.Intent+import android.provider.Settings+import android.view.inputmethod.InputMethodManager+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.unit.dp+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleEventObserver+import androidx.lifecycle.compose.LocalLifecycleOwner+import com.vayunmathur.keyboard.util.KeyboardSettings+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.CenterAlignedTopAppBar+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.IconCheck+import com.vayunmathur.library.ui.IconClose+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Slider+import com.vayunmathur.library.ui.Switch+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.launch++/**+ * Setup flow + live settings. Shows whether the IME is enabled/selected, offers the two+ * system shortcuts to do so, exposes every preference (persisted to DataStore, read live by+ * the service), and provides a field to try the keyboard immediately.+ */+@Composable+fun SetupScreen() {+    val context = LocalContext.current+    val ds = remember { DataStoreUtils.getInstance(context) }+    val scope = rememberCoroutineScope()+    val imm = remember { context.getSystemService(InputMethodManager::class.java) }++    fun isEnabled(): Boolean =+        imm?.enabledInputMethodList?.any { it.packageName == context.packageName } == true++    fun isSelected(): Boolean {+        val id = Settings.Secure.getString(context.contentResolver, Settings.Secure.DEFAULT_INPUT_METHOD)+        return id != null && id.contains(context.packageName)+    }++    var enabled by remember { mutableStateOf(isEnabled()) }+    var selected by remember { mutableStateOf(isSelected()) }++    // Re-check status whenever we return from the system IME settings / picker.+    val lifecycleOwner = LocalLifecycleOwner.current+    DisposableEffect(lifecycleOwner) {+        val observer = LifecycleEventObserver { _, event ->+            if (event == Lifecycle.Event.ON_RESUME) {+                enabled = isEnabled()+                selected = isSelected()+            }+        }+        lifecycleOwner.lifecycle.addObserver(observer)+        onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }+    }++    val keys = KeyboardSettings.Keys+    var haptic by remember { mutableStateOf(ds.getBoolean(keys.HAPTIC, true)) }+    var sound by remember { mutableStateOf(ds.getBoolean(keys.SOUND, false)) }+    var autoCap by remember { mutableStateOf(ds.getBoolean(keys.AUTO_CAP, true)) }+    var doubleSpace by remember { mutableStateOf(ds.getBoolean(keys.DOUBLE_SPACE_PERIOD, true)) }+    var showSuggestions by remember { mutableStateOf(ds.getBoolean(keys.SHOW_SUGGESTIONS, true)) }+    var autoCorrect by remember { mutableStateOf(ds.getBoolean(keys.AUTO_CORRECT, false)) }+    var numberRow by remember { mutableStateOf(ds.getBoolean(keys.NUMBER_ROW, true)) }+    var keyHeight by remember { mutableFloatStateOf((ds.getDouble(keys.KEY_HEIGHT) ?: 1.0).toFloat()) }++    var testText by remember { mutableStateOf("") }++    Scaffold(topBar = { CenterAlignedTopAppBar(title = { Text("Keyboard") }) }) { padding ->+        Column(+            modifier = Modifier+                .fillMaxSize()+                .padding(padding)+                .verticalScroll(rememberScrollState())+                .padding(horizontal = 16.dp),+            verticalArrangement = Arrangement.spacedBy(12.dp),+        ) {+            StatusCard(enabled = enabled, selected = selected)++            Button(+                onClick = { context.startActivity(Intent(Settings.ACTION_INPUT_METHOD_SETTINGS)) },+                modifier = Modifier.fillMaxWidth(),+            ) { Text("Enable keyboard") }++            OutlinedButton(+                onClick = { imm?.showInputMethodPicker() },+                modifier = Modifier.fillMaxWidth(),+            ) { Text("Choose keyboard") }++            HorizontalDivider()++            Text("Settings", style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.primary)++            SettingSwitch("Haptic feedback", haptic) {+                haptic = it; scope.launch { ds.setBoolean(keys.HAPTIC, it) }+            }+            SettingSwitch("Key sound", sound) {+                sound = it; scope.launch { ds.setBoolean(keys.SOUND, it) }+            }+            SettingSwitch("Auto-capitalize", autoCap) {+                autoCap = it; scope.launch { ds.setBoolean(keys.AUTO_CAP, it) }+            }+            SettingSwitch("Double-space inserts period", doubleSpace) {+                doubleSpace = it; scope.launch { ds.setBoolean(keys.DOUBLE_SPACE_PERIOD, it) }+            }+            SettingSwitch("Show suggestions", showSuggestions) {+                showSuggestions = it; scope.launch { ds.setBoolean(keys.SHOW_SUGGESTIONS, it) }+            }+            SettingSwitch("Auto-correct", autoCorrect) {+                autoCorrect = it; scope.launch { ds.setBoolean(keys.AUTO_CORRECT, it) }+            }+            SettingSwitch("Number row", numberRow) {+                numberRow = it; scope.launch { ds.setBoolean(keys.NUMBER_ROW, it) }+            }++            Column {+                Text("Key height", style = MaterialTheme.typography.bodyLarge)+                Slider(+                    value = keyHeight,+                    onValueChange = { keyHeight = it },+                    valueRange = 0.8f..1.4f,+                    onValueChangeFinished = {+                        scope.launch { ds.setDouble(keys.KEY_HEIGHT, keyHeight.toDouble()) }+                    },+                )+            }++            ListItem(+                headlineContent = { Text("Theme") },+                supportingContent = { Text("Follows the system light/dark theme and Material You colors") },+            )++            HorizontalDivider()++            OutlinedTextField(+                value = testText,+                onValueChange = { testText = it },+                label = { Text("Try the keyboard here") },+                modifier = Modifier+                    .fillMaxWidth()+                    .padding(bottom = 24.dp),+            )+        }+    }+}++@Composable+private fun StatusCard(enabled: Boolean, selected: Boolean) {+    Card(modifier = Modifier.fillMaxWidth()) {+        Column(+            modifier = Modifier.padding(16.dp),+            verticalArrangement = Arrangement.spacedBy(8.dp),+        ) {+            StatusRow("Enabled in system settings", enabled)+            StatusRow("Selected as active keyboard", selected)+        }+    }+}++@Composable+private fun StatusRow(label: String, ok: Boolean) {+    Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {+        if (ok) {+            IconCheck(tint = MaterialTheme.colorScheme.primary)+        } else {+            IconClose(tint = MaterialTheme.colorScheme.error)+        }+        Text(label)+    }+}++@Composable+private fun SettingSwitch(title: String, checked: Boolean, onChange: (Boolean) -> Unit) {+    ListItem(+        headlineContent = { Text(title) },+        trailingContent = { Switch(checked = checked, onCheckedChange = onChange) },+    )+}
keyboard/src/main/java/com/vayunmathur/keyboard/ui/SuggestionStrip.kt
diff --git a/keyboard/src/main/java/com/vayunmathur/keyboard/ui/SuggestionStrip.kt b/keyboard/src/main/java/com/vayunmathur/keyboard/ui/SuggestionStrip.ktnew file mode 100644index 0000000000..e555f2f1e3--- /dev/null+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/ui/SuggestionStrip.kt@@ -0,0 +1,67 @@+package com.vayunmathur.keyboard.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+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.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.VerticalDivider++/**+ * The strip above the keys showing up to three candidate words. Tapping one replaces the+ * word being typed. Its height is reserved even when empty so the keyboard doesn't jump.+ */+@Composable+fun SuggestionStrip(+    height: Dp,+    suggestions: List<String>,+    onPick: (String) -> Unit,+) {+    Row(+        modifier = Modifier+            .fillMaxWidth()+            .height(height),+        verticalAlignment = Alignment.CenterVertically,+    ) {+        if (suggestions.isEmpty()) {+            Box(Modifier.fillMaxWidth())+            return@Row+        }+        suggestions.forEachIndexed { index, word ->+            if (index > 0) {+                VerticalDivider(+                    modifier = Modifier+                        .fillMaxHeight()+                        .padding(vertical = 8.dp),+                )+            }+            Box(+                modifier = Modifier+                    .weight(1f)+                    .fillMaxHeight()+                    .clickable { onPick(word) }+                    .padding(horizontal = 8.dp),+                contentAlignment = Alignment.Center,+            ) {+                Text(+                    text = word,+                    color = MaterialTheme.colorScheme.onSurface,+                    fontSize = 16.sp,+                    maxLines = 1,+                    overflow = TextOverflow.Ellipsis,+                )+            }+        }+    }+}
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.ktnew file mode 100644index 0000000000..e864a53e59--- /dev/null+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/util/Dictionary.kt@@ -0,0 +1,174 @@+package com.vayunmathur.keyboard.util++import android.content.Context+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++/**+ * Offline word dictionary backing the suggestion strip and autocorrect.+ *+ * Words are kept lowercase, sorted alphabetically in a parallel [words]/[freqs] pair so+ * prefix lookups are a binary search + short forward scan (a lightweight stand-in for a+ * trie that also gives O(log n) `contains`). Ranking is purely by frequency. The whole+ * thing is loaded once, off the main thread, from `assets/dict/words_en.txt`.+ */+class Dictionary private constructor(+    private val words: List<String>,+    private val freqs: IntArray,+) {+    /** True if [word] (any case) is a known dictionary word. */+    fun contains(word: String): Boolean {+        if (word.isEmpty()) return false+        return indexOf(word.lowercase()) >= 0+    }++    /**+     * Up to [limit] completions of [prefix], most frequent first, capitalized to match how+     * the user typed the prefix. Returns empty for a blank prefix.+     */+    fun suggestions(prefix: String, limit: Int = 3): List<String> {+        if (prefix.isBlank()) return emptyList()+        val lower = prefix.lowercase()+        var i = lowerBound(lower)+        // Collect (index) of all words that start with the prefix, then rank by frequency.+        val matches = ArrayList<Int>()+        while (i < words.size && words[i].startsWith(lower)) {+            matches.add(i)+            i+++        }+        return matches+            .sortedByDescending { freqs[it] }+            .take(limit)+            .map { capitalizeLike(prefix, words[it]) }+    }++    /**+     * A best correction for a misspelled [word], or null if none is confident. Considers+     * dictionary words within edit distance 1, picking the most frequent. Kept deliberately+     * simple/offline; a full scan with a cheap length pre-filter is fine for a starter list.+     */+    fun autocorrect(word: String): String? {+        if (word.length < 2) return null+        val lower = word.lowercase()+        if (contains(lower)) return null+        var best = -1+        var bestFreq = -1+        for (idx in words.indices) {+            val cand = words[idx]+            if (kotlin.math.abs(cand.length - lower.length) > 1) continue+            if (!withinEditDistance1(lower, cand)) continue+            if (freqs[idx] > bestFreq) {+                bestFreq = freqs[idx]+                best = idx+            }+        }+        return if (best >= 0) capitalizeLike(word, words[best]) else null+    }++    // --- internals ---++    /** Index of an exact match, or -1. */+    private fun indexOf(w: String): Int {+        var lo = 0+        var hi = words.size - 1+        while (lo <= hi) {+            val mid = (lo + hi) ushr 1+            val c = words[mid].compareTo(w)+            when {+                c < 0 -> lo = mid + 1+                c > 0 -> hi = mid - 1+                else -> return mid+            }+        }+        return -1+    }++    /** First index whose word is >= [w] (binary search lower bound). */+    private fun lowerBound(w: String): Int {+        var lo = 0+        var hi = words.size+        while (lo < hi) {+            val mid = (lo + hi) ushr 1+            if (words[mid] < w) lo = mid + 1 else hi = mid+        }+        return lo+    }++    companion object {+        /** An empty dictionary used before loading completes. */+        val EMPTY = Dictionary(emptyList(), IntArray(0))++        /** Load and index the bundled word list off the main thread. */+        suspend fun load(context: Context): Dictionary = withContext(Dispatchers.IO) {+            val entries = ArrayList<Pair<String, Int>>()+            runCatching {+                context.assets.open("dict/words_en.txt").bufferedReader().useLines { lines ->+                    // Fallback frequency = position from the top (file is ordered most-common first),+                    // so common words rank above rarer ones even without an explicit column.+                    var order = 0+                    for (raw in lines) {+                        val line = raw.trim()+                        if (line.isEmpty() || line.startsWith("#")) continue+                        val parts = line.split('\t')+                        val word = parts[0].trim().lowercase()+                        if (word.isEmpty()) continue+                        val freq = parts.getOrNull(1)?.trim()?.toIntOrNull() ?: (1_000_000 - order)+                        entries.add(word to freq)+                        order+++                    }+                }+            }+            // De-dup keeping the highest frequency, then sort alphabetically for binary search.+            val byWord = LinkedHashMap<String, Int>()+            for ((w, f) in entries) {+                val prev = byWord[w]+                if (prev == null || f > prev) byWord[w] = f+            }+            val sorted = byWord.entries.sortedBy { it.key }+            Dictionary(sorted.map { it.key }, IntArray(sorted.size) { sorted[it].value })+        }++        /** 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()+            sample.isNotEmpty() && sample[0].isUpperCase() -> word.replaceFirstChar { it.uppercase() }+            else -> word+        }++        /** True iff Levenshtein distance between [a] and [b] is at most 1. */+        private fun withinEditDistance1(a: String, b: String): Boolean {+            val la = a.length+            val lb = b.length+            when (la - lb) {+                0 -> {+                    var diff = 0+                    for (i in 0 until la) if (a[i] != b[i]) {+                        diff+++                        if (diff > 1) return false+                    }+                    return true+                }+                1 -> return isOneInsertion(a, b) // a has the extra char+                -1 -> return isOneInsertion(b, a) // b has the extra char+                else -> return false+            }+        }++        /** True iff [longer] equals [shorter] with exactly one extra character inserted. */+        private fun isOneInsertion(longer: String, shorter: String): Boolean {+            var i = 0+            var j = 0+            var skipped = false+            while (i < longer.length && j < shorter.length) {+                if (longer[i] == shorter[j]) {+                    i++; j+++                } else {+                    if (skipped) return false+                    skipped = true+                    i++ // skip the extra character in the longer string+                }+            }+            return true+        }+    }+}
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.ktnew file mode 100644index 0000000000..035d411fab--- /dev/null+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/util/Emojis.kt@@ -0,0 +1,65 @@+package com.vayunmathur.keyboard.util++/** A named group of emoji shown as one tab on the emoji page. */+data class EmojiCategory(val label: String, val emojis: List<String>)++/**+ * A small, curated, fully-offline emoji set grouped into a few categories. Enough to be+ * usable; a fuller set can be dropped in later without touching the UI.+ */+object Emojis {+    val CATEGORIES: List<EmojiCategory> = listOf(+        EmojiCategory(+            "๐Ÿ˜€",+            listOf(+                "๐Ÿ˜€", "๐Ÿ˜", "๐Ÿ˜‚", "๐Ÿ˜ƒ", "๐Ÿ˜„",+                "๐Ÿ˜…", "๐Ÿ˜†", "๐Ÿ˜‰", "๐Ÿ˜Š", "๐Ÿ˜‹",+                "๐Ÿ˜Ž", "๐Ÿ˜", "๐Ÿ˜˜", "๐Ÿ˜—", "๐Ÿ˜œ",+                "๐Ÿ˜", "๐Ÿค‘", "๐Ÿค—", "๐Ÿค”", "๐Ÿ˜",+                "๐Ÿ™„", "๐Ÿ˜", "๐Ÿ˜’", "๐Ÿ˜ž", "๐Ÿ˜ข",+                "๐Ÿ˜ญ", "๐Ÿ˜ซ", "๐Ÿ˜ ", "๐Ÿ˜ก", "๐Ÿฅณ",+                "๐Ÿ˜‡", "๐Ÿฅฐ", "๐Ÿ˜ด", "๐Ÿคค", "๐Ÿ˜ฑ",+            ),+        ),+        EmojiCategory(+            "๐Ÿ‘",+            listOf(+                "๐Ÿ‘", "๐Ÿ‘Ž", "๐Ÿ‘Œ", "โœŒ๏ธ", "๐Ÿคž",+                "๐Ÿ‘", "๐Ÿ™Œ", "๐Ÿ™", "๐Ÿ’ช", "๐Ÿ‘‹",+                "โœ‹", "๐Ÿค", "โœ๏ธ", "๐Ÿง ", "๐Ÿ‘€",+                "โค๏ธ", "๐Ÿ–ค", "๐Ÿ’”", "๐Ÿ’•", "โœจ",+                "๐Ÿ”ฅ", "๐ŸŽ‰", "๐ŸŽŠ", "โญ", "๐ŸŒŸ",+            ),+        ),+        EmojiCategory(+            "๐Ÿถ",+            listOf(+                "๐Ÿถ", "๐Ÿฑ", "๐Ÿญ", "๐Ÿน", "๐Ÿฐ",+                "๐ŸฆŠ", "๐Ÿป", "๐Ÿผ", "๐Ÿจ", "๐Ÿฏ",+                "๐Ÿฆ", "๐Ÿท", "๐Ÿธ", "๐Ÿต", "๐Ÿ”",+                "๐Ÿง", "๐Ÿฆ", "๐Ÿฆ†", "๐Ÿฆ‰", "๐Ÿ",+                "๐Ÿฆ‹", "๐Ÿž", "๐Ÿข", "๐ŸŸ", "๐Ÿณ",+            ),+        ),+        EmojiCategory(+            "๐Ÿ”",+            listOf(+                "๐ŸŽ", "๐ŸŒ", "๐Ÿ‰", "๐Ÿ‡", "๐Ÿ“",+                "๐Ÿ’", "๐Ÿ‘", "๐ŸŠ", "๐Ÿ‹", "๐Ÿ…",+                "๐Ÿ”", "๐ŸŸ", "๐Ÿ•", "๐ŸŒญ", "๐ŸŒฎ",+                "๐Ÿœ", "๐Ÿฃ", "๐Ÿฉ", "๐Ÿฐ", "โ˜•",+                "๐Ÿบ", "๐Ÿท", "๐Ÿน", "๐Ÿฅค", "๐Ÿฆ",+            ),+        ),+        EmojiCategory(+            "โš™๏ธ",+            listOf(+                "โš™๏ธ", "๐Ÿ“ฑ", "๐Ÿ’ป", "โŒš", "๐Ÿ“ท",+                "๐Ÿ”‹", "๐Ÿ’ก", "๐Ÿ”ฆ", "๐Ÿ”‘", "๐Ÿ”’",+                "๐Ÿ“…", "โœ‰๏ธ", "๐Ÿ“Ž", "โœ‚๏ธ", "๐Ÿ“Œ",+                "๐Ÿ”", "โœ…", "โŒ", "โž•", "โž–",+                "โ—", "โ“", "โค๏ธ", "๐Ÿ’ฐ", "๐ŸŽฏ",+            ),+        ),+    )+}
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.ktnew file mode 100644index 0000000000..3d30b20645--- /dev/null+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/util/KeyboardPrefs.kt@@ -0,0 +1,46 @@+package com.vayunmathur.keyboard.util++import com.vayunmathur.library.util.DataStoreUtils++/**+ * All user-tunable keyboard settings, snapshot into one immutable value so both the+ * setup Activity and the IME service read the same shape. Persisted via [DataStoreUtils]+ * (shared, offline preferences) under the [Keys] names.+ */+data class KeyboardSettings(+    val haptic: Boolean = true,+    val sound: Boolean = false,+    val autoCapitalize: Boolean = true,+    val doubleSpacePeriod: Boolean = true,+    val showSuggestions: Boolean = true,+    val autoCorrect: Boolean = false,+    /** Show a persistent 1โ€“0 number row above the letters. */+    val numberRow: Boolean = true,+    /** Multiplier on the base key height (0.8..1.4). */+    val keyHeightScale: Float = 1f,+) {+    object Keys {+        const val HAPTIC = "kb_haptic"+        const val SOUND = "kb_sound"+        const val AUTO_CAP = "kb_auto_cap"+        const val DOUBLE_SPACE_PERIOD = "kb_double_space_period"+        const val SHOW_SUGGESTIONS = "kb_show_suggestions"+        const val AUTO_CORRECT = "kb_auto_correct"+        const val NUMBER_ROW = "kb_number_row"+        const val KEY_HEIGHT = "kb_key_height"+    }++    companion object {+        /** Read the current persisted snapshot (defaults applied for unset keys). */+        fun load(ds: DataStoreUtils): KeyboardSettings = KeyboardSettings(+            haptic = ds.getBoolean(Keys.HAPTIC, true),+            sound = ds.getBoolean(Keys.SOUND, false),+            autoCapitalize = ds.getBoolean(Keys.AUTO_CAP, true),+            doubleSpacePeriod = ds.getBoolean(Keys.DOUBLE_SPACE_PERIOD, true),+            showSuggestions = ds.getBoolean(Keys.SHOW_SUGGESTIONS, true),+            autoCorrect = ds.getBoolean(Keys.AUTO_CORRECT, false),+            numberRow = ds.getBoolean(Keys.NUMBER_ROW, true),+            keyHeightScale = (ds.getDouble(Keys.KEY_HEIGHT) ?: 1.0).toFloat(),+        )+    }+}
keyboard/src/main/java/com/vayunmathur/keyboard/util/Layouts.kt
diff --git a/keyboard/src/main/java/com/vayunmathur/keyboard/util/Layouts.kt b/keyboard/src/main/java/com/vayunmathur/keyboard/util/Layouts.ktnew file mode 100644index 0000000000..7a26492ce2--- /dev/null+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/util/Layouts.kt@@ -0,0 +1,63 @@+package com.vayunmathur.keyboard.util++/** Which page of keys is currently shown. */+enum class KeyboardPage { LETTERS, SYMBOLS, MORE_SYMBOLS, NUMERIC, EMOJI }++/** Shift/caps state for the letter page. */+enum class ShiftState { OFF, SHIFTED, CAPS_LOCK }++/**+ * Static key layouts. Each page is a list of character rows (one [String] per row, one+ * key per character). Functional keys (shift, backspace, space, enter, page toggles) are+ * added by the UI around these character rows so the data here stays simple.+ */+object Layouts {+    /** QWERTY letters (always lowercase here; the UI upper-cases per shift state). */+    val LETTER_ROWS = listOf(+        "qwertyuiop",+        "asdfghjkl",+        "zxcvbnm",+    )++    val SYMBOL_ROWS = listOf(+        "1234567890",+        "@#\$_&-+()/",+        "*\"':;!?",+    )++    val MORE_SYMBOL_ROWS = listOf(+        "~`|โ€ขโˆšฯ€รทร—ยถ",+        "ยฃยขโ‚ฌยฅ^ยฐ={}",+        "\\%ยฉยฎโ„ขโœ“[]",+    )++    /** Compact numeric pad used for number/phone input types. */+    val NUMERIC_ROWS = listOf(+        "123",+        "456",+        "789",+        "*0#",+    )++    /**+     * Long-press alternates for the letter page: vowels (and รง/รฑ) expose common accents.+     * No digits here โ€” there's a dedicated number row. Long-pressing commits the first+     * alternate (a simple, popup-free version of accent entry); an empty string = no alternate.+     */+    val LETTER_ALTERNATES: Map<Char, String> = mapOf(+        'q' to "", 'w' to "", 'e' to "รฉรจรชรซ", 'r' to "", 't' to "",+        'y' to "รฟ", 'u' to "รบรนรปรผ", 'i' to "รญรฌรฎรฏ", 'o' to "รณรฒรดรถรธ", 'p' to "",+        'a' to "ร รกรขรครฃ", 's' to "รŸ", 'd' to "", 'f' to "", 'g' to "",+        'h' to "", 'j' to "", 'k' to "", 'l' to "",+        'z' to "", 'x' to "", 'c' to "รง", 'v' to "", 'b' to "", 'n' to "รฑ", 'm' to "",+    )++    /** Rows for the current character page, or null for pages the UI renders specially. */+    fun rowsFor(page: KeyboardPage): List<String>? = when (page) {+        KeyboardPage.LETTERS -> LETTER_ROWS+        KeyboardPage.SYMBOLS -> SYMBOL_ROWS+        KeyboardPage.MORE_SYMBOLS -> MORE_SYMBOL_ROWS+        KeyboardPage.NUMERIC -> NUMERIC_ROWS+        KeyboardPage.EMOJI -> null+    }+}
keyboard/src/main/res/values/strings.xml
diff --git a/keyboard/src/main/res/values/strings.xml b/keyboard/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..eca93d6330--- /dev/null+++ b/keyboard/src/main/res/values/strings.xml@@ -0,0 +1,5 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+    <string name="app_name">Keyboard</string>+    <string name="subtype_en">English</string>+</resources>
keyboard/src/main/res/xml/method.xml
diff --git a/keyboard/src/main/res/xml/method.xml b/keyboard/src/main/res/xml/method.xmlnew file mode 100644index 0000000000..64767c1a04--- /dev/null+++ b/keyboard/src/main/res/xml/method.xml@@ -0,0 +1,11 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- IME descriptor: points the system at the setup activity and declares one English subtype. -->+<input-method xmlns:android="http://schemas.android.com/apk/res/android"+    android:settingsActivity="com.vayunmathur.keyboard.MainActivity"+    android:supportsSwitchingToNextInputMethod="true">+    <subtype+        android:label="@string/subtype_en"+        android:imeSubtypeMode="keyboard"+        android:imeSubtypeLocale="en_US"+        android:languageTag="en" />+</input-method>