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