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