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