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