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