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