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