Skip to content

Commit 509bc75

Browse files
4di-helloclaude
andcommitted
Custom AI keys: keep the result when the keyboard hides, insert only into the same field
Some editors hide the keyboard while a custom AI key runs (they react to the cursor being moved for the result). The request was cancelled and the result lost. Now the request keeps running; a result that arrives while the keyboard is hidden is inserted when the keyboard is back in the same field within two minutes. Many apps use the same field id for all their text fields (e.g. every chat), so the field must also be in the same app, have the same input type and the same text (around the cursor, or as a second check the whole text the app gives for extraction), and is never a password field. Otherwise the result is put into the clipboard with a short message instead of the wrong field. The same check applies when the keyboard stayed open. Offline AI: one generation at a time. A cancelled request keeps running in the plugin until it is done; a new one failed with "Context is busy" and gave no output. It now waits for the previous one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VuiaMhLXwhErf9shhrr1uD
1 parent f9a6e6a commit 509bc75

6 files changed

Lines changed: 204 additions & 17 deletions

File tree

‎app/src/main/java/helium314/keyboard/latin/LatinIME.kt‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1090,7 +1090,8 @@ class LatinIME : InputMethodService(),
10901090
keyboardSwitcher.hideGifPicker()
10911091
keyboardSwitcher.hideOcrPanels()
10921092
clipboardHistoryManager.onWindowHidden()
1093-
ProofreadHelper.cancelCurrentJob()
1093+
// an AI request keeps running: a custom key result is inserted when the keyboard is back in the same field,
1094+
// some editors hide the keyboard when the cursor is moved for the result
10941095
val fkm = floatingKeyboardManager
10951096
if (fkm != null) {
10961097
if (!settings.current.mRememberFloatingKeyboard) {
@@ -1123,7 +1124,6 @@ class LatinIME : InputMethodService(),
11231124
if (keyboardSwitcher.isOcrShowing) {
11241125
keyboardSwitcher.hideOcrPanels()
11251126
}
1126-
ProofreadHelper.cancelCurrentJob()
11271127
voiceInputManager?.cancelVoice()
11281128
updateVoiceKeepScreenOn(VoiceInputManager.VoiceState.IDLE)
11291129
releaseVoicePluginOnIdle(preserveExistingSchedule = true)
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// SPDX-License-Identifier: GPL-3.0-only
2+
package helium314.keyboard.latin.inputlogic
3+
4+
/**
5+
* Whether an AI result can be inserted into the field it was asked for. The field is identified by
6+
* the app, the input type and its text: the text around the cursor plus the selection, and as a second way
7+
* the whole text as the app gives it for extraction, because some apps report the selection or the text
8+
* around the cursor unreliably. Without a match the result goes to the clipboard instead.
9+
*/
10+
internal object AiFieldCheck {
11+
class Snapshot(
12+
val packageName: String?,
13+
val inputType: Int,
14+
val isPassword: Boolean,
15+
/** text before the cursor + selected text + text after the cursor */
16+
val aroundCursor: String,
17+
/** the whole text from getExtractedText, null if the app does not give it */
18+
val extracted: String?,
19+
)
20+
21+
class Fingerprint internal constructor(
22+
private val packageName: String?,
23+
private val inputType: Int,
24+
private val aroundHash: Int,
25+
private val aroundLength: Int,
26+
private val extractedHash: Int?,
27+
private val extractedLength: Int,
28+
) {
29+
fun matches(now: Snapshot): Boolean {
30+
if (now.isPassword || now.packageName != packageName || now.inputType != inputType) return false
31+
if (now.aroundCursor.length == aroundLength && now.aroundCursor.hashCode() == aroundHash) return true
32+
val extracted = now.extracted ?: return false
33+
return extractedHash != null && extracted.length == extractedLength && extracted.hashCode() == extractedHash
34+
}
35+
}
36+
37+
fun fingerprint(s: Snapshot) = Fingerprint(
38+
s.packageName, s.inputType, s.aroundCursor.hashCode(), s.aroundCursor.length,
39+
s.extracted?.hashCode(), s.extracted?.length ?: -1,
40+
)
41+
}

‎app/src/main/java/helium314/keyboard/latin/inputlogic/InputLogic.kt‎

Lines changed: 105 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,9 @@ class InputLogic(
158158
mInputLogicHandler.reset()
159159
mConnection.requestCursorUpdates(true, true)
160160
setInlineEmojiSearchAction(false)
161+
// an AI result that arrived while the keyboard was hidden, once the field is ready again
162+
if (mPendingAIResult != null)
163+
android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({ insertPendingAIResult() }, 300)
161164
}
162165

163166
fun onSubtypeChanged(combiningSpec: String?, settingsValues: SettingsValues) {
@@ -3267,28 +3270,30 @@ class InputLogic(
32673270
val targetEditorInfo = getCurrentInputEditorInfo()
32683271
val targetPackage = targetEditorInfo?.packageName
32693272
val targetFieldId = targetEditorInfo?.fieldId
3273+
val targetField = currentAiTarget()
32703274

32713275
ProofreadHelper.customAsync(
32723276
mLatinIME,
32733277
textToProcess, prompt, hasSelection, showThinking,
32743278
onSuccess = { resultText ->
3279+
val result = PendingAIResult(resultText, targetPackage, targetFieldId, hasSelection, shouldAppend,
3280+
SystemClock.uptimeMillis(), targetField)
32753281
if (!mLatinIME.isInputViewShown || !mConnection.isConnected()) {
3276-
Log.w(TAG, "Input view hidden or disconnected during custom AI operation, ignoring result")
3282+
// some editors hide the keyboard meanwhile (e.g. when the cursor is moved): insert when it is back in this field
3283+
Log.i(TAG, "Input view hidden during custom AI operation, keeping the result")
3284+
mPendingAIResult = result
32773285
return@customAsync
32783286
}
32793287
val currentEditor = getCurrentInputEditorInfo()
32803288
if (currentEditor?.packageName != targetPackage || currentEditor?.fieldId != targetFieldId) {
32813289
Log.w(TAG, "Target editor changed during custom AI operation, ignoring result")
32823290
return@customAsync
32833291
}
3284-
if (shouldAppend) {
3285-
val textBefore = mConnection.getTextBeforeCursor(2, 0) ?: ""
3286-
mLatinIME.onTextInput(CustomAIKeyText.separatorBefore(textBefore) + resultText.trim())
3287-
} else if (!hasSelection) {
3288-
mConnection.replaceEntireText(resultText)
3289-
} else {
3290-
mLatinIME.onTextInput(resultText)
3292+
if (!targetField.isCurrent()) {
3293+
keepAIResultInClipboard(resultText)
3294+
return@customAsync
32913295
}
3296+
insertAIResult(result)
32923297
},
32933298
onError = { errorMessage ->
32943299
Log.e(TAG, "Custom AI Error: $errorMessage")
@@ -3297,6 +3302,94 @@ class InputLogic(
32973302
)
32983303
}
32993304

3305+
/** Result of a custom AI key, kept while the keyboard is hidden */
3306+
private class PendingAIResult(
3307+
val text: String, val packageName: String?, val fieldId: Int?,
3308+
val hasSelection: Boolean, val shouldAppend: Boolean, val time: Long, val target: AiTarget
3309+
)
3310+
private var mPendingAIResult: PendingAIResult? = null
3311+
3312+
/**
3313+
* The field an AI request was started in, to insert the result only there. Many apps use the same
3314+
* field id for all their text fields (e.g. every chat), so the text and type of the field are compared
3315+
* too: if they changed, the result is put into the clipboard instead. See [AiFieldCheck].
3316+
*/
3317+
private inner class AiTarget(private val fingerprint: AiFieldCheck.Fingerprint) {
3318+
fun isCurrent(): Boolean {
3319+
val now = aiFieldSnapshot() ?: return false
3320+
return fingerprint.matches(now)
3321+
}
3322+
}
3323+
3324+
private fun currentAiTarget(): AiTarget =
3325+
AiTarget(AiFieldCheck.fingerprint(aiFieldSnapshot() ?: AiFieldCheck.Snapshot(null, 0, true, "", null)))
3326+
3327+
private fun aiFieldSnapshot(): AiFieldCheck.Snapshot? {
3328+
val editor = getCurrentInputEditorInfo() ?: return null
3329+
return AiFieldCheck.Snapshot(editor.packageName, editor.inputType,
3330+
InputTypeUtils.isPasswordInputType(editor.inputType), currentFieldText(), extractedFieldText())
3331+
}
3332+
3333+
/** The whole text as the app gives it for extraction, null if it does not */
3334+
private fun extractedFieldText(): String? = try {
3335+
val request = android.view.inputmethod.ExtractedTextRequest().apply { hintMaxChars = AI_FIELD_TEXT_CHARS * 2 }
3336+
mLatinIME.currentInputConnection?.getExtractedText(request, 0)?.text?.toString()
3337+
} catch (e: Exception) {
3338+
null
3339+
}
3340+
3341+
/** The whole text of the field, also a selected part */
3342+
private fun currentFieldText(): String {
3343+
val before = mConnection.getTextBeforeCursor(AI_FIELD_TEXT_CHARS, 0)?.toString() ?: ""
3344+
val selected = mConnection.getSelectedText(0)?.toString() ?: ""
3345+
val after = mConnection.getTextAfterCursor(AI_FIELD_TEXT_CHARS, 0)?.toString() ?: ""
3346+
return before + selected + after
3347+
}
3348+
3349+
/** An AI result for a field that changed meanwhile: not lost, but not inserted at the wrong place */
3350+
private fun keepAIResultInClipboard(text: String) {
3351+
if (text.isBlank()) return
3352+
Log.w(TAG, "field changed during the AI request, result copied to the clipboard")
3353+
val clipboard = mLatinIME.getSystemService(android.content.Context.CLIPBOARD_SERVICE) as? android.content.ClipboardManager ?: return
3354+
clipboard.setPrimaryClip(android.content.ClipData.newPlainText("AI", text))
3355+
KeyboardSwitcher.getInstance().showToast(mLatinIME.getString(R.string.ai_result_to_clipboard), false)
3356+
}
3357+
3358+
private fun insertAIResult(result: PendingAIResult) {
3359+
if (result.shouldAppend) {
3360+
if (!result.hasSelection) {
3361+
// the cursor may have moved meanwhile, e.g. when the keyboard was hidden and the field tapped again
3362+
val after = mConnection.getTextAfterCursor(AI_FIELD_TEXT_CHARS, 0)?.length ?: 0
3363+
if (after > 0 && mConnection.expectedSelectionEnd >= 0) {
3364+
val end = mConnection.expectedSelectionEnd + after
3365+
mConnection.setSelection(end, end)
3366+
}
3367+
}
3368+
val textBefore = mConnection.getTextBeforeCursor(2, 0) ?: ""
3369+
mLatinIME.onTextInput(CustomAIKeyText.separatorBefore(textBefore) + result.text.trim())
3370+
} else if (!result.hasSelection) {
3371+
mConnection.replaceEntireText(result.text)
3372+
} else {
3373+
mLatinIME.onTextInput(result.text)
3374+
}
3375+
}
3376+
3377+
/** Inserts a result that arrived while the keyboard was hidden, if the keyboard is back in the same field soon */
3378+
private fun insertPendingAIResult() {
3379+
val pending = mPendingAIResult ?: return
3380+
mPendingAIResult = null
3381+
if (SystemClock.uptimeMillis() - pending.time > PENDING_AI_RESULT_MS) return
3382+
if (!mLatinIME.isInputViewShown || !mConnection.isConnected()) return
3383+
val editor = getCurrentInputEditorInfo()
3384+
// a replaced selection is gone, there is nothing left to replace safely
3385+
if (editor?.packageName != pending.packageName || editor?.fieldId != pending.fieldId
3386+
|| (pending.hasSelection && !pending.shouldAppend) || !pending.target.isCurrent()) {
3387+
keepAIResultInClipboard(pending.text)
3388+
return
3389+
}
3390+
insertAIResult(pending)
3391+
}
3392+
33003393
private fun tryJumpToNextPlaceholder(): Boolean {
33013394
val before = mConnection.getTextBeforeCursor(1000, 0)
33023395
val after = mConnection.getTextAfterCursor(1000, 0)
@@ -3440,6 +3533,10 @@ class InputLogic(
34403533
}
34413534
private const val BACKSPACE_WORD_LOOKBACK = 200
34423535
private val THAI_LOCALE = Locale.forLanguageTag("th")
3536+
/** how long a result waits for the keyboard to come back into its field */
3537+
private const val PENDING_AI_RESULT_MS = 2 * 60 * 1000L
3538+
/** text read around the cursor to recognize the field of an AI request */
3539+
private const val AI_FIELD_TEXT_CHARS = 60000
34433540
private val THAI_WORD_BREAK_ITERATOR = object : ThreadLocal<BreakIterator>() {
34443541
override fun initialValue(): BreakIterator = BreakIterator.getWordInstance(THAI_LOCALE)
34453542
}

‎app/src/main/res/values/strings.xml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2121,6 +2121,7 @@ New dictionary:
21212121
<string name="translation_unchanged">Translation unchanged or identical to source text.</string>
21222122
<string name="error_getting_suggestions">Error getting suggestions</string>
21232123
<string name="ai_error_format">AI Error: %s</string>
2124+
<string name="ai_result_to_clipboard">The text field changed meanwhile, the AI result is in the clipboard</string>
21242125
<string name="suggestion_word_removed">\"%1$s\" removed</string>
21252126
<string name="key_set">Key set</string>
21262127
<string name="key_not_set">Not set</string>

‎app/src/offline/java/helium314/keyboard/latin/utils/ProofreadService.kt‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,13 @@ class ProofreadService(private val context: Context) {
8585
isModelAvailable = true
8686
}
8787

88+
/**
89+
* One generation at a time. A cancelled request (e.g. the keyboard was closed) keeps running in
90+
* the plugin until it is done, and a new one would fail with "Context is busy" and give no
91+
* output. It waits here instead. A plain lock, as it is held by the thread blocked in the plugin.
92+
*/
93+
val generateLock = Any()
94+
8895
suspend fun loadModel(
8996
context: Context,
9097
modelPath: String
@@ -404,13 +411,15 @@ class ProofreadService(private val context: Context) {
404411
// Use provider to generate completion
405412
OfflineAiLoader.isBusy = true
406413
val output = try {
407-
provider.generate(fullPrompt, mapOf(
408-
"temperature" to temp.toDouble(),
409-
"top_p" to topP.toDouble(),
410-
"top_k" to topK,
411-
"min_p" to minP.toDouble(),
412-
"max_tokens" to effectiveMaxTokens
413-
))
414+
synchronized(ModelHolder.generateLock) {
415+
provider.generate(fullPrompt, mapOf(
416+
"temperature" to temp.toDouble(),
417+
"top_p" to topP.toDouble(),
418+
"top_k" to topK,
419+
"min_p" to minP.toDouble(),
420+
"max_tokens" to effectiveMaxTokens
421+
))
422+
}
414423
} finally {
415424
OfflineAiLoader.isBusy = false
416425
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// SPDX-License-Identifier: GPL-3.0-only
2+
package helium314.keyboard.latin.inputlogic
3+
4+
import org.junit.Assert.assertFalse
5+
import org.junit.Assert.assertTrue
6+
import org.junit.Test
7+
8+
class AiFieldCheckTest {
9+
private fun snapshot(around: String, extracted: String? = around, pkg: String = "com.example.mail",
10+
inputType: Int = 1, password: Boolean = false) =
11+
AiFieldCheck.Snapshot(pkg, inputType, password, around, extracted)
12+
13+
@Test
14+
fun sameFieldAndTextMatches() {
15+
val target = AiFieldCheck.fingerprint(snapshot("Hallo Welt"))
16+
assertTrue(target.matches(snapshot("Hallo Welt")))
17+
}
18+
19+
@Test
20+
fun changedTextOrOtherAppDoesNotMatch() {
21+
val target = AiFieldCheck.fingerprint(snapshot("Hallo Welt"))
22+
assertFalse(target.matches(snapshot("Hallo Welt!")))
23+
assertFalse(target.matches(snapshot("Hallo Welt", pkg = "com.example.chat")))
24+
assertFalse(target.matches(snapshot("Hallo Welt", inputType = 2)))
25+
assertFalse(target.matches(snapshot("Hallo Welt", password = true)))
26+
}
27+
28+
@Test
29+
fun wholeFieldTextHelpsWhenTheAppReportsTheSelectionUnreliably() {
30+
// when asked, the app did not report the selected part
31+
val target = AiFieldCheck.fingerprint(snapshot("Hallo ", extracted = "Hallo Welt"))
32+
// later it does: the text around the cursor differs, the whole field is the same
33+
assertTrue(target.matches(snapshot("Hallo Welt", extracted = "Hallo Welt")))
34+
// but not if the field really changed
35+
assertFalse(target.matches(snapshot("Hallo Welt", extracted = "Hallo Welt, wie geht's")))
36+
// nor without the whole text
37+
assertFalse(target.matches(snapshot("Hallo Welt", extracted = null)))
38+
}
39+
}

0 commit comments

Comments
 (0)