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