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