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