LatinIME.java revision fb955693d4bb0c8d39092250a4208e385b8a31a7
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License. You may obtain a copy of
6 * 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, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations under
14 * the License.
15 */
16
17package com.android.inputmethod.latin;
18
19import static com.android.inputmethod.latin.Constants.ImeOption.FORCE_ASCII;
20import static com.android.inputmethod.latin.Constants.ImeOption.NO_MICROPHONE;
21import static com.android.inputmethod.latin.Constants.ImeOption.NO_MICROPHONE_COMPAT;
22
23import android.app.Activity;
24import android.app.AlertDialog;
25import android.content.BroadcastReceiver;
26import android.content.Context;
27import android.content.DialogInterface;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.SharedPreferences;
31import android.content.pm.ApplicationInfo;
32import android.content.res.Configuration;
33import android.content.res.Resources;
34import android.graphics.Rect;
35import android.inputmethodservice.InputMethodService;
36import android.media.AudioManager;
37import android.net.ConnectivityManager;
38import android.os.Debug;
39import android.os.IBinder;
40import android.os.Message;
41import android.os.SystemClock;
42import android.preference.PreferenceManager;
43import android.text.InputType;
44import android.text.TextUtils;
45import android.util.Log;
46import android.util.PrintWriterPrinter;
47import android.util.Printer;
48import android.view.KeyCharacterMap;
49import android.view.KeyEvent;
50import android.view.View;
51import android.view.ViewGroup.LayoutParams;
52import android.view.Window;
53import android.view.WindowManager;
54import android.view.inputmethod.CompletionInfo;
55import android.view.inputmethod.CorrectionInfo;
56import android.view.inputmethod.EditorInfo;
57import android.view.inputmethod.InputMethodSubtype;
58
59import com.android.inputmethod.accessibility.AccessibilityUtils;
60import com.android.inputmethod.accessibility.AccessibleKeyboardViewProxy;
61import com.android.inputmethod.compat.CompatUtils;
62import com.android.inputmethod.compat.InputMethodManagerCompatWrapper;
63import com.android.inputmethod.compat.InputMethodServiceCompatUtils;
64import com.android.inputmethod.compat.SuggestionSpanUtils;
65import com.android.inputmethod.keyboard.KeyDetector;
66import com.android.inputmethod.keyboard.Keyboard;
67import com.android.inputmethod.keyboard.KeyboardActionListener;
68import com.android.inputmethod.keyboard.KeyboardId;
69import com.android.inputmethod.keyboard.KeyboardSwitcher;
70import com.android.inputmethod.keyboard.KeyboardView;
71import com.android.inputmethod.keyboard.MainKeyboardView;
72import com.android.inputmethod.latin.LocaleUtils.RunInLocale;
73import com.android.inputmethod.latin.define.ProductionFlag;
74import com.android.inputmethod.latin.suggestions.SuggestionStripView;
75import com.android.inputmethod.research.ResearchLogger;
76
77import java.io.FileDescriptor;
78import java.io.PrintWriter;
79import java.util.ArrayList;
80import java.util.Locale;
81
82/**
83 * Input method implementation for Qwerty'ish keyboard.
84 */
85public class LatinIME extends InputMethodService implements KeyboardActionListener,
86        SuggestionStripView.Listener, TargetApplicationGetter.OnTargetApplicationKnownListener,
87        Suggest.SuggestInitializationListener {
88    private static final String TAG = LatinIME.class.getSimpleName();
89    private static final boolean TRACE = false;
90    private static boolean DEBUG;
91
92    private static final int EXTENDED_TOUCHABLE_REGION_HEIGHT = 100;
93
94    // How many continuous deletes at which to start deleting at a higher speed.
95    private static final int DELETE_ACCELERATE_AT = 20;
96    // Key events coming any faster than this are long-presses.
97    private static final int QUICK_PRESS = 200;
98
99    private static final int PENDING_IMS_CALLBACK_DURATION = 800;
100
101    /**
102     * The name of the scheme used by the Package Manager to warn of a new package installation,
103     * replacement or removal.
104     */
105    private static final String SCHEME_PACKAGE = "package";
106
107    private static final int SPACE_STATE_NONE = 0;
108    // Double space: the state where the user pressed space twice quickly, which LatinIME
109    // resolved as period-space. Undoing this converts the period to a space.
110    private static final int SPACE_STATE_DOUBLE = 1;
111    // Swap punctuation: the state where a weak space and a punctuation from the suggestion strip
112    // have just been swapped. Undoing this swaps them back; the space is still considered weak.
113    private static final int SPACE_STATE_SWAP_PUNCTUATION = 2;
114    // Weak space: a space that should be swapped only by suggestion strip punctuation. Weak
115    // spaces happen when the user presses space, accepting the current suggestion (whether
116    // it's an auto-correction or not).
117    private static final int SPACE_STATE_WEAK = 3;
118    // Phantom space: a not-yet-inserted space that should get inserted on the next input,
119    // character provided it's not a separator. If it's a separator, the phantom space is dropped.
120    // Phantom spaces happen when a user chooses a word from the suggestion strip.
121    private static final int SPACE_STATE_PHANTOM = 4;
122
123    // Current space state of the input method. This can be any of the above constants.
124    private int mSpaceState;
125
126    private SettingsValues mCurrentSettings;
127
128    private View mExtractArea;
129    private View mKeyPreviewBackingView;
130    private View mSuggestionsContainer;
131    private SuggestionStripView mSuggestionStripView;
132    /* package for tests */ Suggest mSuggest;
133    private CompletionInfo[] mApplicationSpecifiedCompletions;
134    private ApplicationInfo mTargetApplicationInfo;
135
136    private InputMethodManagerCompatWrapper mImm;
137    private Resources mResources;
138    private SharedPreferences mPrefs;
139    /* package for tests */ final KeyboardSwitcher mKeyboardSwitcher;
140    private final SubtypeSwitcher mSubtypeSwitcher;
141    private boolean mShouldSwitchToLastSubtype = true;
142
143    private boolean mIsMainDictionaryAvailable;
144    private UserBinaryDictionary mUserDictionary;
145    private UserHistoryDictionary mUserHistoryDictionary;
146    private boolean mIsUserDictionaryAvailable;
147
148    private LastComposedWord mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD;
149    private WordComposer mWordComposer = new WordComposer();
150    private RichInputConnection mConnection = new RichInputConnection(this);
151
152    // Keep track of the last selection range to decide if we need to show word alternatives
153    private static final int NOT_A_CURSOR_POSITION = -1;
154    private int mLastSelectionStart = NOT_A_CURSOR_POSITION;
155    private int mLastSelectionEnd = NOT_A_CURSOR_POSITION;
156
157    // Whether we are expecting an onUpdateSelection event to fire. If it does when we don't
158    // "expect" it, it means the user actually moved the cursor.
159    private boolean mExpectingUpdateSelection;
160    private int mDeleteCount;
161    private long mLastKeyTime;
162
163    private AudioAndHapticFeedbackManager mFeedbackManager;
164
165    // Member variables for remembering the current device orientation.
166    private int mDisplayOrientation;
167
168    // Object for reacting to adding/removing a dictionary pack.
169    private BroadcastReceiver mDictionaryPackInstallReceiver =
170            new DictionaryPackInstallBroadcastReceiver(this);
171
172    // Keeps track of most recently inserted text (multi-character key) for reverting
173    private CharSequence mEnteredText;
174
175    private boolean mIsAutoCorrectionIndicatorOn;
176
177    private AlertDialog mOptionsDialog;
178
179    private final boolean mIsHardwareAcceleratedDrawingEnabled;
180
181    public final UIHandler mHandler = new UIHandler(this);
182
183    public static class UIHandler extends StaticInnerHandlerWrapper<LatinIME> {
184        private static final int MSG_UPDATE_SHIFT_STATE = 1;
185        private static final int MSG_PENDING_IMS_CALLBACK = 6;
186        private static final int MSG_UPDATE_SUGGESTION_STRIP = 7;
187
188        private int mDelayUpdateSuggestions;
189        private int mDelayUpdateShiftState;
190        private long mDoubleSpacesTurnIntoPeriodTimeout;
191        private long mDoubleSpaceTimerStart;
192
193        public UIHandler(LatinIME outerInstance) {
194            super(outerInstance);
195        }
196
197        public void onCreate() {
198            final Resources res = getOuterInstance().getResources();
199            mDelayUpdateSuggestions =
200                    res.getInteger(R.integer.config_delay_update_suggestions);
201            mDelayUpdateShiftState =
202                    res.getInteger(R.integer.config_delay_update_shift_state);
203            mDoubleSpacesTurnIntoPeriodTimeout = res.getInteger(
204                    R.integer.config_double_spaces_turn_into_period_timeout);
205        }
206
207        @Override
208        public void handleMessage(Message msg) {
209            final LatinIME latinIme = getOuterInstance();
210            final KeyboardSwitcher switcher = latinIme.mKeyboardSwitcher;
211            switch (msg.what) {
212            case MSG_UPDATE_SUGGESTION_STRIP:
213                latinIme.updateSuggestionStrip();
214                break;
215            case MSG_UPDATE_SHIFT_STATE:
216                switcher.updateShiftState();
217                break;
218            }
219        }
220
221        public void postUpdateSuggestionStrip() {
222            sendMessageDelayed(obtainMessage(MSG_UPDATE_SUGGESTION_STRIP), mDelayUpdateSuggestions);
223        }
224
225        public void cancelUpdateSuggestionStrip() {
226            removeMessages(MSG_UPDATE_SUGGESTION_STRIP);
227        }
228
229        public boolean hasPendingUpdateSuggestions() {
230            return hasMessages(MSG_UPDATE_SUGGESTION_STRIP);
231        }
232
233        public void postUpdateShiftState() {
234            removeMessages(MSG_UPDATE_SHIFT_STATE);
235            sendMessageDelayed(obtainMessage(MSG_UPDATE_SHIFT_STATE), mDelayUpdateShiftState);
236        }
237
238        public void cancelUpdateShiftState() {
239            removeMessages(MSG_UPDATE_SHIFT_STATE);
240        }
241
242        public void startDoubleSpacesTimer() {
243            mDoubleSpaceTimerStart = SystemClock.uptimeMillis();
244        }
245
246        public void cancelDoubleSpacesTimer() {
247            mDoubleSpaceTimerStart = 0;
248        }
249
250        public boolean isAcceptingDoubleSpaces() {
251            return SystemClock.uptimeMillis() - mDoubleSpaceTimerStart
252                    < mDoubleSpacesTurnIntoPeriodTimeout;
253        }
254
255        // Working variables for the following methods.
256        private boolean mIsOrientationChanging;
257        private boolean mPendingSuccessiveImsCallback;
258        private boolean mHasPendingStartInput;
259        private boolean mHasPendingFinishInputView;
260        private boolean mHasPendingFinishInput;
261        private EditorInfo mAppliedEditorInfo;
262
263        public void startOrientationChanging() {
264            removeMessages(MSG_PENDING_IMS_CALLBACK);
265            resetPendingImsCallback();
266            mIsOrientationChanging = true;
267            final LatinIME latinIme = getOuterInstance();
268            if (latinIme.isInputViewShown()) {
269                latinIme.mKeyboardSwitcher.saveKeyboardState();
270            }
271        }
272
273        private void resetPendingImsCallback() {
274            mHasPendingFinishInputView = false;
275            mHasPendingFinishInput = false;
276            mHasPendingStartInput = false;
277        }
278
279        private void executePendingImsCallback(LatinIME latinIme, EditorInfo editorInfo,
280                boolean restarting) {
281            if (mHasPendingFinishInputView)
282                latinIme.onFinishInputViewInternal(mHasPendingFinishInput);
283            if (mHasPendingFinishInput)
284                latinIme.onFinishInputInternal();
285            if (mHasPendingStartInput)
286                latinIme.onStartInputInternal(editorInfo, restarting);
287            resetPendingImsCallback();
288        }
289
290        public void onStartInput(EditorInfo editorInfo, boolean restarting) {
291            if (hasMessages(MSG_PENDING_IMS_CALLBACK)) {
292                // Typically this is the second onStartInput after orientation changed.
293                mHasPendingStartInput = true;
294            } else {
295                if (mIsOrientationChanging && restarting) {
296                    // This is the first onStartInput after orientation changed.
297                    mIsOrientationChanging = false;
298                    mPendingSuccessiveImsCallback = true;
299                }
300                final LatinIME latinIme = getOuterInstance();
301                executePendingImsCallback(latinIme, editorInfo, restarting);
302                latinIme.onStartInputInternal(editorInfo, restarting);
303            }
304        }
305
306        public void onStartInputView(EditorInfo editorInfo, boolean restarting) {
307            if (hasMessages(MSG_PENDING_IMS_CALLBACK)
308                    && KeyboardId.equivalentEditorInfoForKeyboard(editorInfo, mAppliedEditorInfo)) {
309                // Typically this is the second onStartInputView after orientation changed.
310                resetPendingImsCallback();
311            } else {
312                if (mPendingSuccessiveImsCallback) {
313                    // This is the first onStartInputView after orientation changed.
314                    mPendingSuccessiveImsCallback = false;
315                    resetPendingImsCallback();
316                    sendMessageDelayed(obtainMessage(MSG_PENDING_IMS_CALLBACK),
317                            PENDING_IMS_CALLBACK_DURATION);
318                }
319                final LatinIME latinIme = getOuterInstance();
320                executePendingImsCallback(latinIme, editorInfo, restarting);
321                latinIme.onStartInputViewInternal(editorInfo, restarting);
322                mAppliedEditorInfo = editorInfo;
323            }
324        }
325
326        public void onFinishInputView(boolean finishingInput) {
327            if (hasMessages(MSG_PENDING_IMS_CALLBACK)) {
328                // Typically this is the first onFinishInputView after orientation changed.
329                mHasPendingFinishInputView = true;
330            } else {
331                final LatinIME latinIme = getOuterInstance();
332                latinIme.onFinishInputViewInternal(finishingInput);
333                mAppliedEditorInfo = null;
334            }
335        }
336
337        public void onFinishInput() {
338            if (hasMessages(MSG_PENDING_IMS_CALLBACK)) {
339                // Typically this is the first onFinishInput after orientation changed.
340                mHasPendingFinishInput = true;
341            } else {
342                final LatinIME latinIme = getOuterInstance();
343                executePendingImsCallback(latinIme, null, false);
344                latinIme.onFinishInputInternal();
345            }
346        }
347    }
348
349    public LatinIME() {
350        super();
351        mSubtypeSwitcher = SubtypeSwitcher.getInstance();
352        mKeyboardSwitcher = KeyboardSwitcher.getInstance();
353        mIsHardwareAcceleratedDrawingEnabled =
354                InputMethodServiceCompatUtils.enableHardwareAcceleration(this);
355        Log.i(TAG, "Hardware accelerated drawing: " + mIsHardwareAcceleratedDrawingEnabled);
356    }
357
358    @Override
359    public void onCreate() {
360        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
361        mPrefs = prefs;
362        LatinImeLogger.init(this, prefs);
363        if (ProductionFlag.IS_EXPERIMENTAL) {
364            ResearchLogger.getInstance().init(this, prefs, mKeyboardSwitcher);
365        }
366        InputMethodManagerCompatWrapper.init(this);
367        SubtypeSwitcher.init(this);
368        KeyboardSwitcher.init(this, prefs);
369        AccessibilityUtils.init(this);
370
371        super.onCreate();
372
373        mImm = InputMethodManagerCompatWrapper.getInstance();
374        mHandler.onCreate();
375        DEBUG = LatinImeLogger.sDBG;
376
377        final Resources res = getResources();
378        mResources = res;
379
380        loadSettings();
381
382        ImfUtils.setAdditionalInputMethodSubtypes(this, mCurrentSettings.getAdditionalSubtypes());
383
384        Utils.GCUtils.getInstance().reset();
385        boolean tryGC = true;
386        // Shouldn't this be removed? I think that from Honeycomb on, the GC is now actually working
387        // as expected and this code is useless.
388        for (int i = 0; i < Utils.GCUtils.GC_TRY_LOOP_MAX && tryGC; ++i) {
389            try {
390                initSuggest();
391                tryGC = false;
392            } catch (OutOfMemoryError e) {
393                tryGC = Utils.GCUtils.getInstance().tryGCOrWait("InitSuggest", e);
394            }
395        }
396
397        mDisplayOrientation = res.getConfiguration().orientation;
398
399        // Register to receive ringer mode change and network state change.
400        // Also receive installation and removal of a dictionary pack.
401        final IntentFilter filter = new IntentFilter();
402        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
403        filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION);
404        registerReceiver(mReceiver, filter);
405
406        final IntentFilter packageFilter = new IntentFilter();
407        packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
408        packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
409        packageFilter.addDataScheme(SCHEME_PACKAGE);
410        registerReceiver(mDictionaryPackInstallReceiver, packageFilter);
411
412        final IntentFilter newDictFilter = new IntentFilter();
413        newDictFilter.addAction(
414                DictionaryPackInstallBroadcastReceiver.NEW_DICTIONARY_INTENT_ACTION);
415        registerReceiver(mDictionaryPackInstallReceiver, newDictFilter);
416    }
417
418    // Has to be package-visible for unit tests
419    /* package */ void loadSettings() {
420        // Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged()
421        // is not guaranteed. It may even be called at the same time on a different thread.
422        if (null == mPrefs) mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
423        final InputAttributes inputAttributes =
424                new InputAttributes(getCurrentInputEditorInfo(), isFullscreenMode());
425        final RunInLocale<SettingsValues> job = new RunInLocale<SettingsValues>() {
426            @Override
427            protected SettingsValues job(Resources res) {
428                return new SettingsValues(mPrefs, inputAttributes, LatinIME.this);
429            }
430        };
431        mCurrentSettings = job.runInLocale(mResources, mSubtypeSwitcher.getCurrentSubtypeLocale());
432        mFeedbackManager = new AudioAndHapticFeedbackManager(this, mCurrentSettings);
433        resetContactsDictionary(null == mSuggest ? null : mSuggest.getContactsDictionary());
434    }
435
436    @Override
437    public void onUpdateMainDictionaryAvailability(boolean isMainDictionaryAvailable) {
438        mIsMainDictionaryAvailable = isMainDictionaryAvailable;
439        updateKeyboardViewGestureHandlingModeByMainDictionaryAvailability();
440    }
441
442    private void initSuggest() {
443        final Locale subtypeLocale = mSubtypeSwitcher.getCurrentSubtypeLocale();
444        final String localeStr = subtypeLocale.toString();
445
446        final ContactsBinaryDictionary oldContactsDictionary;
447        if (mSuggest != null) {
448            oldContactsDictionary = mSuggest.getContactsDictionary();
449            mSuggest.close();
450        } else {
451            oldContactsDictionary = null;
452        }
453        mSuggest = new Suggest(this /* Context */, subtypeLocale,
454                this /* SuggestInitializationListener */);
455        if (mCurrentSettings.mCorrectionEnabled) {
456            mSuggest.setAutoCorrectionThreshold(mCurrentSettings.mAutoCorrectionThreshold);
457        }
458
459        mIsMainDictionaryAvailable = DictionaryFactory.isDictionaryAvailable(this, subtypeLocale);
460        if (ProductionFlag.IS_EXPERIMENTAL) {
461            ResearchLogger.getInstance().initSuggest(mSuggest);
462        }
463
464        mUserDictionary = new UserBinaryDictionary(this, localeStr);
465        mIsUserDictionaryAvailable = mUserDictionary.isEnabled();
466        mSuggest.setUserDictionary(mUserDictionary);
467
468        resetContactsDictionary(oldContactsDictionary);
469
470        // Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged()
471        // is not guaranteed. It may even be called at the same time on a different thread.
472        if (null == mPrefs) mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
473        mUserHistoryDictionary = UserHistoryDictionary.getInstance(this, localeStr, mPrefs);
474        mSuggest.setUserHistoryDictionary(mUserHistoryDictionary);
475    }
476
477    /**
478     * Resets the contacts dictionary in mSuggest according to the user settings.
479     *
480     * This method takes an optional contacts dictionary to use when the locale hasn't changed
481     * since the contacts dictionary can be opened or closed as necessary depending on the settings.
482     *
483     * @param oldContactsDictionary an optional dictionary to use, or null
484     */
485    private void resetContactsDictionary(final ContactsBinaryDictionary oldContactsDictionary) {
486        final boolean shouldSetDictionary = (null != mSuggest && mCurrentSettings.mUseContactsDict);
487
488        final ContactsBinaryDictionary dictionaryToUse;
489        if (!shouldSetDictionary) {
490            // Make sure the dictionary is closed. If it is already closed, this is a no-op,
491            // so it's safe to call it anyways.
492            if (null != oldContactsDictionary) oldContactsDictionary.close();
493            dictionaryToUse = null;
494        } else {
495            final Locale locale = mSubtypeSwitcher.getCurrentSubtypeLocale();
496            if (null != oldContactsDictionary) {
497                if (!oldContactsDictionary.mLocale.equals(locale)) {
498                    // If the locale has changed then recreate the contacts dictionary. This
499                    // allows locale dependent rules for handling bigram name predictions.
500                    oldContactsDictionary.close();
501                    dictionaryToUse = new ContactsBinaryDictionary(this, locale);
502                } else {
503                    // Make sure the old contacts dictionary is opened. If it is already open,
504                    // this is a no-op, so it's safe to call it anyways.
505                    oldContactsDictionary.reopen(this);
506                    dictionaryToUse = oldContactsDictionary;
507                }
508            } else {
509                dictionaryToUse = new ContactsBinaryDictionary(this, locale);
510            }
511        }
512
513        if (null != mSuggest) {
514            mSuggest.setContactsDictionary(dictionaryToUse);
515        }
516    }
517
518    /* package private */ void resetSuggestMainDict() {
519        final Locale subtypeLocale = mSubtypeSwitcher.getCurrentSubtypeLocale();
520        mSuggest.resetMainDict(this, subtypeLocale);
521        mIsMainDictionaryAvailable = DictionaryFactory.isDictionaryAvailable(this, subtypeLocale);
522    }
523
524    @Override
525    public void onDestroy() {
526        if (mSuggest != null) {
527            mSuggest.close();
528            mSuggest = null;
529        }
530        unregisterReceiver(mReceiver);
531        unregisterReceiver(mDictionaryPackInstallReceiver);
532        LatinImeLogger.commit();
533        LatinImeLogger.onDestroy();
534        super.onDestroy();
535    }
536
537    @Override
538    public void onConfigurationChanged(Configuration conf) {
539        mSubtypeSwitcher.onConfigurationChanged(conf);
540        // If orientation changed while predicting, commit the change
541        if (mDisplayOrientation != conf.orientation) {
542            mDisplayOrientation = conf.orientation;
543            mHandler.startOrientationChanging();
544            mConnection.beginBatchEdit();
545            commitTyped(LastComposedWord.NOT_A_SEPARATOR);
546            mConnection.finishComposingText();
547            mConnection.endBatchEdit();
548            if (isShowingOptionDialog())
549                mOptionsDialog.dismiss();
550        }
551        super.onConfigurationChanged(conf);
552    }
553
554    @Override
555    public View onCreateInputView() {
556        return mKeyboardSwitcher.onCreateInputView();
557    }
558
559    @Override
560    public void setInputView(View view) {
561        super.setInputView(view);
562        mExtractArea = getWindow().getWindow().getDecorView()
563                .findViewById(android.R.id.extractArea);
564        mKeyPreviewBackingView = view.findViewById(R.id.key_preview_backing);
565        mSuggestionsContainer = view.findViewById(R.id.suggestions_container);
566        mSuggestionStripView = (SuggestionStripView)view.findViewById(R.id.suggestion_strip_view);
567        if (mSuggestionStripView != null)
568            mSuggestionStripView.setListener(this, view);
569        if (LatinImeLogger.sVISUALDEBUG) {
570            mKeyPreviewBackingView.setBackgroundColor(0x10FF0000);
571        }
572    }
573
574    @Override
575    public void setCandidatesView(View view) {
576        // To ensure that CandidatesView will never be set.
577        return;
578    }
579
580    @Override
581    public void onStartInput(EditorInfo editorInfo, boolean restarting) {
582        mHandler.onStartInput(editorInfo, restarting);
583    }
584
585    @Override
586    public void onStartInputView(EditorInfo editorInfo, boolean restarting) {
587        mHandler.onStartInputView(editorInfo, restarting);
588    }
589
590    @Override
591    public void onFinishInputView(boolean finishingInput) {
592        mHandler.onFinishInputView(finishingInput);
593    }
594
595    @Override
596    public void onFinishInput() {
597        mHandler.onFinishInput();
598    }
599
600    @Override
601    public void onCurrentInputMethodSubtypeChanged(InputMethodSubtype subtype) {
602        // Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged()
603        // is not guaranteed. It may even be called at the same time on a different thread.
604        mSubtypeSwitcher.updateSubtype(subtype);
605    }
606
607    private void onStartInputInternal(EditorInfo editorInfo, boolean restarting) {
608        super.onStartInput(editorInfo, restarting);
609    }
610
611    @SuppressWarnings("deprecation")
612    private void onStartInputViewInternal(EditorInfo editorInfo, boolean restarting) {
613        super.onStartInputView(editorInfo, restarting);
614        final KeyboardSwitcher switcher = mKeyboardSwitcher;
615        MainKeyboardView inputView = switcher.getKeyboardView();
616
617        if (editorInfo == null) {
618            Log.e(TAG, "Null EditorInfo in onStartInputView()");
619            if (LatinImeLogger.sDBG) {
620                throw new NullPointerException("Null EditorInfo in onStartInputView()");
621            }
622            return;
623        }
624        if (DEBUG) {
625            Log.d(TAG, "onStartInputView: editorInfo:"
626                    + String.format("inputType=0x%08x imeOptions=0x%08x",
627                            editorInfo.inputType, editorInfo.imeOptions));
628            Log.d(TAG, "All caps = "
629                    + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0)
630                    + ", sentence caps = "
631                    + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0)
632                    + ", word caps = "
633                    + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_WORDS) != 0));
634        }
635        if (ProductionFlag.IS_EXPERIMENTAL) {
636            ResearchLogger.latinIME_onStartInputViewInternal(editorInfo, mPrefs);
637        }
638        if (InputAttributes.inPrivateImeOptions(null, NO_MICROPHONE_COMPAT, editorInfo)) {
639            Log.w(TAG, "Deprecated private IME option specified: "
640                    + editorInfo.privateImeOptions);
641            Log.w(TAG, "Use " + getPackageName() + "." + NO_MICROPHONE + " instead");
642        }
643        if (InputAttributes.inPrivateImeOptions(getPackageName(), FORCE_ASCII, editorInfo)) {
644            Log.w(TAG, "Deprecated private IME option specified: "
645                    + editorInfo.privateImeOptions);
646            Log.w(TAG, "Use EditorInfo.IME_FLAG_FORCE_ASCII flag instead");
647        }
648
649        mTargetApplicationInfo =
650                TargetApplicationGetter.getCachedApplicationInfo(editorInfo.packageName);
651        if (null == mTargetApplicationInfo) {
652            new TargetApplicationGetter(this /* context */, this /* listener */)
653                    .execute(editorInfo.packageName);
654        }
655
656        LatinImeLogger.onStartInputView(editorInfo);
657        // In landscape mode, this method gets called without the input view being created.
658        if (inputView == null) {
659            return;
660        }
661
662        // Forward this event to the accessibility utilities, if enabled.
663        final AccessibilityUtils accessUtils = AccessibilityUtils.getInstance();
664        if (accessUtils.isTouchExplorationEnabled()) {
665            accessUtils.onStartInputViewInternal(editorInfo, restarting);
666        }
667
668        if (!restarting) {
669            mSubtypeSwitcher.updateParametersOnStartInputView();
670        }
671
672        // The EditorInfo might have a flag that affects fullscreen mode.
673        // Note: This call should be done by InputMethodService?
674        updateFullscreenMode();
675        mApplicationSpecifiedCompletions = null;
676
677        final boolean selectionChanged = mLastSelectionStart != editorInfo.initialSelStart
678                || mLastSelectionEnd != editorInfo.initialSelEnd;
679        if (!restarting || selectionChanged) {
680            // If the selection changed, we reset the input state. Essentially, we come here with
681            // restarting == true when the app called setText() or similar. We should reset the
682            // state if the app set the text to something else, but keep it if it set a suggestion
683            // or something.
684            mEnteredText = null;
685            resetComposingState(true /* alsoResetLastComposedWord */);
686            mDeleteCount = 0;
687            mSpaceState = SPACE_STATE_NONE;
688
689            if (mSuggestionStripView != null) {
690                mSuggestionStripView.clear();
691            }
692        }
693
694        if (!restarting) {
695            inputView.closing();
696            loadSettings();
697
698            if (mSuggest != null && mCurrentSettings.mCorrectionEnabled) {
699                mSuggest.setAutoCorrectionThreshold(mCurrentSettings.mAutoCorrectionThreshold);
700            }
701
702            switcher.loadKeyboard(editorInfo, mCurrentSettings);
703            updateKeyboardViewGestureHandlingModeByMainDictionaryAvailability();
704        }
705        setSuggestionStripShownInternal(
706                isSuggestionsStripVisible(), /* needsInputViewShown */ false);
707
708        mLastSelectionStart = editorInfo.initialSelStart;
709        mLastSelectionEnd = editorInfo.initialSelEnd;
710        // If we come here something in the text state is very likely to have changed.
711        // We should update the shift state regardless of whether we are restarting or not, because
712        // this is not perceived as a layout change that may be disruptive like we may have with
713        // switcher.loadKeyboard; in apps like Talk, we come here when the text is sent and the
714        // field gets emptied and we need to re-evaluate the shift state, but not the whole layout
715        // which would be disruptive.
716        mKeyboardSwitcher.updateShiftState();
717
718        mHandler.cancelUpdateSuggestionStrip();
719        mHandler.cancelDoubleSpacesTimer();
720
721        inputView.setKeyPreviewPopupEnabled(mCurrentSettings.mKeyPreviewPopupOn,
722                mCurrentSettings.mKeyPreviewPopupDismissDelay);
723
724        if (TRACE) Debug.startMethodTracing("/data/trace/latinime");
725    }
726
727    // Callback for the TargetApplicationGetter
728    @Override
729    public void onTargetApplicationKnown(final ApplicationInfo info) {
730        mTargetApplicationInfo = info;
731    }
732
733    @Override
734    public void onWindowHidden() {
735        if (ProductionFlag.IS_EXPERIMENTAL) {
736            ResearchLogger.latinIME_onWindowHidden(mLastSelectionStart, mLastSelectionEnd,
737                    getCurrentInputConnection());
738        }
739        super.onWindowHidden();
740        KeyboardView inputView = mKeyboardSwitcher.getKeyboardView();
741        if (inputView != null) inputView.closing();
742    }
743
744    private void onFinishInputInternal() {
745        super.onFinishInput();
746
747        LatinImeLogger.commit();
748        if (ProductionFlag.IS_EXPERIMENTAL) {
749            ResearchLogger.getInstance().latinIME_onFinishInputInternal();
750        }
751
752        KeyboardView inputView = mKeyboardSwitcher.getKeyboardView();
753        if (inputView != null) inputView.closing();
754    }
755
756    private void onFinishInputViewInternal(boolean finishingInput) {
757        super.onFinishInputView(finishingInput);
758        mKeyboardSwitcher.onFinishInputView();
759        KeyboardView inputView = mKeyboardSwitcher.getKeyboardView();
760        if (inputView != null) inputView.cancelAllMessages();
761        // Remove pending messages related to update suggestions
762        mHandler.cancelUpdateSuggestionStrip();
763    }
764
765    @Override
766    public void onUpdateSelection(int oldSelStart, int oldSelEnd,
767            int newSelStart, int newSelEnd,
768            int composingSpanStart, int composingSpanEnd) {
769        super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd,
770                composingSpanStart, composingSpanEnd);
771        if (DEBUG) {
772            Log.i(TAG, "onUpdateSelection: oss=" + oldSelStart
773                    + ", ose=" + oldSelEnd
774                    + ", lss=" + mLastSelectionStart
775                    + ", lse=" + mLastSelectionEnd
776                    + ", nss=" + newSelStart
777                    + ", nse=" + newSelEnd
778                    + ", cs=" + composingSpanStart
779                    + ", ce=" + composingSpanEnd);
780        }
781        if (ProductionFlag.IS_EXPERIMENTAL) {
782            final boolean expectingUpdateSelectionFromLogger =
783                    ResearchLogger.getAndClearLatinIMEExpectingUpdateSelection();
784            ResearchLogger.latinIME_onUpdateSelection(mLastSelectionStart, mLastSelectionEnd,
785                    oldSelStart, oldSelEnd, newSelStart, newSelEnd, composingSpanStart,
786                    composingSpanEnd, mExpectingUpdateSelection,
787                    expectingUpdateSelectionFromLogger, mConnection);
788            if (expectingUpdateSelectionFromLogger) {
789                // TODO: Investigate. Quitting now sounds wrong - we won't do the resetting work
790                return;
791            }
792        }
793
794        // TODO: refactor the following code to be less contrived.
795        // "newSelStart != composingSpanEnd" || "newSelEnd != composingSpanEnd" means
796        // that the cursor is not at the end of the composing span, or there is a selection.
797        // "mLastSelectionStart != newSelStart" means that the cursor is not in the same place
798        // as last time we were called (if there is a selection, it means the start hasn't
799        // changed, so it's the end that did).
800        final boolean selectionChanged = (newSelStart != composingSpanEnd
801                || newSelEnd != composingSpanEnd) && mLastSelectionStart != newSelStart;
802        // if composingSpanStart and composingSpanEnd are -1, it means there is no composing
803        // span in the view - we can use that to narrow down whether the cursor was moved
804        // by us or not. If we are composing a word but there is no composing span, then
805        // we know for sure the cursor moved while we were composing and we should reset
806        // the state.
807        final boolean noComposingSpan = composingSpanStart == -1 && composingSpanEnd == -1;
808        if (!mExpectingUpdateSelection) {
809            // TAKE CARE: there is a race condition when we enter this test even when the user
810            // did not explicitly move the cursor. This happens when typing fast, where two keys
811            // turn this flag on in succession and both onUpdateSelection() calls arrive after
812            // the second one - the first call successfully avoids this test, but the second one
813            // enters. For the moment we rely on noComposingSpan to further reduce the impact.
814
815            // TODO: the following is probably better done in resetEntireInputState().
816            // it should only happen when the cursor moved, and the very purpose of the
817            // test below is to narrow down whether this happened or not. Likewise with
818            // the call to postUpdateShiftState.
819            // We set this to NONE because after a cursor move, we don't want the space
820            // state-related special processing to kick in.
821            mSpaceState = SPACE_STATE_NONE;
822
823            if ((!mWordComposer.isComposingWord()) || selectionChanged || noComposingSpan) {
824                resetEntireInputState();
825            }
826
827            mHandler.postUpdateShiftState();
828        }
829        mExpectingUpdateSelection = false;
830        // TODO: Decide to call restartSuggestionsOnWordBeforeCursorIfAtEndOfWord() or not
831        // here. It would probably be too expensive to call directly here but we may want to post a
832        // message to delay it. The point would be to unify behavior between backspace to the
833        // end of a word and manually put the pointer at the end of the word.
834
835        // Make a note of the cursor position
836        mLastSelectionStart = newSelStart;
837        mLastSelectionEnd = newSelEnd;
838    }
839
840    /**
841     * This is called when the user has clicked on the extracted text view,
842     * when running in fullscreen mode.  The default implementation hides
843     * the suggestions view when this happens, but only if the extracted text
844     * editor has a vertical scroll bar because its text doesn't fit.
845     * Here we override the behavior due to the possibility that a re-correction could
846     * cause the suggestions strip to disappear and re-appear.
847     */
848    @Override
849    public void onExtractedTextClicked() {
850        if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) return;
851
852        super.onExtractedTextClicked();
853    }
854
855    /**
856     * This is called when the user has performed a cursor movement in the
857     * extracted text view, when it is running in fullscreen mode.  The default
858     * implementation hides the suggestions view when a vertical movement
859     * happens, but only if the extracted text editor has a vertical scroll bar
860     * because its text doesn't fit.
861     * Here we override the behavior due to the possibility that a re-correction could
862     * cause the suggestions strip to disappear and re-appear.
863     */
864    @Override
865    public void onExtractedCursorMovement(int dx, int dy) {
866        if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) return;
867
868        super.onExtractedCursorMovement(dx, dy);
869    }
870
871    @Override
872    public void hideWindow() {
873        LatinImeLogger.commit();
874        mKeyboardSwitcher.onHideWindow();
875
876        if (TRACE) Debug.stopMethodTracing();
877        if (mOptionsDialog != null && mOptionsDialog.isShowing()) {
878            mOptionsDialog.dismiss();
879            mOptionsDialog = null;
880        }
881        super.hideWindow();
882    }
883
884    @Override
885    public void onDisplayCompletions(CompletionInfo[] applicationSpecifiedCompletions) {
886        if (DEBUG) {
887            Log.i(TAG, "Received completions:");
888            if (applicationSpecifiedCompletions != null) {
889                for (int i = 0; i < applicationSpecifiedCompletions.length; i++) {
890                    Log.i(TAG, "  #" + i + ": " + applicationSpecifiedCompletions[i]);
891                }
892            }
893        }
894        if (ProductionFlag.IS_EXPERIMENTAL) {
895            ResearchLogger.latinIME_onDisplayCompletions(applicationSpecifiedCompletions);
896        }
897        if (!mCurrentSettings.isApplicationSpecifiedCompletionsOn()) return;
898        mApplicationSpecifiedCompletions = applicationSpecifiedCompletions;
899        if (applicationSpecifiedCompletions == null) {
900            clearSuggestionStrip();
901            return;
902        }
903
904        final ArrayList<SuggestedWords.SuggestedWordInfo> applicationSuggestedWords =
905                SuggestedWords.getFromApplicationSpecifiedCompletions(
906                        applicationSpecifiedCompletions);
907        final SuggestedWords suggestedWords = new SuggestedWords(
908                applicationSuggestedWords,
909                false /* typedWordValid */,
910                false /* hasAutoCorrectionCandidate */,
911                false /* isPunctuationSuggestions */,
912                false /* isObsoleteSuggestions */,
913                false /* isPrediction */);
914        // When in fullscreen mode, show completions generated by the application
915        final boolean isAutoCorrection = false;
916        setSuggestionStrip(suggestedWords, isAutoCorrection);
917        setAutoCorrectionIndicator(isAutoCorrection);
918        // TODO: is this the right thing to do? What should we auto-correct to in
919        // this case? This says to keep whatever the user typed.
920        mWordComposer.setAutoCorrection(mWordComposer.getTypedWord());
921        setSuggestionStripShown(true);
922    }
923
924    private void setSuggestionStripShownInternal(boolean shown, boolean needsInputViewShown) {
925        // TODO: Modify this if we support suggestions with hard keyboard
926        if (onEvaluateInputViewShown() && mSuggestionsContainer != null) {
927            final MainKeyboardView keyboardView = mKeyboardSwitcher.getKeyboardView();
928            final boolean inputViewShown = (keyboardView != null) ? keyboardView.isShown() : false;
929            final boolean shouldShowSuggestions = shown
930                    && (needsInputViewShown ? inputViewShown : true);
931            if (isFullscreenMode()) {
932                mSuggestionsContainer.setVisibility(
933                        shouldShowSuggestions ? View.VISIBLE : View.GONE);
934            } else {
935                mSuggestionsContainer.setVisibility(
936                        shouldShowSuggestions ? View.VISIBLE : View.INVISIBLE);
937            }
938        }
939    }
940
941    private void setSuggestionStripShown(boolean shown) {
942        setSuggestionStripShownInternal(shown, /* needsInputViewShown */true);
943    }
944
945    private int getAdjustedBackingViewHeight() {
946        final int currentHeight = mKeyPreviewBackingView.getHeight();
947        if (currentHeight > 0) {
948            return currentHeight;
949        }
950
951        final KeyboardView keyboardView = mKeyboardSwitcher.getKeyboardView();
952        if (keyboardView == null) {
953            return 0;
954        }
955        final int keyboardHeight = keyboardView.getHeight();
956        final int suggestionsHeight = mSuggestionsContainer.getHeight();
957        final int displayHeight = mResources.getDisplayMetrics().heightPixels;
958        final Rect rect = new Rect();
959        mKeyPreviewBackingView.getWindowVisibleDisplayFrame(rect);
960        final int notificationBarHeight = rect.top;
961        final int remainingHeight = displayHeight - notificationBarHeight - suggestionsHeight
962                - keyboardHeight;
963
964        final LayoutParams params = mKeyPreviewBackingView.getLayoutParams();
965        params.height = mSuggestionStripView.setMoreSuggestionsHeight(remainingHeight);
966        mKeyPreviewBackingView.setLayoutParams(params);
967        return params.height;
968    }
969
970    @Override
971    public void onComputeInsets(InputMethodService.Insets outInsets) {
972        super.onComputeInsets(outInsets);
973        final KeyboardView inputView = mKeyboardSwitcher.getKeyboardView();
974        if (inputView == null || mSuggestionsContainer == null)
975            return;
976        final int adjustedBackingHeight = getAdjustedBackingViewHeight();
977        final boolean backingGone = (mKeyPreviewBackingView.getVisibility() == View.GONE);
978        final int backingHeight = backingGone ? 0 : adjustedBackingHeight;
979        // In fullscreen mode, the height of the extract area managed by InputMethodService should
980        // be considered.
981        // See {@link android.inputmethodservice.InputMethodService#onComputeInsets}.
982        final int extractHeight = isFullscreenMode() ? mExtractArea.getHeight() : 0;
983        final int suggestionsHeight = (mSuggestionsContainer.getVisibility() == View.GONE) ? 0
984                : mSuggestionsContainer.getHeight();
985        final int extraHeight = extractHeight + backingHeight + suggestionsHeight;
986        int touchY = extraHeight;
987        // Need to set touchable region only if input view is being shown
988        final MainKeyboardView keyboardView = mKeyboardSwitcher.getKeyboardView();
989        if (keyboardView != null && keyboardView.isShown()) {
990            if (mSuggestionsContainer.getVisibility() == View.VISIBLE) {
991                touchY -= suggestionsHeight;
992            }
993            final int touchWidth = inputView.getWidth();
994            final int touchHeight = inputView.getHeight() + extraHeight
995                    // Extend touchable region below the keyboard.
996                    + EXTENDED_TOUCHABLE_REGION_HEIGHT;
997            outInsets.touchableInsets = InputMethodService.Insets.TOUCHABLE_INSETS_REGION;
998            outInsets.touchableRegion.set(0, touchY, touchWidth, touchHeight);
999        }
1000        outInsets.contentTopInsets = touchY;
1001        outInsets.visibleTopInsets = touchY;
1002    }
1003
1004    @Override
1005    public boolean onEvaluateFullscreenMode() {
1006        // Reread resource value here, because this method is called by framework anytime as needed.
1007        final boolean isFullscreenModeAllowed =
1008                mCurrentSettings.isFullscreenModeAllowed(getResources());
1009        return super.onEvaluateFullscreenMode() && isFullscreenModeAllowed;
1010    }
1011
1012    @Override
1013    public void updateFullscreenMode() {
1014        super.updateFullscreenMode();
1015
1016        if (mKeyPreviewBackingView == null) return;
1017        // In fullscreen mode, no need to have extra space to show the key preview.
1018        // If not, we should have extra space above the keyboard to show the key preview.
1019        mKeyPreviewBackingView.setVisibility(isFullscreenMode() ? View.GONE : View.VISIBLE);
1020    }
1021
1022    // This will reset the whole input state to the starting state. It will clear
1023    // the composing word, reset the last composed word, tell the inputconnection about it.
1024    private void resetEntireInputState() {
1025        resetComposingState(true /* alsoResetLastComposedWord */);
1026        clearSuggestionStrip();
1027        mConnection.finishComposingText();
1028    }
1029
1030    private void resetComposingState(final boolean alsoResetLastComposedWord) {
1031        mWordComposer.reset();
1032        if (alsoResetLastComposedWord)
1033            mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD;
1034    }
1035
1036    private void commitTyped(final int separatorCode) {
1037        if (!mWordComposer.isComposingWord()) return;
1038        final CharSequence typedWord = mWordComposer.getTypedWord();
1039        if (typedWord.length() > 0) {
1040            mConnection.commitText(typedWord, 1);
1041            if (ProductionFlag.IS_EXPERIMENTAL) {
1042                ResearchLogger.latinIME_commitText(typedWord);
1043            }
1044            final CharSequence prevWord = addToUserHistoryDictionary(typedWord);
1045            mLastComposedWord = mWordComposer.commitWord(
1046                    LastComposedWord.COMMIT_TYPE_USER_TYPED_WORD, typedWord.toString(),
1047                    separatorCode, prevWord);
1048        }
1049        updateSuggestionStrip();
1050    }
1051
1052    // Called from the KeyboardSwitcher which needs to know auto caps state to display
1053    // the right layout.
1054    public int getCurrentAutoCapsState() {
1055        if (!mCurrentSettings.mAutoCap) return Constants.TextUtils.CAP_MODE_OFF;
1056
1057        final EditorInfo ei = getCurrentInputEditorInfo();
1058        if (ei == null) return Constants.TextUtils.CAP_MODE_OFF;
1059
1060        final int inputType = ei.inputType;
1061        if ((inputType & InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0) {
1062            return TextUtils.CAP_MODE_CHARACTERS;
1063        }
1064
1065        final boolean noNeedToCheckCapsMode = (inputType & (InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
1066                | InputType.TYPE_TEXT_FLAG_CAP_WORDS)) == 0;
1067        if (noNeedToCheckCapsMode) return Constants.TextUtils.CAP_MODE_OFF;
1068
1069        // Avoid making heavy round-trip IPC calls of {@link InputConnection#getCursorCapsMode}
1070        // unless needed.
1071        if (mWordComposer.isComposingWord()) return Constants.TextUtils.CAP_MODE_OFF;
1072
1073        // TODO: This blocking IPC call is heavy. Consider doing this without using IPC calls.
1074        // Note: getCursorCapsMode() returns the current capitalization mode that is any
1075        // combination of CAP_MODE_CHARACTERS, CAP_MODE_WORDS, and CAP_MODE_SENTENCES. 0 means none
1076        // of them.
1077        return mConnection.getCursorCapsMode(inputType);
1078    }
1079
1080    private void swapSwapperAndSpace() {
1081        CharSequence lastTwo = mConnection.getTextBeforeCursor(2, 0);
1082        // It is guaranteed lastTwo.charAt(1) is a swapper - else this method is not called.
1083        if (lastTwo != null && lastTwo.length() == 2
1084                && lastTwo.charAt(0) == Keyboard.CODE_SPACE) {
1085            mConnection.deleteSurroundingText(2, 0);
1086            if (ProductionFlag.IS_EXPERIMENTAL) {
1087                ResearchLogger.latinIME_deleteSurroundingText(2);
1088            }
1089            mConnection.commitText(lastTwo.charAt(1) + " ", 1);
1090            if (ProductionFlag.IS_EXPERIMENTAL) {
1091                ResearchLogger.latinIME_swapSwapperAndSpaceWhileInBatchEdit();
1092            }
1093            mKeyboardSwitcher.updateShiftState();
1094        }
1095    }
1096
1097    private boolean maybeDoubleSpace() {
1098        if (!mCurrentSettings.mCorrectionEnabled) return false;
1099        if (!mHandler.isAcceptingDoubleSpaces()) return false;
1100        final CharSequence lastThree = mConnection.getTextBeforeCursor(3, 0);
1101        if (lastThree != null && lastThree.length() == 3
1102                && canBeFollowedByPeriod(lastThree.charAt(0))
1103                && lastThree.charAt(1) == Keyboard.CODE_SPACE
1104                && lastThree.charAt(2) == Keyboard.CODE_SPACE) {
1105            mHandler.cancelDoubleSpacesTimer();
1106            mConnection.deleteSurroundingText(2, 0);
1107            mConnection.commitText(". ", 1);
1108            if (ProductionFlag.IS_EXPERIMENTAL) {
1109                ResearchLogger.latinIME_doubleSpaceAutoPeriod();
1110            }
1111            mKeyboardSwitcher.updateShiftState();
1112            return true;
1113        }
1114        return false;
1115    }
1116
1117    private static boolean canBeFollowedByPeriod(final int codePoint) {
1118        // TODO: Check again whether there really ain't a better way to check this.
1119        // TODO: This should probably be language-dependant...
1120        return Character.isLetterOrDigit(codePoint)
1121                || codePoint == Keyboard.CODE_SINGLE_QUOTE
1122                || codePoint == Keyboard.CODE_DOUBLE_QUOTE
1123                || codePoint == Keyboard.CODE_CLOSING_PARENTHESIS
1124                || codePoint == Keyboard.CODE_CLOSING_SQUARE_BRACKET
1125                || codePoint == Keyboard.CODE_CLOSING_CURLY_BRACKET
1126                || codePoint == Keyboard.CODE_CLOSING_ANGLE_BRACKET;
1127    }
1128
1129    // Callback for the {@link SuggestionStripView}, to call when the "add to dictionary" hint is
1130    // pressed.
1131    @Override
1132    public boolean addWordToUserDictionary(String word) {
1133        mUserDictionary.addWordToUserDictionary(word, 128);
1134        return true;
1135    }
1136
1137    private static boolean isAlphabet(int code) {
1138        return Character.isLetter(code);
1139    }
1140
1141    private void onSettingsKeyPressed() {
1142        if (isShowingOptionDialog()) return;
1143        showSubtypeSelectorAndSettings();
1144    }
1145
1146    // Virtual codes representing custom requests.  These are used in onCustomRequest() below.
1147    public static final int CODE_SHOW_INPUT_METHOD_PICKER = 1;
1148
1149    @Override
1150    public boolean onCustomRequest(int requestCode) {
1151        if (isShowingOptionDialog()) return false;
1152        switch (requestCode) {
1153        case CODE_SHOW_INPUT_METHOD_PICKER:
1154            if (ImfUtils.hasMultipleEnabledIMEsOrSubtypes(
1155                    this, true /* include aux subtypes */)) {
1156                mImm.showInputMethodPicker();
1157                return true;
1158            }
1159            return false;
1160        }
1161        return false;
1162    }
1163
1164    private boolean isShowingOptionDialog() {
1165        return mOptionsDialog != null && mOptionsDialog.isShowing();
1166    }
1167
1168    private static int getActionId(Keyboard keyboard) {
1169        return keyboard != null ? keyboard.mId.imeActionId() : EditorInfo.IME_ACTION_NONE;
1170    }
1171
1172    private void performEditorAction(int actionId) {
1173        mConnection.performEditorAction(actionId);
1174        if (ProductionFlag.IS_EXPERIMENTAL) {
1175            ResearchLogger.latinIME_performEditorAction(actionId);
1176        }
1177    }
1178
1179    private void handleLanguageSwitchKey() {
1180        final boolean includesOtherImes = mCurrentSettings.mIncludesOtherImesInLanguageSwitchList;
1181        final IBinder token = getWindow().getWindow().getAttributes().token;
1182        if (mShouldSwitchToLastSubtype) {
1183            final InputMethodSubtype lastSubtype = mImm.getLastInputMethodSubtype();
1184            final boolean lastSubtypeBelongsToThisIme =
1185                    ImfUtils.checkIfSubtypeBelongsToThisImeAndEnabled(this, lastSubtype);
1186            if ((includesOtherImes || lastSubtypeBelongsToThisIme)
1187                    && mImm.switchToLastInputMethod(token)) {
1188                mShouldSwitchToLastSubtype = false;
1189            } else {
1190                mImm.switchToNextInputMethod(token, !includesOtherImes);
1191                mShouldSwitchToLastSubtype = true;
1192            }
1193        } else {
1194            mImm.switchToNextInputMethod(token, !includesOtherImes);
1195        }
1196    }
1197
1198    private void sendUpDownEnterOrBackspace(final int code) {
1199        final long eventTime = SystemClock.uptimeMillis();
1200        mConnection.sendKeyEvent(new KeyEvent(eventTime, eventTime,
1201                KeyEvent.ACTION_DOWN, code, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0,
1202                KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE));
1203        mConnection.sendKeyEvent(new KeyEvent(SystemClock.uptimeMillis(), eventTime,
1204                KeyEvent.ACTION_UP, code, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0,
1205                KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE));
1206    }
1207
1208    private void sendKeyCodePoint(int code) {
1209        // TODO: Remove this special handling of digit letters.
1210        // For backward compatibility. See {@link InputMethodService#sendKeyChar(char)}.
1211        if (code >= '0' && code <= '9') {
1212            super.sendKeyChar((char)code);
1213            return;
1214        }
1215
1216        // 16 is android.os.Build.VERSION_CODES.JELLY_BEAN but we can't write it because
1217        // we want to be able to compile against the Ice Cream Sandwich SDK.
1218        if (Keyboard.CODE_ENTER == code && mTargetApplicationInfo != null
1219                && mTargetApplicationInfo.targetSdkVersion < 16) {
1220            // Backward compatibility mode. Before Jelly bean, the keyboard would simulate
1221            // a hardware keyboard event on pressing enter or delete. This is bad for many
1222            // reasons (there are race conditions with commits) but some applications are
1223            // relying on this behavior so we continue to support it for older apps.
1224            sendUpDownEnterOrBackspace(KeyEvent.KEYCODE_ENTER);
1225        } else {
1226            final String text = new String(new int[] { code }, 0, 1);
1227            mConnection.commitText(text, text.length());
1228        }
1229        if (ProductionFlag.IS_EXPERIMENTAL) {
1230            ResearchLogger.latinIME_sendKeyCodePoint(code);
1231        }
1232    }
1233
1234    // Implementation of {@link KeyboardActionListener}.
1235    @Override
1236    public void onCodeInput(int primaryCode, int x, int y) {
1237        final long when = SystemClock.uptimeMillis();
1238        if (primaryCode != Keyboard.CODE_DELETE || when > mLastKeyTime + QUICK_PRESS) {
1239            mDeleteCount = 0;
1240        }
1241        mLastKeyTime = when;
1242        mConnection.beginBatchEdit();
1243
1244        if (ProductionFlag.IS_EXPERIMENTAL) {
1245            ResearchLogger.latinIME_onCodeInput(primaryCode, x, y);
1246        }
1247
1248        final KeyboardSwitcher switcher = mKeyboardSwitcher;
1249        // The space state depends only on the last character pressed and its own previous
1250        // state. Here, we revert the space state to neutral if the key is actually modifying
1251        // the input contents (any non-shift key), which is what we should do for
1252        // all inputs that do not result in a special state. Each character handling is then
1253        // free to override the state as they see fit.
1254        final int spaceState = mSpaceState;
1255        if (!mWordComposer.isComposingWord()) mIsAutoCorrectionIndicatorOn = false;
1256
1257        // TODO: Consolidate the double space timer, mLastKeyTime, and the space state.
1258        if (primaryCode != Keyboard.CODE_SPACE) {
1259            mHandler.cancelDoubleSpacesTimer();
1260        }
1261
1262        boolean didAutoCorrect = false;
1263        switch (primaryCode) {
1264        case Keyboard.CODE_DELETE:
1265            mSpaceState = SPACE_STATE_NONE;
1266            handleBackspace(spaceState);
1267            mDeleteCount++;
1268            mExpectingUpdateSelection = true;
1269            mShouldSwitchToLastSubtype = true;
1270            LatinImeLogger.logOnDelete(x, y);
1271            break;
1272        case Keyboard.CODE_SHIFT:
1273        case Keyboard.CODE_SWITCH_ALPHA_SYMBOL:
1274            // Shift and symbol key is handled in onPressKey() and onReleaseKey().
1275            break;
1276        case Keyboard.CODE_SETTINGS:
1277            onSettingsKeyPressed();
1278            break;
1279        case Keyboard.CODE_SHORTCUT:
1280            mSubtypeSwitcher.switchToShortcutIME();
1281            break;
1282        case Keyboard.CODE_ACTION_ENTER:
1283            performEditorAction(getActionId(switcher.getKeyboard()));
1284            break;
1285        case Keyboard.CODE_ACTION_NEXT:
1286            performEditorAction(EditorInfo.IME_ACTION_NEXT);
1287            break;
1288        case Keyboard.CODE_ACTION_PREVIOUS:
1289            performEditorAction(EditorInfo.IME_ACTION_PREVIOUS);
1290            break;
1291        case Keyboard.CODE_LANGUAGE_SWITCH:
1292            handleLanguageSwitchKey();
1293            break;
1294        case Keyboard.CODE_RESEARCH:
1295            if (ProductionFlag.IS_EXPERIMENTAL) {
1296                ResearchLogger.getInstance().presentResearchDialog(this);
1297            }
1298            break;
1299        default:
1300            mSpaceState = SPACE_STATE_NONE;
1301            if (mCurrentSettings.isWordSeparator(primaryCode)) {
1302                didAutoCorrect = handleSeparator(primaryCode, x, y, spaceState);
1303            } else {
1304                if (SPACE_STATE_PHANTOM == spaceState) {
1305                    commitTyped(LastComposedWord.NOT_A_SEPARATOR);
1306                }
1307                final int keyX, keyY;
1308                final Keyboard keyboard = mKeyboardSwitcher.getKeyboard();
1309                if (keyboard != null && keyboard.hasProximityCharsCorrection(primaryCode)) {
1310                    keyX = x;
1311                    keyY = y;
1312                } else {
1313                    keyX = NOT_A_TOUCH_COORDINATE;
1314                    keyY = NOT_A_TOUCH_COORDINATE;
1315                }
1316                handleCharacter(primaryCode, keyX, keyY, spaceState);
1317            }
1318            mExpectingUpdateSelection = true;
1319            mShouldSwitchToLastSubtype = true;
1320            break;
1321        }
1322        switcher.onCodeInput(primaryCode);
1323        // Reset after any single keystroke, except shift and symbol-shift
1324        if (!didAutoCorrect && primaryCode != Keyboard.CODE_SHIFT
1325                && primaryCode != Keyboard.CODE_SWITCH_ALPHA_SYMBOL)
1326            mLastComposedWord.deactivate();
1327        mEnteredText = null;
1328        mConnection.endBatchEdit();
1329    }
1330
1331    // Called from PointerTracker through the KeyboardActionListener interface
1332    @Override
1333    public void onTextInput(CharSequence text) {
1334        mConnection.beginBatchEdit();
1335        commitTyped(LastComposedWord.NOT_A_SEPARATOR);
1336        text = specificTldProcessingOnTextInput(text);
1337        if (SPACE_STATE_PHANTOM == mSpaceState) {
1338            sendKeyCodePoint(Keyboard.CODE_SPACE);
1339        }
1340        mConnection.commitText(text, 1);
1341        if (ProductionFlag.IS_EXPERIMENTAL) {
1342            ResearchLogger.latinIME_commitText(text);
1343        }
1344        mConnection.endBatchEdit();
1345        mKeyboardSwitcher.updateShiftState();
1346        mKeyboardSwitcher.onCodeInput(Keyboard.CODE_OUTPUT_TEXT);
1347        mSpaceState = SPACE_STATE_NONE;
1348        mEnteredText = text;
1349        resetComposingState(true /* alsoResetLastComposedWord */);
1350    }
1351
1352    @Override
1353    public void onStartBatchInput() {
1354        mConnection.beginBatchEdit();
1355        if (mWordComposer.isComposingWord()) {
1356            commitTyped(LastComposedWord.NOT_A_SEPARATOR);
1357            mExpectingUpdateSelection = true;
1358            // TODO: Can we remove this?
1359            mSpaceState = SPACE_STATE_PHANTOM;
1360        }
1361        mConnection.endBatchEdit();
1362        // TODO: Should handle TextUtils.CAP_MODE_CHARACTER.
1363        mWordComposer.setAutoCapitalized(
1364                getCurrentAutoCapsState() != Constants.TextUtils.CAP_MODE_OFF);
1365    }
1366
1367    @Override
1368    public void onUpdateBatchInput(InputPointers batchPointers) {
1369        mWordComposer.setBatchInputPointers(batchPointers);
1370        final SuggestedWords suggestedWords = getSuggestedWords();
1371        showSuggestionStrip(suggestedWords, null);
1372        final String gestureFloatingPreviewText = (suggestedWords.size() > 0)
1373                ? suggestedWords.getWord(0) : null;
1374        mKeyboardSwitcher.getKeyboardView()
1375                .showGestureFloatingPreviewText(gestureFloatingPreviewText);
1376    }
1377
1378    @Override
1379    public void onEndBatchInput(InputPointers batchPointers) {
1380        mWordComposer.setBatchInputPointers(batchPointers);
1381        final SuggestedWords suggestedWords = getSuggestedWords();
1382        showSuggestionStrip(suggestedWords, null);
1383        mKeyboardSwitcher.getKeyboardView().showGestureFloatingPreviewText(null);
1384        if (suggestedWords == null || suggestedWords.size() == 0) {
1385            return;
1386        }
1387        final CharSequence text = suggestedWords.getWord(0);
1388        if (TextUtils.isEmpty(text)) {
1389            return;
1390        }
1391        mWordComposer.setBatchInputWord(text);
1392        mConnection.beginBatchEdit();
1393        if (SPACE_STATE_PHANTOM == mSpaceState) {
1394            sendKeyCodePoint(Keyboard.CODE_SPACE);
1395        }
1396        mConnection.setComposingText(text, 1);
1397        mExpectingUpdateSelection = true;
1398        mConnection.endBatchEdit();
1399        mKeyboardSwitcher.updateShiftState();
1400        mSpaceState = SPACE_STATE_PHANTOM;
1401    }
1402
1403    private CharSequence specificTldProcessingOnTextInput(final CharSequence text) {
1404        if (text.length() <= 1 || text.charAt(0) != Keyboard.CODE_PERIOD
1405                || !Character.isLetter(text.charAt(1))) {
1406            // Not a tld: do nothing.
1407            return text;
1408        }
1409        // We have a TLD (or something that looks like this): make sure we don't add
1410        // a space even if currently in phantom mode.
1411        mSpaceState = SPACE_STATE_NONE;
1412        final CharSequence lastOne = mConnection.getTextBeforeCursor(1, 0);
1413        if (lastOne != null && lastOne.length() == 1
1414                && lastOne.charAt(0) == Keyboard.CODE_PERIOD) {
1415            return text.subSequence(1, text.length());
1416        } else {
1417            return text;
1418        }
1419    }
1420
1421    // Called from PointerTracker through the KeyboardActionListener interface
1422    @Override
1423    public void onCancelInput() {
1424        // User released a finger outside any key
1425        mKeyboardSwitcher.onCancelInput();
1426    }
1427
1428    private void handleBackspace(final int spaceState) {
1429        // In many cases, we may have to put the keyboard in auto-shift state again.
1430        mHandler.postUpdateShiftState();
1431
1432        if (mEnteredText != null && mConnection.sameAsTextBeforeCursor(mEnteredText)) {
1433            // Cancel multi-character input: remove the text we just entered.
1434            // This is triggered on backspace after a key that inputs multiple characters,
1435            // like the smiley key or the .com key.
1436            final int length = mEnteredText.length();
1437            mConnection.deleteSurroundingText(length, 0);
1438            if (ProductionFlag.IS_EXPERIMENTAL) {
1439                ResearchLogger.latinIME_deleteSurroundingText(length);
1440            }
1441            // If we have mEnteredText, then we know that mHasUncommittedTypedChars == false.
1442            // In addition we know that spaceState is false, and that we should not be
1443            // reverting any autocorrect at this point. So we can safely return.
1444            return;
1445        }
1446
1447        if (mWordComposer.isComposingWord()) {
1448            final int length = mWordComposer.size();
1449            if (length > 0) {
1450                // Immediately after a batch input.
1451                if (SPACE_STATE_PHANTOM == spaceState) {
1452                    mWordComposer.reset();
1453                } else {
1454                    mWordComposer.deleteLast();
1455                }
1456                mConnection.setComposingText(getTextWithUnderline(mWordComposer.getTypedWord()), 1);
1457                mHandler.postUpdateSuggestionStrip();
1458            } else {
1459                mConnection.deleteSurroundingText(1, 0);
1460                if (ProductionFlag.IS_EXPERIMENTAL) {
1461                    ResearchLogger.latinIME_deleteSurroundingText(1);
1462                }
1463            }
1464        } else {
1465            if (mLastComposedWord.canRevertCommit()) {
1466                Utils.Stats.onAutoCorrectionCancellation();
1467                revertCommit();
1468                return;
1469            }
1470            if (SPACE_STATE_DOUBLE == spaceState) {
1471                mHandler.cancelDoubleSpacesTimer();
1472                if (mConnection.revertDoubleSpace()) {
1473                    // No need to reset mSpaceState, it has already be done (that's why we
1474                    // receive it as a parameter)
1475                    return;
1476                }
1477            } else if (SPACE_STATE_SWAP_PUNCTUATION == spaceState) {
1478                if (mConnection.revertSwapPunctuation()) {
1479                    // Likewise
1480                    return;
1481                }
1482            }
1483
1484            // No cancelling of commit/double space/swap: we have a regular backspace.
1485            // We should backspace one char and restart suggestion if at the end of a word.
1486            if (mLastSelectionStart != mLastSelectionEnd) {
1487                // If there is a selection, remove it.
1488                final int lengthToDelete = mLastSelectionEnd - mLastSelectionStart;
1489                mConnection.setSelection(mLastSelectionEnd, mLastSelectionEnd);
1490                mConnection.deleteSurroundingText(lengthToDelete, 0);
1491                if (ProductionFlag.IS_EXPERIMENTAL) {
1492                    ResearchLogger.latinIME_deleteSurroundingText(lengthToDelete);
1493                }
1494            } else {
1495                // There is no selection, just delete one character.
1496                if (NOT_A_CURSOR_POSITION == mLastSelectionEnd) {
1497                    // This should never happen.
1498                    Log.e(TAG, "Backspace when we don't know the selection position");
1499                }
1500                // 16 is android.os.Build.VERSION_CODES.JELLY_BEAN but we can't write it because
1501                // we want to be able to compile against the Ice Cream Sandwich SDK.
1502                if (mTargetApplicationInfo != null
1503                        && mTargetApplicationInfo.targetSdkVersion < 16) {
1504                    // Backward compatibility mode. Before Jelly bean, the keyboard would simulate
1505                    // a hardware keyboard event on pressing enter or delete. This is bad for many
1506                    // reasons (there are race conditions with commits) but some applications are
1507                    // relying on this behavior so we continue to support it for older apps.
1508                    sendUpDownEnterOrBackspace(KeyEvent.KEYCODE_DEL);
1509                } else {
1510                    mConnection.deleteSurroundingText(1, 0);
1511                }
1512                if (ProductionFlag.IS_EXPERIMENTAL) {
1513                    ResearchLogger.latinIME_deleteSurroundingText(1);
1514                }
1515                if (mDeleteCount > DELETE_ACCELERATE_AT) {
1516                    mConnection.deleteSurroundingText(1, 0);
1517                    if (ProductionFlag.IS_EXPERIMENTAL) {
1518                        ResearchLogger.latinIME_deleteSurroundingText(1);
1519                    }
1520                }
1521            }
1522            if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) {
1523                restartSuggestionsOnWordBeforeCursorIfAtEndOfWord();
1524            }
1525        }
1526    }
1527
1528    private boolean maybeStripSpace(final int code,
1529            final int spaceState, final boolean isFromSuggestionStrip) {
1530        if (Keyboard.CODE_ENTER == code && SPACE_STATE_SWAP_PUNCTUATION == spaceState) {
1531            mConnection.removeTrailingSpace();
1532            return false;
1533        } else if ((SPACE_STATE_WEAK == spaceState
1534                || SPACE_STATE_SWAP_PUNCTUATION == spaceState)
1535                && isFromSuggestionStrip) {
1536            if (mCurrentSettings.isWeakSpaceSwapper(code)) {
1537                return true;
1538            } else {
1539                if (mCurrentSettings.isWeakSpaceStripper(code)) {
1540                    mConnection.removeTrailingSpace();
1541                }
1542                return false;
1543            }
1544        } else {
1545            return false;
1546        }
1547    }
1548
1549    private void handleCharacter(final int primaryCode, final int x,
1550            final int y, final int spaceState) {
1551        boolean isComposingWord = mWordComposer.isComposingWord();
1552
1553        if (SPACE_STATE_PHANTOM == spaceState &&
1554                !mCurrentSettings.isSymbolExcludedFromWordSeparators(primaryCode)) {
1555            if (isComposingWord) {
1556                // Sanity check
1557                throw new RuntimeException("Should not be composing here");
1558            }
1559            sendKeyCodePoint(Keyboard.CODE_SPACE);
1560        }
1561
1562        // NOTE: isCursorTouchingWord() is a blocking IPC call, so it often takes several
1563        // dozen milliseconds. Avoid calling it as much as possible, since we are on the UI
1564        // thread here.
1565        if (!isComposingWord && (isAlphabet(primaryCode)
1566                || mCurrentSettings.isSymbolExcludedFromWordSeparators(primaryCode))
1567                && mCurrentSettings.isSuggestionsRequested(mDisplayOrientation) &&
1568                !mConnection.isCursorTouchingWord(mCurrentSettings)) {
1569            // Reset entirely the composing state anyway, then start composing a new word unless
1570            // the character is a single quote. The idea here is, single quote is not a
1571            // separator and it should be treated as a normal character, except in the first
1572            // position where it should not start composing a word.
1573            isComposingWord = (Keyboard.CODE_SINGLE_QUOTE != primaryCode);
1574            // Here we don't need to reset the last composed word. It will be reset
1575            // when we commit this one, if we ever do; if on the other hand we backspace
1576            // it entirely and resume suggestions on the previous word, we'd like to still
1577            // have touch coordinates for it.
1578            resetComposingState(false /* alsoResetLastComposedWord */);
1579        }
1580        if (isComposingWord) {
1581            final int keyX, keyY;
1582            if (KeyboardActionListener.Adapter.isInvalidCoordinate(x)
1583                    || KeyboardActionListener.Adapter.isInvalidCoordinate(y)) {
1584                keyX = x;
1585                keyY = y;
1586            } else {
1587                final KeyDetector keyDetector =
1588                        mKeyboardSwitcher.getKeyboardView().getKeyDetector();
1589                keyX = keyDetector.getTouchX(x);
1590                keyY = keyDetector.getTouchY(y);
1591            }
1592            mWordComposer.add(primaryCode, keyX, keyY);
1593            // If it's the first letter, make note of auto-caps state
1594            if (mWordComposer.size() == 1) {
1595                mWordComposer.setAutoCapitalized(
1596                        getCurrentAutoCapsState() != Constants.TextUtils.CAP_MODE_OFF);
1597            }
1598            mConnection.setComposingText(getTextWithUnderline(mWordComposer.getTypedWord()), 1);
1599        } else {
1600            final boolean swapWeakSpace = maybeStripSpace(primaryCode,
1601                    spaceState, KeyboardActionListener.SUGGESTION_STRIP_COORDINATE == x);
1602
1603            sendKeyCodePoint(primaryCode);
1604
1605            if (swapWeakSpace) {
1606                swapSwapperAndSpace();
1607                mSpaceState = SPACE_STATE_WEAK;
1608            }
1609            // In case the "add to dictionary" hint was still displayed.
1610            if (null != mSuggestionStripView) mSuggestionStripView.dismissAddToDictionaryHint();
1611        }
1612        mHandler.postUpdateSuggestionStrip();
1613        Utils.Stats.onNonSeparator((char)primaryCode, x, y);
1614    }
1615
1616    // Returns true if we did an autocorrection, false otherwise.
1617    private boolean handleSeparator(final int primaryCode, final int x, final int y,
1618            final int spaceState) {
1619        boolean didAutoCorrect = false;
1620        // Handle separator
1621        if (mWordComposer.isComposingWord()) {
1622            // In certain languages where single quote is a separator, it's better
1623            // not to auto correct, but accept the typed word. For instance,
1624            // in Italian dov' should not be expanded to dove' because the elision
1625            // requires the last vowel to be removed.
1626            if (mCurrentSettings.mCorrectionEnabled && primaryCode != Keyboard.CODE_SINGLE_QUOTE) {
1627                commitCurrentAutoCorrection(primaryCode);
1628                didAutoCorrect = true;
1629            } else {
1630                commitTyped(primaryCode);
1631            }
1632        }
1633
1634        final boolean swapWeakSpace = maybeStripSpace(primaryCode, spaceState,
1635                KeyboardActionListener.SUGGESTION_STRIP_COORDINATE == x);
1636
1637        if (SPACE_STATE_PHANTOM == spaceState &&
1638                mCurrentSettings.isPhantomSpacePromotingSymbol(primaryCode)) {
1639            sendKeyCodePoint(Keyboard.CODE_SPACE);
1640        }
1641        sendKeyCodePoint(primaryCode);
1642
1643        if (Keyboard.CODE_SPACE == primaryCode) {
1644            if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) {
1645                if (maybeDoubleSpace()) {
1646                    mSpaceState = SPACE_STATE_DOUBLE;
1647                } else if (!isShowingPunctuationList()) {
1648                    mSpaceState = SPACE_STATE_WEAK;
1649                }
1650            }
1651
1652            mHandler.startDoubleSpacesTimer();
1653            if (!mConnection.isCursorTouchingWord(mCurrentSettings)) {
1654                mHandler.postUpdateSuggestionStrip();
1655            }
1656        } else {
1657            if (swapWeakSpace) {
1658                swapSwapperAndSpace();
1659                mSpaceState = SPACE_STATE_SWAP_PUNCTUATION;
1660            } else if (SPACE_STATE_PHANTOM == spaceState
1661                    && !mCurrentSettings.isWeakSpaceStripper(primaryCode)) {
1662                // If we are in phantom space state, and the user presses a separator, we want to
1663                // stay in phantom space state so that the next keypress has a chance to add the
1664                // space. For example, if I type "Good dat", pick "day" from the suggestion strip
1665                // then insert a comma and go on to typing the next word, I want the space to be
1666                // inserted automatically before the next word, the same way it is when I don't
1667                // input the comma.
1668                // The case is a little different if the separator is a space stripper. Such a
1669                // separator does not normally need a space on the right (that's the difference
1670                // between swappers and strippers), so we should not stay in phantom space state if
1671                // the separator is a stripper. Hence the additional test above.
1672                mSpaceState = SPACE_STATE_PHANTOM;
1673            }
1674
1675            // Set punctuation right away. onUpdateSelection will fire but tests whether it is
1676            // already displayed or not, so it's okay.
1677            setPunctuationSuggestions();
1678        }
1679
1680        Utils.Stats.onSeparator((char)primaryCode, x, y);
1681
1682        return didAutoCorrect;
1683    }
1684
1685    private CharSequence getTextWithUnderline(final CharSequence text) {
1686        return mIsAutoCorrectionIndicatorOn
1687                ? SuggestionSpanUtils.getTextWithAutoCorrectionIndicatorUnderline(this, text)
1688                : text;
1689    }
1690
1691    private void handleClose() {
1692        commitTyped(LastComposedWord.NOT_A_SEPARATOR);
1693        requestHideSelf(0);
1694        MainKeyboardView inputView = mKeyboardSwitcher.getKeyboardView();
1695        if (inputView != null)
1696            inputView.closing();
1697    }
1698
1699    // TODO: make this private
1700    // Outside LatinIME, only used by the test suite.
1701    /* package for tests */ boolean isShowingPunctuationList() {
1702        if (mSuggestionStripView == null) return false;
1703        return mCurrentSettings.mSuggestPuncList == mSuggestionStripView.getSuggestions();
1704    }
1705
1706    private boolean isSuggestionsStripVisible() {
1707        if (mSuggestionStripView == null)
1708            return false;
1709        if (mSuggestionStripView.isShowingAddToDictionaryHint())
1710            return true;
1711        if (!mCurrentSettings.isSuggestionStripVisibleInOrientation(mDisplayOrientation))
1712            return false;
1713        if (mCurrentSettings.isApplicationSpecifiedCompletionsOn())
1714            return true;
1715        return mCurrentSettings.isSuggestionsRequested(mDisplayOrientation);
1716    }
1717
1718    private void clearSuggestionStrip() {
1719        setSuggestionStrip(SuggestedWords.EMPTY, false);
1720        setAutoCorrectionIndicator(false);
1721    }
1722
1723    private void setSuggestionStrip(final SuggestedWords words, final boolean isAutoCorrection) {
1724        if (mSuggestionStripView != null) {
1725            mSuggestionStripView.setSuggestions(words);
1726            mKeyboardSwitcher.onAutoCorrectionStateChanged(isAutoCorrection);
1727        }
1728    }
1729
1730    private void setAutoCorrectionIndicator(final boolean newAutoCorrectionIndicator) {
1731        // Put a blue underline to a word in TextView which will be auto-corrected.
1732        if (mIsAutoCorrectionIndicatorOn != newAutoCorrectionIndicator
1733                && mWordComposer.isComposingWord()) {
1734            mIsAutoCorrectionIndicatorOn = newAutoCorrectionIndicator;
1735            final CharSequence textWithUnderline =
1736                    getTextWithUnderline(mWordComposer.getTypedWord());
1737            mConnection.setComposingText(textWithUnderline, 1);
1738        }
1739    }
1740
1741    private void updateSuggestionStrip() {
1742        mHandler.cancelUpdateSuggestionStrip();
1743
1744        // Check if we have a suggestion engine attached.
1745        if (mSuggest == null || !mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) {
1746            if (mWordComposer.isComposingWord()) {
1747                Log.w(TAG, "Called updateSuggestionsOrPredictions but suggestions were not "
1748                        + "requested!");
1749                mWordComposer.setAutoCorrection(mWordComposer.getTypedWord());
1750            }
1751            return;
1752        }
1753
1754        if (!mWordComposer.isComposingWord() && !mCurrentSettings.mBigramPredictionEnabled) {
1755            setPunctuationSuggestions();
1756            return;
1757        }
1758
1759        final SuggestedWords suggestedWords = getSuggestedWords();
1760        final String typedWord = mWordComposer.getTypedWord();
1761        showSuggestionStrip(suggestedWords, typedWord);
1762    }
1763
1764    private SuggestedWords getSuggestedWords() {
1765        final String typedWord = mWordComposer.getTypedWord();
1766        // Get the word on which we should search the bigrams. If we are composing a word, it's
1767        // whatever is *before* the half-committed word in the buffer, hence 2; if we aren't, we
1768        // should just skip whitespace if any, so 1.
1769        // TODO: this is slow (2-way IPC) - we should probably cache this instead.
1770        final CharSequence prevWord =
1771                mConnection.getNthPreviousWord(mCurrentSettings.mWordSeparators,
1772                mWordComposer.isComposingWord() ? 2 : 1);
1773        final SuggestedWords suggestedWords = mSuggest.getSuggestedWords(mWordComposer,
1774                prevWord, mKeyboardSwitcher.getKeyboard().getProximityInfo(),
1775                mCurrentSettings.mCorrectionEnabled);
1776        return maybeRetrieveOlderSuggestions(typedWord, suggestedWords);
1777    }
1778
1779    private SuggestedWords maybeRetrieveOlderSuggestions(final CharSequence typedWord,
1780            final SuggestedWords suggestedWords) {
1781        // TODO: consolidate this into getSuggestedWords
1782        // We update the suggestion strip only when we have some suggestions to show, i.e. when
1783        // the suggestion count is > 1; else, we leave the old suggestions, with the typed word
1784        // replaced with the new one. However, when the word is a dictionary word, or when the
1785        // length of the typed word is 1 or 0 (after a deletion typically), we do want to remove the
1786        // old suggestions. Also, if we are showing the "add to dictionary" hint, we need to
1787        // revert to suggestions - although it is unclear how we can come here if it's displayed.
1788        if (suggestedWords.size() > 1 || typedWord.length() <= 1
1789                || !suggestedWords.mTypedWordValid
1790                || mSuggestionStripView.isShowingAddToDictionaryHint()) {
1791            return suggestedWords;
1792        } else {
1793            SuggestedWords previousSuggestions = mSuggestionStripView.getSuggestions();
1794            if (previousSuggestions == mCurrentSettings.mSuggestPuncList) {
1795                previousSuggestions = SuggestedWords.EMPTY;
1796            }
1797            final ArrayList<SuggestedWords.SuggestedWordInfo> typedWordAndPreviousSuggestions =
1798                    SuggestedWords.getTypedWordAndPreviousSuggestions(
1799                            typedWord, previousSuggestions);
1800            return new SuggestedWords(typedWordAndPreviousSuggestions,
1801                            false /* typedWordValid */,
1802                            false /* hasAutoCorrectionCandidate */,
1803                            false /* isPunctuationSuggestions */,
1804                            true /* isObsoleteSuggestions */,
1805                            false /* isPrediction */);
1806        }
1807    }
1808
1809    private void showSuggestionStrip(final SuggestedWords suggestedWords,
1810            final CharSequence typedWord) {
1811        if (null == suggestedWords || suggestedWords.size() <= 0) {
1812            clearSuggestionStrip();
1813            return;
1814        }
1815        final CharSequence autoCorrection;
1816        if (suggestedWords.size() > 0) {
1817            if (suggestedWords.mWillAutoCorrect) {
1818                autoCorrection = suggestedWords.getWord(1);
1819            } else {
1820                autoCorrection = typedWord;
1821            }
1822        } else {
1823            autoCorrection = null;
1824        }
1825        mWordComposer.setAutoCorrection(autoCorrection);
1826        final boolean isAutoCorrection = suggestedWords.willAutoCorrect();
1827        setSuggestionStrip(suggestedWords, isAutoCorrection);
1828        setAutoCorrectionIndicator(isAutoCorrection);
1829        setSuggestionStripShown(isSuggestionsStripVisible());
1830    }
1831
1832    private void commitCurrentAutoCorrection(final int separatorCodePoint) {
1833        // Complete any pending suggestions query first
1834        if (mHandler.hasPendingUpdateSuggestions()) {
1835            updateSuggestionStrip();
1836        }
1837        final CharSequence typedAutoCorrection = mWordComposer.getAutoCorrectionOrNull();
1838        final String typedWord = mWordComposer.getTypedWord();
1839        final CharSequence autoCorrection = (typedAutoCorrection != null)
1840                ? typedAutoCorrection : typedWord;
1841        if (autoCorrection != null) {
1842            if (TextUtils.isEmpty(typedWord)) {
1843                throw new RuntimeException("We have an auto-correction but the typed word "
1844                        + "is empty? Impossible! I must commit suicide.");
1845            }
1846            Utils.Stats.onAutoCorrection(typedWord, autoCorrection.toString(), separatorCodePoint);
1847            if (ProductionFlag.IS_EXPERIMENTAL) {
1848                ResearchLogger.latinIME_commitCurrentAutoCorrection(typedWord,
1849                        autoCorrection.toString());
1850            }
1851            mExpectingUpdateSelection = true;
1852            commitChosenWord(autoCorrection, LastComposedWord.COMMIT_TYPE_DECIDED_WORD,
1853                    separatorCodePoint);
1854            if (!typedWord.equals(autoCorrection)) {
1855                // This will make the correction flash for a short while as a visual clue
1856                // to the user that auto-correction happened.
1857                mConnection.commitCorrection(
1858                        new CorrectionInfo(mLastSelectionEnd - typedWord.length(),
1859                        typedWord, autoCorrection));
1860            }
1861        }
1862    }
1863
1864    // Called from {@link SuggestionStripView} through the {@link SuggestionStripView#Listener}
1865    // interface
1866    @Override
1867    public void pickSuggestionManually(final int index, final CharSequence suggestion,
1868            final int x, final int y) {
1869        final SuggestedWords suggestedWords = mSuggestionStripView.getSuggestions();
1870        // If this is a punctuation picked from the suggestion strip, pass it to onCodeInput
1871        if (suggestion.length() == 1 && isShowingPunctuationList()) {
1872            // Word separators are suggested before the user inputs something.
1873            // So, LatinImeLogger logs "" as a user's input.
1874            LatinImeLogger.logOnManualSuggestion("", suggestion.toString(), index, suggestedWords);
1875            // Rely on onCodeInput to do the complicated swapping/stripping logic consistently.
1876            if (ProductionFlag.IS_EXPERIMENTAL) {
1877                ResearchLogger.latinIME_punctuationSuggestion(index, suggestion, x, y);
1878            }
1879            final int primaryCode = suggestion.charAt(0);
1880            onCodeInput(primaryCode,
1881                    KeyboardActionListener.SUGGESTION_STRIP_COORDINATE,
1882                    KeyboardActionListener.SUGGESTION_STRIP_COORDINATE);
1883            return;
1884        }
1885
1886        mConnection.beginBatchEdit();
1887        if (SPACE_STATE_PHANTOM == mSpaceState && suggestion.length() > 0
1888                // In the batch input mode, a manually picked suggested word should just replace
1889                // the current batch input text and there is no need for a phantom space.
1890                && !mWordComposer.isBatchMode()) {
1891            int firstChar = Character.codePointAt(suggestion, 0);
1892            if ((!mCurrentSettings.isWeakSpaceStripper(firstChar))
1893                    && (!mCurrentSettings.isWeakSpaceSwapper(firstChar))) {
1894                sendKeyCodePoint(Keyboard.CODE_SPACE);
1895            }
1896        }
1897
1898        if (mCurrentSettings.isApplicationSpecifiedCompletionsOn()
1899                && mApplicationSpecifiedCompletions != null
1900                && index >= 0 && index < mApplicationSpecifiedCompletions.length) {
1901            if (mSuggestionStripView != null) {
1902                mSuggestionStripView.clear();
1903            }
1904            mKeyboardSwitcher.updateShiftState();
1905            resetComposingState(true /* alsoResetLastComposedWord */);
1906            final CompletionInfo completionInfo = mApplicationSpecifiedCompletions[index];
1907            mConnection.commitCompletion(completionInfo);
1908            mConnection.endBatchEdit();
1909            if (ProductionFlag.IS_EXPERIMENTAL) {
1910                ResearchLogger.latinIME_pickApplicationSpecifiedCompletion(index,
1911                        completionInfo.getText(), x, y);
1912            }
1913            return;
1914        }
1915
1916        // We need to log before we commit, because the word composer will store away the user
1917        // typed word.
1918        final String replacedWord = mWordComposer.getTypedWord().toString();
1919        LatinImeLogger.logOnManualSuggestion(replacedWord,
1920                suggestion.toString(), index, suggestedWords);
1921        if (ProductionFlag.IS_EXPERIMENTAL) {
1922            ResearchLogger.latinIME_pickSuggestionManually(replacedWord, index, suggestion, x, y);
1923        }
1924        mExpectingUpdateSelection = true;
1925        commitChosenWord(suggestion, LastComposedWord.COMMIT_TYPE_MANUAL_PICK,
1926                LastComposedWord.NOT_A_SEPARATOR);
1927        mConnection.endBatchEdit();
1928        // Don't allow cancellation of manual pick
1929        mLastComposedWord.deactivate();
1930        mSpaceState = SPACE_STATE_PHANTOM;
1931        // TODO: is this necessary?
1932        mKeyboardSwitcher.updateShiftState();
1933
1934        // We should show the "Touch again to save" hint if the user pressed the first entry
1935        // AND it's in none of our current dictionaries (main, user or otherwise).
1936        // Please note that if mSuggest is null, it means that everything is off: suggestion
1937        // and correction, so we shouldn't try to show the hint
1938        final boolean showingAddToDictionaryHint = index == 0 && mSuggest != null
1939                // If the suggestion is not in the dictionary, the hint should be shown.
1940                && !AutoCorrection.isValidWord(mSuggest.getUnigramDictionaries(), suggestion, true);
1941
1942        Utils.Stats.onSeparator((char)Keyboard.CODE_SPACE, WordComposer.NOT_A_COORDINATE,
1943                WordComposer.NOT_A_COORDINATE);
1944        if (showingAddToDictionaryHint && mIsUserDictionaryAvailable) {
1945            mSuggestionStripView.showAddToDictionaryHint(
1946                    suggestion, mCurrentSettings.mHintToSaveText);
1947        } else {
1948            // If we're not showing the "Touch again to save", then update the suggestion strip.
1949            mHandler.postUpdateSuggestionStrip();
1950        }
1951    }
1952
1953    /**
1954     * Commits the chosen word to the text field and saves it for later retrieval.
1955     */
1956    private void commitChosenWord(final CharSequence chosenWord, final int commitType,
1957            final int separatorCode) {
1958        final SuggestedWords suggestedWords = mSuggestionStripView.getSuggestions();
1959        mConnection.commitText(SuggestionSpanUtils.getTextWithSuggestionSpan(
1960                this, chosenWord, suggestedWords, mIsMainDictionaryAvailable), 1);
1961        if (ProductionFlag.IS_EXPERIMENTAL) {
1962            ResearchLogger.latinIME_commitText(chosenWord);
1963        }
1964        // Add the word to the user history dictionary
1965        final CharSequence prevWord = addToUserHistoryDictionary(chosenWord);
1966        // TODO: figure out here if this is an auto-correct or if the best word is actually
1967        // what user typed. Note: currently this is done much later in
1968        // LastComposedWord#didCommitTypedWord by string equality of the remembered
1969        // strings.
1970        mLastComposedWord = mWordComposer.commitWord(commitType, chosenWord.toString(),
1971                separatorCode, prevWord);
1972    }
1973
1974    private void setPunctuationSuggestions() {
1975        if (mCurrentSettings.mBigramPredictionEnabled) {
1976            clearSuggestionStrip();
1977        } else {
1978            setSuggestionStrip(mCurrentSettings.mSuggestPuncList, false);
1979        }
1980        setAutoCorrectionIndicator(false);
1981        setSuggestionStripShown(isSuggestionsStripVisible());
1982    }
1983
1984    private CharSequence addToUserHistoryDictionary(final CharSequence suggestion) {
1985        if (TextUtils.isEmpty(suggestion)) return null;
1986
1987        // If correction is not enabled, we don't add words to the user history dictionary.
1988        // That's to avoid unintended additions in some sensitive fields, or fields that
1989        // expect to receive non-words.
1990        if (!mCurrentSettings.mCorrectionEnabled) return null;
1991
1992        final UserHistoryDictionary userHistoryDictionary = mUserHistoryDictionary;
1993        if (userHistoryDictionary != null) {
1994            final CharSequence prevWord
1995                    = mConnection.getNthPreviousWord(mCurrentSettings.mWordSeparators, 2);
1996            final String secondWord;
1997            if (mWordComposer.isAutoCapitalized() && !mWordComposer.isMostlyCaps()) {
1998                secondWord = suggestion.toString().toLowerCase(
1999                        mSubtypeSwitcher.getCurrentSubtypeLocale());
2000            } else {
2001                secondWord = suggestion.toString();
2002            }
2003            // We demote unrecognized words (frequency < 0, below) by specifying them as "invalid".
2004            // We don't add words with 0-frequency (assuming they would be profanity etc.).
2005            final int maxFreq = AutoCorrection.getMaxFrequency(
2006                    mSuggest.getUnigramDictionaries(), suggestion);
2007            if (maxFreq == 0) return null;
2008            userHistoryDictionary.addToUserHistory(null == prevWord ? null : prevWord.toString(),
2009                    secondWord, maxFreq > 0);
2010            return prevWord;
2011        }
2012        return null;
2013    }
2014
2015    /**
2016     * Check if the cursor is actually at the end of a word. If so, restart suggestions on this
2017     * word, else do nothing.
2018     */
2019    private void restartSuggestionsOnWordBeforeCursorIfAtEndOfWord() {
2020        final CharSequence word = mConnection.getWordBeforeCursorIfAtEndOfWord(mCurrentSettings);
2021        if (null != word) {
2022            restartSuggestionsOnWordBeforeCursor(word);
2023        }
2024    }
2025
2026    private void restartSuggestionsOnWordBeforeCursor(final CharSequence word) {
2027        mWordComposer.setComposingWord(word, mKeyboardSwitcher.getKeyboard());
2028        final int length = word.length();
2029        mConnection.deleteSurroundingText(length, 0);
2030        if (ProductionFlag.IS_EXPERIMENTAL) {
2031            ResearchLogger.latinIME_deleteSurroundingText(length);
2032        }
2033        mConnection.setComposingText(word, 1);
2034        mHandler.postUpdateSuggestionStrip();
2035    }
2036
2037    private void revertCommit() {
2038        final CharSequence previousWord = mLastComposedWord.mPrevWord;
2039        final String originallyTypedWord = mLastComposedWord.mTypedWord;
2040        final CharSequence committedWord = mLastComposedWord.mCommittedWord;
2041        final int cancelLength = committedWord.length();
2042        final int separatorLength = LastComposedWord.getSeparatorLength(
2043                mLastComposedWord.mSeparatorCode);
2044        // TODO: should we check our saved separator against the actual contents of the text view?
2045        final int deleteLength = cancelLength + separatorLength;
2046        if (DEBUG) {
2047            if (mWordComposer.isComposingWord()) {
2048                throw new RuntimeException("revertCommit, but we are composing a word");
2049            }
2050            final String wordBeforeCursor =
2051                    mConnection.getTextBeforeCursor(deleteLength, 0)
2052                            .subSequence(0, cancelLength).toString();
2053            if (!TextUtils.equals(committedWord, wordBeforeCursor)) {
2054                throw new RuntimeException("revertCommit check failed: we thought we were "
2055                        + "reverting \"" + committedWord
2056                        + "\", but before the cursor we found \"" + wordBeforeCursor + "\"");
2057            }
2058        }
2059        mConnection.deleteSurroundingText(deleteLength, 0);
2060        if (ProductionFlag.IS_EXPERIMENTAL) {
2061            ResearchLogger.latinIME_deleteSurroundingText(deleteLength);
2062        }
2063        if (!TextUtils.isEmpty(previousWord) && !TextUtils.isEmpty(committedWord)) {
2064            mUserHistoryDictionary.cancelAddingUserHistory(
2065                    previousWord.toString(), committedWord.toString());
2066        }
2067        mConnection.commitText(originallyTypedWord, 1);
2068        // Re-insert the separator
2069        sendKeyCodePoint(mLastComposedWord.mSeparatorCode);
2070        Utils.Stats.onSeparator(mLastComposedWord.mSeparatorCode, WordComposer.NOT_A_COORDINATE,
2071                WordComposer.NOT_A_COORDINATE);
2072        if (ProductionFlag.IS_EXPERIMENTAL) {
2073            ResearchLogger.latinIME_revertCommit(originallyTypedWord);
2074        }
2075        // Don't restart suggestion yet. We'll restart if the user deletes the
2076        // separator.
2077        mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD;
2078        // We have a separator between the word and the cursor: we should show predictions.
2079        mHandler.postUpdateSuggestionStrip();
2080    }
2081
2082    // Used by the RingCharBuffer
2083    public boolean isWordSeparator(int code) {
2084        return mCurrentSettings.isWordSeparator(code);
2085    }
2086
2087    // Notify that language or mode have been changed and toggleLanguage will update KeyboardID
2088    // according to new language or mode. Called from SubtypeSwitcher.
2089    public void onRefreshKeyboard() {
2090        // When the device locale is changed in SetupWizard etc., this method may get called via
2091        // onConfigurationChanged before SoftInputWindow is shown.
2092        initSuggest();
2093        loadSettings();
2094        if (mKeyboardSwitcher.getKeyboardView() != null) {
2095            // Reload keyboard because the current language has been changed.
2096            mKeyboardSwitcher.loadKeyboard(getCurrentInputEditorInfo(), mCurrentSettings);
2097            updateKeyboardViewGestureHandlingModeByMainDictionaryAvailability();
2098        }
2099        // Since we just changed languages, we should re-evaluate suggestions with whatever word
2100        // we are currently composing. If we are not composing anything, we may want to display
2101        // predictions or punctuation signs (which is done by the updateSuggestionStrip anyway).
2102        mHandler.postUpdateSuggestionStrip();
2103    }
2104
2105    private void updateKeyboardViewGestureHandlingModeByMainDictionaryAvailability() {
2106        final MainKeyboardView keyboardView = mKeyboardSwitcher.getKeyboardView();
2107        if (keyboardView != null) {
2108            final boolean shouldHandleGesture = mCurrentSettings.mGestureInputEnabled
2109                    && mIsMainDictionaryAvailable;
2110            keyboardView.setGestureHandlingMode(shouldHandleGesture,
2111                    mCurrentSettings.mGesturePreviewTrailEnabled,
2112                    mCurrentSettings.mGestureFloatingPreviewTextEnabled);
2113        }
2114    }
2115
2116    // TODO: Remove this method from {@link LatinIME} and move {@link FeedbackManager} to
2117    // {@link KeyboardSwitcher}. Called from KeyboardSwitcher
2118    public void hapticAndAudioFeedback(final int primaryCode) {
2119        mFeedbackManager.hapticAndAudioFeedback(primaryCode, mKeyboardSwitcher.getKeyboardView());
2120    }
2121
2122    // Callback called by PointerTracker through the KeyboardActionListener. This is called when a
2123    // key is depressed; release matching call is onReleaseKey below.
2124    @Override
2125    public void onPressKey(int primaryCode) {
2126        mKeyboardSwitcher.onPressKey(primaryCode);
2127    }
2128
2129    // Callback by PointerTracker through the KeyboardActionListener. This is called when a key
2130    // is released; press matching call is onPressKey above.
2131    @Override
2132    public void onReleaseKey(int primaryCode, boolean withSliding) {
2133        mKeyboardSwitcher.onReleaseKey(primaryCode, withSliding);
2134
2135        // If accessibility is on, ensure the user receives keyboard state updates.
2136        if (AccessibilityUtils.getInstance().isTouchExplorationEnabled()) {
2137            switch (primaryCode) {
2138            case Keyboard.CODE_SHIFT:
2139                AccessibleKeyboardViewProxy.getInstance().notifyShiftState();
2140                break;
2141            case Keyboard.CODE_SWITCH_ALPHA_SYMBOL:
2142                AccessibleKeyboardViewProxy.getInstance().notifySymbolsState();
2143                break;
2144            }
2145        }
2146
2147        if (Keyboard.CODE_DELETE == primaryCode) {
2148            // This is a stopgap solution to avoid leaving a high surrogate alone in a text view.
2149            // In the future, we need to deprecate deteleSurroundingText() and have a surrogate
2150            // pair-friendly way of deleting characters in InputConnection.
2151            final CharSequence lastChar = mConnection.getTextBeforeCursor(1, 0);
2152            if (!TextUtils.isEmpty(lastChar) && Character.isHighSurrogate(lastChar.charAt(0))) {
2153                mConnection.deleteSurroundingText(1, 0);
2154            }
2155        }
2156    }
2157
2158    // receive ringer mode change and network state change.
2159    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
2160        @Override
2161        public void onReceive(Context context, Intent intent) {
2162            final String action = intent.getAction();
2163            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
2164                mSubtypeSwitcher.onNetworkStateChanged(intent);
2165            } else if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) {
2166                mFeedbackManager.onRingerModeChanged();
2167            }
2168        }
2169    };
2170
2171    private void launchSettings() {
2172        handleClose();
2173        launchSubActivity(SettingsActivity.class);
2174    }
2175
2176    // Called from debug code only
2177    public void launchDebugSettings() {
2178        handleClose();
2179        launchSubActivity(DebugSettingsActivity.class);
2180    }
2181
2182    public void launchKeyboardedDialogActivity(Class<? extends Activity> activityClass) {
2183        // Put the text in the attached EditText into a safe, saved state before switching to a
2184        // new activity that will also use the soft keyboard.
2185        commitTyped(LastComposedWord.NOT_A_SEPARATOR);
2186        launchSubActivity(activityClass);
2187    }
2188
2189    private void launchSubActivity(Class<? extends Activity> activityClass) {
2190        Intent intent = new Intent();
2191        intent.setClass(LatinIME.this, activityClass);
2192        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2193        startActivity(intent);
2194    }
2195
2196    private void showSubtypeSelectorAndSettings() {
2197        final CharSequence title = getString(R.string.english_ime_input_options);
2198        final CharSequence[] items = new CharSequence[] {
2199                // TODO: Should use new string "Select active input modes".
2200                getString(R.string.language_selection_title),
2201                getString(R.string.english_ime_settings),
2202        };
2203        final Context context = this;
2204        final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
2205            @Override
2206            public void onClick(DialogInterface di, int position) {
2207                di.dismiss();
2208                switch (position) {
2209                case 0:
2210                    Intent intent = CompatUtils.getInputLanguageSelectionIntent(
2211                            ImfUtils.getInputMethodIdOfThisIme(context),
2212                            Intent.FLAG_ACTIVITY_NEW_TASK
2213                            | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
2214                            | Intent.FLAG_ACTIVITY_CLEAR_TOP);
2215                    startActivity(intent);
2216                    break;
2217                case 1:
2218                    launchSettings();
2219                    break;
2220                }
2221            }
2222        };
2223        final AlertDialog.Builder builder = new AlertDialog.Builder(this)
2224                .setItems(items, listener)
2225                .setTitle(title);
2226        showOptionDialog(builder.create());
2227    }
2228
2229    public void showOptionDialog(AlertDialog dialog) {
2230        final IBinder windowToken = mKeyboardSwitcher.getKeyboardView().getWindowToken();
2231        if (windowToken == null) return;
2232
2233        dialog.setCancelable(true);
2234        dialog.setCanceledOnTouchOutside(true);
2235
2236        final Window window = dialog.getWindow();
2237        final WindowManager.LayoutParams lp = window.getAttributes();
2238        lp.token = windowToken;
2239        lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
2240        window.setAttributes(lp);
2241        window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
2242
2243        mOptionsDialog = dialog;
2244        dialog.show();
2245    }
2246
2247    @Override
2248    protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
2249        super.dump(fd, fout, args);
2250
2251        final Printer p = new PrintWriterPrinter(fout);
2252        p.println("LatinIME state :");
2253        final Keyboard keyboard = mKeyboardSwitcher.getKeyboard();
2254        final int keyboardMode = keyboard != null ? keyboard.mId.mMode : -1;
2255        p.println("  Keyboard mode = " + keyboardMode);
2256        p.println("  mIsSuggestionsSuggestionsRequested = "
2257                + mCurrentSettings.isSuggestionsRequested(mDisplayOrientation));
2258        p.println("  mCorrectionEnabled=" + mCurrentSettings.mCorrectionEnabled);
2259        p.println("  isComposingWord=" + mWordComposer.isComposingWord());
2260        p.println("  mSoundOn=" + mCurrentSettings.mSoundOn);
2261        p.println("  mVibrateOn=" + mCurrentSettings.mVibrateOn);
2262        p.println("  mKeyPreviewPopupOn=" + mCurrentSettings.mKeyPreviewPopupOn);
2263        p.println("  inputAttributes=" + mCurrentSettings.getInputAttributesDebugString());
2264    }
2265}
2266