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