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