Modern Apps git

← Modern-Apps.git

keyboard: voice input on long-press of enter (#678)

Commit
a12d1d88ca2eca57d283c882bfb8127ecb109dca
Author
vayun-mathur <[email protected]>
When
2026-09-11 17:18 UTC (2 months ago)
Parents
5a0881f

Diff

keyboard/src/main/AndroidManifest.xml
diff --git a/keyboard/src/main/AndroidManifest.xml b/keyboard/src/main/AndroidManifest.xmlindex cdd21d6684..08f4d00566 100644--- a/keyboard/src/main/AndroidManifest.xml+++ b/keyboard/src/main/AndroidManifest.xml@@ -2,6 +2,17 @@ <manifest xmlns:android="http://schemas.android.com/apk/res/android">      <uses-permission android:name="android.permission.VIBRATE" />+    <!-- Dictation (long-press on enter). Requested at that point by VoicePermissionActivity,+         never at startup: an IME cannot show a runtime permission dialog itself. -->+    <uses-permission android:name="android.permission.RECORD_AUDIO" />++    <!-- SpeechRecognizer.isRecognitionAvailable() and the bind behind it both need to see the+         recognition service, which package visibility hides by default. -->+    <queries>+        <intent>+            <action android:name="android.speech.RecognitionService" />+        </intent>+    </queries>      <application         android:allowBackup="true"@@ -23,6 +34,15 @@             </intent-filter>         </activity> +        <!-- Invisible trampoline for the microphone prompt; see VoicePermissionActivity.+             Deliberately not android:noHistory, which would finish it under the dialog. -->+        <activity+            android:name=".platform.VoicePermissionActivity"+            android:excludeFromRecents="true"+            android:exported="false"+            android:launchMode="singleTop"+            android:theme="@android:style/Theme.Translucent.NoTitleBar" />+         <service             android:name=".ime.KeyboardService"             android:label="@string/app_name"
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 53129bddfb..954494c253 100644--- a/keyboard/src/main/java/com/vayunmathur/keyboard/ime/KeyboardService.kt+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/ime/KeyboardService.kt@@ -2,13 +2,16 @@ package com.vayunmathur.keyboard.ime  import android.content.ClipDescription import android.content.ClipboardManager+import android.content.Intent import android.inputmethodservice.InputMethodService import android.media.AudioManager+import android.net.Uri import android.os.Build import android.os.SystemClock import android.os.VibrationEffect import android.os.Vibrator import android.os.VibratorManager+import android.provider.Settings import android.text.InputType import android.view.KeyEvent import android.view.View@@ -37,6 +40,10 @@ import androidx.savedstate.SavedStateRegistry import androidx.savedstate.SavedStateRegistryController import androidx.savedstate.SavedStateRegistryOwner import androidx.savedstate.setViewTreeSavedStateRegistryOwner+import com.vayunmathur.keyboard.platform.VoiceFailure+import com.vayunmathur.keyboard.platform.VoiceInput+import com.vayunmathur.keyboard.platform.VoicePermission+import com.vayunmathur.keyboard.platform.VoicePermissionResult import com.vayunmathur.keyboard.ui.KeyboardScreen import com.vayunmathur.keyboard.util.ClipItem import com.vayunmathur.keyboard.util.ClipboardStore@@ -53,6 +60,7 @@ import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.util.DataStoreUtils import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.delay@@ -74,6 +82,12 @@ private const val DOUBLE_TAP_MS = 300L /** How long a freshly copied clip is offered in the strip before the chip gives up the slot. */ private const val CLIP_CHIP_MS = 60_000L +/** How long a dictation failure stays in the strip before it clears itself. */+private const val VOICE_MESSAGE_MS = 6_000L++/** How long a granted microphone still counts as "the user just asked for dictation". */+private const val VOICE_GRANT_MS = 30_000L+ class KeyboardService : InputMethodService(),     LifecycleOwner, ViewModelStoreOwner, SavedStateRegistryOwner, ImeActions { @@ -131,6 +145,20 @@ class KeyboardService : InputMethodService(),      private var vibrator: Vibrator? = null +    private val voiceInput by lazy { VoiceInput(this) }++    /** Clears a dictation failure from the strip after a while; cancelled by the next change. */+    private var voiceMessageJob: Job? = null++    /** True between [onWindowShown] and [onWindowHidden] — i.e. while there is a live field. */+    private var windowShown = false++    /**+     * When the microphone was granted while the keyboard was away for the prompt, so+     * dictation can pick up where it left off. Zero when nothing is waiting.+     */+    private var voiceGrantedAt = 0L+     /** This IME's id in the framework, resolved once from [InputMethodManager.getInputMethodList]. */     private var imeId: String? = null @@ -159,6 +187,7 @@ class KeyboardService : InputMethodService(),         syncComposer()         registerLayoutSubtypes()         observeSettings()+        scope.launch { VoicePermission.results.collect { onVoicePermissionResult(it) } }     }      /** Keep [KeyboardState.settings] in sync with DataStore so changes apply live. */@@ -381,6 +410,15 @@ class KeyboardService : InputMethodService(),         super.onWindowShown()         lifecycleRegistry.currentState = Lifecycle.State.RESUMED         updateBottomInset()+        windowShown = true+        // Resume the dictation the permission prompt interrupted — but only if the keyboard+        // came straight back. Granting and then wandering off must not open the microphone+        // the next time some unrelated field is tapped.+        if (voiceGrantedAt != 0L) {+            val resumed = SystemClock.uptimeMillis() - voiceGrantedAt < VOICE_GRANT_MS+            voiceGrantedAt = 0L+            if (resumed) beginListening()+        }     }      /**@@ -401,6 +439,7 @@ class KeyboardService : InputMethodService(),      override fun onWindowHidden() {         super.onWindowHidden()+        windowShown = false         // Keep the composition alive (STARTED, not DESTROYED) so re-showing is instant.         lifecycleRegistry.currentState = Lifecycle.State.STARTED     }@@ -425,6 +464,9 @@ class KeyboardService : InputMethodService(),         pendingComposition = ""         before.invalidate()         composer?.reset()+        // There is no longer a field for a transcript to land in. A failure raised *after*+        // this (the permission prompt is what took the field away) still shows on the way back.+        if (kbState.voice != null) dismissVoice()     }      override fun onDestroy() {@@ -433,6 +475,7 @@ class KeyboardService : InputMethodService(),             getSystemService(ClipboardManager::class.java)?.removePrimaryClipChangedListener(it)         }         clipListener = null+        voiceInput.destroy()         store.clear()         scope.cancel()         super.onDestroy()@@ -900,6 +943,124 @@ class KeyboardService : InputMethodService(),         kbState.clipSuggestion = null     } +    // --- Voice input ---++    /**+     * Long-press on enter. Pressing again while the microphone is live stops it, so the one+     * gesture both starts and ends a dictation.+     */+    override fun onVoiceInput() {+        feedback()+        if (kbState.voice is VoiceState.Listening) {+            stopVoiceInput()+            return+        }+        // Checked up front rather than left to the recognizer: on a device with no+        // recognition service there is nothing to bind to, and saying so is more use than+        // a generic failure.+        if (!voiceInput.isAvailable()) {+            showVoiceFailure(VoiceFailure.UNAVAILABLE)+            return+        }+        if (!VoicePermission.isGranted(this)) {+            setVoiceState(null)+            VoicePermission.request(this)+            return+        }+        beginListening()+    }++    override fun stopVoiceInput() {+        // stopListening, not cancel: the recognizer still reports the words it already has.+        voiceInput.stop()+        if (kbState.voice is VoiceState.Listening) setVoiceState(VoiceState.Transcribing)+    }++    override fun dismissVoice() {+        voiceInput.cancel()+        setVoiceState(null)+    }++    override fun openVoiceSettings() {+        dismissVoice()+        val intent = Intent(+            Settings.ACTION_APPLICATION_DETAILS_SETTINGS,+            Uri.fromParts("package", packageName, null),+        ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+        runCatching { startActivity(intent) }+    }++    private fun onVoicePermissionResult(result: VoicePermissionResult) {+        when (result) {+            // The prompt took the focus, which hid the keyboard along with the field. Wait+            // for both back before listening, or the transcript would have nowhere to go.+            VoicePermissionResult.GRANTED -> {+                if (windowShown) beginListening() else voiceGrantedAt = SystemClock.uptimeMillis()+            }+            VoicePermissionResult.DENIED -> showVoiceFailure(VoiceFailure.PERMISSION_DENIED)+            VoicePermissionResult.BLOCKED -> showVoiceFailure(VoiceFailure.PERMISSION_BLOCKED)+        }+    }++    private fun beginListening() {+        setVoiceState(VoiceState.Listening(""))+        voiceInput.start(+            // Dictate in the language the user chose to type in, which is a better guess+            // than the device locale on a keyboard whose whole point is switching scripts.+            languageTag = kbState.settings.activeLayout.id.substringBefore('_'),+            onPartial = { partial ->+                if (kbState.voice is VoiceState.Listening) {+                    setVoiceState(VoiceState.Listening(partial))+                }+            },+            onTranscribing = {+                if (kbState.voice is VoiceState.Listening) setVoiceState(VoiceState.Transcribing)+            },+            onFinal = { text ->+                setVoiceState(null)+                commitVoiceText(text)+            },+            onFailure = ::showVoiceFailure,+        )+    }++    /**+     * Put a transcript into the field. Anything still composing is settled first — dictated+     * text is finished text, not a continuation of the half-typed word — and `commitText`+     * then replaces the selection, which is what dictating over selected text should do.+     */+    private fun commitVoiceText(text: String) {+        val ic = currentInputConnection ?: return+        finishComposition(ic)+        commitCurrentWord(ic, autoCorrect = false)+        // Read before committing: the mirror drops the selection as soon as it is told.+        val replacedSelection = before.hasSelection+        val needsSpace = !replacedSelection &&+            textBeforeCursor().lastOrNull()?.isWhitespace() == false+        commit(ic, if (needsSpace) " $text" else text)+        // What surrounded the replaced selection is text we never saw.+        if (replacedSelection) before.invalidate()+        kbState.suggestions = emptyList()+        updateAutoCapShift()+    }++    private fun showVoiceFailure(failure: VoiceFailure) {+        setVoiceState(VoiceState.Failed(failure))+    }++    private fun setVoiceState(state: VoiceState?) {+        voiceMessageJob?.cancel()+        voiceMessageJob = null+        kbState.voice = state+        // A blocked microphone is the one failure that carries an action, so it waits to be+        // read and dismissed instead of timing out from under the user's finger.+        if (state !is VoiceState.Failed || state.failure == VoiceFailure.PERMISSION_BLOCKED) return+        voiceMessageJob = scope.launch {+            delay(VOICE_MESSAGE_MS)+            if (kbState.voice == state) kbState.voice = null+        }+    }+     // --- Emoji search ---      override fun startEmojiSearch() {
keyboard/src/main/java/com/vayunmathur/keyboard/ime/KeyboardState.kt
diff --git a/keyboard/src/main/java/com/vayunmathur/keyboard/ime/KeyboardState.kt b/keyboard/src/main/java/com/vayunmathur/keyboard/ime/KeyboardState.ktindex 13e5c5e6ab..c03a1e8427 100644--- a/keyboard/src/main/java/com/vayunmathur/keyboard/ime/KeyboardState.kt+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/ime/KeyboardState.kt@@ -3,6 +3,7 @@ package com.vayunmathur.keyboard.ime import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue+import com.vayunmathur.keyboard.platform.VoiceFailure import com.vayunmathur.keyboard.util.ClipItem import com.vayunmathur.keyboard.util.EmojiData import com.vayunmathur.keyboard.util.KeyboardPage@@ -19,6 +20,21 @@ enum class EnterAction { RETURN, GO, SEARCH, SEND, NEXT, DONE, PREVIOUS }  */ enum class TextVariation { NORMAL, EMAIL, URL } +/**+ * What voice input is doing, or null when it is idle. An IME has no window of its own to put+ * a dialog in, so dictation reports itself in the strip above the keys.+ */+sealed interface VoiceState {+    /** Capturing audio; [partial] is the best transcript so far, which may be blank. */+    data class Listening(val partial: String) : VoiceState++    /** Capture is over and the recognizer is still working on it. */+    data object Transcribing : VoiceState++    /** The session ended with no text to commit. */+    data class Failed(val failure: VoiceFailure) : VoiceState+}+ /**  * 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]@@ -85,6 +101,9 @@ class KeyboardState {      * starts typing or enough time passes — it is an offer, not a permanent extra row.      */     var clipSuggestion by mutableStateOf<ClipItem?>(null)++    /** Dictation progress or its last failure, shown in place of the strip. Null when idle. */+    var voice by mutableStateOf<VoiceState?>(null) }  /**@@ -115,6 +134,18 @@ interface ImeActions {     /** Dismiss the strip chip without deleting the clip behind it. */     fun dismissClipSuggestion() +    /** Start dictating, or stop and commit if it is already listening (long-press on enter). */+    fun onVoiceInput()++    /** Stop capturing and commit whatever has been heard so far. */+    fun stopVoiceInput()++    /** Clear the dictation strip, abandoning any session behind it. */+    fun dismissVoice()++    /** Open this app's system settings, the only way back from a blocked microphone. */+    fun openVoiceSettings()+     companion object {         /**          * Does nothing. Lets `src/screenshotTest` render [@@ -137,6 +168,10 @@ interface ImeActions {             override fun deleteClip(item: ClipItem) {}             override fun clearClips() {}             override fun dismissClipSuggestion() {}+            override fun onVoiceInput() {}+            override fun stopVoiceInput() {}+            override fun dismissVoice() {}+            override fun openVoiceSettings() {}         }     } }
keyboard/src/main/java/com/vayunmathur/keyboard/platform/VoiceInput.kt
diff --git a/keyboard/src/main/java/com/vayunmathur/keyboard/platform/VoiceInput.kt b/keyboard/src/main/java/com/vayunmathur/keyboard/platform/VoiceInput.ktnew file mode 100644index 0000000000..68d53946d6--- /dev/null+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/platform/VoiceInput.kt@@ -0,0 +1,149 @@+package com.vayunmathur.keyboard.platform++import android.content.Context+import android.content.Intent+import android.os.Bundle+import android.speech.RecognitionListener+import android.speech.RecognizerIntent+import android.speech.SpeechRecognizer+import android.util.Log+import java.util.Locale++private const val TAG = "VoiceInput"++/**+ * Why a dictation session ended without text. The recognizer's own error codes are not+ * user-facing; [com.vayunmathur.keyboard.ui.VoiceStrip] turns these into a message.+ */+enum class VoiceFailure {+    /** No recognition service installed at all — the normal state on a de-Googled ROM. */+    UNAVAILABLE,+    PERMISSION_DENIED,++    /** Denied with "don't ask again", so only the system settings screen can undo it. */+    PERMISSION_BLOCKED,+    NETWORK,+    NO_SPEECH,+    BUSY,+    AUDIO,+    OTHER,+}++/**+ * Dictation driven straight from the IME with [SpeechRecognizer].+ *+ * An `InputMethodService` is not an Activity, so `ACTION_RECOGNIZE_SPEECH` — which hands its+ * transcript back as an activity result — is not reachable from here. [SpeechRecognizer] is+ * the same engine without that requirement: it binds the recognition service directly and+ * delivers the transcript to a listener. It also streams partial results, which is what lets+ * the strip show words while they are still being spoken.+ *+ * Main thread only, like the framework class it wraps.+ */+class VoiceInput(private val context: Context) {++    private var recognizer: SpeechRecognizer? = null++    fun isAvailable(): Boolean = SpeechRecognizer.isRecognitionAvailable(context)++    /**+     * Listen for one utterance in [languageTag], or in whatever the recognizer picks when it+     * is blank. Exactly one of [onFinal] and [onFailure] ends the session, so the caller can+     * always reset on either.+     */+    fun start(+        languageTag: String,+        onPartial: (String) -> Unit,+        onTranscribing: () -> Unit,+        onFinal: (String) -> Unit,+        onFailure: (VoiceFailure) -> Unit,+    ) {+        if (!isAvailable()) {+            onFailure(VoiceFailure.UNAVAILABLE)+            return+        }+        // One recognizer, cancelled rather than destroyed between sessions: rebinding the+        // service before the previous session has cleared reports ERROR_RECOGNIZER_BUSY.+        val sr = recognizer+            ?: SpeechRecognizer.createSpeechRecognizer(context).also { recognizer = it }+        runCatching { sr.cancel() }++        val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {+            putExtra(+                RecognizerIntent.EXTRA_LANGUAGE_MODEL,+                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM,+            )+            if (languageTag.isNotEmpty()) {+                putExtra(+                    RecognizerIntent.EXTRA_LANGUAGE,+                    Locale.forLanguageTag(languageTag).toLanguageTag(),+                )+            }+            putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)+            putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1)+        }++        sr.setRecognitionListener(object : RecognitionListener {+            override fun onReadyForSpeech(params: Bundle?) {}+            override fun onBeginningOfSpeech() {}+            override fun onRmsChanged(rmsdB: Float) {}+            override fun onBufferReceived(buffer: ByteArray?) {}++            // Capture has ended; an on-device model still has to transcribe it.+            override fun onEndOfSpeech() {+                onTranscribing()+            }++            override fun onError(error: Int) {+                onFailure(error.toFailure())+            }++            override fun onPartialResults(partialResults: Bundle?) {+                firstResult(partialResults)?.let(onPartial)+            }++            override fun onResults(results: Bundle?) {+                val text = firstResult(results)+                if (text == null) onFailure(VoiceFailure.NO_SPEECH) else onFinal(text)+            }++            override fun onEvent(eventType: Int, params: Bundle?) {}+        })++        try {+            sr.startListening(intent)+        } catch (t: Throwable) {+            Log.e(TAG, "startListening failed", t)+            onFailure(VoiceFailure.OTHER)+        }+    }++    /** Stop capturing but keep the session: the recognizer still reports what it heard. */+    fun stop() {+        runCatching { recognizer?.stopListening() }+    }++    /** Abandon the session outright, with no result. */+    fun cancel() {+        runCatching { recognizer?.cancel() }+    }++    fun destroy() {+        runCatching { recognizer?.destroy() }+        recognizer = null+    }++    private fun firstResult(bundle: Bundle?): String? =+        bundle?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)+            ?.firstOrNull()+            ?.takeIf { it.isNotBlank() }+}++private fun Int.toFailure(): VoiceFailure = when (this) {+    SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS -> VoiceFailure.PERMISSION_DENIED+    SpeechRecognizer.ERROR_NETWORK, SpeechRecognizer.ERROR_NETWORK_TIMEOUT -> VoiceFailure.NETWORK+    SpeechRecognizer.ERROR_NO_MATCH, SpeechRecognizer.ERROR_SPEECH_TIMEOUT -> VoiceFailure.NO_SPEECH+    SpeechRecognizer.ERROR_RECOGNIZER_BUSY -> VoiceFailure.BUSY+    SpeechRecognizer.ERROR_AUDIO -> VoiceFailure.AUDIO+    else -> VoiceFailure.OTHER+}
keyboard/src/main/java/com/vayunmathur/keyboard/platform/VoicePermissionActivity.kt
diff --git a/keyboard/src/main/java/com/vayunmathur/keyboard/platform/VoicePermissionActivity.kt b/keyboard/src/main/java/com/vayunmathur/keyboard/platform/VoicePermissionActivity.ktnew file mode 100644index 0000000000..38c4e0e5ec--- /dev/null+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/platform/VoicePermissionActivity.kt@@ -0,0 +1,76 @@+package com.vayunmathur.keyboard.platform++import android.Manifest+import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.result.contract.ActivityResultContracts+import androidx.core.content.ContextCompat+import kotlinx.coroutines.flow.MutableSharedFlow+import kotlinx.coroutines.flow.SharedFlow++/** What the user did with the microphone prompt. */+enum class VoicePermissionResult { GRANTED, DENIED, BLOCKED }++/**+ * The microphone permission, on behalf of the IME.+ *+ * An `InputMethodService` cannot show a runtime permission dialog: the framework only grants+ * a permission to an Activity's request, and the IME has no Activity. So the service starts+ * [VoicePermissionActivity] and learns the outcome from [results] — a plain in-process flow,+ * which is enough because the activity and the service share the app's process.+ */+object VoicePermission {++    private val _results = MutableSharedFlow<VoicePermissionResult>(extraBufferCapacity = 1)+    val results: SharedFlow<VoicePermissionResult> = _results++    fun isGranted(context: Context): Boolean =+        ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) ==+            PackageManager.PERMISSION_GRANTED++    fun request(context: Context) {+        context.startActivity(+            Intent(context, VoicePermissionActivity::class.java)+                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),+        )+    }++    internal fun publish(result: VoicePermissionResult) {+        _results.tryEmit(result)+    }+}++/**+ * Invisible trampoline that asks for `RECORD_AUDIO` and reports the answer to [VoicePermission].+ *+ * **Not `android:noHistory`**: that finishes an activity the moment it stops being visible, and+ * the system permission dialog does exactly that, so the result callback would never arrive.+ */+class VoicePermissionActivity : ComponentActivity() {++    private val request = registerForActivityResult(+        ActivityResultContracts.RequestPermission(),+    ) { granted ->+        // Straight after a denial, shouldShowRequestPermissionRationale is false only when+        // the user chose "don't ask again" — that is the one case a further prompt cannot fix.+        VoicePermission.publish(+            when {+                granted -> VoicePermissionResult.GRANTED+                shouldShowRequestPermissionRationale(Manifest.permission.RECORD_AUDIO) ->+                    VoicePermissionResult.DENIED+                else -> VoicePermissionResult.BLOCKED+            },+        )+        finish()+    }++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        // Only on a fresh launch: registerForActivityResult restores a pending request across+        // a configuration change itself, and asking again would stack a second dialog.+        if (savedInstanceState == null) request.launch(Manifest.permission.RECORD_AUDIO)+    }+}
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 46d5b6dfce..ccb1685371 100644--- a/keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyButton.kt+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyButton.kt@@ -4,6 +4,7 @@ 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.awaitFirstDown import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.gestures.waitForUpOrCancellation@@ -393,7 +394,12 @@ private object KeyPreviewPositionProvider : PopupPositionProvider {     } } -/** A functional key that only needs a tap (page toggles, comma/period, emoji, enter). */+/**+ * A functional key that only needs a tap (page toggles, comma/period, emoji, enter).+ *+ * [onLongClick] is optional and is the only extra gesture the key knows: unlike [CharKey]+ * there is no popup to slide onto, so the press simply fires once the hold is long enough.+ */ @Composable fun RowScope.SpecialKey(     height: Dp,@@ -403,6 +409,8 @@ fun RowScope.SpecialKey(     pressedContainerColor: Color = pressedKeyColor(),     pressedContentColor: Color = MaterialTheme.colorScheme.onSurface,     onClick: () -> Unit,+    onLongClick: (() -> Unit)? = null,+    onLongClickLabel: String? = null,     content: @Composable () -> Unit, ) {     val interaction = remember { MutableInteractionSource() }@@ -411,7 +419,13 @@ fun RowScope.SpecialKey(         modifier = Modifier             .weight(weight)             .height(height + KeyPadding * 2)-            .clickable(interactionSource = interaction, indication = null, onClick = onClick)+            .combinedClickable(+                interactionSource = interaction,+                indication = null,+                onLongClickLabel = onLongClickLabel,+                onLongClick = onLongClick,+                onClick = onClick,+            )             .padding(KeyPadding)             .clip(KeyShape)             .background(if (pressed) pressedContainerColor else containerColor),
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 7b588cdd12..f130d5c509 100644--- a/keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyboardScreen.kt+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyboardScreen.kt@@ -70,21 +70,37 @@ fun KeyboardScreen(state: KeyboardState, actions: ImeActions) {     // 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 } }+    val voice = state.voice     Surface(color = MaterialTheme.colorScheme.surfaceContainer) {         Column(             modifier = Modifier                 .fillMaxWidth()                 .padding(bottom = bottomPad),         ) {-            if (searching) {+            when {+                // Dictation outranks everything else in the strip: it is the only thing up+                // there that the user has to be able to see and stop.+                voice != null -> {+                    VoiceStrip(+                        height = StripHeight,+                        state = voice,+                        onStop = actions::stopVoiceInput,+                        onDismiss = actions::dismissVoice,+                        onOpenSettings = actions::openVoiceSettings,+                    )+                    KeyPage(state, actions, keyHeight)+                }                 // 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.-                EmojiSearchStrip(state, actions)-                LettersPage(state, actions, keyHeight)-            } else {-                Strip(state, actions)-                KeyPage(state, actions, keyHeight)+                searching -> {+                    EmojiSearchStrip(state, actions)+                    LettersPage(state, actions, keyHeight)+                }+                else -> {+                    Strip(state, actions)+                    KeyPage(state, actions, keyHeight)+                }             }         }     }@@ -575,6 +591,10 @@ private fun RowScope.EnterKey(state: KeyboardState, actions: ImeActions, keyHeig         pressedContainerColor = MaterialTheme.colorScheme.primaryContainer,         pressedContentColor = MaterialTheme.colorScheme.onPrimaryContainer,         onClick = actions::onEnter,+        // Enter had no hold gesture of its own, and it is the one key that is present on+        // every page, which is why dictation lives here (issue #678).+        onLongClick = actions::onVoiceInput,+        onLongClickLabel = stringResource(R.string.voice_input),     ) {         // A custom action carries an app-supplied label ("Join", "Post", ...) whose purpose         // we can't map to an icon, so that one case stays textual; every standard action
keyboard/src/main/java/com/vayunmathur/keyboard/ui/VoiceStrip.kt
diff --git a/keyboard/src/main/java/com/vayunmathur/keyboard/ui/VoiceStrip.kt b/keyboard/src/main/java/com/vayunmathur/keyboard/ui/VoiceStrip.ktnew file mode 100644index 0000000000..8a758126c8--- /dev/null+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/ui/VoiceStrip.kt@@ -0,0 +1,130 @@+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.foundation.layout.size+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.keyboard.R+import com.vayunmathur.keyboard.ime.VoiceState+import com.vayunmathur.keyboard.platform.VoiceFailure+import com.vayunmathur.library.ui.IconClose+import com.vayunmathur.library.ui.IconMic+import com.vayunmathur.library.ui.IconMicOff+import com.vayunmathur.library.ui.IconSettings+import com.vayunmathur.library.ui.IconStop+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text++/**+ * The dictation strip, which takes over the slot above the keys for as long as voice input+ * has something to say.+ *+ * An IME cannot open a dialog — that would take focus from the very field being dictated+ * into — so this row is the whole of the feedback: it shows that the microphone is live,+ * echoes the words as the recognizer hears them, and carries the button that ends the+ * session. A failure stays here too, next to the affordance that can fix it, rather than+ * going out as a message no scaffold in an IME would be collecting.+ */+@Composable+fun VoiceStrip(+    height: Dp,+    state: VoiceState,+    onStop: () -> Unit,+    onDismiss: () -> Unit,+    onOpenSettings: () -> Unit,+) {+    Row(+        modifier = Modifier+            .fillMaxWidth()+            .height(height)+            .padding(horizontal = 6.dp, vertical = 4.dp),+        verticalAlignment = Alignment.CenterVertically,+    ) {+        val failed = state as? VoiceState.Failed+        val tint = if (failed != null) {+            MaterialTheme.colorScheme.error+        } else {+            MaterialTheme.colorScheme.primary+        }+        Box(+            modifier = Modifier.fillMaxHeight().padding(horizontal = 6.dp),+            contentAlignment = Alignment.Center,+        ) {+            if (failed != null) {+                IconMicOff(modifier = Modifier.size(18.dp), tint = tint)+            } else {+                IconMic(modifier = Modifier.size(18.dp), tint = tint)+            }+        }+        Text(+            text = label(state),+            color = if (failed != null) tint else MaterialTheme.colorScheme.onSurface,+            fontSize = 14.sp,+            maxLines = 1,+            overflow = TextOverflow.Ellipsis,+            modifier = Modifier.weight(1f),+        )+        if (failed?.failure == VoiceFailure.PERMISSION_BLOCKED) {+            StripButton(onClick = onOpenSettings) {+                IconSettings(+                    modifier = Modifier.size(18.dp),+                    tint = MaterialTheme.colorScheme.onSurfaceVariant,+                )+            }+        }+        StripButton(onClick = if (state is VoiceState.Listening) onStop else onDismiss) {+            val buttonTint = MaterialTheme.colorScheme.onSurfaceVariant+            if (state is VoiceState.Listening) {+                IconStop(modifier = Modifier.size(20.dp), tint = buttonTint)+            } else {+                IconClose(modifier = Modifier.size(18.dp), tint = buttonTint)+            }+        }+    }+}++@Composable+private fun StripButton(onClick: () -> Unit, content: @Composable () -> Unit) {+    Box(+        modifier = Modifier+            .fillMaxHeight()+            .clip(RoundedCornerShape(8.dp))+            .clickable(onClick = onClick)+            .padding(horizontal = 8.dp),+        contentAlignment = Alignment.Center,+    ) { content() }+}++/** The strip's one line of text. Partial results replace "Listening…" as soon as any arrive. */+@Composable+private fun label(state: VoiceState): String = when (state) {+    is VoiceState.Listening ->+        state.partial.ifBlank { stringResource(R.string.voice_listening) }+    VoiceState.Transcribing -> stringResource(R.string.voice_transcribing)+    is VoiceState.Failed -> stringResource(+        when (state.failure) {+            VoiceFailure.UNAVAILABLE -> R.string.voice_unavailable+            VoiceFailure.PERMISSION_DENIED -> R.string.voice_permission_denied+            VoiceFailure.PERMISSION_BLOCKED -> R.string.voice_permission_blocked+            VoiceFailure.NETWORK -> R.string.voice_network+            VoiceFailure.NO_SPEECH -> R.string.voice_no_speech+            VoiceFailure.BUSY -> R.string.voice_busy+            VoiceFailure.AUDIO -> R.string.voice_audio_error+            VoiceFailure.OTHER -> R.string.voice_failed+        },+    )+}
keyboard/src/main/res/values/strings.xml
diff --git a/keyboard/src/main/res/values/strings.xml b/keyboard/src/main/res/values/strings.xmlindex f133d12893..9315576703 100644--- a/keyboard/src/main/res/values/strings.xml+++ b/keyboard/src/main/res/values/strings.xml@@ -17,4 +17,27 @@     <string name="clear_clipboard">Clear all</string>     <string name="clear_clipboard_history">Clear clipboard history</string>     <string name="copied_text_shows_up_here">Copied text and images show up here</string>++    <!-- Accessibility label for the long-press action on the keyboard's enter key, which starts dictation. -->+    <string name="voice_input">Voice input</string>+    <!-- Keyboard: shown in the strip above the keys while the microphone is recording speech. -->+    <string name="voice_listening">Listening…</string>+    <!-- Keyboard: shown in the strip above the keys after recording stops, while the speech is being turned into text. -->+    <string name="voice_transcribing">Transcribing…</string>+    <!-- Keyboard error in the strip above the keys: the device has no speech recognition app installed at all. -->+    <string name="voice_unavailable">No speech recognition app installed</string>+    <!-- Keyboard error in the strip above the keys: the user declined the microphone permission prompt. -->+    <string name="voice_permission_denied">Voice input needs the microphone</string>+    <!-- Keyboard error in the strip above the keys: the microphone permission was permanently denied, so it can only be granted in system settings. A settings button sits next to this text. -->+    <string name="voice_permission_blocked">Allow the microphone in Settings</string>+    <!-- Keyboard error in the strip above the keys: speech recognition needs a network connection and there is none. -->+    <string name="voice_network">Voice input needs a connection</string>+    <!-- Keyboard error in the strip above the keys: the recording contained no recognizable speech. -->+    <string name="voice_no_speech">Didn\'t catch that</string>+    <!-- Keyboard error in the strip above the keys: the speech recognizer is already busy with another request. -->+    <string name="voice_busy">Speech recognizer is busy</string>+    <!-- Keyboard error in the strip above the keys: the microphone could not be recorded from. -->+    <string name="voice_audio_error">Couldn\'t record audio</string>+    <!-- Keyboard error in the strip above the keys: dictation failed for a reason we cannot be more specific about. -->+    <string name="voice_failed">Voice input failed</string> </resources>