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