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