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