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