InputLogic.java revision fa4c59f9b6663e5de08692f853e968603dfc10e9
1/* 2 * Copyright (C) 2013 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.inputmethod.latin.inputlogic; 18 19import android.os.SystemClock; 20import android.text.SpannableString; 21import android.text.TextUtils; 22import android.text.style.SuggestionSpan; 23import android.util.Log; 24import android.view.KeyCharacterMap; 25import android.view.KeyEvent; 26import android.view.inputmethod.CorrectionInfo; 27import android.view.inputmethod.EditorInfo; 28 29import com.android.inputmethod.compat.SuggestionSpanUtils; 30import com.android.inputmethod.event.Event; 31import com.android.inputmethod.event.InputTransaction; 32import com.android.inputmethod.keyboard.KeyboardSwitcher; 33import com.android.inputmethod.keyboard.ProximityInfo; 34import com.android.inputmethod.latin.Constants; 35import com.android.inputmethod.latin.Dictionary; 36import com.android.inputmethod.latin.DictionaryFacilitator; 37import com.android.inputmethod.latin.InputPointers; 38import com.android.inputmethod.latin.LastComposedWord; 39import com.android.inputmethod.latin.LatinIME; 40import com.android.inputmethod.latin.LatinImeLogger; 41import com.android.inputmethod.latin.PrevWordsInfo; 42import com.android.inputmethod.latin.RichInputConnection; 43import com.android.inputmethod.latin.Suggest; 44import com.android.inputmethod.latin.Suggest.OnGetSuggestedWordsCallback; 45import com.android.inputmethod.latin.SuggestedWords; 46import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; 47import com.android.inputmethod.latin.WordComposer; 48import com.android.inputmethod.latin.settings.SettingsValues; 49import com.android.inputmethod.latin.settings.SpacingAndPunctuations; 50import com.android.inputmethod.latin.suggestions.SuggestionStripViewAccessor; 51import com.android.inputmethod.latin.utils.AsyncResultHolder; 52import com.android.inputmethod.latin.utils.InputTypeUtils; 53import com.android.inputmethod.latin.utils.RecapitalizeStatus; 54import com.android.inputmethod.latin.utils.StringUtils; 55import com.android.inputmethod.latin.utils.TextRange; 56 57import java.util.ArrayList; 58import java.util.TreeSet; 59import java.util.concurrent.TimeUnit; 60 61/** 62 * This class manages the input logic. 63 */ 64public final class InputLogic { 65 private static final String TAG = InputLogic.class.getSimpleName(); 66 67 // TODO : Remove this member when we can. 68 private final LatinIME mLatinIME; 69 private final SuggestionStripViewAccessor mSuggestionStripViewAccessor; 70 71 // Never null. 72 private InputLogicHandler mInputLogicHandler = InputLogicHandler.NULL_HANDLER; 73 74 // TODO : make all these fields private as soon as possible. 75 // Current space state of the input method. This can be any of the above constants. 76 private int mSpaceState; 77 // Never null 78 public SuggestedWords mSuggestedWords = SuggestedWords.EMPTY; 79 public final Suggest mSuggest; 80 private final DictionaryFacilitator mDictionaryFacilitator; 81 82 public LastComposedWord mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD; 83 public final WordComposer mWordComposer; 84 public final RichInputConnection mConnection; 85 private final RecapitalizeStatus mRecapitalizeStatus = new RecapitalizeStatus(); 86 87 private int mDeleteCount; 88 private long mLastKeyTime; 89 public final TreeSet<Long> mCurrentlyPressedHardwareKeys = new TreeSet<>(); 90 91 // Keeps track of most recently inserted text (multi-character key) for reverting 92 private String mEnteredText; 93 94 // TODO: This boolean is persistent state and causes large side effects at unexpected times. 95 // Find a way to remove it for readability. 96 private boolean mIsAutoCorrectionIndicatorOn; 97 private long mDoubleSpacePeriodCountdownStart; 98 99 /** 100 * Create a new instance of the input logic. 101 * @param latinIME the instance of the parent LatinIME. We should remove this when we can. 102 * @param suggestionStripViewAccessor an object to access the suggestion strip view. 103 * @param dictionaryFacilitator facilitator for getting suggestions and updating user history 104 * dictionary. 105 */ 106 public InputLogic(final LatinIME latinIME, 107 final SuggestionStripViewAccessor suggestionStripViewAccessor, 108 final DictionaryFacilitator dictionaryFacilitator) { 109 mLatinIME = latinIME; 110 mSuggestionStripViewAccessor = suggestionStripViewAccessor; 111 mWordComposer = new WordComposer(); 112 mConnection = new RichInputConnection(latinIME); 113 mInputLogicHandler = InputLogicHandler.NULL_HANDLER; 114 mSuggest = new Suggest(dictionaryFacilitator); 115 mDictionaryFacilitator = dictionaryFacilitator; 116 } 117 118 /** 119 * Initializes the input logic for input in an editor. 120 * 121 * Call this when input starts or restarts in some editor (typically, in onStartInputView). 122 * 123 * @param combiningSpec the combining spec string for this subtype 124 */ 125 public void startInput(final String combiningSpec) { 126 mEnteredText = null; 127 mWordComposer.restartCombining(combiningSpec); 128 resetComposingState(true /* alsoResetLastComposedWord */); 129 mDeleteCount = 0; 130 mSpaceState = SpaceState.NONE; 131 mRecapitalizeStatus.disable(); // Do not perform recapitalize until the cursor is moved once 132 mCurrentlyPressedHardwareKeys.clear(); 133 mSuggestedWords = SuggestedWords.EMPTY; 134 // In some cases (namely, after rotation of the device) editorInfo.initialSelStart is lying 135 // so we try using some heuristics to find out about these and fix them. 136 mConnection.tryFixLyingCursorPosition(); 137 cancelDoubleSpacePeriodCountdown(); 138 if (InputLogicHandler.NULL_HANDLER == mInputLogicHandler) { 139 mInputLogicHandler = new InputLogicHandler(mLatinIME, this); 140 } else { 141 mInputLogicHandler.reset(); 142 } 143 } 144 145 /** 146 * Call this when the subtype changes. 147 * @param combiningSpec the spec string for the combining rules 148 */ 149 public void onSubtypeChanged(final String combiningSpec) { 150 finishInput(); 151 startInput(combiningSpec); 152 } 153 154 /** 155 * Clean up the input logic after input is finished. 156 */ 157 public void finishInput() { 158 if (mWordComposer.isComposingWord()) { 159 mConnection.finishComposingText(); 160 } 161 resetComposingState(true /* alsoResetLastComposedWord */); 162 mInputLogicHandler.reset(); 163 } 164 165 // Normally this class just gets out of scope after the process ends, but in unit tests, we 166 // create several instances of LatinIME in the same process, which results in several 167 // instances of InputLogic. This cleans up the associated handler so that tests don't leak 168 // handlers. 169 public void recycle() { 170 final InputLogicHandler inputLogicHandler = mInputLogicHandler; 171 mInputLogicHandler = InputLogicHandler.NULL_HANDLER; 172 inputLogicHandler.destroy(); 173 mDictionaryFacilitator.closeDictionaries(); 174 } 175 176 /** 177 * React to a string input. 178 * 179 * This is triggered by keys that input many characters at once, like the ".com" key or 180 * some additional keys for example. 181 * 182 * @param settingsValues the current values of the settings. 183 * @param event the input event containing the data. 184 * @return the complete transaction object 185 */ 186 public InputTransaction onTextInput(final SettingsValues settingsValues, final Event event, 187 final int keyboardShiftMode, 188 // TODO: remove this argument 189 final LatinIME.UIHandler handler) { 190 final String rawText = event.mText.toString(); 191 final InputTransaction inputTransaction = new InputTransaction(settingsValues, event, 192 SystemClock.uptimeMillis(), mSpaceState, 193 getActualCapsMode(settingsValues, keyboardShiftMode)); 194 mConnection.beginBatchEdit(); 195 if (mWordComposer.isComposingWord()) { 196 commitCurrentAutoCorrection(settingsValues, rawText, handler); 197 } else { 198 resetComposingState(true /* alsoResetLastComposedWord */); 199 } 200 handler.postUpdateSuggestionStrip(); 201 final String text = performSpecificTldProcessingOnTextInput(rawText); 202 if (SpaceState.PHANTOM == mSpaceState) { 203 promotePhantomSpace(settingsValues); 204 } 205 mConnection.commitText(text, 1); 206 mConnection.endBatchEdit(); 207 // Space state must be updated before calling updateShiftState 208 mSpaceState = SpaceState.NONE; 209 mEnteredText = text; 210 inputTransaction.setDidAffectContents(); 211 inputTransaction.requireShiftUpdate(InputTransaction.SHIFT_UPDATE_NOW); 212 return inputTransaction; 213 } 214 215 /** 216 * A suggestion was picked from the suggestion strip. 217 * @param settingsValues the current values of the settings. 218 * @param suggestionInfo the suggestion info. 219 * @param keyboardShiftState the shift state of the keyboard, as returned by 220 * {@link com.android.inputmethod.keyboard.KeyboardSwitcher#getKeyboardShiftMode()} 221 * @return the complete transaction object 222 */ 223 // Called from {@link SuggestionStripView} through the {@link SuggestionStripView#Listener} 224 // interface 225 public InputTransaction onPickSuggestionManually(final SettingsValues settingsValues, 226 final SuggestedWordInfo suggestionInfo, final int keyboardShiftState, 227 // TODO: remove these arguments 228 final int currentKeyboardScriptId, final LatinIME.UIHandler handler) { 229 final SuggestedWords suggestedWords = mSuggestedWords; 230 final String suggestion = suggestionInfo.mWord; 231 // If this is a punctuation picked from the suggestion strip, pass it to onCodeInput 232 if (suggestion.length() == 1 && suggestedWords.isPunctuationSuggestions()) { 233 // Word separators are suggested before the user inputs something. 234 // Rely on onCodeInput to do the complicated swapping/stripping logic consistently. 235 final Event event = Event.createPunctuationSuggestionPickedEvent(suggestionInfo); 236 return onCodeInput(settingsValues, event, keyboardShiftState, 237 currentKeyboardScriptId, handler); 238 } 239 240 final Event event = Event.createSuggestionPickedEvent(suggestionInfo); 241 final InputTransaction inputTransaction = new InputTransaction(settingsValues, 242 event, SystemClock.uptimeMillis(), mSpaceState, keyboardShiftState); 243 // Manual pick affects the contents of the editor, so we take note of this. It's important 244 // for the sequence of language switching. 245 inputTransaction.setDidAffectContents(); 246 mConnection.beginBatchEdit(); 247 if (SpaceState.PHANTOM == mSpaceState && suggestion.length() > 0 248 // In the batch input mode, a manually picked suggested word should just replace 249 // the current batch input text and there is no need for a phantom space. 250 && !mWordComposer.isBatchMode()) { 251 final int firstChar = Character.codePointAt(suggestion, 0); 252 if (!settingsValues.isWordSeparator(firstChar) 253 || settingsValues.isUsuallyPrecededBySpace(firstChar)) { 254 promotePhantomSpace(settingsValues); 255 } 256 } 257 258 // TODO: We should not need the following branch. We should be able to take the same 259 // code path as for other kinds, use commitChosenWord, and do everything normally. We will 260 // however need to reset the suggestion strip right away, because we know we can't take 261 // the risk of calling commitCompletion twice because we don't know how the app will react. 262 if (suggestionInfo.isKindOf(SuggestedWordInfo.KIND_APP_DEFINED)) { 263 mSuggestedWords = SuggestedWords.EMPTY; 264 mSuggestionStripViewAccessor.setNeutralSuggestionStrip(); 265 inputTransaction.requireShiftUpdate(InputTransaction.SHIFT_UPDATE_NOW); 266 resetComposingState(true /* alsoResetLastComposedWord */); 267 mConnection.commitCompletion(suggestionInfo.mApplicationSpecifiedCompletionInfo); 268 mConnection.endBatchEdit(); 269 return inputTransaction; 270 } 271 272 // We need to log before we commit, because the word composer will store away the user 273 // typed word. 274 final String replacedWord = mWordComposer.getTypedWord(); 275 commitChosenWord(settingsValues, suggestion, 276 LastComposedWord.COMMIT_TYPE_MANUAL_PICK, LastComposedWord.NOT_A_SEPARATOR); 277 mConnection.endBatchEdit(); 278 // Don't allow cancellation of manual pick 279 mLastComposedWord.deactivate(); 280 // Space state must be updated before calling updateShiftState 281 mSpaceState = SpaceState.PHANTOM; 282 inputTransaction.requireShiftUpdate(InputTransaction.SHIFT_UPDATE_NOW); 283 284 // We should show the "Touch again to save" hint if the user pressed the first entry 285 // AND it's in none of our current dictionaries (main, user or otherwise). 286 final boolean showingAddToDictionaryHint = 287 (suggestionInfo.isKindOf(SuggestedWordInfo.KIND_TYPED) 288 || suggestionInfo.isKindOf(SuggestedWordInfo.KIND_OOV_CORRECTION)) 289 && !mDictionaryFacilitator.isValidWord(suggestion, true /* ignoreCase */); 290 291 if (showingAddToDictionaryHint && mDictionaryFacilitator.isUserDictionaryEnabled()) { 292 mSuggestionStripViewAccessor.showAddToDictionaryHint(suggestion); 293 } else { 294 // If we're not showing the "Touch again to save", then update the suggestion strip. 295 handler.postUpdateSuggestionStrip(); 296 } 297 return inputTransaction; 298 } 299 300 /** 301 * Consider an update to the cursor position. Evaluate whether this update has happened as 302 * part of normal typing or whether it was an explicit cursor move by the user. In any case, 303 * do the necessary adjustments. 304 * @param oldSelStart old selection start 305 * @param oldSelEnd old selection end 306 * @param newSelStart new selection start 307 * @param newSelEnd new selection end 308 * @return whether the cursor has moved as a result of user interaction. 309 */ 310 public boolean onUpdateSelection(final int oldSelStart, final int oldSelEnd, 311 final int newSelStart, final int newSelEnd) { 312 if (mConnection.isBelatedExpectedUpdate(oldSelStart, newSelStart, oldSelEnd, newSelEnd)) { 313 return false; 314 } 315 // TODO: the following is probably better done in resetEntireInputState(). 316 // it should only happen when the cursor moved, and the very purpose of the 317 // test below is to narrow down whether this happened or not. Likewise with 318 // the call to updateShiftState. 319 // We set this to NONE because after a cursor move, we don't want the space 320 // state-related special processing to kick in. 321 mSpaceState = SpaceState.NONE; 322 323 final boolean selectionChangedOrSafeToReset = 324 oldSelStart != newSelStart || oldSelEnd != newSelEnd // selection changed 325 || !mWordComposer.isComposingWord(); // safe to reset 326 final boolean hasOrHadSelection = (oldSelStart != oldSelEnd || newSelStart != newSelEnd); 327 final int moveAmount = newSelStart - oldSelStart; 328 // As an added small gift from the framework, it happens upon rotation when there 329 // is a selection that we get a wrong cursor position delivered to startInput() that 330 // does not get reflected in the oldSel{Start,End} parameters to the next call to 331 // onUpdateSelection. In this case, we may have set a composition, and when we're here 332 // we realize we shouldn't have. In theory, in this case, selectionChangedOrSafeToReset 333 // should be true, but that is if the framework had taken that wrong cursor position 334 // into account, which means we have to reset the entire composing state whenever there 335 // is or was a selection regardless of whether it changed or not. 336 if (hasOrHadSelection || (selectionChangedOrSafeToReset 337 && !mWordComposer.moveCursorByAndReturnIfInsideComposingWord(moveAmount))) { 338 // If we are composing a word and moving the cursor, we would want to set a 339 // suggestion span for recorrection to work correctly. Unfortunately, that 340 // would involve the keyboard committing some new text, which would move the 341 // cursor back to where it was. Latin IME could then fix the position of the cursor 342 // again, but the asynchronous nature of the calls results in this wreaking havoc 343 // with selection on double tap and the like. 344 // Another option would be to send suggestions each time we set the composing 345 // text, but that is probably too expensive to do, so we decided to leave things 346 // as is. 347 // Also, we're posting a resume suggestions message, and this will update the 348 // suggestions strip in a few milliseconds, so if we cleared the suggestion strip here 349 // we'd have the suggestion strip noticeably janky. To avoid that, we don't clear 350 // it here, which means we'll keep outdated suggestions for a split second but the 351 // visual result is better. 352 resetEntireInputState(newSelStart, newSelEnd, false /* clearSuggestionStrip */); 353 } else { 354 // resetEntireInputState calls resetCachesUponCursorMove, but forcing the 355 // composition to end. But in all cases where we don't reset the entire input 356 // state, we still want to tell the rich input connection about the new cursor 357 // position so that it can update its caches. 358 mConnection.resetCachesUponCursorMoveAndReturnSuccess( 359 newSelStart, newSelEnd, false /* shouldFinishComposition */); 360 } 361 362 // The cursor has been moved : we now accept to perform recapitalization 363 mRecapitalizeStatus.enable(); 364 // We moved the cursor. If we are touching a word, we need to resume suggestion. 365 mLatinIME.mHandler.postResumeSuggestions(false /* shouldIncludeResumedWordInSuggestions */, 366 true /* shouldDelay */); 367 // Stop the last recapitalization, if started. 368 mRecapitalizeStatus.stop(); 369 return true; 370 } 371 372 /** 373 * React to a code input. It may be a code point to insert, or a symbolic value that influences 374 * the keyboard behavior. 375 * 376 * Typically, this is called whenever a key is pressed on the software keyboard. This is not 377 * the entry point for gesture input; see the onBatchInput* family of functions for this. 378 * 379 * @param settingsValues the current settings values. 380 * @param event the event to handle. 381 * @param keyboardShiftMode the current shift mode of the keyboard, as returned by 382 * {@link com.android.inputmethod.keyboard.KeyboardSwitcher#getKeyboardShiftMode()} 383 * @return the complete transaction object 384 */ 385 public InputTransaction onCodeInput(final SettingsValues settingsValues, final Event event, 386 final int keyboardShiftMode, 387 // TODO: remove these arguments 388 final int currentKeyboardScriptId, final LatinIME.UIHandler handler) { 389 final InputTransaction inputTransaction = new InputTransaction(settingsValues, event, 390 SystemClock.uptimeMillis(), mSpaceState, 391 getActualCapsMode(settingsValues, keyboardShiftMode)); 392 if (event.mKeyCode != Constants.CODE_DELETE 393 || inputTransaction.mTimestamp > mLastKeyTime + Constants.LONG_PRESS_MILLISECONDS) { 394 mDeleteCount = 0; 395 } 396 mLastKeyTime = inputTransaction.mTimestamp; 397 mConnection.beginBatchEdit(); 398 if (!mWordComposer.isComposingWord()) { 399 mIsAutoCorrectionIndicatorOn = false; 400 } 401 402 // TODO: Consolidate the double-space period timer, mLastKeyTime, and the space state. 403 if (event.mCodePoint != Constants.CODE_SPACE) { 404 cancelDoubleSpacePeriodCountdown(); 405 } 406 407 boolean didAutoCorrect = false; 408 if (event.isFunctionalKeyEvent()) { 409 // A special key, like delete, shift, emoji, or the settings key. 410 switch (event.mKeyCode) { 411 case Constants.CODE_DELETE: 412 handleBackspace(inputTransaction, currentKeyboardScriptId); 413 // Backspace is a functional key, but it affects the contents of the editor. 414 inputTransaction.setDidAffectContents(); 415 break; 416 case Constants.CODE_SHIFT: 417 performRecapitalization(inputTransaction.mSettingsValues); 418 inputTransaction.requireShiftUpdate(InputTransaction.SHIFT_UPDATE_NOW); 419 if (mSuggestedWords.mIsPrediction) { 420 inputTransaction.setRequiresUpdateSuggestions(); 421 } 422 break; 423 case Constants.CODE_CAPSLOCK: 424 // Note: Changing keyboard to shift lock state is handled in 425 // {@link KeyboardSwitcher#onCodeInput(int)}. 426 break; 427 case Constants.CODE_SYMBOL_SHIFT: 428 // Note: Calling back to the keyboard on the symbol Shift key is handled in 429 // {@link #onPressKey(int,int,boolean)} and {@link #onReleaseKey(int,boolean)}. 430 break; 431 case Constants.CODE_SWITCH_ALPHA_SYMBOL: 432 // Note: Calling back to the keyboard on symbol key is handled in 433 // {@link #onPressKey(int,int,boolean)} and {@link #onReleaseKey(int,boolean)}. 434 break; 435 case Constants.CODE_SETTINGS: 436 onSettingsKeyPressed(); 437 break; 438 case Constants.CODE_SHORTCUT: 439 // We need to switch to the shortcut IME. This is handled by LatinIME since the 440 // input logic has no business with IME switching. 441 break; 442 case Constants.CODE_ACTION_NEXT: 443 performEditorAction(EditorInfo.IME_ACTION_NEXT); 444 break; 445 case Constants.CODE_ACTION_PREVIOUS: 446 performEditorAction(EditorInfo.IME_ACTION_PREVIOUS); 447 break; 448 case Constants.CODE_LANGUAGE_SWITCH: 449 handleLanguageSwitchKey(); 450 break; 451 case Constants.CODE_EMOJI: 452 // Note: Switching emoji keyboard is being handled in 453 // {@link KeyboardState#onCodeInput(int,int)}. 454 break; 455 case Constants.CODE_ALPHA_FROM_EMOJI: 456 // Note: Switching back from Emoji keyboard to the main keyboard is being 457 // handled in {@link KeyboardState#onCodeInput(int,int)}. 458 break; 459 case Constants.CODE_SHIFT_ENTER: 460 // TODO: remove this object 461 final Event tmpEvent = Event.createSoftwareKeypressEvent(Constants.CODE_ENTER, 462 event.mKeyCode, event.mX, event.mY, event.isKeyRepeat()); 463 final InputTransaction tmpTransaction = new InputTransaction( 464 inputTransaction.mSettingsValues, tmpEvent, 465 inputTransaction.mTimestamp, inputTransaction.mSpaceState, 466 inputTransaction.mShiftState); 467 didAutoCorrect = handleNonSpecialCharacter(tmpTransaction, handler); 468 // Shift + Enter is treated as a functional key but it results in adding a new 469 // line, so that does affect the contents of the editor. 470 inputTransaction.setDidAffectContents(); 471 break; 472 default: 473 throw new RuntimeException("Unknown key code : " + event.mKeyCode); 474 } 475 } else { 476 inputTransaction.setDidAffectContents(); 477 switch (event.mCodePoint) { 478 case Constants.CODE_ENTER: 479 final EditorInfo editorInfo = getCurrentInputEditorInfo(); 480 final int imeOptionsActionId = 481 InputTypeUtils.getImeOptionsActionIdFromEditorInfo(editorInfo); 482 if (InputTypeUtils.IME_ACTION_CUSTOM_LABEL == imeOptionsActionId) { 483 // Either we have an actionLabel and we should performEditorAction with 484 // actionId regardless of its value. 485 performEditorAction(editorInfo.actionId); 486 } else if (EditorInfo.IME_ACTION_NONE != imeOptionsActionId) { 487 // We didn't have an actionLabel, but we had another action to execute. 488 // EditorInfo.IME_ACTION_NONE explicitly means no action. In contrast, 489 // EditorInfo.IME_ACTION_UNSPECIFIED is the default value for an action, so it 490 // means there should be an action and the app didn't bother to set a specific 491 // code for it - presumably it only handles one. It does not have to be treated 492 // in any specific way: anything that is not IME_ACTION_NONE should be sent to 493 // performEditorAction. 494 performEditorAction(imeOptionsActionId); 495 } else { 496 // No action label, and the action from imeOptions is NONE: this is a regular 497 // enter key that should input a carriage return. 498 didAutoCorrect = handleNonSpecialCharacter(inputTransaction, handler); 499 } 500 break; 501 default: 502 didAutoCorrect = handleNonSpecialCharacter(inputTransaction, handler); 503 break; 504 } 505 } 506 if (!didAutoCorrect && event.mKeyCode != Constants.CODE_SHIFT 507 && event.mKeyCode != Constants.CODE_CAPSLOCK 508 && event.mKeyCode != Constants.CODE_SWITCH_ALPHA_SYMBOL) 509 mLastComposedWord.deactivate(); 510 if (Constants.CODE_DELETE != event.mKeyCode) { 511 mEnteredText = null; 512 } 513 mConnection.endBatchEdit(); 514 return inputTransaction; 515 } 516 517 public void onStartBatchInput(final SettingsValues settingsValues, 518 // TODO: remove these arguments 519 final KeyboardSwitcher keyboardSwitcher, final LatinIME.UIHandler handler) { 520 mInputLogicHandler.onStartBatchInput(); 521 handler.showGesturePreviewAndSuggestionStrip( 522 SuggestedWords.EMPTY, false /* dismissGestureFloatingPreviewText */); 523 handler.cancelUpdateSuggestionStrip(); 524 ++mAutoCommitSequenceNumber; 525 mConnection.beginBatchEdit(); 526 if (mWordComposer.isComposingWord()) { 527 if (mWordComposer.isCursorFrontOrMiddleOfComposingWord()) { 528 // If we are in the middle of a recorrection, we need to commit the recorrection 529 // first so that we can insert the batch input at the current cursor position. 530 resetEntireInputState(mConnection.getExpectedSelectionStart(), 531 mConnection.getExpectedSelectionEnd(), true /* clearSuggestionStrip */); 532 } else if (mWordComposer.isSingleLetter()) { 533 // We auto-correct the previous (typed, not gestured) string iff it's one character 534 // long. The reason for this is, even in the middle of gesture typing, you'll still 535 // tap one-letter words and you want them auto-corrected (typically, "i" in English 536 // should become "I"). However for any longer word, we assume that the reason for 537 // tapping probably is that the word you intend to type is not in the dictionary, 538 // so we do not attempt to correct, on the assumption that if that was a dictionary 539 // word, the user would probably have gestured instead. 540 commitCurrentAutoCorrection(settingsValues, LastComposedWord.NOT_A_SEPARATOR, 541 handler); 542 } else { 543 commitTyped(settingsValues, LastComposedWord.NOT_A_SEPARATOR); 544 } 545 } 546 final int codePointBeforeCursor = mConnection.getCodePointBeforeCursor(); 547 if (Character.isLetterOrDigit(codePointBeforeCursor) 548 || settingsValues.isUsuallyFollowedBySpace(codePointBeforeCursor)) { 549 final boolean autoShiftHasBeenOverriden = keyboardSwitcher.getKeyboardShiftMode() != 550 getCurrentAutoCapsState(settingsValues); 551 mSpaceState = SpaceState.PHANTOM; 552 if (!autoShiftHasBeenOverriden) { 553 // When we change the space state, we need to update the shift state of the 554 // keyboard unless it has been overridden manually. This is happening for example 555 // after typing some letters and a period, then gesturing; the keyboard is not in 556 // caps mode yet, but since a gesture is starting, it should go in caps mode, 557 // unless the user explictly said it should not. 558 keyboardSwitcher.requestUpdatingShiftState(getCurrentAutoCapsState(settingsValues), 559 getCurrentRecapitalizeState()); 560 } 561 } 562 mConnection.endBatchEdit(); 563 mWordComposer.setCapitalizedModeAtStartComposingTime( 564 getActualCapsMode(settingsValues, keyboardSwitcher.getKeyboardShiftMode())); 565 } 566 567 /* The sequence number member is only used in onUpdateBatchInput. It is increased each time 568 * auto-commit happens. The reason we need this is, when auto-commit happens we trim the 569 * input pointers that are held in a singleton, and to know how much to trim we rely on the 570 * results of the suggestion process that is held in mSuggestedWords. 571 * However, the suggestion process is asynchronous, and sometimes we may enter the 572 * onUpdateBatchInput method twice without having recomputed suggestions yet, or having 573 * received new suggestions generated from not-yet-trimmed input pointers. In this case, the 574 * mIndexOfTouchPointOfSecondWords member will be out of date, and we must not use it lest we 575 * remove an unrelated number of pointers (possibly even more than are left in the input 576 * pointers, leading to a crash). 577 * To avoid that, we increase the sequence number each time we auto-commit and trim the 578 * input pointers, and we do not use any suggested words that have been generated with an 579 * earlier sequence number. 580 */ 581 private int mAutoCommitSequenceNumber = 1; 582 public void onUpdateBatchInput(final SettingsValues settingsValues, 583 final InputPointers batchPointers, 584 // TODO: remove these arguments 585 final KeyboardSwitcher keyboardSwitcher) { 586 if (settingsValues.mPhraseGestureEnabled) { 587 final SuggestedWordInfo candidate = mSuggestedWords.getAutoCommitCandidate(); 588 // If these suggested words have been generated with out of date input pointers, then 589 // we skip auto-commit (see comments above on the mSequenceNumber member). 590 if (null != candidate 591 && mSuggestedWords.mSequenceNumber >= mAutoCommitSequenceNumber) { 592 if (candidate.mSourceDict.shouldAutoCommit(candidate)) { 593 final String[] commitParts = candidate.mWord.split(Constants.WORD_SEPARATOR, 2); 594 batchPointers.shift(candidate.mIndexOfTouchPointOfSecondWord); 595 promotePhantomSpace(settingsValues); 596 mConnection.commitText(commitParts[0], 0); 597 mSpaceState = SpaceState.PHANTOM; 598 keyboardSwitcher.requestUpdatingShiftState( 599 getCurrentAutoCapsState(settingsValues), getCurrentRecapitalizeState()); 600 mWordComposer.setCapitalizedModeAtStartComposingTime(getActualCapsMode( 601 settingsValues, keyboardSwitcher.getKeyboardShiftMode())); 602 ++mAutoCommitSequenceNumber; 603 } 604 } 605 } 606 mInputLogicHandler.onUpdateBatchInput(batchPointers, mAutoCommitSequenceNumber); 607 } 608 609 public void onEndBatchInput(final InputPointers batchPointers) { 610 mInputLogicHandler.updateTailBatchInput(batchPointers, mAutoCommitSequenceNumber); 611 ++mAutoCommitSequenceNumber; 612 } 613 614 // TODO: remove this argument 615 public void onCancelBatchInput(final LatinIME.UIHandler handler) { 616 mInputLogicHandler.onCancelBatchInput(); 617 handler.showGesturePreviewAndSuggestionStrip( 618 SuggestedWords.EMPTY, true /* dismissGestureFloatingPreviewText */); 619 } 620 621 // TODO: on the long term, this method should become private, but it will be difficult. 622 // Especially, how do we deal with InputMethodService.onDisplayCompletions? 623 public void setSuggestedWords(final SuggestedWords suggestedWords) { 624 mSuggestedWords = suggestedWords; 625 final boolean newAutoCorrectionIndicator = suggestedWords.mWillAutoCorrect; 626 // Put a blue underline to a word in TextView which will be auto-corrected. 627 if (mIsAutoCorrectionIndicatorOn != newAutoCorrectionIndicator 628 && mWordComposer.isComposingWord()) { 629 mIsAutoCorrectionIndicatorOn = newAutoCorrectionIndicator; 630 final CharSequence textWithUnderline = 631 getTextWithUnderline(mWordComposer.getTypedWord()); 632 // TODO: when called from an updateSuggestionStrip() call that results from a posted 633 // message, this is called outside any batch edit. Potentially, this may result in some 634 // janky flickering of the screen, although the display speed makes it unlikely in 635 // the practice. 636 mConnection.setComposingText(textWithUnderline, 1); 637 } 638 } 639 640 /** 641 * Handle inputting a code point to the editor. 642 * 643 * Non-special keys are those that generate a single code point. 644 * This includes all letters, digits, punctuation, separators, emoji. It excludes keys that 645 * manage keyboard-related stuff like shift, language switch, settings, layout switch, or 646 * any key that results in multiple code points like the ".com" key. 647 * 648 * @param inputTransaction The transaction in progress. 649 * @return whether this caused an auto-correction to happen. 650 */ 651 private boolean handleNonSpecialCharacter(final InputTransaction inputTransaction, 652 // TODO: remove this argument 653 final LatinIME.UIHandler handler) { 654 final int codePoint = inputTransaction.mEvent.mCodePoint; 655 mSpaceState = SpaceState.NONE; 656 final boolean didAutoCorrect; 657 if (inputTransaction.mSettingsValues.isWordSeparator(codePoint) 658 || Character.getType(codePoint) == Character.OTHER_SYMBOL) { 659 didAutoCorrect = handleSeparator(inputTransaction, 660 inputTransaction.mEvent.isSuggestionStripPress(), handler); 661 } else { 662 didAutoCorrect = false; 663 if (SpaceState.PHANTOM == inputTransaction.mSpaceState) { 664 if (mWordComposer.isCursorFrontOrMiddleOfComposingWord()) { 665 // If we are in the middle of a recorrection, we need to commit the recorrection 666 // first so that we can insert the character at the current cursor position. 667 resetEntireInputState(mConnection.getExpectedSelectionStart(), 668 mConnection.getExpectedSelectionEnd(), true /* clearSuggestionStrip */); 669 } else { 670 commitTyped(inputTransaction.mSettingsValues, LastComposedWord.NOT_A_SEPARATOR); 671 } 672 } 673 handleNonSeparator(inputTransaction.mSettingsValues, inputTransaction); 674 } 675 return didAutoCorrect; 676 } 677 678 /** 679 * Handle a non-separator. 680 * @param settingsValues The current settings values. 681 * @param inputTransaction The transaction in progress. 682 */ 683 private void handleNonSeparator(final SettingsValues settingsValues, 684 final InputTransaction inputTransaction) { 685 final int codePoint = inputTransaction.mEvent.mCodePoint; 686 // TODO: refactor this method to stop flipping isComposingWord around all the time, and 687 // make it shorter (possibly cut into several pieces). Also factor handleNonSpecialCharacter 688 // which has the same name as other handle* methods but is not the same. 689 boolean isComposingWord = mWordComposer.isComposingWord(); 690 691 // TODO: remove isWordConnector() and use isUsuallyFollowedBySpace() instead. 692 // See onStartBatchInput() to see how to do it. 693 if (SpaceState.PHANTOM == inputTransaction.mSpaceState 694 && !settingsValues.isWordConnector(codePoint)) { 695 if (isComposingWord) { 696 // Sanity check 697 throw new RuntimeException("Should not be composing here"); 698 } 699 promotePhantomSpace(settingsValues); 700 } 701 702 if (mWordComposer.isCursorFrontOrMiddleOfComposingWord()) { 703 // If we are in the middle of a recorrection, we need to commit the recorrection 704 // first so that we can insert the character at the current cursor position. 705 resetEntireInputState(mConnection.getExpectedSelectionStart(), 706 mConnection.getExpectedSelectionEnd(), true /* clearSuggestionStrip */); 707 isComposingWord = false; 708 } 709 // We want to find out whether to start composing a new word with this character. If so, 710 // we need to reset the composing state and switch isComposingWord. The order of the 711 // tests is important for good performance. 712 // We only start composing if we're not already composing. 713 if (!isComposingWord 714 // We only start composing if this is a word code point. Essentially that means it's a 715 // a letter or a word connector. 716 && settingsValues.isWordCodePoint(codePoint) 717 // We never go into composing state if suggestions are not requested. 718 && settingsValues.isSuggestionsRequested() && 719 // In languages with spaces, we only start composing a word when we are not already 720 // touching a word. In languages without spaces, the above conditions are sufficient. 721 (!mConnection.isCursorTouchingWord(settingsValues.mSpacingAndPunctuations) 722 || !settingsValues.mSpacingAndPunctuations.mCurrentLanguageHasSpaces)) { 723 // Reset entirely the composing state anyway, then start composing a new word unless 724 // the character is a word connector. The idea here is, word connectors are not 725 // separators and they should be treated as normal characters, except in the first 726 // position where they should not start composing a word. 727 isComposingWord = !settingsValues.mSpacingAndPunctuations.isWordConnector(codePoint); 728 // Here we don't need to reset the last composed word. It will be reset 729 // when we commit this one, if we ever do; if on the other hand we backspace 730 // it entirely and resume suggestions on the previous word, we'd like to still 731 // have touch coordinates for it. 732 resetComposingState(false /* alsoResetLastComposedWord */); 733 } 734 if (isComposingWord) { 735 mWordComposer.processEvent(inputTransaction.mEvent); 736 // If it's the first letter, make note of auto-caps state 737 if (mWordComposer.isSingleLetter()) { 738 mWordComposer.setCapitalizedModeAtStartComposingTime(inputTransaction.mShiftState); 739 } 740 mConnection.setComposingText(getTextWithUnderline( 741 mWordComposer.getTypedWord()), 1); 742 } else { 743 final boolean swapWeakSpace = tryStripSpaceAndReturnWhetherShouldSwapInstead( 744 inputTransaction, inputTransaction.mEvent.isSuggestionStripPress()); 745 746 if (swapWeakSpace && trySwapSwapperAndSpace(inputTransaction)) { 747 mSpaceState = SpaceState.WEAK; 748 } else { 749 sendKeyCodePoint(settingsValues, codePoint); 750 } 751 // In case the "add to dictionary" hint was still displayed. 752 mSuggestionStripViewAccessor.dismissAddToDictionaryHint(); 753 } 754 inputTransaction.setRequiresUpdateSuggestions(); 755 } 756 757 /** 758 * Handle input of a separator code point. 759 * @param inputTransaction The transaction in progress. 760 * @param isFromSuggestionStrip whether this code point comes from the suggestion strip. 761 * @return whether this caused an auto-correction to happen. 762 */ 763 private boolean handleSeparator(final InputTransaction inputTransaction, 764 final boolean isFromSuggestionStrip, 765 // TODO: remove this argument 766 final LatinIME.UIHandler handler) { 767 final int codePoint = inputTransaction.mEvent.mCodePoint; 768 final SettingsValues settingsValues = inputTransaction.mSettingsValues; 769 boolean didAutoCorrect = false; 770 final boolean wasComposingWord = mWordComposer.isComposingWord(); 771 // We avoid sending spaces in languages without spaces if we were composing. 772 final boolean shouldAvoidSendingCode = Constants.CODE_SPACE == codePoint 773 && !settingsValues.mSpacingAndPunctuations.mCurrentLanguageHasSpaces 774 && wasComposingWord; 775 if (mWordComposer.isCursorFrontOrMiddleOfComposingWord()) { 776 // If we are in the middle of a recorrection, we need to commit the recorrection 777 // first so that we can insert the separator at the current cursor position. 778 resetEntireInputState(mConnection.getExpectedSelectionStart(), 779 mConnection.getExpectedSelectionEnd(), true /* clearSuggestionStrip */); 780 } 781 // isComposingWord() may have changed since we stored wasComposing 782 if (mWordComposer.isComposingWord()) { 783 if (settingsValues.mAutoCorrectionEnabled) { 784 final String separator = shouldAvoidSendingCode ? LastComposedWord.NOT_A_SEPARATOR 785 : StringUtils.newSingleCodePointString(codePoint); 786 commitCurrentAutoCorrection(settingsValues, separator, handler); 787 didAutoCorrect = true; 788 } else { 789 commitTyped(settingsValues, 790 StringUtils.newSingleCodePointString(codePoint)); 791 } 792 } 793 794 final boolean swapWeakSpace = tryStripSpaceAndReturnWhetherShouldSwapInstead( 795 inputTransaction, isFromSuggestionStrip); 796 797 final boolean isInsideDoubleQuoteOrAfterDigit = Constants.CODE_DOUBLE_QUOTE == codePoint 798 && mConnection.isInsideDoubleQuoteOrAfterDigit(); 799 800 final boolean needsPrecedingSpace; 801 if (SpaceState.PHANTOM != inputTransaction.mSpaceState) { 802 needsPrecedingSpace = false; 803 } else if (Constants.CODE_DOUBLE_QUOTE == codePoint) { 804 // Double quotes behave like they are usually preceded by space iff we are 805 // not inside a double quote or after a digit. 806 needsPrecedingSpace = !isInsideDoubleQuoteOrAfterDigit; 807 } else if (settingsValues.mSpacingAndPunctuations.isClusteringSymbol(codePoint) 808 && settingsValues.mSpacingAndPunctuations.isClusteringSymbol( 809 mConnection.getCodePointBeforeCursor())) { 810 needsPrecedingSpace = false; 811 } else { 812 needsPrecedingSpace = settingsValues.isUsuallyPrecededBySpace(codePoint); 813 } 814 815 if (needsPrecedingSpace) { 816 promotePhantomSpace(settingsValues); 817 } 818 819 if (tryPerformDoubleSpacePeriod(inputTransaction)) { 820 mSpaceState = SpaceState.DOUBLE; 821 inputTransaction.setRequiresUpdateSuggestions(); 822 } else if (swapWeakSpace && trySwapSwapperAndSpace(inputTransaction)) { 823 mSpaceState = SpaceState.SWAP_PUNCTUATION; 824 mSuggestionStripViewAccessor.setNeutralSuggestionStrip(); 825 } else if (Constants.CODE_SPACE == codePoint) { 826 if (!mSuggestedWords.isPunctuationSuggestions()) { 827 mSpaceState = SpaceState.WEAK; 828 } 829 830 startDoubleSpacePeriodCountdown(inputTransaction); 831 if (wasComposingWord || mSuggestedWords.isEmpty()) { 832 inputTransaction.setRequiresUpdateSuggestions(); 833 } 834 835 if (!shouldAvoidSendingCode) { 836 sendKeyCodePoint(settingsValues, codePoint); 837 } 838 } else { 839 if ((SpaceState.PHANTOM == inputTransaction.mSpaceState 840 && settingsValues.isUsuallyFollowedBySpace(codePoint)) 841 || (Constants.CODE_DOUBLE_QUOTE == codePoint 842 && isInsideDoubleQuoteOrAfterDigit)) { 843 // If we are in phantom space state, and the user presses a separator, we want to 844 // stay in phantom space state so that the next keypress has a chance to add the 845 // space. For example, if I type "Good dat", pick "day" from the suggestion strip 846 // then insert a comma and go on to typing the next word, I want the space to be 847 // inserted automatically before the next word, the same way it is when I don't 848 // input the comma. A double quote behaves like it's usually followed by space if 849 // we're inside a double quote. 850 // The case is a little different if the separator is a space stripper. Such a 851 // separator does not normally need a space on the right (that's the difference 852 // between swappers and strippers), so we should not stay in phantom space state if 853 // the separator is a stripper. Hence the additional test above. 854 mSpaceState = SpaceState.PHANTOM; 855 } 856 857 sendKeyCodePoint(settingsValues, codePoint); 858 859 // Set punctuation right away. onUpdateSelection will fire but tests whether it is 860 // already displayed or not, so it's okay. 861 mSuggestionStripViewAccessor.setNeutralSuggestionStrip(); 862 } 863 864 inputTransaction.requireShiftUpdate(InputTransaction.SHIFT_UPDATE_NOW); 865 return didAutoCorrect; 866 } 867 868 /** 869 * Handle a press on the backspace key. 870 * @param inputTransaction The transaction in progress. 871 */ 872 private void handleBackspace(final InputTransaction inputTransaction, 873 // TODO: remove this argument, put it into settingsValues 874 final int currentKeyboardScriptId) { 875 mSpaceState = SpaceState.NONE; 876 mDeleteCount++; 877 878 // In many cases after backspace, we need to update the shift state. Normally we need 879 // to do this right away to avoid the shift state being out of date in case the user types 880 // backspace then some other character very fast. However, in the case of backspace key 881 // repeat, this can lead to flashiness when the cursor flies over positions where the 882 // shift state should be updated, so if this is a key repeat, we update after a small delay. 883 // Then again, even in the case of a key repeat, if the cursor is at start of text, it 884 // can't go any further back, so we can update right away even if it's a key repeat. 885 final int shiftUpdateKind = 886 inputTransaction.mEvent.isKeyRepeat() && mConnection.getExpectedSelectionStart() > 0 887 ? InputTransaction.SHIFT_UPDATE_LATER : InputTransaction.SHIFT_UPDATE_NOW; 888 inputTransaction.requireShiftUpdate(shiftUpdateKind); 889 890 if (mWordComposer.isCursorFrontOrMiddleOfComposingWord()) { 891 // If we are in the middle of a recorrection, we need to commit the recorrection 892 // first so that we can remove the character at the current cursor position. 893 resetEntireInputState(mConnection.getExpectedSelectionStart(), 894 mConnection.getExpectedSelectionEnd(), true /* clearSuggestionStrip */); 895 // When we exit this if-clause, mWordComposer.isComposingWord() will return false. 896 } 897 if (mWordComposer.isComposingWord()) { 898 if (mWordComposer.isBatchMode()) { 899 final String rejectedSuggestion = mWordComposer.getTypedWord(); 900 mWordComposer.reset(); 901 mWordComposer.setRejectedBatchModeSuggestion(rejectedSuggestion); 902 if (!TextUtils.isEmpty(rejectedSuggestion)) { 903 mDictionaryFacilitator.removeWordFromPersonalizedDicts(rejectedSuggestion); 904 } 905 } else { 906 mWordComposer.processEvent(inputTransaction.mEvent); 907 } 908 if (mWordComposer.isComposingWord()) { 909 mConnection.setComposingText(getTextWithUnderline(mWordComposer.getTypedWord()), 1); 910 } else { 911 mConnection.commitText("", 1); 912 } 913 inputTransaction.setRequiresUpdateSuggestions(); 914 } else { 915 if (mLastComposedWord.canRevertCommit()) { 916 revertCommit(inputTransaction); 917 return; 918 } 919 if (mEnteredText != null && mConnection.sameAsTextBeforeCursor(mEnteredText)) { 920 // Cancel multi-character input: remove the text we just entered. 921 // This is triggered on backspace after a key that inputs multiple characters, 922 // like the smiley key or the .com key. 923 mConnection.deleteSurroundingText(mEnteredText.length(), 0); 924 mEnteredText = null; 925 // If we have mEnteredText, then we know that mHasUncommittedTypedChars == false. 926 // In addition we know that spaceState is false, and that we should not be 927 // reverting any autocorrect at this point. So we can safely return. 928 return; 929 } 930 if (SpaceState.DOUBLE == inputTransaction.mSpaceState) { 931 cancelDoubleSpacePeriodCountdown(); 932 if (mConnection.revertDoubleSpacePeriod()) { 933 // No need to reset mSpaceState, it has already be done (that's why we 934 // receive it as a parameter) 935 inputTransaction.setRequiresUpdateSuggestions(); 936 mWordComposer.setCapitalizedModeAtStartComposingTime( 937 WordComposer.CAPS_MODE_OFF); 938 return; 939 } 940 } else if (SpaceState.SWAP_PUNCTUATION == inputTransaction.mSpaceState) { 941 if (mConnection.revertSwapPunctuation()) { 942 // Likewise 943 return; 944 } 945 } 946 947 // No cancelling of commit/double space/swap: we have a regular backspace. 948 // We should backspace one char and restart suggestion if at the end of a word. 949 if (mConnection.hasSelection()) { 950 // If there is a selection, remove it. 951 final int numCharsDeleted = mConnection.getExpectedSelectionEnd() 952 - mConnection.getExpectedSelectionStart(); 953 mConnection.setSelection(mConnection.getExpectedSelectionEnd(), 954 mConnection.getExpectedSelectionEnd()); 955 mConnection.deleteSurroundingText(numCharsDeleted, 0); 956 } else { 957 // There is no selection, just delete one character. 958 if (Constants.NOT_A_CURSOR_POSITION == mConnection.getExpectedSelectionEnd()) { 959 // This should never happen. 960 Log.e(TAG, "Backspace when we don't know the selection position"); 961 } 962 if (inputTransaction.mSettingsValues.isBeforeJellyBean() || 963 inputTransaction.mSettingsValues.mInputAttributes.isTypeNull()) { 964 // There are two possible reasons to send a key event: either the field has 965 // type TYPE_NULL, in which case the keyboard should send events, or we are 966 // running in backward compatibility mode. Before Jelly bean, the keyboard 967 // would simulate a hardware keyboard event on pressing enter or delete. This 968 // is bad for many reasons (there are race conditions with commits) but some 969 // applications are relying on this behavior so we continue to support it for 970 // older apps, so we retain this behavior if the app has target SDK < JellyBean. 971 sendDownUpKeyEvent(KeyEvent.KEYCODE_DEL); 972 if (mDeleteCount > Constants.DELETE_ACCELERATE_AT) { 973 sendDownUpKeyEvent(KeyEvent.KEYCODE_DEL); 974 } 975 } else { 976 final int codePointBeforeCursor = mConnection.getCodePointBeforeCursor(); 977 if (codePointBeforeCursor == Constants.NOT_A_CODE) { 978 // HACK for backward compatibility with broken apps that haven't realized 979 // yet that hardware keyboards are not the only way of inputting text. 980 // Nothing to delete before the cursor. We should not do anything, but many 981 // broken apps expect something to happen in this case so that they can 982 // catch it and have their broken interface react. If you need the keyboard 983 // to do this, you're doing it wrong -- please fix your app. 984 mConnection.deleteSurroundingText(1, 0); 985 return; 986 } 987 final int lengthToDelete = 988 Character.isSupplementaryCodePoint(codePointBeforeCursor) ? 2 : 1; 989 mConnection.deleteSurroundingText(lengthToDelete, 0); 990 if (mDeleteCount > Constants.DELETE_ACCELERATE_AT) { 991 final int codePointBeforeCursorToDeleteAgain = 992 mConnection.getCodePointBeforeCursor(); 993 if (codePointBeforeCursorToDeleteAgain != Constants.NOT_A_CODE) { 994 final int lengthToDeleteAgain = Character.isSupplementaryCodePoint( 995 codePointBeforeCursorToDeleteAgain) ? 2 : 1; 996 mConnection.deleteSurroundingText(lengthToDeleteAgain, 0); 997 } 998 } 999 } 1000 } 1001 if (inputTransaction.mSettingsValues 1002 .isCurrentOrientationAllowingSuggestionsPerUserSettings() 1003 && inputTransaction.mSettingsValues.mSpacingAndPunctuations 1004 .mCurrentLanguageHasSpaces 1005 && !mConnection.isCursorFollowedByWordCharacter( 1006 inputTransaction.mSettingsValues.mSpacingAndPunctuations)) { 1007 restartSuggestionsOnWordTouchedByCursor(inputTransaction.mSettingsValues, 1008 true /* shouldIncludeResumedWordInSuggestions */, currentKeyboardScriptId); 1009 } 1010 } 1011 } 1012 1013 /** 1014 * Handle a press on the language switch key (the "globe key") 1015 */ 1016 private void handleLanguageSwitchKey() { 1017 mLatinIME.switchToNextSubtype(); 1018 } 1019 1020 /** 1021 * Swap a space with a space-swapping punctuation sign. 1022 * 1023 * This method will check that there are two characters before the cursor and that the first 1024 * one is a space before it does the actual swapping. 1025 * @param inputTransaction The transaction in progress. 1026 * @return true if the swap has been performed, false if it was prevented by preliminary checks. 1027 */ 1028 private boolean trySwapSwapperAndSpace(final InputTransaction inputTransaction) { 1029 final int codePointBeforeCursor = mConnection.getCodePointBeforeCursor(); 1030 if (Constants.CODE_SPACE != codePointBeforeCursor) { 1031 return false; 1032 } 1033 mConnection.deleteSurroundingText(1, 0); 1034 final String text = inputTransaction.mEvent.getTextToCommit() + " "; 1035 mConnection.commitText(text, 1); 1036 inputTransaction.requireShiftUpdate(InputTransaction.SHIFT_UPDATE_NOW); 1037 return true; 1038 } 1039 1040 /* 1041 * Strip a trailing space if necessary and returns whether it's a swap weak space situation. 1042 * @param inputTransaction The transaction in progress. 1043 * @param isFromSuggestionStrip Whether this code point is coming from the suggestion strip. 1044 * @return whether we should swap the space instead of removing it. 1045 */ 1046 private boolean tryStripSpaceAndReturnWhetherShouldSwapInstead( 1047 final InputTransaction inputTransaction, final boolean isFromSuggestionStrip) { 1048 final int codePoint = inputTransaction.mEvent.mCodePoint; 1049 if (Constants.CODE_ENTER == codePoint && 1050 SpaceState.SWAP_PUNCTUATION == inputTransaction.mSpaceState) { 1051 mConnection.removeTrailingSpace(); 1052 return false; 1053 } 1054 if ((SpaceState.WEAK == inputTransaction.mSpaceState 1055 || SpaceState.SWAP_PUNCTUATION == inputTransaction.mSpaceState) 1056 && isFromSuggestionStrip) { 1057 if (inputTransaction.mSettingsValues.isUsuallyPrecededBySpace(codePoint)) { 1058 return false; 1059 } 1060 if (inputTransaction.mSettingsValues.isUsuallyFollowedBySpace(codePoint)) { 1061 return true; 1062 } 1063 mConnection.removeTrailingSpace(); 1064 } 1065 return false; 1066 } 1067 1068 public void startDoubleSpacePeriodCountdown(final InputTransaction inputTransaction) { 1069 mDoubleSpacePeriodCountdownStart = inputTransaction.mTimestamp; 1070 } 1071 1072 public void cancelDoubleSpacePeriodCountdown() { 1073 mDoubleSpacePeriodCountdownStart = 0; 1074 } 1075 1076 public boolean isDoubleSpacePeriodCountdownActive(final InputTransaction inputTransaction) { 1077 return inputTransaction.mTimestamp - mDoubleSpacePeriodCountdownStart 1078 < inputTransaction.mSettingsValues.mDoubleSpacePeriodTimeout; 1079 } 1080 1081 /** 1082 * Apply the double-space-to-period transformation if applicable. 1083 * 1084 * The double-space-to-period transformation means that we replace two spaces with a 1085 * period-space sequence of characters. This typically happens when the user presses space 1086 * twice in a row quickly. 1087 * This method will check that the double-space-to-period is active in settings, that the 1088 * two spaces have been input close enough together, that the typed character is a space 1089 * and that the previous character allows for the transformation to take place. If all of 1090 * these conditions are fulfilled, this method applies the transformation and returns true. 1091 * Otherwise, it does nothing and returns false. 1092 * 1093 * @param inputTransaction The transaction in progress. 1094 * @return true if we applied the double-space-to-period transformation, false otherwise. 1095 */ 1096 private boolean tryPerformDoubleSpacePeriod(final InputTransaction inputTransaction) { 1097 // Check the setting, the typed character and the countdown. If any of the conditions is 1098 // not fulfilled, return false. 1099 if (!inputTransaction.mSettingsValues.mUseDoubleSpacePeriod 1100 || Constants.CODE_SPACE != inputTransaction.mEvent.mCodePoint 1101 || !isDoubleSpacePeriodCountdownActive(inputTransaction)) { 1102 return false; 1103 } 1104 // We only do this when we see one space and an accepted code point before the cursor. 1105 // The code point may be a surrogate pair but the space may not, so we need 3 chars. 1106 final CharSequence lastTwo = mConnection.getTextBeforeCursor(3, 0); 1107 if (null == lastTwo) return false; 1108 final int length = lastTwo.length(); 1109 if (length < 2) return false; 1110 if (lastTwo.charAt(length - 1) != Constants.CODE_SPACE) return false; 1111 // We know there is a space in pos -1, and we have at least two chars. If we have only two 1112 // chars, isSurrogatePairs can't return true as charAt(1) is a space, so this is fine. 1113 final int firstCodePoint = 1114 Character.isSurrogatePair(lastTwo.charAt(0), lastTwo.charAt(1)) ? 1115 Character.codePointAt(lastTwo, length - 3) : lastTwo.charAt(length - 2); 1116 if (canBeFollowedByDoubleSpacePeriod(firstCodePoint)) { 1117 cancelDoubleSpacePeriodCountdown(); 1118 mConnection.deleteSurroundingText(1, 0); 1119 final String textToInsert = inputTransaction.mSettingsValues.mSpacingAndPunctuations 1120 .mSentenceSeparatorAndSpace; 1121 mConnection.commitText(textToInsert, 1); 1122 inputTransaction.requireShiftUpdate(InputTransaction.SHIFT_UPDATE_NOW); 1123 inputTransaction.setRequiresUpdateSuggestions(); 1124 return true; 1125 } 1126 return false; 1127 } 1128 1129 /** 1130 * Returns whether this code point can be followed by the double-space-to-period transformation. 1131 * 1132 * See #maybeDoubleSpaceToPeriod for details. 1133 * Generally, most word characters can be followed by the double-space-to-period transformation, 1134 * while most punctuation can't. Some punctuation however does allow for this to take place 1135 * after them, like the closing parenthesis for example. 1136 * 1137 * @param codePoint the code point after which we may want to apply the transformation 1138 * @return whether it's fine to apply the transformation after this code point. 1139 */ 1140 private static boolean canBeFollowedByDoubleSpacePeriod(final int codePoint) { 1141 // TODO: This should probably be a blacklist rather than a whitelist. 1142 // TODO: This should probably be language-dependant... 1143 return Character.isLetterOrDigit(codePoint) 1144 || codePoint == Constants.CODE_SINGLE_QUOTE 1145 || codePoint == Constants.CODE_DOUBLE_QUOTE 1146 || codePoint == Constants.CODE_CLOSING_PARENTHESIS 1147 || codePoint == Constants.CODE_CLOSING_SQUARE_BRACKET 1148 || codePoint == Constants.CODE_CLOSING_CURLY_BRACKET 1149 || codePoint == Constants.CODE_CLOSING_ANGLE_BRACKET 1150 || codePoint == Constants.CODE_PLUS 1151 || codePoint == Constants.CODE_PERCENT 1152 || Character.getType(codePoint) == Character.OTHER_SYMBOL; 1153 } 1154 1155 /** 1156 * Performs a recapitalization event. 1157 * @param settingsValues The current settings values. 1158 */ 1159 private void performRecapitalization(final SettingsValues settingsValues) { 1160 if (!mConnection.hasSelection() || !mRecapitalizeStatus.mIsEnabled()) { 1161 return; // No selection or recapitalize is disabled for now 1162 } 1163 final int selectionStart = mConnection.getExpectedSelectionStart(); 1164 final int selectionEnd = mConnection.getExpectedSelectionEnd(); 1165 final int numCharsSelected = selectionEnd - selectionStart; 1166 if (numCharsSelected > Constants.MAX_CHARACTERS_FOR_RECAPITALIZATION) { 1167 // We bail out if we have too many characters for performance reasons. We don't want 1168 // to suck possibly multiple-megabyte data. 1169 return; 1170 } 1171 // If we have a recapitalize in progress, use it; otherwise, start a new one. 1172 if (!mRecapitalizeStatus.isStarted() 1173 || !mRecapitalizeStatus.isSetAt(selectionStart, selectionEnd)) { 1174 final CharSequence selectedText = 1175 mConnection.getSelectedText(0 /* flags, 0 for no styles */); 1176 if (TextUtils.isEmpty(selectedText)) return; // Race condition with the input connection 1177 mRecapitalizeStatus.start(selectionStart, selectionEnd, selectedText.toString(), 1178 settingsValues.mLocale, 1179 settingsValues.mSpacingAndPunctuations.mSortedWordSeparators); 1180 // We trim leading and trailing whitespace. 1181 mRecapitalizeStatus.trim(); 1182 } 1183 mConnection.finishComposingText(); 1184 mRecapitalizeStatus.rotate(); 1185 mConnection.setSelection(selectionEnd, selectionEnd); 1186 mConnection.deleteSurroundingText(numCharsSelected, 0); 1187 mConnection.commitText(mRecapitalizeStatus.getRecapitalizedString(), 0); 1188 mConnection.setSelection(mRecapitalizeStatus.getNewCursorStart(), 1189 mRecapitalizeStatus.getNewCursorEnd()); 1190 } 1191 1192 private void performAdditionToUserHistoryDictionary(final SettingsValues settingsValues, 1193 final String suggestion, final PrevWordsInfo prevWordsInfo) { 1194 // If correction is not enabled, we don't add words to the user history dictionary. 1195 // That's to avoid unintended additions in some sensitive fields, or fields that 1196 // expect to receive non-words. 1197 if (!settingsValues.mAutoCorrectionEnabled) return; 1198 1199 if (TextUtils.isEmpty(suggestion)) return; 1200 final boolean wasAutoCapitalized = 1201 mWordComposer.wasAutoCapitalized() && !mWordComposer.isMostlyCaps(); 1202 final int timeStampInSeconds = (int)TimeUnit.MILLISECONDS.toSeconds( 1203 System.currentTimeMillis()); 1204 mDictionaryFacilitator.addToUserHistory(suggestion, wasAutoCapitalized, 1205 prevWordsInfo, timeStampInSeconds, settingsValues.mBlockPotentiallyOffensive); 1206 } 1207 1208 public void performUpdateSuggestionStripSync(final SettingsValues settingsValues) { 1209 // Check if we have a suggestion engine attached. 1210 if (!settingsValues.isSuggestionsRequested()) { 1211 if (mWordComposer.isComposingWord()) { 1212 Log.w(TAG, "Called updateSuggestionsOrPredictions but suggestions were not " 1213 + "requested!"); 1214 } 1215 // Clear the suggestions strip. 1216 mSuggestionStripViewAccessor.showSuggestionStrip(SuggestedWords.EMPTY); 1217 return; 1218 } 1219 1220 if (!mWordComposer.isComposingWord() && !settingsValues.mBigramPredictionEnabled) { 1221 mSuggestionStripViewAccessor.setNeutralSuggestionStrip(); 1222 return; 1223 } 1224 1225 final AsyncResultHolder<SuggestedWords> holder = new AsyncResultHolder<>(); 1226 mInputLogicHandler.getSuggestedWords(Suggest.SESSION_TYPING, 1227 SuggestedWords.NOT_A_SEQUENCE_NUMBER, new OnGetSuggestedWordsCallback() { 1228 @Override 1229 public void onGetSuggestedWords(final SuggestedWords suggestedWords) { 1230 final String typedWord = mWordComposer.getTypedWord(); 1231 // Show new suggestions if we have at least one. Otherwise keep the old 1232 // suggestions with the new typed word. Exception: if the length of the 1233 // typed word is <= 1 (after a deletion typically) we clear old suggestions. 1234 if (suggestedWords.size() > 1 || typedWord.length() <= 1) { 1235 holder.set(suggestedWords); 1236 } else { 1237 holder.set(retrieveOlderSuggestions(typedWord, mSuggestedWords)); 1238 } 1239 } 1240 } 1241 ); 1242 1243 // This line may cause the current thread to wait. 1244 final SuggestedWords suggestedWords = holder.get(null, 1245 Constants.GET_SUGGESTED_WORDS_TIMEOUT); 1246 if (suggestedWords != null) { 1247 mSuggestionStripViewAccessor.showSuggestionStrip(suggestedWords); 1248 } 1249 } 1250 1251 /** 1252 * Check if the cursor is touching a word. If so, restart suggestions on this word, else 1253 * do nothing. 1254 * 1255 * @param settingsValues the current values of the settings. 1256 * @param shouldIncludeResumedWordInSuggestions whether to include the word on which we resume 1257 * suggestions in the suggestion list. 1258 */ 1259 // TODO: make this private. 1260 public void restartSuggestionsOnWordTouchedByCursor(final SettingsValues settingsValues, 1261 final boolean shouldIncludeResumedWordInSuggestions, 1262 // TODO: remove this argument, put it into settingsValues 1263 final int currentKeyboardScriptId) { 1264 // HACK: We may want to special-case some apps that exhibit bad behavior in case of 1265 // recorrection. This is a temporary, stopgap measure that will be removed later. 1266 // TODO: remove this. 1267 if (settingsValues.isBrokenByRecorrection() 1268 // Recorrection is not supported in languages without spaces because we don't know 1269 // how to segment them yet. 1270 || !settingsValues.mSpacingAndPunctuations.mCurrentLanguageHasSpaces 1271 // If no suggestions are requested, don't try restarting suggestions. 1272 || !settingsValues.isSuggestionsRequested() 1273 // If we are currently in a batch input, we must not resume suggestions, or the result 1274 // of the batch input will replace the new composition. This may happen in the corner case 1275 // that the app moves the cursor on its own accord during a batch input. 1276 || mInputLogicHandler.isInBatchInput() 1277 // If the cursor is not touching a word, or if there is a selection, return right away. 1278 || mConnection.hasSelection() 1279 // If we don't know the cursor location, return. 1280 || mConnection.getExpectedSelectionStart() < 0) { 1281 mSuggestionStripViewAccessor.setNeutralSuggestionStrip(); 1282 return; 1283 } 1284 final int expectedCursorPosition = mConnection.getExpectedSelectionStart(); 1285 if (!mConnection.isCursorTouchingWord(settingsValues.mSpacingAndPunctuations)) { 1286 // Show predictions. 1287 mWordComposer.setCapitalizedModeAtStartComposingTime(WordComposer.CAPS_MODE_OFF); 1288 mLatinIME.mHandler.postUpdateSuggestionStrip(); 1289 return; 1290 } 1291 final TextRange range = mConnection.getWordRangeAtCursor( 1292 settingsValues.mSpacingAndPunctuations.mSortedWordSeparators); 1293 if (null == range) return; // Happens if we don't have an input connection at all 1294 if (range.length() <= 0) return; // Race condition. No text to resume on, so bail out. 1295 // If for some strange reason (editor bug or so) we measure the text before the cursor as 1296 // longer than what the entire text is supposed to be, the safe thing to do is bail out. 1297 if (range.mHasUrlSpans) return; // If there are links, we don't resume suggestions. Making 1298 // edits to a linkified text through batch commands would ruin the URL spans, and unless 1299 // we take very complicated steps to preserve the whole link, we can't do things right so 1300 // we just do not resume because it's safer. 1301 final int numberOfCharsInWordBeforeCursor = range.getNumberOfCharsInWordBeforeCursor(); 1302 if (numberOfCharsInWordBeforeCursor > expectedCursorPosition) return; 1303 final ArrayList<SuggestedWordInfo> suggestions = new ArrayList<>(); 1304 final String typedWord = range.mWord.toString(); 1305 if (shouldIncludeResumedWordInSuggestions) { 1306 suggestions.add(new SuggestedWordInfo(typedWord, 1307 SuggestedWords.MAX_SUGGESTIONS + 1, 1308 SuggestedWordInfo.KIND_TYPED, Dictionary.DICTIONARY_USER_TYPED, 1309 SuggestedWordInfo.NOT_AN_INDEX /* indexOfTouchPointOfSecondWord */, 1310 SuggestedWordInfo.NOT_A_CONFIDENCE /* autoCommitFirstWordConfidence */)); 1311 } 1312 if (!isResumableWord(settingsValues, typedWord)) { 1313 mSuggestionStripViewAccessor.setNeutralSuggestionStrip(); 1314 return; 1315 } 1316 int i = 0; 1317 for (final SuggestionSpan span : range.getSuggestionSpansAtWord()) { 1318 for (final String s : span.getSuggestions()) { 1319 ++i; 1320 if (!TextUtils.equals(s, typedWord)) { 1321 suggestions.add(new SuggestedWordInfo(s, 1322 SuggestedWords.MAX_SUGGESTIONS - i, 1323 SuggestedWordInfo.KIND_RESUMED, Dictionary.DICTIONARY_RESUMED, 1324 SuggestedWordInfo.NOT_AN_INDEX /* indexOfTouchPointOfSecondWord */, 1325 SuggestedWordInfo.NOT_A_CONFIDENCE 1326 /* autoCommitFirstWordConfidence */)); 1327 } 1328 } 1329 } 1330 final int[] codePoints = StringUtils.toCodePointArray(typedWord); 1331 // We want the previous word for suggestion. If we have chars in the word 1332 // before the cursor, then we want the word before that, hence 2; otherwise, 1333 // we want the word immediately before the cursor, hence 1. 1334 final PrevWordsInfo prevWordsInfo = getPrevWordsInfoFromNthPreviousWordForSuggestion( 1335 settingsValues.mSpacingAndPunctuations, 1336 0 == numberOfCharsInWordBeforeCursor ? 1 : 2); 1337 mWordComposer.setComposingWord(codePoints, 1338 mLatinIME.getCoordinatesForCurrentKeyboard(codePoints)); 1339 mWordComposer.setCursorPositionWithinWord( 1340 typedWord.codePointCount(0, numberOfCharsInWordBeforeCursor)); 1341 mConnection.setComposingRegion(expectedCursorPosition - numberOfCharsInWordBeforeCursor, 1342 expectedCursorPosition + range.getNumberOfCharsInWordAfterCursor()); 1343 if (suggestions.size() <= (shouldIncludeResumedWordInSuggestions ? 1 : 0)) { 1344 // If there weren't any suggestion spans on this word, suggestions#size() will be 1 1345 // if shouldIncludeResumedWordInSuggestions is true, 0 otherwise. In this case, we 1346 // have no useful suggestions, so we will try to compute some for it instead. 1347 mInputLogicHandler.getSuggestedWords(Suggest.SESSION_TYPING, 1348 SuggestedWords.NOT_A_SEQUENCE_NUMBER, new OnGetSuggestedWordsCallback() { 1349 @Override 1350 public void onGetSuggestedWords( 1351 final SuggestedWords suggestedWordsIncludingTypedWord) { 1352 final SuggestedWords suggestedWords; 1353 if (suggestedWordsIncludingTypedWord.size() > 1 1354 && !shouldIncludeResumedWordInSuggestions) { 1355 // We were able to compute new suggestions for this word. 1356 // Remove the typed word, since we don't want to display it in this 1357 // case. The #getSuggestedWordsExcludingTypedWord() method sets 1358 // willAutoCorrect to false. 1359 suggestedWords = suggestedWordsIncludingTypedWord 1360 .getSuggestedWordsExcludingTypedWord(); 1361 } else { 1362 // No saved suggestions, and we were unable to compute any good one 1363 // either. Rather than displaying an empty suggestion strip, we'll 1364 // display the original word alone in the middle. 1365 // Since there is only one word, willAutoCorrect is false. 1366 suggestedWords = suggestedWordsIncludingTypedWord; 1367 } 1368 mIsAutoCorrectionIndicatorOn = false; 1369 mLatinIME.mHandler.showSuggestionStrip(suggestedWords); 1370 }}); 1371 } else { 1372 // We found suggestion spans in the word. We'll create the SuggestedWords out of 1373 // them, and make willAutoCorrect false. We make typedWordValid false, because the 1374 // color of the word in the suggestion strip changes according to this parameter, 1375 // and false gives the correct color. 1376 final SuggestedWords suggestedWords = new SuggestedWords(suggestions, 1377 null /* rawSuggestions */, typedWord, 1378 false /* typedWordValid */, false /* willAutoCorrect */, 1379 false /* isObsoleteSuggestions */, false /* isPrediction */, 1380 SuggestedWords.NOT_A_SEQUENCE_NUMBER); 1381 mIsAutoCorrectionIndicatorOn = false; 1382 mLatinIME.mHandler.showSuggestionStrip(suggestedWords); 1383 } 1384 } 1385 1386 /** 1387 * Reverts a previous commit with auto-correction. 1388 * 1389 * This is triggered upon pressing backspace just after a commit with auto-correction. 1390 * 1391 * @param inputTransaction The transaction in progress. 1392 */ 1393 private void revertCommit(final InputTransaction inputTransaction) { 1394 final CharSequence originallyTypedWord = mLastComposedWord.mTypedWord; 1395 final CharSequence committedWord = mLastComposedWord.mCommittedWord; 1396 final String committedWordString = committedWord.toString(); 1397 final int cancelLength = committedWord.length(); 1398 // We want java chars, not codepoints for the following. 1399 final int separatorLength = mLastComposedWord.mSeparatorString.length(); 1400 // TODO: should we check our saved separator against the actual contents of the text view? 1401 final int deleteLength = cancelLength + separatorLength; 1402 if (LatinImeLogger.sDBG) { 1403 if (mWordComposer.isComposingWord()) { 1404 throw new RuntimeException("revertCommit, but we are composing a word"); 1405 } 1406 final CharSequence wordBeforeCursor = 1407 mConnection.getTextBeforeCursor(deleteLength, 0).subSequence(0, cancelLength); 1408 if (!TextUtils.equals(committedWord, wordBeforeCursor)) { 1409 throw new RuntimeException("revertCommit check failed: we thought we were " 1410 + "reverting \"" + committedWord 1411 + "\", but before the cursor we found \"" + wordBeforeCursor + "\""); 1412 } 1413 } 1414 mConnection.deleteSurroundingText(deleteLength, 0); 1415 if (!TextUtils.isEmpty(committedWord)) { 1416 mDictionaryFacilitator.removeWordFromPersonalizedDicts(committedWordString); 1417 } 1418 final String stringToCommit = originallyTypedWord + mLastComposedWord.mSeparatorString; 1419 final SpannableString textToCommit = new SpannableString(stringToCommit); 1420 if (committedWord instanceof SpannableString) { 1421 final SpannableString committedWordWithSuggestionSpans = (SpannableString)committedWord; 1422 final Object[] spans = committedWordWithSuggestionSpans.getSpans(0, 1423 committedWord.length(), Object.class); 1424 final int lastCharIndex = textToCommit.length() - 1; 1425 // We will collect all suggestions in the following array. 1426 final ArrayList<String> suggestions = new ArrayList<>(); 1427 // First, add the committed word to the list of suggestions. 1428 suggestions.add(committedWordString); 1429 for (final Object span : spans) { 1430 // If this is a suggestion span, we check that the locale is the right one, and 1431 // that the word is not the committed word. That should mostly be the case. 1432 // Given this, we add it to the list of suggestions, otherwise we discard it. 1433 if (span instanceof SuggestionSpan) { 1434 final SuggestionSpan suggestionSpan = (SuggestionSpan)span; 1435 if (!suggestionSpan.getLocale().equals( 1436 inputTransaction.mSettingsValues.mLocale.toString())) { 1437 continue; 1438 } 1439 for (final String suggestion : suggestionSpan.getSuggestions()) { 1440 if (!suggestion.equals(committedWordString)) { 1441 suggestions.add(suggestion); 1442 } 1443 } 1444 } else { 1445 // If this is not a suggestion span, we just add it as is. 1446 textToCommit.setSpan(span, 0 /* start */, lastCharIndex /* end */, 1447 committedWordWithSuggestionSpans.getSpanFlags(span)); 1448 } 1449 } 1450 // Add the suggestion list to the list of suggestions. 1451 textToCommit.setSpan(new SuggestionSpan(inputTransaction.mSettingsValues.mLocale, 1452 suggestions.toArray(new String[suggestions.size()]), 0 /* flags */), 1453 0 /* start */, lastCharIndex /* end */, 0 /* flags */); 1454 } 1455 if (inputTransaction.mSettingsValues.mSpacingAndPunctuations.mCurrentLanguageHasSpaces) { 1456 // For languages with spaces, we revert to the typed string, but the cursor is still 1457 // after the separator so we don't resume suggestions. If the user wants to correct 1458 // the word, they have to press backspace again. 1459 mConnection.commitText(textToCommit, 1); 1460 } else { 1461 // For languages without spaces, we revert the typed string but the cursor is flush 1462 // with the typed word, so we need to resume suggestions right away. 1463 final int[] codePoints = StringUtils.toCodePointArray(stringToCommit); 1464 mWordComposer.setComposingWord(codePoints, 1465 mLatinIME.getCoordinatesForCurrentKeyboard(codePoints)); 1466 mConnection.setComposingText(textToCommit, 1); 1467 } 1468 // Don't restart suggestion yet. We'll restart if the user deletes the separator. 1469 mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD; 1470 // We have a separator between the word and the cursor: we should show predictions. 1471 inputTransaction.setRequiresUpdateSuggestions(); 1472 } 1473 1474 /** 1475 * Factor in auto-caps and manual caps and compute the current caps mode. 1476 * @param settingsValues the current settings values. 1477 * @param keyboardShiftMode the current shift mode of the keyboard. See 1478 * KeyboardSwitcher#getKeyboardShiftMode() for possible values. 1479 * @return the actual caps mode the keyboard is in right now. 1480 */ 1481 private int getActualCapsMode(final SettingsValues settingsValues, 1482 final int keyboardShiftMode) { 1483 if (keyboardShiftMode != WordComposer.CAPS_MODE_AUTO_SHIFTED) { 1484 return keyboardShiftMode; 1485 } 1486 final int auto = getCurrentAutoCapsState(settingsValues); 1487 if (0 != (auto & TextUtils.CAP_MODE_CHARACTERS)) { 1488 return WordComposer.CAPS_MODE_AUTO_SHIFT_LOCKED; 1489 } 1490 if (0 != auto) { 1491 return WordComposer.CAPS_MODE_AUTO_SHIFTED; 1492 } 1493 return WordComposer.CAPS_MODE_OFF; 1494 } 1495 1496 /** 1497 * Gets the current auto-caps state, factoring in the space state. 1498 * 1499 * This method tries its best to do this in the most efficient possible manner. It avoids 1500 * getting text from the editor if possible at all. 1501 * This is called from the KeyboardSwitcher (through a trampoline in LatinIME) because it 1502 * needs to know auto caps state to display the right layout. 1503 * 1504 * @param settingsValues the relevant settings values 1505 * @return a caps mode from TextUtils.CAP_MODE_* or Constants.TextUtils.CAP_MODE_OFF. 1506 */ 1507 public int getCurrentAutoCapsState(final SettingsValues settingsValues) { 1508 if (!settingsValues.mAutoCap) return Constants.TextUtils.CAP_MODE_OFF; 1509 1510 final EditorInfo ei = getCurrentInputEditorInfo(); 1511 if (ei == null) return Constants.TextUtils.CAP_MODE_OFF; 1512 final int inputType = ei.inputType; 1513 // Warning: this depends on mSpaceState, which may not be the most current value. If 1514 // mSpaceState gets updated later, whoever called this may need to be told about it. 1515 return mConnection.getCursorCapsMode(inputType, settingsValues.mSpacingAndPunctuations, 1516 SpaceState.PHANTOM == mSpaceState); 1517 } 1518 1519 public int getCurrentRecapitalizeState() { 1520 if (!mRecapitalizeStatus.isStarted() 1521 || !mRecapitalizeStatus.isSetAt(mConnection.getExpectedSelectionStart(), 1522 mConnection.getExpectedSelectionEnd())) { 1523 // Not recapitalizing at the moment 1524 return RecapitalizeStatus.NOT_A_RECAPITALIZE_MODE; 1525 } 1526 return mRecapitalizeStatus.getCurrentMode(); 1527 } 1528 1529 /** 1530 * @return the editor info for the current editor 1531 */ 1532 private EditorInfo getCurrentInputEditorInfo() { 1533 return mLatinIME.getCurrentInputEditorInfo(); 1534 } 1535 1536 /** 1537 * Get information fo previous words from the nth previous word before the cursor as context 1538 * for the suggestion process. 1539 * @param spacingAndPunctuations the current spacing and punctuations settings. 1540 * @param nthPreviousWord reverse index of the word to get (1-indexed) 1541 * @return the information of previous words 1542 */ 1543 // TODO: Make this private 1544 public PrevWordsInfo getPrevWordsInfoFromNthPreviousWordForSuggestion( 1545 final SpacingAndPunctuations spacingAndPunctuations, final int nthPreviousWord) { 1546 if (spacingAndPunctuations.mCurrentLanguageHasSpaces) { 1547 // If we are typing in a language with spaces we can just look up the previous 1548 // word information from textview. 1549 return mConnection.getPrevWordsInfoFromNthPreviousWord( 1550 spacingAndPunctuations, nthPreviousWord); 1551 } else { 1552 return LastComposedWord.NOT_A_COMPOSED_WORD == mLastComposedWord ? 1553 PrevWordsInfo.BEGINNING_OF_SENTENCE : 1554 new PrevWordsInfo(new PrevWordsInfo.WordInfo( 1555 mLastComposedWord.mCommittedWord.toString())); 1556 } 1557 } 1558 1559 /** 1560 * Tests the passed word for resumability. 1561 * 1562 * We can resume suggestions on words whose first code point is a word code point (with some 1563 * nuances: check the code for details). 1564 * 1565 * @param settings the current values of the settings. 1566 * @param word the word to evaluate. 1567 * @return whether it's fine to resume suggestions on this word. 1568 */ 1569 private static boolean isResumableWord(final SettingsValues settings, final String word) { 1570 final int firstCodePoint = word.codePointAt(0); 1571 return settings.isWordCodePoint(firstCodePoint) 1572 && Constants.CODE_SINGLE_QUOTE != firstCodePoint 1573 && Constants.CODE_DASH != firstCodePoint; 1574 } 1575 1576 /** 1577 * @param actionId the action to perform 1578 */ 1579 private void performEditorAction(final int actionId) { 1580 mConnection.performEditorAction(actionId); 1581 } 1582 1583 /** 1584 * Perform the processing specific to inputting TLDs. 1585 * 1586 * Some keys input a TLD (specifically, the ".com" key) and this warrants some specific 1587 * processing. First, if this is a TLD, we ignore PHANTOM spaces -- this is done by type 1588 * of character in onCodeInput, but since this gets inputted as a whole string we need to 1589 * do it here specifically. Then, if the last character before the cursor is a period, then 1590 * we cut the dot at the start of ".com". This is because humans tend to type "www.google." 1591 * and then press the ".com" key and instinctively don't expect to get "www.google..com". 1592 * 1593 * @param text the raw text supplied to onTextInput 1594 * @return the text to actually send to the editor 1595 */ 1596 private String performSpecificTldProcessingOnTextInput(final String text) { 1597 if (text.length() <= 1 || text.charAt(0) != Constants.CODE_PERIOD 1598 || !Character.isLetter(text.charAt(1))) { 1599 // Not a tld: do nothing. 1600 return text; 1601 } 1602 // We have a TLD (or something that looks like this): make sure we don't add 1603 // a space even if currently in phantom mode. 1604 mSpaceState = SpaceState.NONE; 1605 final int codePointBeforeCursor = mConnection.getCodePointBeforeCursor(); 1606 // If no code point, #getCodePointBeforeCursor returns NOT_A_CODE_POINT. 1607 if (Constants.CODE_PERIOD == codePointBeforeCursor) { 1608 return text.substring(1); 1609 } else { 1610 return text; 1611 } 1612 } 1613 1614 /** 1615 * Handle a press on the settings key. 1616 */ 1617 private void onSettingsKeyPressed() { 1618 mLatinIME.displaySettingsDialog(); 1619 } 1620 1621 /** 1622 * Resets the whole input state to the starting state. 1623 * 1624 * This will clear the composing word, reset the last composed word, clear the suggestion 1625 * strip and tell the input connection about it so that it can refresh its caches. 1626 * 1627 * @param newSelStart the new selection start, in java characters. 1628 * @param newSelEnd the new selection end, in java characters. 1629 * @param clearSuggestionStrip whether this method should clear the suggestion strip. 1630 */ 1631 // TODO: how is this different from startInput ?! 1632 private void resetEntireInputState(final int newSelStart, final int newSelEnd, 1633 final boolean clearSuggestionStrip) { 1634 final boolean shouldFinishComposition = mWordComposer.isComposingWord(); 1635 resetComposingState(true /* alsoResetLastComposedWord */); 1636 if (clearSuggestionStrip) { 1637 mSuggestionStripViewAccessor.setNeutralSuggestionStrip(); 1638 } 1639 mConnection.resetCachesUponCursorMoveAndReturnSuccess(newSelStart, newSelEnd, 1640 shouldFinishComposition); 1641 } 1642 1643 /** 1644 * Resets only the composing state. 1645 * 1646 * Compare #resetEntireInputState, which also clears the suggestion strip and resets the 1647 * input connection caches. This only deals with the composing state. 1648 * 1649 * @param alsoResetLastComposedWord whether to also reset the last composed word. 1650 */ 1651 private void resetComposingState(final boolean alsoResetLastComposedWord) { 1652 mWordComposer.reset(); 1653 if (alsoResetLastComposedWord) { 1654 mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD; 1655 } 1656 } 1657 1658 /** 1659 * Make a {@link com.android.inputmethod.latin.SuggestedWords} object containing a typed word 1660 * and obsolete suggestions. 1661 * See {@link com.android.inputmethod.latin.SuggestedWords#getTypedWordAndPreviousSuggestions( 1662 * String, com.android.inputmethod.latin.SuggestedWords)}. 1663 * @param typedWord The typed word as a string. 1664 * @param previousSuggestedWords The previously suggested words. 1665 * @return Obsolete suggestions with the newly typed word. 1666 */ 1667 private SuggestedWords retrieveOlderSuggestions(final String typedWord, 1668 final SuggestedWords previousSuggestedWords) { 1669 final SuggestedWords oldSuggestedWords = 1670 previousSuggestedWords.isPunctuationSuggestions() ? SuggestedWords.EMPTY 1671 : previousSuggestedWords; 1672 final ArrayList<SuggestedWords.SuggestedWordInfo> typedWordAndPreviousSuggestions = 1673 SuggestedWords.getTypedWordAndPreviousSuggestions(typedWord, oldSuggestedWords); 1674 return new SuggestedWords(typedWordAndPreviousSuggestions, null /* rawSuggestions */, 1675 false /* typedWordValid */, false /* hasAutoCorrectionCandidate */, 1676 true /* isObsoleteSuggestions */, false /* isPrediction */); 1677 } 1678 1679 /** 1680 * Gets a chunk of text with or the auto-correction indicator underline span as appropriate. 1681 * 1682 * This method looks at the old state of the auto-correction indicator to put or not put 1683 * the underline span as appropriate. It is important to note that this does not correspond 1684 * exactly to whether this word will be auto-corrected to or not: what's important here is 1685 * to keep the same indication as before. 1686 * When we add a new code point to a composing word, we don't know yet if we are going to 1687 * auto-correct it until the suggestions are computed. But in the mean time, we still need 1688 * to display the character and to extend the previous underline. To avoid any flickering, 1689 * the underline should keep the same color it used to have, even if that's not ultimately 1690 * the correct color for this new word. When the suggestions are finished evaluating, we 1691 * will call this method again to fix the color of the underline. 1692 * 1693 * @param text the text on which to maybe apply the span. 1694 * @return the same text, with the auto-correction underline span if that's appropriate. 1695 */ 1696 // TODO: Shouldn't this go in some *Utils class instead? 1697 private CharSequence getTextWithUnderline(final String text) { 1698 return mIsAutoCorrectionIndicatorOn 1699 ? SuggestionSpanUtils.getTextWithAutoCorrectionIndicatorUnderline(mLatinIME, text) 1700 : text; 1701 } 1702 1703 /** 1704 * Sends a DOWN key event followed by an UP key event to the editor. 1705 * 1706 * If possible at all, avoid using this method. It causes all sorts of race conditions with 1707 * the text view because it goes through a different, asynchronous binder. Also, batch edits 1708 * are ignored for key events. Use the normal software input methods instead. 1709 * 1710 * @param keyCode the key code to send inside the key event. 1711 */ 1712 private void sendDownUpKeyEvent(final int keyCode) { 1713 final long eventTime = SystemClock.uptimeMillis(); 1714 mConnection.sendKeyEvent(new KeyEvent(eventTime, eventTime, 1715 KeyEvent.ACTION_DOWN, keyCode, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 1716 KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE)); 1717 mConnection.sendKeyEvent(new KeyEvent(SystemClock.uptimeMillis(), eventTime, 1718 KeyEvent.ACTION_UP, keyCode, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 1719 KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE)); 1720 } 1721 1722 /** 1723 * Sends a code point to the editor, using the most appropriate method. 1724 * 1725 * Normally we send code points with commitText, but there are some cases (where backward 1726 * compatibility is a concern for example) where we want to use deprecated methods. 1727 * 1728 * @param settingsValues the current values of the settings. 1729 * @param codePoint the code point to send. 1730 */ 1731 // TODO: replace these two parameters with an InputTransaction 1732 private void sendKeyCodePoint(final SettingsValues settingsValues, final int codePoint) { 1733 // TODO: Remove this special handling of digit letters. 1734 // For backward compatibility. See {@link InputMethodService#sendKeyChar(char)}. 1735 if (codePoint >= '0' && codePoint <= '9') { 1736 sendDownUpKeyEvent(codePoint - '0' + KeyEvent.KEYCODE_0); 1737 return; 1738 } 1739 1740 // TODO: we should do this also when the editor has TYPE_NULL 1741 if (Constants.CODE_ENTER == codePoint && settingsValues.isBeforeJellyBean()) { 1742 // Backward compatibility mode. Before Jelly bean, the keyboard would simulate 1743 // a hardware keyboard event on pressing enter or delete. This is bad for many 1744 // reasons (there are race conditions with commits) but some applications are 1745 // relying on this behavior so we continue to support it for older apps. 1746 sendDownUpKeyEvent(KeyEvent.KEYCODE_ENTER); 1747 } else { 1748 mConnection.commitText(StringUtils.newSingleCodePointString(codePoint), 1); 1749 } 1750 } 1751 1752 /** 1753 * Promote a phantom space to an actual space. 1754 * 1755 * This essentially inserts a space, and that's it. It just checks the options and the text 1756 * before the cursor are appropriate before doing it. 1757 * 1758 * @param settingsValues the current values of the settings. 1759 */ 1760 private void promotePhantomSpace(final SettingsValues settingsValues) { 1761 if (settingsValues.shouldInsertSpacesAutomatically() 1762 && settingsValues.mSpacingAndPunctuations.mCurrentLanguageHasSpaces 1763 && !mConnection.textBeforeCursorLooksLikeURL()) { 1764 sendKeyCodePoint(settingsValues, Constants.CODE_SPACE); 1765 } 1766 } 1767 1768 /** 1769 * Do the final processing after a batch input has ended. This commits the word to the editor. 1770 * @param settingsValues the current values of the settings. 1771 * @param suggestedWords suggestedWords to use. 1772 */ 1773 public void onUpdateTailBatchInputCompleted(final SettingsValues settingsValues, 1774 final SuggestedWords suggestedWords, 1775 // TODO: remove this argument 1776 final KeyboardSwitcher keyboardSwitcher) { 1777 final String batchInputText = suggestedWords.isEmpty() ? null : suggestedWords.getWord(0); 1778 if (TextUtils.isEmpty(batchInputText)) { 1779 return; 1780 } 1781 mConnection.beginBatchEdit(); 1782 if (SpaceState.PHANTOM == mSpaceState) { 1783 promotePhantomSpace(settingsValues); 1784 } 1785 final SuggestedWordInfo autoCommitCandidate = mSuggestedWords.getAutoCommitCandidate(); 1786 // Commit except the last word for phrase gesture if the top suggestion is eligible for auto 1787 // commit. 1788 if (settingsValues.mPhraseGestureEnabled && null != autoCommitCandidate) { 1789 // Find the last space 1790 final int indexOfLastSpace = batchInputText.lastIndexOf(Constants.CODE_SPACE) + 1; 1791 if (0 != indexOfLastSpace) { 1792 mConnection.commitText(batchInputText.substring(0, indexOfLastSpace), 1); 1793 final SuggestedWords suggestedWordsForLastWordOfPhraseGesture = 1794 suggestedWords.getSuggestedWordsForLastWordOfPhraseGesture(); 1795 mLatinIME.showSuggestionStrip(suggestedWordsForLastWordOfPhraseGesture); 1796 } 1797 final String lastWord = batchInputText.substring(indexOfLastSpace); 1798 mWordComposer.setBatchInputWord(lastWord); 1799 mConnection.setComposingText(lastWord, 1); 1800 } else { 1801 mWordComposer.setBatchInputWord(batchInputText); 1802 mConnection.setComposingText(batchInputText, 1); 1803 } 1804 mConnection.endBatchEdit(); 1805 // Space state must be updated before calling updateShiftState 1806 mSpaceState = SpaceState.PHANTOM; 1807 keyboardSwitcher.requestUpdatingShiftState(getCurrentAutoCapsState(settingsValues), 1808 getCurrentRecapitalizeState()); 1809 } 1810 1811 /** 1812 * Commit the typed string to the editor. 1813 * 1814 * This is typically called when we should commit the currently composing word without applying 1815 * auto-correction to it. Typically, we come here upon pressing a separator when the keyboard 1816 * is configured to not do auto-correction at all (because of the settings or the properties of 1817 * the editor). In this case, `separatorString' is set to the separator that was pressed. 1818 * We also come here in a variety of cases with external user action. For example, when the 1819 * cursor is moved while there is a composition, or when the keyboard is closed, or when the 1820 * user presses the Send button for an SMS, we don't auto-correct as that would be unexpected. 1821 * In this case, `separatorString' is set to NOT_A_SEPARATOR. 1822 * 1823 * @param settingsValues the current values of the settings. 1824 * @param separatorString the separator that's causing the commit, or NOT_A_SEPARATOR if none. 1825 */ 1826 // TODO: Make this private 1827 public void commitTyped(final SettingsValues settingsValues, final String separatorString) { 1828 if (!mWordComposer.isComposingWord()) return; 1829 final String typedWord = mWordComposer.getTypedWord(); 1830 if (typedWord.length() > 0) { 1831 commitChosenWord(settingsValues, typedWord, 1832 LastComposedWord.COMMIT_TYPE_USER_TYPED_WORD, separatorString); 1833 } 1834 } 1835 1836 /** 1837 * Commit the current auto-correction. 1838 * 1839 * This will commit the best guess of the keyboard regarding what the user meant by typing 1840 * the currently composing word. The IME computes suggestions and assigns a confidence score 1841 * to each of them; when it's confident enough in one suggestion, it replaces the typed string 1842 * by this suggestion at commit time. When it's not confident enough, or when it has no 1843 * suggestions, or when the settings or environment does not allow for auto-correction, then 1844 * this method just commits the typed string. 1845 * Note that if suggestions are currently being computed in the background, this method will 1846 * block until the computation returns. This is necessary for consistency (it would be very 1847 * strange if pressing space would commit a different word depending on how fast you press). 1848 * 1849 * @param settingsValues the current value of the settings. 1850 * @param separator the separator that's causing the commit to happen. 1851 */ 1852 private void commitCurrentAutoCorrection(final SettingsValues settingsValues, 1853 final String separator, 1854 // TODO: Remove this argument. 1855 final LatinIME.UIHandler handler) { 1856 // Complete any pending suggestions query first 1857 if (handler.hasPendingUpdateSuggestions()) { 1858 handler.cancelUpdateSuggestionStrip(); 1859 performUpdateSuggestionStripSync(settingsValues); 1860 } 1861 final String typedAutoCorrection = mWordComposer.getAutoCorrectionOrNull(); 1862 final String typedWord = mWordComposer.getTypedWord(); 1863 final String autoCorrection = (typedAutoCorrection != null) 1864 ? typedAutoCorrection : typedWord; 1865 if (autoCorrection != null) { 1866 if (TextUtils.isEmpty(typedWord)) { 1867 throw new RuntimeException("We have an auto-correction but the typed word " 1868 + "is empty? Impossible! I must commit suicide."); 1869 } 1870 commitChosenWord(settingsValues, autoCorrection, 1871 LastComposedWord.COMMIT_TYPE_DECIDED_WORD, separator); 1872 if (!typedWord.equals(autoCorrection)) { 1873 // This will make the correction flash for a short while as a visual clue 1874 // to the user that auto-correction happened. It has no other effect; in particular 1875 // note that this won't affect the text inside the text field AT ALL: it only makes 1876 // the segment of text starting at the supplied index and running for the length 1877 // of the auto-correction flash. At this moment, the "typedWord" argument is 1878 // ignored by TextView. 1879 mConnection.commitCorrection(new CorrectionInfo( 1880 mConnection.getExpectedSelectionEnd() - autoCorrection.length(), 1881 typedWord, autoCorrection)); 1882 } 1883 } 1884 } 1885 1886 /** 1887 * Commits the chosen word to the text field and saves it for later retrieval. 1888 * 1889 * @param settingsValues the current values of the settings. 1890 * @param chosenWord the word we want to commit. 1891 * @param commitType the type of the commit, as one of LastComposedWord.COMMIT_TYPE_* 1892 * @param separatorString the separator that's causing the commit, or NOT_A_SEPARATOR if none. 1893 */ 1894 private void commitChosenWord(final SettingsValues settingsValues, final String chosenWord, 1895 final int commitType, final String separatorString) { 1896 final SuggestedWords suggestedWords = mSuggestedWords; 1897 final CharSequence chosenWordWithSuggestions = 1898 SuggestionSpanUtils.getTextWithSuggestionSpan(mLatinIME, chosenWord, 1899 suggestedWords); 1900 // When we are composing word, get previous words information from the 2nd previous word 1901 // because the 1st previous word is the word to be committed. Otherwise get previous words 1902 // information from the 1st previous word. 1903 final PrevWordsInfo prevWordsInfo = mConnection.getPrevWordsInfoFromNthPreviousWord( 1904 settingsValues.mSpacingAndPunctuations, mWordComposer.isComposingWord() ? 2 : 1); 1905 mConnection.commitText(chosenWordWithSuggestions, 1); 1906 // Add the word to the user history dictionary 1907 performAdditionToUserHistoryDictionary(settingsValues, chosenWord, prevWordsInfo); 1908 // TODO: figure out here if this is an auto-correct or if the best word is actually 1909 // what user typed. Note: currently this is done much later in 1910 // LastComposedWord#didCommitTypedWord by string equality of the remembered 1911 // strings. 1912 mLastComposedWord = mWordComposer.commitWord(commitType, 1913 chosenWordWithSuggestions, separatorString, prevWordsInfo); 1914 } 1915 1916 /** 1917 * Retry resetting caches in the rich input connection. 1918 * 1919 * When the editor can't be accessed we can't reset the caches, so we schedule a retry. 1920 * This method handles the retry, and re-schedules a new retry if we still can't access. 1921 * We only retry up to 5 times before giving up. 1922 * 1923 * @param settingsValues the current values of the settings. 1924 * @param tryResumeSuggestions Whether we should resume suggestions or not. 1925 * @param remainingTries How many times we may try again before giving up. 1926 * @return whether true if the caches were successfully reset, false otherwise. 1927 */ 1928 // TODO: make this private 1929 public boolean retryResetCachesAndReturnSuccess(final SettingsValues settingsValues, 1930 final boolean tryResumeSuggestions, final int remainingTries, 1931 // TODO: remove these arguments 1932 final LatinIME.UIHandler handler) { 1933 final boolean shouldFinishComposition = mConnection.hasSelection() 1934 || !mConnection.isCursorPositionKnown(); 1935 if (!mConnection.resetCachesUponCursorMoveAndReturnSuccess( 1936 mConnection.getExpectedSelectionStart(), mConnection.getExpectedSelectionEnd(), 1937 shouldFinishComposition)) { 1938 if (0 < remainingTries) { 1939 handler.postResetCaches(tryResumeSuggestions, remainingTries - 1); 1940 return false; 1941 } 1942 // If remainingTries is 0, we should stop waiting for new tries, however we'll still 1943 // return true as we need to perform other tasks (for example, loading the keyboard). 1944 } 1945 mConnection.tryFixLyingCursorPosition(); 1946 if (tryResumeSuggestions) { 1947 // This is triggered when starting input anew, so we want to include the resumed 1948 // word in suggestions. 1949 handler.postResumeSuggestions(true /* shouldIncludeResumedWordInSuggestions */, 1950 true /* shouldDelay */); 1951 } 1952 return true; 1953 } 1954 1955 public void getSuggestedWords(final SettingsValues settingsValues, 1956 final ProximityInfo proximityInfo, final int keyboardShiftMode, final int sessionId, 1957 final int sequenceNumber, final OnGetSuggestedWordsCallback callback) { 1958 mWordComposer.adviseCapitalizedModeBeforeFetchingSuggestions( 1959 getActualCapsMode(settingsValues, keyboardShiftMode)); 1960 mSuggest.getSuggestedWords(mWordComposer, 1961 getPrevWordsInfoFromNthPreviousWordForSuggestion( 1962 settingsValues.mSpacingAndPunctuations, 1963 // Get the word on which we should search the bigrams. If we are composing 1964 // a word, it's whatever is *before* the half-committed word in the buffer, 1965 // hence 2; if we aren't, we should just skip whitespace if any, so 1. 1966 mWordComposer.isComposingWord() ? 2 : 1), 1967 proximityInfo, settingsValues.mBlockPotentiallyOffensive, 1968 settingsValues.mAutoCorrectionEnabled, 1969 settingsValues.mAdditionalFeaturesSettingValues, 1970 sessionId, sequenceNumber, callback); 1971 } 1972} 1973