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