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