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