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