InputLogic.java revision 1c2f1ada8305e36defa8572da687a4596bf083ea
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 index the index of the suggestion. 217 * @param suggestionInfo the suggestion info. 218 * @param keyboardShiftState the shift state of the keyboard, as returned by 219 * {@link com.android.inputmethod.keyboard.KeyboardSwitcher#getKeyboardShiftMode()} 220 * @return the complete transaction object 221 */ 222 // Called from {@link SuggestionStripView} through the {@link SuggestionStripView#Listener} 223 // interface 224 public InputTransaction onPickSuggestionManually(final SettingsValues settingsValues, 225 final int index, final SuggestedWordInfo suggestionInfo, final int keyboardShiftState, 226 // TODO: remove this argument 227 final LatinIME.UIHandler handler) { 228 final SuggestedWords suggestedWords = mSuggestedWords; 229 final String suggestion = suggestionInfo.mWord; 230 // If this is a punctuation picked from the suggestion strip, pass it to onCodeInput 231 if (suggestion.length() == 1 && suggestedWords.isPunctuationSuggestions()) { 232 // Word separators are suggested before the user inputs something. 233 // Rely on onCodeInput to do the complicated swapping/stripping logic consistently. 234 final Event event = Event.createPunctuationSuggestionPickedEvent(suggestionInfo); 235 return onCodeInput(settingsValues, event, keyboardShiftState, 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 this argument 382 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.NOT_A_KEY_CODE != event.mKeyCode) { 403 // A special key, like delete, shift, emoji, or the settings key. 404 switch (event.mKeyCode) { 405 case Constants.CODE_DELETE: 406 handleBackspace(inputTransaction); 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 mSpaceState = SpaceState.NONE; 862 mDeleteCount++; 863 864 // In many cases after backspace, we need to update the shift state. Normally we need 865 // to do this right away to avoid the shift state being out of date in case the user types 866 // backspace then some other character very fast. However, in the case of backspace key 867 // repeat, this can lead to flashiness when the cursor flies over positions where the 868 // shift state should be updated, so if this is a key repeat, we update after a small delay. 869 // Then again, even in the case of a key repeat, if the cursor is at start of text, it 870 // can't go any further back, so we can update right away even if it's a key repeat. 871 final int shiftUpdateKind = 872 inputTransaction.mEvent.isKeyRepeat() && mConnection.getExpectedSelectionStart() > 0 873 ? InputTransaction.SHIFT_UPDATE_LATER : InputTransaction.SHIFT_UPDATE_NOW; 874 inputTransaction.requireShiftUpdate(shiftUpdateKind); 875 876 if (mWordComposer.isCursorFrontOrMiddleOfComposingWord()) { 877 // If we are in the middle of a recorrection, we need to commit the recorrection 878 // first so that we can remove the character at the current cursor position. 879 resetEntireInputState(mConnection.getExpectedSelectionStart(), 880 mConnection.getExpectedSelectionEnd(), true /* clearSuggestionStrip */); 881 // When we exit this if-clause, mWordComposer.isComposingWord() will return false. 882 } 883 if (mWordComposer.isComposingWord()) { 884 if (mWordComposer.isBatchMode()) { 885 final String rejectedSuggestion = mWordComposer.getTypedWord(); 886 mWordComposer.reset(); 887 mWordComposer.setRejectedBatchModeSuggestion(rejectedSuggestion); 888 if (!TextUtils.isEmpty(rejectedSuggestion)) { 889 mDictionaryFacilitator.removeWordFromPersonalizedDicts(rejectedSuggestion); 890 } 891 } else { 892 mWordComposer.processEvent(inputTransaction.mEvent); 893 } 894 if (mWordComposer.isComposingWord()) { 895 mConnection.setComposingText(getTextWithUnderline(mWordComposer.getTypedWord()), 1); 896 } else { 897 mConnection.commitText("", 1); 898 } 899 inputTransaction.setRequiresUpdateSuggestions(); 900 } else { 901 if (mLastComposedWord.canRevertCommit()) { 902 revertCommit(inputTransaction); 903 return; 904 } 905 if (mEnteredText != null && mConnection.sameAsTextBeforeCursor(mEnteredText)) { 906 // Cancel multi-character input: remove the text we just entered. 907 // This is triggered on backspace after a key that inputs multiple characters, 908 // like the smiley key or the .com key. 909 mConnection.deleteSurroundingText(mEnteredText.length(), 0); 910 mEnteredText = null; 911 // If we have mEnteredText, then we know that mHasUncommittedTypedChars == false. 912 // In addition we know that spaceState is false, and that we should not be 913 // reverting any autocorrect at this point. So we can safely return. 914 return; 915 } 916 if (SpaceState.DOUBLE == inputTransaction.mSpaceState) { 917 cancelDoubleSpacePeriodCountdown(); 918 if (mConnection.revertDoubleSpacePeriod()) { 919 // No need to reset mSpaceState, it has already be done (that's why we 920 // receive it as a parameter) 921 inputTransaction.setRequiresUpdateSuggestions(); 922 mWordComposer.setCapitalizedModeAtStartComposingTime( 923 WordComposer.CAPS_MODE_OFF); 924 return; 925 } 926 } else if (SpaceState.SWAP_PUNCTUATION == inputTransaction.mSpaceState) { 927 if (mConnection.revertSwapPunctuation()) { 928 // Likewise 929 return; 930 } 931 } 932 933 // No cancelling of commit/double space/swap: we have a regular backspace. 934 // We should backspace one char and restart suggestion if at the end of a word. 935 if (mConnection.hasSelection()) { 936 // If there is a selection, remove it. 937 final int numCharsDeleted = mConnection.getExpectedSelectionEnd() 938 - mConnection.getExpectedSelectionStart(); 939 mConnection.setSelection(mConnection.getExpectedSelectionEnd(), 940 mConnection.getExpectedSelectionEnd()); 941 mConnection.deleteSurroundingText(numCharsDeleted, 0); 942 } else { 943 // There is no selection, just delete one character. 944 if (Constants.NOT_A_CURSOR_POSITION == mConnection.getExpectedSelectionEnd()) { 945 // This should never happen. 946 Log.e(TAG, "Backspace when we don't know the selection position"); 947 } 948 if (inputTransaction.mSettingsValues.isBeforeJellyBean() || 949 inputTransaction.mSettingsValues.mInputAttributes.isTypeNull()) { 950 // There are two possible reasons to send a key event: either the field has 951 // type TYPE_NULL, in which case the keyboard should send events, or we are 952 // running in backward compatibility mode. Before Jelly bean, the keyboard 953 // would simulate a hardware keyboard event on pressing enter or delete. This 954 // is bad for many reasons (there are race conditions with commits) but some 955 // applications are relying on this behavior so we continue to support it for 956 // older apps, so we retain this behavior if the app has target SDK < JellyBean. 957 sendDownUpKeyEvent(KeyEvent.KEYCODE_DEL); 958 if (mDeleteCount > Constants.DELETE_ACCELERATE_AT) { 959 sendDownUpKeyEvent(KeyEvent.KEYCODE_DEL); 960 } 961 } else { 962 final int codePointBeforeCursor = mConnection.getCodePointBeforeCursor(); 963 if (codePointBeforeCursor == Constants.NOT_A_CODE) { 964 // HACK for backward compatibility with broken apps that haven't realized 965 // yet that hardware keyboards are not the only way of inputting text. 966 // Nothing to delete before the cursor. We should not do anything, but many 967 // broken apps expect something to happen in this case so that they can 968 // catch it and have their broken interface react. If you need the keyboard 969 // to do this, you're doing it wrong -- please fix your app. 970 mConnection.deleteSurroundingText(1, 0); 971 return; 972 } 973 final int lengthToDelete = 974 Character.isSupplementaryCodePoint(codePointBeforeCursor) ? 2 : 1; 975 mConnection.deleteSurroundingText(lengthToDelete, 0); 976 if (mDeleteCount > Constants.DELETE_ACCELERATE_AT) { 977 final int codePointBeforeCursorToDeleteAgain = 978 mConnection.getCodePointBeforeCursor(); 979 if (codePointBeforeCursorToDeleteAgain != Constants.NOT_A_CODE) { 980 final int lengthToDeleteAgain = Character.isSupplementaryCodePoint( 981 codePointBeforeCursorToDeleteAgain) ? 2 : 1; 982 mConnection.deleteSurroundingText(lengthToDeleteAgain, 0); 983 } 984 } 985 } 986 } 987 if (inputTransaction.mSettingsValues 988 .isCurrentOrientationAllowingSuggestionsPerUserSettings() 989 && inputTransaction.mSettingsValues.mSpacingAndPunctuations 990 .mCurrentLanguageHasSpaces 991 && !mConnection.isCursorFollowedByWordCharacter( 992 inputTransaction.mSettingsValues.mSpacingAndPunctuations)) { 993 restartSuggestionsOnWordTouchedByCursor(inputTransaction.mSettingsValues, 994 true /* shouldIncludeResumedWordInSuggestions */); 995 } 996 } 997 } 998 999 /** 1000 * Handle a press on the language switch key (the "globe key") 1001 */ 1002 private void handleLanguageSwitchKey() { 1003 mLatinIME.switchToNextSubtype(); 1004 } 1005 1006 /** 1007 * Swap a space with a space-swapping punctuation sign. 1008 * 1009 * This method will check that there are two characters before the cursor and that the first 1010 * one is a space before it does the actual swapping. 1011 * @param inputTransaction The transaction in progress. 1012 * @return true if the swap has been performed, false if it was prevented by preliminary checks. 1013 */ 1014 private boolean trySwapSwapperAndSpace(final InputTransaction inputTransaction) { 1015 final int codePointBeforeCursor = mConnection.getCodePointBeforeCursor(); 1016 if (Constants.CODE_SPACE != codePointBeforeCursor) { 1017 return false; 1018 } 1019 mConnection.deleteSurroundingText(1, 0); 1020 final String text = inputTransaction.mEvent.getTextToCommit() + " "; 1021 mConnection.commitText(text, 1); 1022 inputTransaction.requireShiftUpdate(InputTransaction.SHIFT_UPDATE_NOW); 1023 return true; 1024 } 1025 1026 /* 1027 * Strip a trailing space if necessary and returns whether it's a swap weak space situation. 1028 * @param inputTransaction The transaction in progress. 1029 * @param isFromSuggestionStrip Whether this code point is coming from the suggestion strip. 1030 * @return whether we should swap the space instead of removing it. 1031 */ 1032 private boolean tryStripSpaceAndReturnWhetherShouldSwapInstead( 1033 final InputTransaction inputTransaction, final boolean isFromSuggestionStrip) { 1034 final int codePoint = inputTransaction.mEvent.mCodePoint; 1035 if (Constants.CODE_ENTER == codePoint && 1036 SpaceState.SWAP_PUNCTUATION == inputTransaction.mSpaceState) { 1037 mConnection.removeTrailingSpace(); 1038 return false; 1039 } 1040 if ((SpaceState.WEAK == inputTransaction.mSpaceState 1041 || SpaceState.SWAP_PUNCTUATION == inputTransaction.mSpaceState) 1042 && isFromSuggestionStrip) { 1043 if (inputTransaction.mSettingsValues.isUsuallyPrecededBySpace(codePoint)) { 1044 return false; 1045 } 1046 if (inputTransaction.mSettingsValues.isUsuallyFollowedBySpace(codePoint)) { 1047 return true; 1048 } 1049 mConnection.removeTrailingSpace(); 1050 } 1051 return false; 1052 } 1053 1054 public void startDoubleSpacePeriodCountdown(final InputTransaction inputTransaction) { 1055 mDoubleSpacePeriodCountdownStart = inputTransaction.mTimestamp; 1056 } 1057 1058 public void cancelDoubleSpacePeriodCountdown() { 1059 mDoubleSpacePeriodCountdownStart = 0; 1060 } 1061 1062 public boolean isDoubleSpacePeriodCountdownActive(final InputTransaction inputTransaction) { 1063 return inputTransaction.mTimestamp - mDoubleSpacePeriodCountdownStart 1064 < inputTransaction.mSettingsValues.mDoubleSpacePeriodTimeout; 1065 } 1066 1067 /** 1068 * Apply the double-space-to-period transformation if applicable. 1069 * 1070 * The double-space-to-period transformation means that we replace two spaces with a 1071 * period-space sequence of characters. This typically happens when the user presses space 1072 * twice in a row quickly. 1073 * This method will check that the double-space-to-period is active in settings, that the 1074 * two spaces have been input close enough together, that the typed character is a space 1075 * and that the previous character allows for the transformation to take place. If all of 1076 * these conditions are fulfilled, this method applies the transformation and returns true. 1077 * Otherwise, it does nothing and returns false. 1078 * 1079 * @param inputTransaction The transaction in progress. 1080 * @return true if we applied the double-space-to-period transformation, false otherwise. 1081 */ 1082 private boolean tryPerformDoubleSpacePeriod(final InputTransaction inputTransaction) { 1083 // Check the setting, the typed character and the countdown. If any of the conditions is 1084 // not fulfilled, return false. 1085 if (!inputTransaction.mSettingsValues.mUseDoubleSpacePeriod 1086 || Constants.CODE_SPACE != inputTransaction.mEvent.mCodePoint 1087 || !isDoubleSpacePeriodCountdownActive(inputTransaction)) { 1088 return false; 1089 } 1090 // We only do this when we see one space and an accepted code point before the cursor. 1091 // The code point may be a surrogate pair but the space may not, so we need 3 chars. 1092 final CharSequence lastTwo = mConnection.getTextBeforeCursor(3, 0); 1093 if (null == lastTwo) return false; 1094 final int length = lastTwo.length(); 1095 if (length < 2) return false; 1096 if (lastTwo.charAt(length - 1) != Constants.CODE_SPACE) return false; 1097 // We know there is a space in pos -1, and we have at least two chars. If we have only two 1098 // chars, isSurrogatePairs can't return true as charAt(1) is a space, so this is fine. 1099 final int firstCodePoint = 1100 Character.isSurrogatePair(lastTwo.charAt(0), lastTwo.charAt(1)) ? 1101 Character.codePointAt(lastTwo, length - 3) : lastTwo.charAt(length - 2); 1102 if (canBeFollowedByDoubleSpacePeriod(firstCodePoint)) { 1103 cancelDoubleSpacePeriodCountdown(); 1104 mConnection.deleteSurroundingText(1, 0); 1105 final String textToInsert = inputTransaction.mSettingsValues.mSpacingAndPunctuations 1106 .mSentenceSeparatorAndSpace; 1107 mConnection.commitText(textToInsert, 1); 1108 inputTransaction.requireShiftUpdate(InputTransaction.SHIFT_UPDATE_NOW); 1109 inputTransaction.setRequiresUpdateSuggestions(); 1110 return true; 1111 } 1112 return false; 1113 } 1114 1115 /** 1116 * Returns whether this code point can be followed by the double-space-to-period transformation. 1117 * 1118 * See #maybeDoubleSpaceToPeriod for details. 1119 * Generally, most word characters can be followed by the double-space-to-period transformation, 1120 * while most punctuation can't. Some punctuation however does allow for this to take place 1121 * after them, like the closing parenthesis for example. 1122 * 1123 * @param codePoint the code point after which we may want to apply the transformation 1124 * @return whether it's fine to apply the transformation after this code point. 1125 */ 1126 private static boolean canBeFollowedByDoubleSpacePeriod(final int codePoint) { 1127 // TODO: This should probably be a blacklist rather than a whitelist. 1128 // TODO: This should probably be language-dependant... 1129 return Character.isLetterOrDigit(codePoint) 1130 || codePoint == Constants.CODE_SINGLE_QUOTE 1131 || codePoint == Constants.CODE_DOUBLE_QUOTE 1132 || codePoint == Constants.CODE_CLOSING_PARENTHESIS 1133 || codePoint == Constants.CODE_CLOSING_SQUARE_BRACKET 1134 || codePoint == Constants.CODE_CLOSING_CURLY_BRACKET 1135 || codePoint == Constants.CODE_CLOSING_ANGLE_BRACKET 1136 || codePoint == Constants.CODE_PLUS 1137 || codePoint == Constants.CODE_PERCENT 1138 || Character.getType(codePoint) == Character.OTHER_SYMBOL; 1139 } 1140 1141 /** 1142 * Performs a recapitalization event. 1143 * @param settingsValues The current settings values. 1144 */ 1145 private void performRecapitalization(final SettingsValues settingsValues) { 1146 if (!mConnection.hasSelection() || !mRecapitalizeStatus.mIsEnabled()) { 1147 return; // No selection or recapitalize is disabled for now 1148 } 1149 final int selectionStart = mConnection.getExpectedSelectionStart(); 1150 final int selectionEnd = mConnection.getExpectedSelectionEnd(); 1151 final int numCharsSelected = selectionEnd - selectionStart; 1152 if (numCharsSelected > Constants.MAX_CHARACTERS_FOR_RECAPITALIZATION) { 1153 // We bail out if we have too many characters for performance reasons. We don't want 1154 // to suck possibly multiple-megabyte data. 1155 return; 1156 } 1157 // If we have a recapitalize in progress, use it; otherwise, start a new one. 1158 if (!mRecapitalizeStatus.isStarted() 1159 || !mRecapitalizeStatus.isSetAt(selectionStart, selectionEnd)) { 1160 final CharSequence selectedText = 1161 mConnection.getSelectedText(0 /* flags, 0 for no styles */); 1162 if (TextUtils.isEmpty(selectedText)) return; // Race condition with the input connection 1163 mRecapitalizeStatus.start(selectionStart, selectionEnd, selectedText.toString(), 1164 settingsValues.mLocale, 1165 settingsValues.mSpacingAndPunctuations.mSortedWordSeparators); 1166 // We trim leading and trailing whitespace. 1167 mRecapitalizeStatus.trim(); 1168 } 1169 mConnection.finishComposingText(); 1170 mRecapitalizeStatus.rotate(); 1171 mConnection.setSelection(selectionEnd, selectionEnd); 1172 mConnection.deleteSurroundingText(numCharsSelected, 0); 1173 mConnection.commitText(mRecapitalizeStatus.getRecapitalizedString(), 0); 1174 mConnection.setSelection(mRecapitalizeStatus.getNewCursorStart(), 1175 mRecapitalizeStatus.getNewCursorEnd()); 1176 } 1177 1178 private void performAdditionToUserHistoryDictionary(final SettingsValues settingsValues, 1179 final String suggestion, final PrevWordsInfo prevWordsInfo) { 1180 // If correction is not enabled, we don't add words to the user history dictionary. 1181 // That's to avoid unintended additions in some sensitive fields, or fields that 1182 // expect to receive non-words. 1183 if (!settingsValues.mAutoCorrectionEnabled) return; 1184 1185 if (TextUtils.isEmpty(suggestion)) return; 1186 final boolean wasAutoCapitalized = 1187 mWordComposer.wasAutoCapitalized() && !mWordComposer.isMostlyCaps(); 1188 final int timeStampInSeconds = (int)TimeUnit.MILLISECONDS.toSeconds( 1189 System.currentTimeMillis()); 1190 mDictionaryFacilitator.addToUserHistory(suggestion, wasAutoCapitalized, 1191 prevWordsInfo, timeStampInSeconds, settingsValues.mBlockPotentiallyOffensive); 1192 } 1193 1194 public void performUpdateSuggestionStripSync(final SettingsValues settingsValues) { 1195 // Check if we have a suggestion engine attached. 1196 if (!settingsValues.isSuggestionsRequested()) { 1197 if (mWordComposer.isComposingWord()) { 1198 Log.w(TAG, "Called updateSuggestionsOrPredictions but suggestions were not " 1199 + "requested!"); 1200 } 1201 // Clear the suggestions strip. 1202 mSuggestionStripViewAccessor.showSuggestionStrip(SuggestedWords.EMPTY); 1203 return; 1204 } 1205 1206 if (!mWordComposer.isComposingWord() && !settingsValues.mBigramPredictionEnabled) { 1207 mSuggestionStripViewAccessor.setNeutralSuggestionStrip(); 1208 return; 1209 } 1210 1211 final AsyncResultHolder<SuggestedWords> holder = new AsyncResultHolder<>(); 1212 mInputLogicHandler.getSuggestedWords(Suggest.SESSION_TYPING, 1213 SuggestedWords.NOT_A_SEQUENCE_NUMBER, new OnGetSuggestedWordsCallback() { 1214 @Override 1215 public void onGetSuggestedWords(final SuggestedWords suggestedWords) { 1216 final String typedWord = mWordComposer.getTypedWord(); 1217 // Show new suggestions if we have at least one. Otherwise keep the old 1218 // suggestions with the new typed word. Exception: if the length of the 1219 // typed word is <= 1 (after a deletion typically) we clear old suggestions. 1220 if (suggestedWords.size() > 1 || typedWord.length() <= 1) { 1221 holder.set(suggestedWords); 1222 } else { 1223 holder.set(retrieveOlderSuggestions(typedWord, mSuggestedWords)); 1224 } 1225 } 1226 } 1227 ); 1228 1229 // This line may cause the current thread to wait. 1230 final SuggestedWords suggestedWords = holder.get(null, 1231 Constants.GET_SUGGESTED_WORDS_TIMEOUT); 1232 if (suggestedWords != null) { 1233 mSuggestionStripViewAccessor.showSuggestionStrip(suggestedWords); 1234 } 1235 } 1236 1237 /** 1238 * Check if the cursor is touching a word. If so, restart suggestions on this word, else 1239 * do nothing. 1240 * 1241 * @param settingsValues the current values of the settings. 1242 * @param shouldIncludeResumedWordInSuggestions whether to include the word on which we resume 1243 * suggestions in the suggestion list. 1244 */ 1245 // TODO: make this private. 1246 public void restartSuggestionsOnWordTouchedByCursor(final SettingsValues settingsValues, 1247 final boolean shouldIncludeResumedWordInSuggestions) { 1248 // HACK: We may want to special-case some apps that exhibit bad behavior in case of 1249 // recorrection. This is a temporary, stopgap measure that will be removed later. 1250 // TODO: remove this. 1251 if (settingsValues.isBrokenByRecorrection() 1252 // Recorrection is not supported in languages without spaces because we don't know 1253 // how to segment them yet. 1254 || !settingsValues.mSpacingAndPunctuations.mCurrentLanguageHasSpaces 1255 // If no suggestions are requested, don't try restarting suggestions. 1256 || !settingsValues.isSuggestionsRequested() 1257 // If we are currently in a batch input, we must not resume suggestions, or the result 1258 // of the batch input will replace the new composition. This may happen in the corner case 1259 // that the app moves the cursor on its own accord during a batch input. 1260 || mInputLogicHandler.isInBatchInput() 1261 // If the cursor is not touching a word, or if there is a selection, return right away. 1262 || mConnection.hasSelection() 1263 // If we don't know the cursor location, return. 1264 || mConnection.getExpectedSelectionStart() < 0) { 1265 mSuggestionStripViewAccessor.setNeutralSuggestionStrip(); 1266 return; 1267 } 1268 final int expectedCursorPosition = mConnection.getExpectedSelectionStart(); 1269 if (!mConnection.isCursorTouchingWord(settingsValues.mSpacingAndPunctuations)) { 1270 // Show predictions. 1271 mWordComposer.setCapitalizedModeAtStartComposingTime(WordComposer.CAPS_MODE_OFF); 1272 mLatinIME.mHandler.postUpdateSuggestionStrip(); 1273 return; 1274 } 1275 final TextRange range = mConnection.getWordRangeAtCursor( 1276 settingsValues.mSpacingAndPunctuations.mSortedWordSeparators, 1277 0 /* additionalPrecedingWordsCount */); 1278 if (null == range) return; // Happens if we don't have an input connection at all 1279 if (range.length() <= 0) return; // Race condition. No text to resume on, so bail out. 1280 // If for some strange reason (editor bug or so) we measure the text before the cursor as 1281 // longer than what the entire text is supposed to be, the safe thing to do is bail out. 1282 if (range.mHasUrlSpans) return; // If there are links, we don't resume suggestions. Making 1283 // edits to a linkified text through batch commands would ruin the URL spans, and unless 1284 // we take very complicated steps to preserve the whole link, we can't do things right so 1285 // we just do not resume because it's safer. 1286 final int numberOfCharsInWordBeforeCursor = range.getNumberOfCharsInWordBeforeCursor(); 1287 if (numberOfCharsInWordBeforeCursor > expectedCursorPosition) return; 1288 final ArrayList<SuggestedWordInfo> suggestions = new ArrayList<>(); 1289 final String typedWord = range.mWord.toString(); 1290 if (shouldIncludeResumedWordInSuggestions) { 1291 suggestions.add(new SuggestedWordInfo(typedWord, 1292 SuggestedWords.MAX_SUGGESTIONS + 1, 1293 SuggestedWordInfo.KIND_TYPED, Dictionary.DICTIONARY_USER_TYPED, 1294 SuggestedWordInfo.NOT_AN_INDEX /* indexOfTouchPointOfSecondWord */, 1295 SuggestedWordInfo.NOT_A_CONFIDENCE /* autoCommitFirstWordConfidence */)); 1296 } 1297 if (!isResumableWord(settingsValues, typedWord)) { 1298 mSuggestionStripViewAccessor.setNeutralSuggestionStrip(); 1299 return; 1300 } 1301 int i = 0; 1302 for (final SuggestionSpan span : range.getSuggestionSpansAtWord()) { 1303 for (final String s : span.getSuggestions()) { 1304 ++i; 1305 if (!TextUtils.equals(s, typedWord)) { 1306 suggestions.add(new SuggestedWordInfo(s, 1307 SuggestedWords.MAX_SUGGESTIONS - i, 1308 SuggestedWordInfo.KIND_RESUMED, Dictionary.DICTIONARY_RESUMED, 1309 SuggestedWordInfo.NOT_AN_INDEX /* indexOfTouchPointOfSecondWord */, 1310 SuggestedWordInfo.NOT_A_CONFIDENCE 1311 /* autoCommitFirstWordConfidence */)); 1312 } 1313 } 1314 } 1315 final int[] codePoints = StringUtils.toCodePointArray(typedWord); 1316 // We want the previous word for suggestion. If we have chars in the word 1317 // before the cursor, then we want the word before that, hence 2; otherwise, 1318 // we want the word immediately before the cursor, hence 1. 1319 final PrevWordsInfo prevWordsInfo = getPrevWordsInfoFromNthPreviousWordForSuggestion( 1320 settingsValues.mSpacingAndPunctuations, 1321 0 == numberOfCharsInWordBeforeCursor ? 1 : 2); 1322 mWordComposer.setComposingWord(codePoints, 1323 mLatinIME.getCoordinatesForCurrentKeyboard(codePoints)); 1324 mWordComposer.setCursorPositionWithinWord( 1325 typedWord.codePointCount(0, numberOfCharsInWordBeforeCursor)); 1326 mConnection.setComposingRegion(expectedCursorPosition - numberOfCharsInWordBeforeCursor, 1327 expectedCursorPosition + range.getNumberOfCharsInWordAfterCursor()); 1328 if (suggestions.size() <= (shouldIncludeResumedWordInSuggestions ? 1 : 0)) { 1329 // If there weren't any suggestion spans on this word, suggestions#size() will be 1 1330 // if shouldIncludeResumedWordInSuggestions is true, 0 otherwise. In this case, we 1331 // have no useful suggestions, so we will try to compute some for it instead. 1332 mInputLogicHandler.getSuggestedWords(Suggest.SESSION_TYPING, 1333 SuggestedWords.NOT_A_SEQUENCE_NUMBER, new OnGetSuggestedWordsCallback() { 1334 @Override 1335 public void onGetSuggestedWords( 1336 final SuggestedWords suggestedWordsIncludingTypedWord) { 1337 final SuggestedWords suggestedWords; 1338 if (suggestedWordsIncludingTypedWord.size() > 1 1339 && !shouldIncludeResumedWordInSuggestions) { 1340 // We were able to compute new suggestions for this word. 1341 // Remove the typed word, since we don't want to display it in this 1342 // case. The #getSuggestedWordsExcludingTypedWord() method sets 1343 // willAutoCorrect to false. 1344 suggestedWords = suggestedWordsIncludingTypedWord 1345 .getSuggestedWordsExcludingTypedWord(); 1346 } else { 1347 // No saved suggestions, and we were unable to compute any good one 1348 // either. Rather than displaying an empty suggestion strip, we'll 1349 // display the original word alone in the middle. 1350 // Since there is only one word, willAutoCorrect is false. 1351 suggestedWords = suggestedWordsIncludingTypedWord; 1352 } 1353 mIsAutoCorrectionIndicatorOn = false; 1354 mLatinIME.mHandler.showSuggestionStrip(suggestedWords); 1355 }}); 1356 } else { 1357 // We found suggestion spans in the word. We'll create the SuggestedWords out of 1358 // them, and make willAutoCorrect false. We make typedWordValid false, because the 1359 // color of the word in the suggestion strip changes according to this parameter, 1360 // and false gives the correct color. 1361 final SuggestedWords suggestedWords = new SuggestedWords(suggestions, 1362 null /* rawSuggestions */, typedWord, 1363 false /* typedWordValid */, false /* willAutoCorrect */, 1364 false /* isObsoleteSuggestions */, false /* isPrediction */, 1365 SuggestedWords.NOT_A_SEQUENCE_NUMBER); 1366 mIsAutoCorrectionIndicatorOn = false; 1367 mLatinIME.mHandler.showSuggestionStrip(suggestedWords); 1368 } 1369 } 1370 1371 /** 1372 * Reverts a previous commit with auto-correction. 1373 * 1374 * This is triggered upon pressing backspace just after a commit with auto-correction. 1375 * 1376 * @param inputTransaction The transaction in progress. 1377 */ 1378 private void revertCommit(final InputTransaction inputTransaction) { 1379 final CharSequence originallyTypedWord = mLastComposedWord.mTypedWord; 1380 final CharSequence committedWord = mLastComposedWord.mCommittedWord; 1381 final String committedWordString = committedWord.toString(); 1382 final int cancelLength = committedWord.length(); 1383 // We want java chars, not codepoints for the following. 1384 final int separatorLength = mLastComposedWord.mSeparatorString.length(); 1385 // TODO: should we check our saved separator against the actual contents of the text view? 1386 final int deleteLength = cancelLength + separatorLength; 1387 if (LatinImeLogger.sDBG) { 1388 if (mWordComposer.isComposingWord()) { 1389 throw new RuntimeException("revertCommit, but we are composing a word"); 1390 } 1391 final CharSequence wordBeforeCursor = 1392 mConnection.getTextBeforeCursor(deleteLength, 0).subSequence(0, cancelLength); 1393 if (!TextUtils.equals(committedWord, wordBeforeCursor)) { 1394 throw new RuntimeException("revertCommit check failed: we thought we were " 1395 + "reverting \"" + committedWord 1396 + "\", but before the cursor we found \"" + wordBeforeCursor + "\""); 1397 } 1398 } 1399 mConnection.deleteSurroundingText(deleteLength, 0); 1400 if (!TextUtils.isEmpty(committedWord)) { 1401 mDictionaryFacilitator.removeWordFromPersonalizedDicts(committedWordString); 1402 } 1403 final String stringToCommit = originallyTypedWord + mLastComposedWord.mSeparatorString; 1404 final SpannableString textToCommit = new SpannableString(stringToCommit); 1405 if (committedWord instanceof SpannableString) { 1406 final SpannableString committedWordWithSuggestionSpans = (SpannableString)committedWord; 1407 final Object[] spans = committedWordWithSuggestionSpans.getSpans(0, 1408 committedWord.length(), Object.class); 1409 final int lastCharIndex = textToCommit.length() - 1; 1410 // We will collect all suggestions in the following array. 1411 final ArrayList<String> suggestions = new ArrayList<>(); 1412 // First, add the committed word to the list of suggestions. 1413 suggestions.add(committedWordString); 1414 for (final Object span : spans) { 1415 // If this is a suggestion span, we check that the locale is the right one, and 1416 // that the word is not the committed word. That should mostly be the case. 1417 // Given this, we add it to the list of suggestions, otherwise we discard it. 1418 if (span instanceof SuggestionSpan) { 1419 final SuggestionSpan suggestionSpan = (SuggestionSpan)span; 1420 if (!suggestionSpan.getLocale().equals( 1421 inputTransaction.mSettingsValues.mLocale.toString())) { 1422 continue; 1423 } 1424 for (final String suggestion : suggestionSpan.getSuggestions()) { 1425 if (!suggestion.equals(committedWordString)) { 1426 suggestions.add(suggestion); 1427 } 1428 } 1429 } else { 1430 // If this is not a suggestion span, we just add it as is. 1431 textToCommit.setSpan(span, 0 /* start */, lastCharIndex /* end */, 1432 committedWordWithSuggestionSpans.getSpanFlags(span)); 1433 } 1434 } 1435 // Add the suggestion list to the list of suggestions. 1436 textToCommit.setSpan(new SuggestionSpan(inputTransaction.mSettingsValues.mLocale, 1437 suggestions.toArray(new String[suggestions.size()]), 0 /* flags */), 1438 0 /* start */, lastCharIndex /* end */, 0 /* flags */); 1439 } 1440 if (inputTransaction.mSettingsValues.mSpacingAndPunctuations.mCurrentLanguageHasSpaces) { 1441 // For languages with spaces, we revert to the typed string, but the cursor is still 1442 // after the separator so we don't resume suggestions. If the user wants to correct 1443 // the word, they have to press backspace again. 1444 mConnection.commitText(textToCommit, 1); 1445 } else { 1446 // For languages without spaces, we revert the typed string but the cursor is flush 1447 // with the typed word, so we need to resume suggestions right away. 1448 final int[] codePoints = StringUtils.toCodePointArray(stringToCommit); 1449 mWordComposer.setComposingWord(codePoints, 1450 mLatinIME.getCoordinatesForCurrentKeyboard(codePoints)); 1451 mConnection.setComposingText(textToCommit, 1); 1452 } 1453 // Don't restart suggestion yet. We'll restart if the user deletes the separator. 1454 mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD; 1455 // We have a separator between the word and the cursor: we should show predictions. 1456 inputTransaction.setRequiresUpdateSuggestions(); 1457 } 1458 1459 /** 1460 * Factor in auto-caps and manual caps and compute the current caps mode. 1461 * @param settingsValues the current settings values. 1462 * @param keyboardShiftMode the current shift mode of the keyboard. See 1463 * KeyboardSwitcher#getKeyboardShiftMode() for possible values. 1464 * @return the actual caps mode the keyboard is in right now. 1465 */ 1466 private int getActualCapsMode(final SettingsValues settingsValues, 1467 final int keyboardShiftMode) { 1468 if (keyboardShiftMode != WordComposer.CAPS_MODE_AUTO_SHIFTED) { 1469 return keyboardShiftMode; 1470 } 1471 final int auto = getCurrentAutoCapsState(settingsValues); 1472 if (0 != (auto & TextUtils.CAP_MODE_CHARACTERS)) { 1473 return WordComposer.CAPS_MODE_AUTO_SHIFT_LOCKED; 1474 } 1475 if (0 != auto) { 1476 return WordComposer.CAPS_MODE_AUTO_SHIFTED; 1477 } 1478 return WordComposer.CAPS_MODE_OFF; 1479 } 1480 1481 /** 1482 * Gets the current auto-caps state, factoring in the space state. 1483 * 1484 * This method tries its best to do this in the most efficient possible manner. It avoids 1485 * getting text from the editor if possible at all. 1486 * This is called from the KeyboardSwitcher (through a trampoline in LatinIME) because it 1487 * needs to know auto caps state to display the right layout. 1488 * 1489 * @param settingsValues the relevant settings values 1490 * @return a caps mode from TextUtils.CAP_MODE_* or Constants.TextUtils.CAP_MODE_OFF. 1491 */ 1492 public int getCurrentAutoCapsState(final SettingsValues settingsValues) { 1493 if (!settingsValues.mAutoCap) return Constants.TextUtils.CAP_MODE_OFF; 1494 1495 final EditorInfo ei = getCurrentInputEditorInfo(); 1496 if (ei == null) return Constants.TextUtils.CAP_MODE_OFF; 1497 final int inputType = ei.inputType; 1498 // Warning: this depends on mSpaceState, which may not be the most current value. If 1499 // mSpaceState gets updated later, whoever called this may need to be told about it. 1500 return mConnection.getCursorCapsMode(inputType, settingsValues.mSpacingAndPunctuations, 1501 SpaceState.PHANTOM == mSpaceState); 1502 } 1503 1504 public int getCurrentRecapitalizeState() { 1505 if (!mRecapitalizeStatus.isStarted() 1506 || !mRecapitalizeStatus.isSetAt(mConnection.getExpectedSelectionStart(), 1507 mConnection.getExpectedSelectionEnd())) { 1508 // Not recapitalizing at the moment 1509 return RecapitalizeStatus.NOT_A_RECAPITALIZE_MODE; 1510 } 1511 return mRecapitalizeStatus.getCurrentMode(); 1512 } 1513 1514 /** 1515 * @return the editor info for the current editor 1516 */ 1517 private EditorInfo getCurrentInputEditorInfo() { 1518 return mLatinIME.getCurrentInputEditorInfo(); 1519 } 1520 1521 /** 1522 * Get information fo previous words from the nth previous word before the cursor as context 1523 * for the suggestion process. 1524 * @param spacingAndPunctuations the current spacing and punctuations settings. 1525 * @param nthPreviousWord reverse index of the word to get (1-indexed) 1526 * @return the information of previous words 1527 */ 1528 // TODO: Make this private 1529 public PrevWordsInfo getPrevWordsInfoFromNthPreviousWordForSuggestion( 1530 final SpacingAndPunctuations spacingAndPunctuations, final int nthPreviousWord) { 1531 if (spacingAndPunctuations.mCurrentLanguageHasSpaces) { 1532 // If we are typing in a language with spaces we can just look up the previous 1533 // word information from textview. 1534 return mConnection.getPrevWordsInfoFromNthPreviousWord( 1535 spacingAndPunctuations, nthPreviousWord); 1536 } else { 1537 return LastComposedWord.NOT_A_COMPOSED_WORD == mLastComposedWord ? 1538 PrevWordsInfo.BEGINNING_OF_SENTENCE : 1539 new PrevWordsInfo(new PrevWordsInfo.WordInfo( 1540 mLastComposedWord.mCommittedWord.toString())); 1541 } 1542 } 1543 1544 /** 1545 * Tests the passed word for resumability. 1546 * 1547 * We can resume suggestions on words whose first code point is a word code point (with some 1548 * nuances: check the code for details). 1549 * 1550 * @param settings the current values of the settings. 1551 * @param word the word to evaluate. 1552 * @return whether it's fine to resume suggestions on this word. 1553 */ 1554 private static boolean isResumableWord(final SettingsValues settings, final String word) { 1555 final int firstCodePoint = word.codePointAt(0); 1556 return settings.isWordCodePoint(firstCodePoint) 1557 && Constants.CODE_SINGLE_QUOTE != firstCodePoint 1558 && Constants.CODE_DASH != firstCodePoint; 1559 } 1560 1561 /** 1562 * @param actionId the action to perform 1563 */ 1564 private void performEditorAction(final int actionId) { 1565 mConnection.performEditorAction(actionId); 1566 } 1567 1568 /** 1569 * Perform the processing specific to inputting TLDs. 1570 * 1571 * Some keys input a TLD (specifically, the ".com" key) and this warrants some specific 1572 * processing. First, if this is a TLD, we ignore PHANTOM spaces -- this is done by type 1573 * of character in onCodeInput, but since this gets inputted as a whole string we need to 1574 * do it here specifically. Then, if the last character before the cursor is a period, then 1575 * we cut the dot at the start of ".com". This is because humans tend to type "www.google." 1576 * and then press the ".com" key and instinctively don't expect to get "www.google..com". 1577 * 1578 * @param text the raw text supplied to onTextInput 1579 * @return the text to actually send to the editor 1580 */ 1581 private String performSpecificTldProcessingOnTextInput(final String text) { 1582 if (text.length() <= 1 || text.charAt(0) != Constants.CODE_PERIOD 1583 || !Character.isLetter(text.charAt(1))) { 1584 // Not a tld: do nothing. 1585 return text; 1586 } 1587 // We have a TLD (or something that looks like this): make sure we don't add 1588 // a space even if currently in phantom mode. 1589 mSpaceState = SpaceState.NONE; 1590 final int codePointBeforeCursor = mConnection.getCodePointBeforeCursor(); 1591 // If no code point, #getCodePointBeforeCursor returns NOT_A_CODE_POINT. 1592 if (Constants.CODE_PERIOD == codePointBeforeCursor) { 1593 return text.substring(1); 1594 } else { 1595 return text; 1596 } 1597 } 1598 1599 /** 1600 * Handle a press on the settings key. 1601 */ 1602 private void onSettingsKeyPressed() { 1603 mLatinIME.displaySettingsDialog(); 1604 } 1605 1606 /** 1607 * Resets the whole input state to the starting state. 1608 * 1609 * This will clear the composing word, reset the last composed word, clear the suggestion 1610 * strip and tell the input connection about it so that it can refresh its caches. 1611 * 1612 * @param newSelStart the new selection start, in java characters. 1613 * @param newSelEnd the new selection end, in java characters. 1614 * @param clearSuggestionStrip whether this method should clear the suggestion strip. 1615 */ 1616 // TODO: how is this different from startInput ?! 1617 private void resetEntireInputState(final int newSelStart, final int newSelEnd, 1618 final boolean clearSuggestionStrip) { 1619 final boolean shouldFinishComposition = mWordComposer.isComposingWord(); 1620 resetComposingState(true /* alsoResetLastComposedWord */); 1621 if (clearSuggestionStrip) { 1622 mSuggestionStripViewAccessor.setNeutralSuggestionStrip(); 1623 } 1624 mConnection.resetCachesUponCursorMoveAndReturnSuccess(newSelStart, newSelEnd, 1625 shouldFinishComposition); 1626 } 1627 1628 /** 1629 * Resets only the composing state. 1630 * 1631 * Compare #resetEntireInputState, which also clears the suggestion strip and resets the 1632 * input connection caches. This only deals with the composing state. 1633 * 1634 * @param alsoResetLastComposedWord whether to also reset the last composed word. 1635 */ 1636 private void resetComposingState(final boolean alsoResetLastComposedWord) { 1637 mWordComposer.reset(); 1638 if (alsoResetLastComposedWord) { 1639 mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD; 1640 } 1641 } 1642 1643 /** 1644 * Make a {@link com.android.inputmethod.latin.SuggestedWords} object containing a typed word 1645 * and obsolete suggestions. 1646 * See {@link com.android.inputmethod.latin.SuggestedWords#getTypedWordAndPreviousSuggestions( 1647 * String, com.android.inputmethod.latin.SuggestedWords)}. 1648 * @param typedWord The typed word as a string. 1649 * @param previousSuggestedWords The previously suggested words. 1650 * @return Obsolete suggestions with the newly typed word. 1651 */ 1652 private SuggestedWords retrieveOlderSuggestions(final String typedWord, 1653 final SuggestedWords previousSuggestedWords) { 1654 final SuggestedWords oldSuggestedWords = 1655 previousSuggestedWords.isPunctuationSuggestions() ? SuggestedWords.EMPTY 1656 : previousSuggestedWords; 1657 final ArrayList<SuggestedWords.SuggestedWordInfo> typedWordAndPreviousSuggestions = 1658 SuggestedWords.getTypedWordAndPreviousSuggestions(typedWord, oldSuggestedWords); 1659 return new SuggestedWords(typedWordAndPreviousSuggestions, null /* rawSuggestions */, 1660 false /* typedWordValid */, false /* hasAutoCorrectionCandidate */, 1661 true /* isObsoleteSuggestions */, false /* isPrediction */); 1662 } 1663 1664 /** 1665 * Gets a chunk of text with or the auto-correction indicator underline span as appropriate. 1666 * 1667 * This method looks at the old state of the auto-correction indicator to put or not put 1668 * the underline span as appropriate. It is important to note that this does not correspond 1669 * exactly to whether this word will be auto-corrected to or not: what's important here is 1670 * to keep the same indication as before. 1671 * When we add a new code point to a composing word, we don't know yet if we are going to 1672 * auto-correct it until the suggestions are computed. But in the mean time, we still need 1673 * to display the character and to extend the previous underline. To avoid any flickering, 1674 * the underline should keep the same color it used to have, even if that's not ultimately 1675 * the correct color for this new word. When the suggestions are finished evaluating, we 1676 * will call this method again to fix the color of the underline. 1677 * 1678 * @param text the text on which to maybe apply the span. 1679 * @return the same text, with the auto-correction underline span if that's appropriate. 1680 */ 1681 // TODO: Shouldn't this go in some *Utils class instead? 1682 private CharSequence getTextWithUnderline(final String text) { 1683 return mIsAutoCorrectionIndicatorOn 1684 ? SuggestionSpanUtils.getTextWithAutoCorrectionIndicatorUnderline(mLatinIME, text) 1685 : text; 1686 } 1687 1688 /** 1689 * Sends a DOWN key event followed by an UP key event to the editor. 1690 * 1691 * If possible at all, avoid using this method. It causes all sorts of race conditions with 1692 * the text view because it goes through a different, asynchronous binder. Also, batch edits 1693 * are ignored for key events. Use the normal software input methods instead. 1694 * 1695 * @param keyCode the key code to send inside the key event. 1696 */ 1697 private void sendDownUpKeyEvent(final int keyCode) { 1698 final long eventTime = SystemClock.uptimeMillis(); 1699 mConnection.sendKeyEvent(new KeyEvent(eventTime, eventTime, 1700 KeyEvent.ACTION_DOWN, keyCode, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 1701 KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE)); 1702 mConnection.sendKeyEvent(new KeyEvent(SystemClock.uptimeMillis(), eventTime, 1703 KeyEvent.ACTION_UP, keyCode, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 1704 KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE)); 1705 } 1706 1707 /** 1708 * Sends a code point to the editor, using the most appropriate method. 1709 * 1710 * Normally we send code points with commitText, but there are some cases (where backward 1711 * compatibility is a concern for example) where we want to use deprecated methods. 1712 * 1713 * @param settingsValues the current values of the settings. 1714 * @param codePoint the code point to send. 1715 */ 1716 // TODO: replace these two parameters with an InputTransaction 1717 private void sendKeyCodePoint(final SettingsValues settingsValues, final int codePoint) { 1718 // TODO: Remove this special handling of digit letters. 1719 // For backward compatibility. See {@link InputMethodService#sendKeyChar(char)}. 1720 if (codePoint >= '0' && codePoint <= '9') { 1721 sendDownUpKeyEvent(codePoint - '0' + KeyEvent.KEYCODE_0); 1722 return; 1723 } 1724 1725 // TODO: we should do this also when the editor has TYPE_NULL 1726 if (Constants.CODE_ENTER == codePoint && settingsValues.isBeforeJellyBean()) { 1727 // Backward compatibility mode. Before Jelly bean, the keyboard would simulate 1728 // a hardware keyboard event on pressing enter or delete. This is bad for many 1729 // reasons (there are race conditions with commits) but some applications are 1730 // relying on this behavior so we continue to support it for older apps. 1731 sendDownUpKeyEvent(KeyEvent.KEYCODE_ENTER); 1732 } else { 1733 mConnection.commitText(StringUtils.newSingleCodePointString(codePoint), 1); 1734 } 1735 } 1736 1737 /** 1738 * Promote a phantom space to an actual space. 1739 * 1740 * This essentially inserts a space, and that's it. It just checks the options and the text 1741 * before the cursor are appropriate before doing it. 1742 * 1743 * @param settingsValues the current values of the settings. 1744 */ 1745 private void promotePhantomSpace(final SettingsValues settingsValues) { 1746 if (settingsValues.shouldInsertSpacesAutomatically() 1747 && settingsValues.mSpacingAndPunctuations.mCurrentLanguageHasSpaces 1748 && !mConnection.textBeforeCursorLooksLikeURL()) { 1749 sendKeyCodePoint(settingsValues, Constants.CODE_SPACE); 1750 } 1751 } 1752 1753 /** 1754 * Do the final processing after a batch input has ended. This commits the word to the editor. 1755 * @param settingsValues the current values of the settings. 1756 * @param suggestedWords suggestedWords to use. 1757 */ 1758 public void onUpdateTailBatchInputCompleted(final SettingsValues settingsValues, 1759 final SuggestedWords suggestedWords, 1760 // TODO: remove this argument 1761 final KeyboardSwitcher keyboardSwitcher) { 1762 final String batchInputText = suggestedWords.isEmpty() ? null : suggestedWords.getWord(0); 1763 if (TextUtils.isEmpty(batchInputText)) { 1764 return; 1765 } 1766 mConnection.beginBatchEdit(); 1767 if (SpaceState.PHANTOM == mSpaceState) { 1768 promotePhantomSpace(settingsValues); 1769 } 1770 final SuggestedWordInfo autoCommitCandidate = mSuggestedWords.getAutoCommitCandidate(); 1771 // Commit except the last word for phrase gesture if the top suggestion is eligible for auto 1772 // commit. 1773 if (settingsValues.mPhraseGestureEnabled && null != autoCommitCandidate) { 1774 // Find the last space 1775 final int indexOfLastSpace = batchInputText.lastIndexOf(Constants.CODE_SPACE) + 1; 1776 if (0 != indexOfLastSpace) { 1777 mConnection.commitText(batchInputText.substring(0, indexOfLastSpace), 1); 1778 final SuggestedWords suggestedWordsForLastWordOfPhraseGesture = 1779 suggestedWords.getSuggestedWordsForLastWordOfPhraseGesture(); 1780 mLatinIME.showSuggestionStrip(suggestedWordsForLastWordOfPhraseGesture); 1781 } 1782 final String lastWord = batchInputText.substring(indexOfLastSpace); 1783 mWordComposer.setBatchInputWord(lastWord); 1784 mConnection.setComposingText(lastWord, 1); 1785 } else { 1786 mWordComposer.setBatchInputWord(batchInputText); 1787 mConnection.setComposingText(batchInputText, 1); 1788 } 1789 mConnection.endBatchEdit(); 1790 // Space state must be updated before calling updateShiftState 1791 mSpaceState = SpaceState.PHANTOM; 1792 keyboardSwitcher.requestUpdatingShiftState(getCurrentAutoCapsState(settingsValues), 1793 getCurrentRecapitalizeState()); 1794 } 1795 1796 /** 1797 * Commit the typed string to the editor. 1798 * 1799 * This is typically called when we should commit the currently composing word without applying 1800 * auto-correction to it. Typically, we come here upon pressing a separator when the keyboard 1801 * is configured to not do auto-correction at all (because of the settings or the properties of 1802 * the editor). In this case, `separatorString' is set to the separator that was pressed. 1803 * We also come here in a variety of cases with external user action. For example, when the 1804 * cursor is moved while there is a composition, or when the keyboard is closed, or when the 1805 * user presses the Send button for an SMS, we don't auto-correct as that would be unexpected. 1806 * In this case, `separatorString' is set to NOT_A_SEPARATOR. 1807 * 1808 * @param settingsValues the current values of the settings. 1809 * @param separatorString the separator that's causing the commit, or NOT_A_SEPARATOR if none. 1810 */ 1811 // TODO: Make this private 1812 public void commitTyped(final SettingsValues settingsValues, final String separatorString) { 1813 if (!mWordComposer.isComposingWord()) return; 1814 final String typedWord = mWordComposer.getTypedWord(); 1815 if (typedWord.length() > 0) { 1816 commitChosenWord(settingsValues, typedWord, 1817 LastComposedWord.COMMIT_TYPE_USER_TYPED_WORD, separatorString); 1818 } 1819 } 1820 1821 /** 1822 * Commit the current auto-correction. 1823 * 1824 * This will commit the best guess of the keyboard regarding what the user meant by typing 1825 * the currently composing word. The IME computes suggestions and assigns a confidence score 1826 * to each of them; when it's confident enough in one suggestion, it replaces the typed string 1827 * by this suggestion at commit time. When it's not confident enough, or when it has no 1828 * suggestions, or when the settings or environment does not allow for auto-correction, then 1829 * this method just commits the typed string. 1830 * Note that if suggestions are currently being computed in the background, this method will 1831 * block until the computation returns. This is necessary for consistency (it would be very 1832 * strange if pressing space would commit a different word depending on how fast you press). 1833 * 1834 * @param settingsValues the current value of the settings. 1835 * @param separator the separator that's causing the commit to happen. 1836 */ 1837 private void commitCurrentAutoCorrection(final SettingsValues settingsValues, 1838 final String separator, 1839 // TODO: Remove this argument. 1840 final LatinIME.UIHandler handler) { 1841 // Complete any pending suggestions query first 1842 if (handler.hasPendingUpdateSuggestions()) { 1843 handler.cancelUpdateSuggestionStrip(); 1844 performUpdateSuggestionStripSync(settingsValues); 1845 } 1846 final String typedAutoCorrection = mWordComposer.getAutoCorrectionOrNull(); 1847 final String typedWord = mWordComposer.getTypedWord(); 1848 final String autoCorrection = (typedAutoCorrection != null) 1849 ? typedAutoCorrection : typedWord; 1850 if (autoCorrection != null) { 1851 if (TextUtils.isEmpty(typedWord)) { 1852 throw new RuntimeException("We have an auto-correction but the typed word " 1853 + "is empty? Impossible! I must commit suicide."); 1854 } 1855 commitChosenWord(settingsValues, autoCorrection, 1856 LastComposedWord.COMMIT_TYPE_DECIDED_WORD, separator); 1857 if (!typedWord.equals(autoCorrection)) { 1858 // This will make the correction flash for a short while as a visual clue 1859 // to the user that auto-correction happened. It has no other effect; in particular 1860 // note that this won't affect the text inside the text field AT ALL: it only makes 1861 // the segment of text starting at the supplied index and running for the length 1862 // of the auto-correction flash. At this moment, the "typedWord" argument is 1863 // ignored by TextView. 1864 mConnection.commitCorrection(new CorrectionInfo( 1865 mConnection.getExpectedSelectionEnd() - autoCorrection.length(), 1866 typedWord, autoCorrection)); 1867 } 1868 } 1869 } 1870 1871 /** 1872 * Commits the chosen word to the text field and saves it for later retrieval. 1873 * 1874 * @param settingsValues the current values of the settings. 1875 * @param chosenWord the word we want to commit. 1876 * @param commitType the type of the commit, as one of LastComposedWord.COMMIT_TYPE_* 1877 * @param separatorString the separator that's causing the commit, or NOT_A_SEPARATOR if none. 1878 */ 1879 private void commitChosenWord(final SettingsValues settingsValues, final String chosenWord, 1880 final int commitType, final String separatorString) { 1881 final SuggestedWords suggestedWords = mSuggestedWords; 1882 final CharSequence chosenWordWithSuggestions = 1883 SuggestionSpanUtils.getTextWithSuggestionSpan(mLatinIME, chosenWord, 1884 suggestedWords); 1885 // When we are composing word, get previous words information from the 2nd previous word 1886 // because the 1st previous word is the word to be committed. Otherwise get previous words 1887 // information from the 1st previous word. 1888 final PrevWordsInfo prevWordsInfo = mConnection.getPrevWordsInfoFromNthPreviousWord( 1889 settingsValues.mSpacingAndPunctuations, mWordComposer.isComposingWord() ? 2 : 1); 1890 mConnection.commitText(chosenWordWithSuggestions, 1); 1891 // Add the word to the user history dictionary 1892 performAdditionToUserHistoryDictionary(settingsValues, chosenWord, prevWordsInfo); 1893 // TODO: figure out here if this is an auto-correct or if the best word is actually 1894 // what user typed. Note: currently this is done much later in 1895 // LastComposedWord#didCommitTypedWord by string equality of the remembered 1896 // strings. 1897 mLastComposedWord = mWordComposer.commitWord(commitType, 1898 chosenWordWithSuggestions, separatorString, prevWordsInfo); 1899 } 1900 1901 /** 1902 * Retry resetting caches in the rich input connection. 1903 * 1904 * When the editor can't be accessed we can't reset the caches, so we schedule a retry. 1905 * This method handles the retry, and re-schedules a new retry if we still can't access. 1906 * We only retry up to 5 times before giving up. 1907 * 1908 * @param settingsValues the current values of the settings. 1909 * @param tryResumeSuggestions Whether we should resume suggestions or not. 1910 * @param remainingTries How many times we may try again before giving up. 1911 * @return whether true if the caches were successfully reset, false otherwise. 1912 */ 1913 // TODO: make this private 1914 public boolean retryResetCachesAndReturnSuccess(final SettingsValues settingsValues, 1915 final boolean tryResumeSuggestions, final int remainingTries, 1916 // TODO: remove these arguments 1917 final LatinIME.UIHandler handler) { 1918 final boolean shouldFinishComposition = mConnection.hasSelection() 1919 || !mConnection.isCursorPositionKnown(); 1920 if (!mConnection.resetCachesUponCursorMoveAndReturnSuccess( 1921 mConnection.getExpectedSelectionStart(), mConnection.getExpectedSelectionEnd(), 1922 shouldFinishComposition)) { 1923 if (0 < remainingTries) { 1924 handler.postResetCaches(tryResumeSuggestions, remainingTries - 1); 1925 return false; 1926 } 1927 // If remainingTries is 0, we should stop waiting for new tries, however we'll still 1928 // return true as we need to perform other tasks (for example, loading the keyboard). 1929 } 1930 mConnection.tryFixLyingCursorPosition(); 1931 if (tryResumeSuggestions) { 1932 // This is triggered when starting input anew, so we want to include the resumed 1933 // word in suggestions. 1934 handler.postResumeSuggestions(true /* shouldIncludeResumedWordInSuggestions */); 1935 } 1936 return true; 1937 } 1938 1939 public void getSuggestedWords(final SettingsValues settingsValues, 1940 final ProximityInfo proximityInfo, final int keyboardShiftMode, final int sessionId, 1941 final int sequenceNumber, final OnGetSuggestedWordsCallback callback) { 1942 mWordComposer.adviseCapitalizedModeBeforeFetchingSuggestions( 1943 getActualCapsMode(settingsValues, keyboardShiftMode)); 1944 mSuggest.getSuggestedWords(mWordComposer, 1945 getPrevWordsInfoFromNthPreviousWordForSuggestion( 1946 settingsValues.mSpacingAndPunctuations, 1947 // Get the word on which we should search the bigrams. If we are composing 1948 // a word, it's whatever is *before* the half-committed word in the buffer, 1949 // hence 2; if we aren't, we should just skip whitespace if any, so 1. 1950 mWordComposer.isComposingWord() ? 2 : 1), 1951 proximityInfo, settingsValues.mBlockPotentiallyOffensive, 1952 settingsValues.mAutoCorrectionEnabled, 1953 settingsValues.mAdditionalFeaturesSettingValues, 1954 sessionId, sequenceNumber, callback); 1955 } 1956} 1957