@@ -158,6 +158,10 @@ class InputLogic(
158158 mInputLogicHandler.reset()
159159 mConnection.requestCursorUpdates(true , true )
160160 setInlineEmojiSearchAction(false )
161+ mInputSession++
162+ // a custom AI key result that arrived while the keyboard was hidden, once the field is ready again
163+ if (mPendingAIResult != null )
164+ android.os.Handler (android.os.Looper .getMainLooper()).postDelayed({ insertPendingAIResult() }, 300 )
161165 }
162166
163167 fun onSubtypeChanged (combiningSpec : String? , settingsValues : SettingsValues ) {
@@ -3267,28 +3271,37 @@ class InputLogic(
32673271 val targetEditorInfo = getCurrentInputEditorInfo()
32683272 val targetPackage = targetEditorInfo?.packageName
32693273 val targetFieldId = targetEditorInfo?.fieldId
3274+ // to recognize the field if the keyboard is hidden or another field opened meanwhile; from the text read
3275+ // above, which is the whole text without a selection (with a selection, such a result goes to the clipboard)
3276+ val targetInputType = targetEditorInfo?.inputType ? : 0
3277+ val targetField = if (hasSelection) null else AiFieldCheck .fingerprint(targetPackage, targetInputType,
3278+ InputTypeUtils .isPasswordInputType(targetInputType), textToProcess)
3279+ val inputSession = mInputSession
3280+ mPendingAIResult = null // an older result must not be inserted after this one
32703281
32713282 ProofreadHelper .customAsync(
32723283 mLatinIME,
32733284 textToProcess, prompt, hasSelection, showThinking,
32743285 onSuccess = { resultText ->
32753286 if (! mLatinIME.isInputViewShown || ! mConnection.isConnected()) {
3276- Log .w(TAG , " Input view hidden or disconnected during custom AI operation, ignoring result" )
3287+ // some editors hide the keyboard meanwhile (e.g. when the cursor is moved):
3288+ // insert when the keyboard is back in this field, see insertPendingAIResult
3289+ Log .i(TAG , " Input view hidden during custom AI operation, keeping the result" )
3290+ mPendingAIResult = PendingAIResult (resultText, targetPackage, targetFieldId, hasSelection,
3291+ shouldAppend, SystemClock .uptimeMillis(), targetField)
32773292 return @customAsync
32783293 }
32793294 val currentEditor = getCurrentInputEditorInfo()
32803295 if (currentEditor?.packageName != targetPackage || currentEditor?.fieldId != targetFieldId) {
32813296 Log .w(TAG , " Target editor changed during custom AI operation, ignoring result" )
32823297 return @customAsync
32833298 }
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)
3299+ // another field was opened meanwhile, e.g. another chat with the same field id
3300+ if (mInputSession != inputSession && ! isSameAiField(targetField)) {
3301+ keepAIResultInClipboard(resultText)
3302+ return @customAsync
32913303 }
3304+ insertAIResult(resultText, hasSelection, shouldAppend, moveToEnd = false )
32923305 },
32933306 onError = { errorMessage ->
32943307 Log .e(TAG , " Custom AI Error: $errorMessage " )
@@ -3297,6 +3310,79 @@ class InputLogic(
32973310 )
32983311 }
32993312
3313+ /* * counts the fields opened, to notice if another field was opened during an AI request */
3314+ private var mInputSession = 0
3315+
3316+ /* * Result of a custom AI key that arrived while the keyboard was hidden */
3317+ private class PendingAIResult (
3318+ val text : String , val packageName : String? , val fieldId : Int? ,
3319+ val hasSelection : Boolean , val shouldAppend : Boolean , val time : Long , val target : AiFieldCheck .Fingerprint ?
3320+ )
3321+ private var mPendingAIResult: PendingAIResult ? = null
3322+
3323+ /* * Whether the current field is the one of [target], see [AiFieldCheck] */
3324+ private fun isSameAiField (target : AiFieldCheck .Fingerprint ? ): Boolean {
3325+ val editor = getCurrentInputEditorInfo() ? : return false
3326+ if (target == null ) return false
3327+ val before = mConnection.getTextBeforeCursor(AI_FIELD_TEXT_CHARS , 0 )?.toString() ? : " "
3328+ val selected = mConnection.getSelectedText(0 )?.toString() ? : " "
3329+ val after = mConnection.getTextAfterCursor(AI_FIELD_TEXT_CHARS , 0 )?.toString() ? : " "
3330+ return target.matches(editor.packageName, editor.inputType, InputTypeUtils .isPasswordInputType(editor.inputType),
3331+ before + selected + after) { extractedFieldText() }
3332+ }
3333+
3334+ /* * The whole text as the app gives it for extraction, null if it does not */
3335+ private fun extractedFieldText (): String? = try {
3336+ val request = android.view.inputmethod.ExtractedTextRequest ().apply { hintMaxChars = AI_FIELD_TEXT_CHARS * 2 }
3337+ mLatinIME.currentInputConnection?.getExtractedText(request, 0 )?.text?.toString()
3338+ } catch (e: Exception ) {
3339+ null
3340+ }
3341+
3342+ /* * An AI result for a field that changed meanwhile: not lost, but not inserted at the wrong place */
3343+ private fun keepAIResultInClipboard (text : String ) {
3344+ if (text.isBlank()) return
3345+ Log .w(TAG , " field changed during the AI request, result copied to the clipboard" )
3346+ val clipboard = mLatinIME.getSystemService(android.content.Context .CLIPBOARD_SERVICE ) as ? android.content.ClipboardManager ? : return
3347+ clipboard.setPrimaryClip(android.content.ClipData .newPlainText(" AI" , text))
3348+ KeyboardSwitcher .getInstance().showToast(mLatinIME.getString(R .string.ai_result_to_clipboard), false )
3349+ }
3350+
3351+ private fun insertAIResult (text : String , hasSelection : Boolean , shouldAppend : Boolean , moveToEnd : Boolean ) {
3352+ if (shouldAppend) {
3353+ if (moveToEnd && ! hasSelection) {
3354+ // the field was tapped again after the keyboard was hidden: the cursor may be elsewhere
3355+ val after = mConnection.getTextAfterCursor(AI_FIELD_TEXT_CHARS , 0 )?.length ? : 0
3356+ if (after > 0 && mConnection.expectedSelectionEnd >= 0 ) {
3357+ val end = mConnection.expectedSelectionEnd + after
3358+ mConnection.setSelection(end, end)
3359+ }
3360+ }
3361+ val textBefore = mConnection.getTextBeforeCursor(2 , 0 ) ? : " "
3362+ mLatinIME.onTextInput(CustomAIKeyText .separatorBefore(textBefore) + text.trim())
3363+ } else if (! hasSelection) {
3364+ mConnection.replaceEntireText(text)
3365+ } else {
3366+ mLatinIME.onTextInput(text)
3367+ }
3368+ }
3369+
3370+ /* * Inserts a result that arrived while the keyboard was hidden, if the keyboard is back in the same field soon */
3371+ private fun insertPendingAIResult () {
3372+ val pending = mPendingAIResult ? : return
3373+ mPendingAIResult = null
3374+ if (SystemClock .uptimeMillis() - pending.time > PENDING_AI_RESULT_MS ) return
3375+ if (! mLatinIME.isInputViewShown || ! mConnection.isConnected()) return
3376+ val editor = getCurrentInputEditorInfo()
3377+ // a newer request is running, or a selection was to be replaced: it is gone with the hidden keyboard
3378+ if (ProofreadHelper .isOperationInProgress || editor?.packageName != pending.packageName
3379+ || editor?.fieldId != pending.fieldId || pending.hasSelection || ! isSameAiField(pending.target)) {
3380+ keepAIResultInClipboard(pending.text)
3381+ return
3382+ }
3383+ insertAIResult(pending.text, hasSelection = false , shouldAppend = pending.shouldAppend, moveToEnd = true )
3384+ }
3385+
33003386 private fun tryJumpToNextPlaceholder (): Boolean {
33013387 val before = mConnection.getTextBeforeCursor(1000 , 0 )
33023388 val after = mConnection.getTextAfterCursor(1000 , 0 )
@@ -3440,6 +3526,10 @@ class InputLogic(
34403526 }
34413527 private const val BACKSPACE_WORD_LOOKBACK = 200
34423528 private val THAI_LOCALE = Locale .forLanguageTag(" th" )
3529+ /* * how long a result waits for the keyboard to come back into its field */
3530+ private const val PENDING_AI_RESULT_MS = 2 * 60 * 1000L
3531+ /* * text read around the cursor to recognize the field of an AI request, as for the request */
3532+ private const val AI_FIELD_TEXT_CHARS = 60000
34433533 private val THAI_WORD_BREAK_ITERATOR = object : ThreadLocal <BreakIterator >() {
34443534 override fun initialValue (): BreakIterator = BreakIterator .getWordInstance(THAI_LOCALE )
34453535 }
0 commit comments