@@ -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 }
0 commit comments