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