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