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