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