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