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