Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -214,6 +217,7 @@ class VoiceInputManager(
pluginManager.cancelSession()
val sessionId = UUID.randomUUID().toString()
activeSessionId = sessionId
sessionEditor = editorKey(ims.currentInputEditorInfo)
needsCapitalStart = true
sessionEmittedText = ""
isCurrentSessionOnline = false
Expand Down Expand Up @@ -248,6 +252,7 @@ class VoiceInputManager(
if (!bound) {
cancelConnectingTimeout()
notifyError("Failed to bind to voice plugin")
cleanupSession()
updateState(VoiceState.ERROR)
return
}
Expand All @@ -265,6 +270,7 @@ class VoiceInputManager(
}
val sessionId = UUID.randomUUID().toString()
activeSessionId = sessionId
sessionEditor = editorKey(ims.currentInputEditorInfo)
needsCapitalStart = true
sessionEmittedText = ""
isCurrentSessionOnline = true
Expand Down Expand Up @@ -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)
}
Expand All @@ -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) {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
}
}
Expand Down Expand Up @@ -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)
}

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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, "")
Expand Down Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
@@ -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)))
}
}
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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")
Expand Down
Loading