Skip to content
Open
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
5 changes: 3 additions & 2 deletions app/src/main/java/helium314/keyboard/latin/LatinIME.kt
Original file line number Diff line number Diff line change
Expand Up @@ -1090,7 +1090,8 @@ class LatinIME : InputMethodService(),
keyboardSwitcher.hideGifPicker()
keyboardSwitcher.hideOcrPanels()
clipboardHistoryManager.onWindowHidden()
ProofreadHelper.cancelCurrentJob()
// a custom AI key request keeps running, its result is inserted when the keyboard is back in the same field
ProofreadHelper.cancelCurrentJob(keepCustomKeyJob = true)
val fkm = floatingKeyboardManager
if (fkm != null) {
if (!settings.current.mRememberFloatingKeyboard) {
Expand Down Expand Up @@ -1123,7 +1124,7 @@ class LatinIME : InputMethodService(),
if (keyboardSwitcher.isOcrShowing) {
keyboardSwitcher.hideOcrPanels()
}
ProofreadHelper.cancelCurrentJob()
ProofreadHelper.cancelCurrentJob(keepCustomKeyJob = true)
voiceInputManager?.cancelVoice()
updateVoiceKeepScreenOn(VoiceInputManager.VoiceState.IDLE)
releaseVoicePluginOnIdle(preserveExistingSchedule = true)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// SPDX-License-Identifier: GPL-3.0-only
package helium314.keyboard.latin.inputlogic

/**
* Whether an AI result can still be inserted into the field it was asked for, after the keyboard was
* hidden or another field was opened meanwhile. Many apps use the same field id for all their text
* fields (e.g. every chat), so the field is identified by the app, the input type and its text as it
* was read for the request. Only a hash and the length of the text are kept.
*/
internal object AiFieldCheck {
class Fingerprint internal constructor(
private val packageName: String?,
private val inputType: Int,
private val textHash: Int,
private val textLength: Int,
) {
/**
* [aroundCursor]: text before the cursor + selected text + text after the cursor. [extracted]
* gives the whole text as the app gives it for extraction; it is only asked for if the text
* around the cursor differs, as some apps report it unreliably.
*/
fun matches(packageName: String?, inputType: Int, isPassword: Boolean, aroundCursor: String, extracted: () -> String?): Boolean {
if (isPassword || packageName != this.packageName || inputType != this.inputType) return false
if (isSameText(aroundCursor)) return true
return extracted()?.let { isSameText(it) } == true
}

private fun isSameText(text: String) = text.length == textLength && text.hashCode() == textHash
}

/** [text]: the whole text of the field as read for the request. Null for password fields: nothing is inserted there later. */
fun fingerprint(packageName: String?, inputType: Int, isPassword: Boolean, text: String): Fingerprint? =
if (isPassword) null else Fingerprint(packageName, inputType, text.hashCode(), text.length)
}
106 changes: 98 additions & 8 deletions app/src/main/java/helium314/keyboard/latin/inputlogic/InputLogic.kt
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,10 @@ class InputLogic(
mInputLogicHandler.reset()
mConnection.requestCursorUpdates(true, true)
setInlineEmojiSearchAction(false)
mInputSession++
// a custom AI key result that arrived while the keyboard was hidden, once the field is ready again
if (mPendingAIResult != null)
android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({ insertPendingAIResult() }, 300)
}

fun onSubtypeChanged(combiningSpec: String?, settingsValues: SettingsValues) {
Expand Down Expand Up @@ -3267,28 +3271,37 @@ class InputLogic(
val targetEditorInfo = getCurrentInputEditorInfo()
val targetPackage = targetEditorInfo?.packageName
val targetFieldId = targetEditorInfo?.fieldId
// to recognize the field if the keyboard is hidden or another field opened meanwhile; from the text read
// above, which is the whole text without a selection (with a selection, such a result goes to the clipboard)
val targetInputType = targetEditorInfo?.inputType ?: 0
val targetField = if (hasSelection) null else AiFieldCheck.fingerprint(targetPackage, targetInputType,
InputTypeUtils.isPasswordInputType(targetInputType), textToProcess)
val inputSession = mInputSession
mPendingAIResult = null // an older result must not be inserted after this one

ProofreadHelper.customAsync(
mLatinIME,
textToProcess, prompt, hasSelection, showThinking,
onSuccess = { resultText ->
if (!mLatinIME.isInputViewShown || !mConnection.isConnected()) {
Log.w(TAG, "Input view hidden or disconnected during custom AI operation, ignoring result")
// some editors hide the keyboard meanwhile (e.g. when the cursor is moved):
// insert when the keyboard is back in this field, see insertPendingAIResult
Log.i(TAG, "Input view hidden during custom AI operation, keeping the result")
mPendingAIResult = PendingAIResult(resultText, targetPackage, targetFieldId, hasSelection,
shouldAppend, SystemClock.uptimeMillis(), targetField)
return@customAsync
}
val currentEditor = getCurrentInputEditorInfo()
if (currentEditor?.packageName != targetPackage || currentEditor?.fieldId != targetFieldId) {
Log.w(TAG, "Target editor changed during custom AI operation, ignoring result")
return@customAsync
}
if (shouldAppend) {
val textBefore = mConnection.getTextBeforeCursor(2, 0) ?: ""
mLatinIME.onTextInput(CustomAIKeyText.separatorBefore(textBefore) + resultText.trim())
} else if (!hasSelection) {
mConnection.replaceEntireText(resultText)
} else {
mLatinIME.onTextInput(resultText)
// another field was opened meanwhile, e.g. another chat with the same field id
if (mInputSession != inputSession && !isSameAiField(targetField)) {
keepAIResultInClipboard(resultText)
return@customAsync
}
insertAIResult(resultText, hasSelection, shouldAppend, moveToEnd = false)
},
onError = { errorMessage ->
Log.e(TAG, "Custom AI Error: $errorMessage")
Expand All @@ -3297,6 +3310,79 @@ class InputLogic(
)
}

/** counts the fields opened, to notice if another field was opened during an AI request */
private var mInputSession = 0

/** Result of a custom AI key that arrived while the keyboard was hidden */
private class PendingAIResult(
val text: String, val packageName: String?, val fieldId: Int?,
val hasSelection: Boolean, val shouldAppend: Boolean, val time: Long, val target: AiFieldCheck.Fingerprint?
)
private var mPendingAIResult: PendingAIResult? = null

/** Whether the current field is the one of [target], see [AiFieldCheck] */
private fun isSameAiField(target: AiFieldCheck.Fingerprint?): Boolean {
val editor = getCurrentInputEditorInfo() ?: return false
if (target == null) return false
val before = mConnection.getTextBeforeCursor(AI_FIELD_TEXT_CHARS, 0)?.toString() ?: ""
val selected = mConnection.getSelectedText(0)?.toString() ?: ""
val after = mConnection.getTextAfterCursor(AI_FIELD_TEXT_CHARS, 0)?.toString() ?: ""
return target.matches(editor.packageName, editor.inputType, InputTypeUtils.isPasswordInputType(editor.inputType),
before + selected + after) { extractedFieldText() }
}

/** The whole text as the app gives it for extraction, null if it does not */
private fun extractedFieldText(): String? = try {
val request = android.view.inputmethod.ExtractedTextRequest().apply { hintMaxChars = AI_FIELD_TEXT_CHARS * 2 }
mLatinIME.currentInputConnection?.getExtractedText(request, 0)?.text?.toString()
} catch (e: Exception) {
null
}

/** An AI result for a field that changed meanwhile: not lost, but not inserted at the wrong place */
private fun keepAIResultInClipboard(text: String) {
if (text.isBlank()) return
Log.w(TAG, "field changed during the AI request, result copied to the clipboard")
val clipboard = mLatinIME.getSystemService(android.content.Context.CLIPBOARD_SERVICE) as? android.content.ClipboardManager ?: return
clipboard.setPrimaryClip(android.content.ClipData.newPlainText("AI", text))
KeyboardSwitcher.getInstance().showToast(mLatinIME.getString(R.string.ai_result_to_clipboard), false)
}

private fun insertAIResult(text: String, hasSelection: Boolean, shouldAppend: Boolean, moveToEnd: Boolean) {
if (shouldAppend) {
if (moveToEnd && !hasSelection) {
// the field was tapped again after the keyboard was hidden: the cursor may be elsewhere
val after = mConnection.getTextAfterCursor(AI_FIELD_TEXT_CHARS, 0)?.length ?: 0
if (after > 0 && mConnection.expectedSelectionEnd >= 0) {
val end = mConnection.expectedSelectionEnd + after
mConnection.setSelection(end, end)
}
}
val textBefore = mConnection.getTextBeforeCursor(2, 0) ?: ""
mLatinIME.onTextInput(CustomAIKeyText.separatorBefore(textBefore) + text.trim())
} else if (!hasSelection) {
mConnection.replaceEntireText(text)
} else {
mLatinIME.onTextInput(text)
}
}

/** Inserts a result that arrived while the keyboard was hidden, if the keyboard is back in the same field soon */
private fun insertPendingAIResult() {
val pending = mPendingAIResult ?: return
mPendingAIResult = null
if (SystemClock.uptimeMillis() - pending.time > PENDING_AI_RESULT_MS) return
if (!mLatinIME.isInputViewShown || !mConnection.isConnected()) return
val editor = getCurrentInputEditorInfo()
// a newer request is running, or a selection was to be replaced: it is gone with the hidden keyboard
if (ProofreadHelper.isOperationInProgress || editor?.packageName != pending.packageName
|| editor?.fieldId != pending.fieldId || pending.hasSelection || !isSameAiField(pending.target)) {
keepAIResultInClipboard(pending.text)
return
}
insertAIResult(pending.text, hasSelection = false, shouldAppend = pending.shouldAppend, moveToEnd = true)
}

private fun tryJumpToNextPlaceholder(): Boolean {
val before = mConnection.getTextBeforeCursor(1000, 0)
val after = mConnection.getTextAfterCursor(1000, 0)
Expand Down Expand Up @@ -3440,6 +3526,10 @@ class InputLogic(
}
private const val BACKSPACE_WORD_LOOKBACK = 200
private val THAI_LOCALE = Locale.forLanguageTag("th")
/** how long a result waits for the keyboard to come back into its field */
private const val PENDING_AI_RESULT_MS = 2 * 60 * 1000L
/** text read around the cursor to recognize the field of an AI request, as for the request */
private const val AI_FIELD_TEXT_CHARS = 60000
private val THAI_WORD_BREAK_ITERATOR = object : ThreadLocal<BreakIterator>() {
override fun initialValue(): BreakIterator = BreakIterator.getWordInstance(THAI_LOCALE)
}
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2128,6 +2128,7 @@ New dictionary:
<string name="translation_unchanged">Translation unchanged or identical to source text.</string>
<string name="error_getting_suggestions">Error getting suggestions</string>
<string name="ai_error_format">AI Error: %s</string>
<string name="ai_result_to_clipboard">The text field changed meanwhile, the AI result is in the clipboard</string>
<string name="suggestion_word_removed">\"%1$s\" removed</string>
<string name="key_set">Key set</string>
<string name="key_not_set">Not set</string>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,15 @@ object ProofreadHelper {
}
}

fun cancelCurrentJob() {
/** whether the running request was started by a custom AI key */
private var currentJobIsCustomKey = false

/**
* Cancels the running request, e.g. when the keyboard is hidden. With [keepCustomKeyJob], a request
* of a custom AI key keeps running: its result is inserted when the keyboard is back in the same field.
*/
fun cancelCurrentJob(keepCustomKeyJob: Boolean = false) {
if (keepCustomKeyJob && currentJobIsCustomKey && isOperationInProgress) return
cancelCurrentOperation()
}

Expand All @@ -79,7 +87,8 @@ object ProofreadHelper {
skipModelCheck: Boolean = false,
apiCall: suspend (ProofreadService) -> Result<String>,
onSuccess: (String) -> Unit,
onError: (String) -> Unit
onError: (String) -> Unit,
isCustomKey: Boolean = false
) {
val service = ProofreadService(context)

Expand Down Expand Up @@ -113,6 +122,7 @@ object ProofreadHelper {
}

// Launch coroutine for inference and track it for cancellation
currentJobIsCustomKey = isCustomKey
currentJob = scope.launch {
val result = apiCall(service)

Expand Down Expand Up @@ -471,7 +481,8 @@ object ProofreadHelper {
errorResId = R.string.proofread_error,
apiCall = { service -> service.proofread(text, overridePrompt = prompt, showThinking = showThinking) },
onSuccess = onSuccess,
onError = onError
onError = onError,
isCustomKey = true
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import helium314.keyboard.latin.settings.Defaults
import helium314.keyboard.latin.settings.Settings
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.coroutines.isActive
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.CoroutineScope
Expand Down Expand Up @@ -85,6 +86,14 @@ class ProofreadService(private val context: Context) {
isModelAvailable = true
}

/**
* One generation at a time. A cancelled request keeps running in the plugin until it is done
* (e.g. a custom AI key whose keyboard was hidden, or a cancelled one), and a new one would fail
* with "Context is busy" and give no output. It waits here instead. A plain lock, as it is held by
* the thread blocked in the plugin.
*/
val generateLock = Any()

suspend fun loadModel(
context: Context,
modelPath: String
Expand Down Expand Up @@ -413,13 +422,20 @@ class ProofreadService(private val context: Context) {
// Use provider to generate completion
OfflineAiLoader.isBusy = true
val output = try {
provider.generate(fullPrompt, mapOf(
"temperature" to temp.toDouble(),
"top_p" to topP.toDouble(),
"top_k" to topK,
"min_p" to minP.toDouble(),
"max_tokens" to effectiveMaxTokens
))
synchronized(ModelHolder.generateLock) {
// cancelled while waiting for the previous generation: don't start one, it can't be stopped
if (!isActive) {
ModelHolder.scheduleUnload(context)
return@withContext Result.failure(ProofreadException("Cancelled"))
}
provider.generate(fullPrompt, mapOf(
"temperature" to temp.toDouble(),
"top_p" to topP.toDouble(),
"top_k" to topK,
"min_p" to minP.toDouble(),
"max_tokens" to effectiveMaxTokens
))
}
} finally {
OfflineAiLoader.isBusy = false
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,15 @@ object ProofreadHelper {
}
}

fun cancelCurrentJob() {
/** whether the running request was started by a custom AI key */
private var currentJobIsCustomKey = false

/**
* Cancels the running request, e.g. when the keyboard is hidden. With [keepCustomKeyJob], a request
* of a custom AI key keeps running: its result is inserted when the keyboard is back in the same field.
*/
fun cancelCurrentJob(keepCustomKeyJob: Boolean = false) {
if (keepCustomKeyJob && currentJobIsCustomKey && isOperationInProgress) return
cancelCurrentOperation()
}

Expand All @@ -71,7 +79,8 @@ object ProofreadHelper {
onSuccess: (String) -> Unit,
onError: (String) -> Unit,
allowEmptyInput: Boolean = false,
skipApiKeyCheck: Boolean = false
skipApiKeyCheck: Boolean = false,
isCustomKey: Boolean = false
) {
val service = ProofreadService(context)

Expand Down Expand Up @@ -144,6 +153,7 @@ object ProofreadHelper {
}

// Launch coroutine for API call and track it for cancellation
currentJobIsCustomKey = isCustomKey
currentJob = scope.launch {
val result = apiCall(service)

Expand Down Expand Up @@ -540,6 +550,7 @@ object ProofreadHelper {
apiCall = { service -> service.proofread(text, overridePrompt = prompt, showThinking = showThinking) },
onSuccess = onSuccess,
onError = onError,
isCustomKey = true,
allowEmptyInput = true
)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// SPDX-License-Identifier: GPL-3.0-only
package helium314.keyboard.latin.inputlogic

import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test

class AiFieldCheckTest {
private val pkg = "com.example.chat"
private val target = AiFieldCheck.fingerprint(pkg, 1, false, "Hallo Welt")!!

@Test
fun sameFieldAndTextMatches() {
assertTrue(target.matches(pkg, 1, false, "Hallo Welt") { null })
}

@Test
fun otherChatOrChangedTextDoesNotMatch() {
// same app and field id, but another chat with other text
assertFalse(target.matches(pkg, 1, false, "Bis morgen") { "Bis morgen" })
assertFalse(target.matches(pkg, 1, false, "Hallo Welt!") { null })
assertFalse(target.matches("com.example.mail", 1, false, "Hallo Welt") { null })
assertFalse(target.matches(pkg, 2, false, "Hallo Welt") { null })
assertFalse(target.matches(pkg, 1, true, "Hallo Welt") { null })
}

@Test
fun wholeTextIsOnlyReadWhenNeeded() {
var reads = 0
assertTrue(target.matches(pkg, 1, false, "Hallo Welt") { reads++; "Hallo Welt" })
assertEquals(0, reads)
// the app reports the text around the cursor unreliably, the whole text is the same
assertTrue(target.matches(pkg, 1, false, "Hallo ") { reads++; "Hallo Welt" })
assertEquals(1, reads)
}

@Test
fun passwordFieldsAreNeverRemembered() {
assertNull(AiFieldCheck.fingerprint(pkg, 1, true, "secret"))
}
}
Loading