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