From be32cb67c659cddbae78c17720cb5201c7ebb51b Mon Sep 17 00:00:00 2001 From: LeanBitLab Date: Fri, 4 Dec 2026 17:59:17 +0530 Subject: [PATCH] fix(voice): keep dictation in its field and clean up failed starts (#1078) - do not write results into a changed or password field after an input restart - stop recording at once when the plugin cannot start a session - clean up when binding to the plugin fails - a queued silence timeout no longer cancels a later or finishing dictation - switch to the voice app's entry for the keyboard language, if it has one --- .../keyboard/latin/RichInputMethodManager.kt | 7 +++ .../keyboard/latin/voice/VoiceInputManager.kt | 55 +++++++++++++++---- .../latin/voice/VoiceFieldChangeTest.kt | 25 +++++++++ .../latin/voice/VoiceProviderRoutingTest.kt | 16 ++++++ 4 files changed, 93 insertions(+), 10 deletions(-) create mode 100644 app/src/test/java/helium314/keyboard/latin/voice/VoiceFieldChangeTest.kt diff --git a/app/src/main/java/helium314/keyboard/latin/RichInputMethodManager.kt b/app/src/main/java/helium314/keyboard/latin/RichInputMethodManager.kt index 4a956516c..6ac7e4561 100644 --- a/app/src/main/java/helium314/keyboard/latin/RichInputMethodManager.kt +++ b/app/src/main/java/helium314/keyboard/latin/RichInputMethodManager.kt @@ -160,7 +160,14 @@ class RichInputMethodManager private constructor() { return null } + /** the voice app to switch to, with its entry for the keyboard language if it has one */ internal fun getTargetShortcut(): Shortcut? { + val target = getTargetVoiceApp() ?: return null + val language = currentSubtypeLocale.language + return shortcuts.firstOrNull { it.imi.id == target.imi.id && it.subtype.locale().language == language } ?: target + } + + private fun getTargetVoiceApp(): Shortcut? { if (shortcuts.isEmpty()) return null val p = context.prefs() val selectedApp = p.getString(VoiceConstants.PREF_VOICE_THIRD_PARTY_APP, VoiceConstants.VOICE_APP_SYSTEM_DEFAULT) diff --git a/app/src/main/java/helium314/keyboard/latin/voice/VoiceInputManager.kt b/app/src/main/java/helium314/keyboard/latin/voice/VoiceInputManager.kt index 161ba2aba..90c9f7463 100644 --- a/app/src/main/java/helium314/keyboard/latin/voice/VoiceInputManager.kt +++ b/app/src/main/java/helium314/keyboard/latin/voice/VoiceInputManager.kt @@ -112,6 +112,9 @@ class VoiceInputManager( private var state = VoiceState.IDLE private var activeSessionId: String? = null + /** the field the dictation was started in: its text goes only there */ + private var sessionEditor: String? = null + private var audioRecord: AudioRecord? = null private var audioPipeWriteSide: ParcelFileDescriptor? = null private var audioPipeReadSide: ParcelFileDescriptor? = null @@ -214,6 +217,7 @@ class VoiceInputManager( pluginManager.cancelSession() val sessionId = UUID.randomUUID().toString() activeSessionId = sessionId + sessionEditor = editorKey(ims.currentInputEditorInfo) needsCapitalStart = true sessionEmittedText = "" isCurrentSessionOnline = false @@ -248,6 +252,7 @@ class VoiceInputManager( if (!bound) { cancelConnectingTimeout() notifyError("Failed to bind to voice plugin") + cleanupSession() updateState(VoiceState.ERROR) return } @@ -265,6 +270,7 @@ class VoiceInputManager( } val sessionId = UUID.randomUUID().toString() activeSessionId = sessionId + sessionEditor = editorKey(ims.currentInputEditorInfo) needsCapitalStart = true sessionEmittedText = "" isCurrentSessionOnline = true @@ -422,14 +428,18 @@ class VoiceInputManager( } // Start hardware audio capture IMMEDIATELY so the green mic privacy dot appears without IPC delay - startAudioRecordingThread() + if (!startAudioRecordingThread()) { + failHandshake("Failed to start audio recording") + return + } try { val pfdForPlugin = audioPipeReadSide if (pfdForPlugin != null) { audioPipeReadSide = null try { - pluginManager.startSession(config, pfdForPlugin, callback) + if (!pluginManager.startSession(config, pfdForPlugin, callback)) + failHandshake("Failed to start voice session with plugin") } finally { closeQuietly(pfdForPlugin) } @@ -438,13 +448,18 @@ class VoiceInputManager( } } catch (e: Exception) { Log.e(TAG, "Remote exception starting voice session", e) - cancelHandshakeTimeout() - notifyError("Failed to start voice session with plugin") - cleanupSession() - updateState(VoiceState.ERROR) + failHandshake("Failed to start voice session with plugin") } } + private fun failHandshake(message: String) { + cancelHandshakeTimeout() + notifyError(message) + cleanupSession() + updateState(VoiceState.ERROR) + onOfflineSessionIdle?.invoke() + } + private fun startAudioRecordingThread(): Boolean { stopAudioLoop() // Prevent zombie thread overlap on rapid re-entry if (ContextCompat.checkSelfPermission(ims, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { @@ -546,6 +561,8 @@ class VoiceInputManager( else -> 120.0 } + // a timeout posted by this thread must not end a later session + val sessionId = activeSessionId audioThread = Thread({ val buffer = ByteArray(FRAME_SIZE_BYTES) var outputStream: FileOutputStream? = null @@ -652,11 +669,14 @@ class VoiceInputManager( if (silenceTimeoutMs > 0L) { if (hasSpoken && (now - lastSpeechTime > silenceTimeoutMs)) { Log.i(TAG, "Silence timeout (${silenceTimeoutMs}ms) detected after speech. Stopping voice input.") - mainHandler.post { stopVoice() } + mainHandler.post { if (activeSessionId == sessionId) stopVoice() } break } else if (!hasSpoken && (now - sessionStartTime > initialTimeoutMs)) { Log.i(TAG, "Initial silence timeout (${initialTimeoutMs}ms) detected. Cancelling voice input.") - mainHandler.post { cancelVoice() } + // not if stop was tapped meanwhile: that dictation is being transcribed + mainHandler.post { + if (activeSessionId == sessionId && state != VoiceState.PROCESSING_FINAL) cancelVoice() + } break } } @@ -874,6 +894,7 @@ class VoiceInputManager( updateState(VoiceState.PROCESSING_FINAL) scheduleProcessingTimeout() activeSessionId = UUID.randomUUID().toString() + sessionEditor = editorKey(ims.currentInputEditorInfo) transcribeOnlineWav(cached.wavBytes, cached.languageTag, retryCount = 0) } @@ -957,8 +978,6 @@ class VoiceInputManager( /** the field the dictation was started in: text of later pieces goes only there */ private var piecewiseEditor: String? = null - private fun editorKey(info: EditorInfo?): String? = info?.let { "${it.packageName}|${it.fieldId}|${it.inputType}" } - private fun startPiecewiseRecording() { piecewiseGeneration++ piecewiseActive = true @@ -1111,6 +1130,16 @@ class VoiceInputManager( } if (!isRecording.get() && !isFinal) return + // a restarted input (some web pages) doesn't cancel the dictation: don't write into another field + val editor = ims.currentInputEditorInfo + if (!mayDictateInto(sessionEditor, editor)) { + Log.w(TAG, "syncRecognizedText: field changed, dropping the dictation") + android.widget.Toast.makeText(ims, ims.getString(R.string.voice_piecewise_field_changed), android.widget.Toast.LENGTH_LONG).show() + sessionEmittedText = "" // it is in the previous field, cancelling must not delete from this one + cancelVoice() + return + } + val isSmartPunctuationEnabled = ims.prefs().getBoolean(VoiceConstants.PREF_VOICE_SMART_PUNCTUATION, true) val processedRaw = if (!isSmartPunctuationEnabled) { rawText.replace(PUNCTUATION_REGEX, "") @@ -1387,6 +1416,12 @@ class VoiceInputManager( else -> VoiceKeyAction.START } + internal fun editorKey(info: EditorInfo?): String? = info?.let { "${it.packageName}|${it.fieldId}|${it.inputType}" } + + /** whether dictated text may go into [info], for a dictation started in the field with key [startedIn] */ + internal fun mayDictateInto(startedIn: String?, info: EditorInfo?) = + !isBlockedEditor(info) && (startedIn == null || editorKey(info) == startedIn) + fun isBlockedEditor(info: EditorInfo?): Boolean { if (info == null) return false return InputTypeUtils.isAnyPasswordInputType(info.inputType) diff --git a/app/src/test/java/helium314/keyboard/latin/voice/VoiceFieldChangeTest.kt b/app/src/test/java/helium314/keyboard/latin/voice/VoiceFieldChangeTest.kt new file mode 100644 index 000000000..03864e833 --- /dev/null +++ b/app/src/test/java/helium314/keyboard/latin/voice/VoiceFieldChangeTest.kt @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: GPL-3.0-only +package helium314.keyboard.latin.voice + +import android.text.InputType +import android.view.inputmethod.EditorInfo +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +@RunWith(RobolectricTestRunner::class) +class VoiceFieldChangeTest { + private fun field(id: Int, type: Int = InputType.TYPE_CLASS_TEXT) = + EditorInfo().apply { packageName = "a.b"; fieldId = id; inputType = type } + + @Test fun dictationStaysInItsField() { + val start = VoiceInputManager.editorKey(field(1))!! + assertTrue(VoiceInputManager.mayDictateInto(start, field(1))) + assertFalse(VoiceInputManager.mayDictateInto(start, field(2))) + val password = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD + assertFalse(VoiceInputManager.mayDictateInto(start, field(1, password))) + assertFalse(VoiceInputManager.mayDictateInto(null, field(1, password))) + } +} diff --git a/app/src/test/java/helium314/keyboard/latin/voice/VoiceProviderRoutingTest.kt b/app/src/test/java/helium314/keyboard/latin/voice/VoiceProviderRoutingTest.kt index e75f2e322..8ca605d19 100644 --- a/app/src/test/java/helium314/keyboard/latin/voice/VoiceProviderRoutingTest.kt +++ b/app/src/test/java/helium314/keyboard/latin/voice/VoiceProviderRoutingTest.kt @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-3.0-only package helium314.keyboard.latin.voice +import helium314.keyboard.latin.utils.locale import android.content.Context import android.content.SharedPreferences import android.os.Build @@ -85,6 +86,21 @@ class VoiceProviderRoutingTest { assertNull(pkg) } + @Test + fun testTargetShortcut_prefersEntryForKeyboardLanguage() { + fun entry(locale: String) = Shortcut( + InputMethodInfo("a.voice", "VoiceService", "a.voice", null), + InputMethodSubtype.InputMethodSubtypeBuilder().setSubtypeMode("voice").setSubtypeLocale(locale).build() + ) + val keyboard = richImm.currentSubtypeLocale.language + richImm.setShortcutsForTesting(listOf(entry("zz"), entry(keyboard))) + assertEquals(keyboard, richImm.getTargetShortcut()!!.subtype.locale().language) + + // none for the keyboard language: the app's first entry, as before + richImm.setShortcutsForTesting(listOf(entry("zz"), entry("yy"))) + assertEquals("zz", richImm.getTargetShortcut()!!.subtype.locale().language) + } + @Test fun testTargetShortcut_honorsExplicitUserSelection() { val google = createShortcut("com.google.android.googlequicksearchbox")