LatinIME.java revision 26b3d1de7ec8d94d982aab0ba54590de3462274c
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.inputmethod.latin;
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.AlertDialog;
24import android.content.BroadcastReceiver;
25import android.content.Context;
26import android.content.DialogInterface;
27import android.content.DialogInterface.OnClickListener;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.res.Configuration;
31import android.content.res.Resources;
32import android.inputmethodservice.InputMethodService;
33import android.media.AudioManager;
34import android.net.ConnectivityManager;
35import android.os.Debug;
36import android.os.IBinder;
37import android.os.Message;
38import android.preference.PreferenceManager;
39import android.text.InputType;
40import android.text.TextUtils;
41import android.util.Log;
42import android.util.PrintWriterPrinter;
43import android.util.Printer;
44import android.util.SparseArray;
45import android.view.Gravity;
46import android.view.KeyEvent;
47import android.view.View;
48import android.view.ViewGroup.LayoutParams;
49import android.view.ViewTreeObserver;
50import android.view.Window;
51import android.view.WindowManager;
52import android.view.inputmethod.CompletionInfo;
53import android.view.inputmethod.CursorAnchorInfo;
54import android.view.inputmethod.EditorInfo;
55import android.view.inputmethod.InputMethodSubtype;
56import android.widget.TextView;
57
58import com.android.inputmethod.accessibility.AccessibilityUtils;
59import com.android.inputmethod.annotations.UsedForTesting;
60import com.android.inputmethod.compat.CursorAnchorInfoCompatWrapper;
61import com.android.inputmethod.compat.InputMethodServiceCompatUtils;
62import com.android.inputmethod.dictionarypack.DictionaryPackConstants;
63import com.android.inputmethod.event.Event;
64import com.android.inputmethod.event.HardwareEventDecoder;
65import com.android.inputmethod.event.HardwareKeyboardEventDecoder;
66import com.android.inputmethod.event.InputTransaction;
67import com.android.inputmethod.keyboard.Keyboard;
68import com.android.inputmethod.keyboard.KeyboardActionListener;
69import com.android.inputmethod.keyboard.KeyboardId;
70import com.android.inputmethod.keyboard.KeyboardSwitcher;
71import com.android.inputmethod.keyboard.MainKeyboardView;
72import com.android.inputmethod.keyboard.TextDecoratorUi;
73import com.android.inputmethod.latin.Suggest.OnGetSuggestedWordsCallback;
74import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo;
75import com.android.inputmethod.latin.define.DebugFlags;
76import com.android.inputmethod.latin.define.ProductionFlags;
77import com.android.inputmethod.latin.inputlogic.InputLogic;
78import com.android.inputmethod.latin.personalization.ContextualDictionaryUpdater;
79import com.android.inputmethod.latin.personalization.DictionaryDecayBroadcastReciever;
80import com.android.inputmethod.latin.personalization.PersonalizationDictionaryUpdater;
81import com.android.inputmethod.latin.personalization.PersonalizationHelper;
82import com.android.inputmethod.latin.settings.Settings;
83import com.android.inputmethod.latin.settings.SettingsActivity;
84import com.android.inputmethod.latin.settings.SettingsValues;
85import com.android.inputmethod.latin.suggestions.SuggestionStripView;
86import com.android.inputmethod.latin.suggestions.SuggestionStripViewAccessor;
87import com.android.inputmethod.latin.utils.ApplicationUtils;
88import com.android.inputmethod.latin.utils.CapsModeUtils;
89import com.android.inputmethod.latin.utils.CoordinateUtils;
90import com.android.inputmethod.latin.utils.CursorAnchorInfoUtils;
91import com.android.inputmethod.latin.utils.DialogUtils;
92import com.android.inputmethod.latin.utils.DistracterFilterCheckingExactMatchesAndSuggestions;
93import com.android.inputmethod.latin.utils.ImportantNoticeUtils;
94import com.android.inputmethod.latin.utils.IntentUtils;
95import com.android.inputmethod.latin.utils.JniUtils;
96import com.android.inputmethod.latin.utils.LeakGuardHandlerWrapper;
97import com.android.inputmethod.latin.utils.StatsUtils;
98import com.android.inputmethod.latin.utils.SubtypeLocaleUtils;
99import com.android.inputmethod.latin.utils.ViewLayoutUtils;
100
101import java.io.FileDescriptor;
102import java.io.PrintWriter;
103import java.util.ArrayList;
104import java.util.List;
105import java.util.Locale;
106import java.util.concurrent.TimeUnit;
107
108/**
109 * Input method implementation for Qwerty'ish keyboard.
110 */
111public class LatinIME extends InputMethodService implements KeyboardActionListener,
112        SuggestionStripView.Listener, SuggestionStripViewAccessor,
113        DictionaryFacilitator.DictionaryInitializationListener,
114        ImportantNoticeDialog.ImportantNoticeDialogListener {
115    private static final String TAG = LatinIME.class.getSimpleName();
116    private static final boolean TRACE = false;
117    private static boolean DEBUG = false;
118
119    private static final int EXTENDED_TOUCHABLE_REGION_HEIGHT = 100;
120
121    private static final int PENDING_IMS_CALLBACK_DURATION = 800;
122
123    private static final int DELAY_WAIT_FOR_DICTIONARY_LOAD = 2000; // 2s
124
125    private static final int PERIOD_FOR_AUDIO_AND_HAPTIC_FEEDBACK_IN_KEY_REPEAT = 2;
126
127    /**
128     * The name of the scheme used by the Package Manager to warn of a new package installation,
129     * replacement or removal.
130     */
131    private static final String SCHEME_PACKAGE = "package";
132
133    private final Settings mSettings;
134    private final DictionaryFacilitator mDictionaryFacilitator =
135            new DictionaryFacilitator(
136                    new DistracterFilterCheckingExactMatchesAndSuggestions(this /* context */));
137    // TODO: Move from LatinIME.
138    private final PersonalizationDictionaryUpdater mPersonalizationDictionaryUpdater =
139            new PersonalizationDictionaryUpdater(this /* context */, mDictionaryFacilitator);
140    private final ContextualDictionaryUpdater mContextualDictionaryUpdater =
141            new ContextualDictionaryUpdater(this /* context */, mDictionaryFacilitator,
142                    new Runnable() {
143                        @Override
144                        public void run() {
145                            mHandler.postUpdateSuggestionStrip(SuggestedWords.INPUT_STYLE_NONE);
146                        }
147                    });
148    private final InputLogic mInputLogic = new InputLogic(this /* LatinIME */,
149            this /* SuggestionStripViewAccessor */, mDictionaryFacilitator);
150    // We expect to have only one decoder in almost all cases, hence the default capacity of 1.
151    // If it turns out we need several, it will get grown seamlessly.
152    final SparseArray<HardwareEventDecoder> mHardwareEventDecoders = new SparseArray<>(1);
153
154    // TODO: Move these {@link View}s to {@link KeyboardSwitcher}.
155    private View mInputView;
156    private SuggestionStripView mSuggestionStripView;
157    private TextView mExtractEditText;
158
159    private RichInputMethodManager mRichImm;
160    @UsedForTesting final KeyboardSwitcher mKeyboardSwitcher;
161    private final SubtypeSwitcher mSubtypeSwitcher;
162    private final SubtypeState mSubtypeState = new SubtypeState();
163    private final SpecialKeyDetector mSpecialKeyDetector;
164    // Working variable for {@link #startShowingInputView()} and
165    // {@link #onEvaluateInputViewShown()}.
166    private boolean mIsExecutingStartShowingInputView;
167
168    // Object for reacting to adding/removing a dictionary pack.
169    private final BroadcastReceiver mDictionaryPackInstallReceiver =
170            new DictionaryPackInstallBroadcastReceiver(this);
171
172    private final BroadcastReceiver mDictionaryDumpBroadcastReceiver =
173            new DictionaryDumpBroadcastReceiver(this);
174
175    private AlertDialog mOptionsDialog;
176
177    private final boolean mIsHardwareAcceleratedDrawingEnabled;
178
179    public final UIHandler mHandler = new UIHandler(this);
180
181    public static final class UIHandler extends LeakGuardHandlerWrapper<LatinIME> {
182        private static final int MSG_UPDATE_SHIFT_STATE = 0;
183        private static final int MSG_PENDING_IMS_CALLBACK = 1;
184        private static final int MSG_UPDATE_SUGGESTION_STRIP = 2;
185        private static final int MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP = 3;
186        private static final int MSG_RESUME_SUGGESTIONS = 4;
187        private static final int MSG_REOPEN_DICTIONARIES = 5;
188        private static final int MSG_UPDATE_TAIL_BATCH_INPUT_COMPLETED = 6;
189        private static final int MSG_RESET_CACHES = 7;
190        private static final int MSG_WAIT_FOR_DICTIONARY_LOAD = 8;
191        private static final int MSG_SHOW_COMMIT_INDICATOR = 9;
192        // Update this when adding new messages
193        private static final int MSG_LAST = MSG_SHOW_COMMIT_INDICATOR;
194
195        private static final int ARG1_NOT_GESTURE_INPUT = 0;
196        private static final int ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT = 1;
197        private static final int ARG1_SHOW_GESTURE_FLOATING_PREVIEW_TEXT = 2;
198        private static final int ARG2_UNUSED = 0;
199        private static final int ARG1_FALSE = 0;
200        private static final int ARG1_TRUE = 1;
201
202        private int mDelayInMillisecondsToUpdateSuggestions;
203        private int mDelayInMillisecondsToUpdateShiftState;
204        private int mDelayInMillisecondsToShowCommitIndicator;
205
206        public UIHandler(final LatinIME ownerInstance) {
207            super(ownerInstance);
208        }
209
210        public void onCreate() {
211            final LatinIME latinIme = getOwnerInstance();
212            if (latinIme == null) {
213                return;
214            }
215            final Resources res = latinIme.getResources();
216            mDelayInMillisecondsToUpdateSuggestions = res.getInteger(
217                    R.integer.config_delay_in_milliseconds_to_update_suggestions);
218            mDelayInMillisecondsToUpdateShiftState = res.getInteger(
219                    R.integer.config_delay_in_milliseconds_to_update_shift_state);
220            mDelayInMillisecondsToShowCommitIndicator = res.getInteger(
221                    R.integer.text_decorator_delay_in_milliseconds_to_show_commit_indicator);
222        }
223
224        @Override
225        public void handleMessage(final Message msg) {
226            final LatinIME latinIme = getOwnerInstance();
227            if (latinIme == null) {
228                return;
229            }
230            final KeyboardSwitcher switcher = latinIme.mKeyboardSwitcher;
231            switch (msg.what) {
232            case MSG_UPDATE_SUGGESTION_STRIP:
233                cancelUpdateSuggestionStrip();
234                latinIme.mInputLogic.performUpdateSuggestionStripSync(
235                        latinIme.mSettings.getCurrent(), msg.arg1 /* inputStyle */);
236                break;
237            case MSG_UPDATE_SHIFT_STATE:
238                switcher.requestUpdatingShiftState(latinIme.getCurrentAutoCapsState(),
239                        latinIme.getCurrentRecapitalizeState());
240                break;
241            case MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP:
242                if (msg.arg1 == ARG1_NOT_GESTURE_INPUT) {
243                    final SuggestedWords suggestedWords = (SuggestedWords) msg.obj;
244                    latinIme.showSuggestionStrip(suggestedWords);
245                } else {
246                    latinIme.showGesturePreviewAndSuggestionStrip((SuggestedWords) msg.obj,
247                            msg.arg1 == ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT);
248                }
249                break;
250            case MSG_RESUME_SUGGESTIONS:
251                latinIme.mInputLogic.restartSuggestionsOnWordTouchedByCursor(
252                        latinIme.mSettings.getCurrent(),
253                        msg.arg1 == ARG1_TRUE /* shouldIncludeResumedWordInSuggestions */,
254                        latinIme.mKeyboardSwitcher.getCurrentKeyboardScriptId());
255                break;
256            case MSG_REOPEN_DICTIONARIES:
257                // We need to re-evaluate the currently composing word in case the script has
258                // changed.
259                postWaitForDictionaryLoad();
260                latinIme.resetSuggest();
261                break;
262            case MSG_UPDATE_TAIL_BATCH_INPUT_COMPLETED:
263                latinIme.mInputLogic.onUpdateTailBatchInputCompleted(
264                        latinIme.mSettings.getCurrent(),
265                        (SuggestedWords) msg.obj, latinIme.mKeyboardSwitcher);
266                break;
267            case MSG_RESET_CACHES:
268                final SettingsValues settingsValues = latinIme.mSettings.getCurrent();
269                if (latinIme.mInputLogic.retryResetCachesAndReturnSuccess(
270                        msg.arg1 == ARG1_TRUE /* tryResumeSuggestions */,
271                        msg.arg2 /* remainingTries */, this /* handler */)) {
272                    // If we were able to reset the caches, then we can reload the keyboard.
273                    // Otherwise, we'll do it when we can.
274                    latinIme.mKeyboardSwitcher.loadKeyboard(latinIme.getCurrentInputEditorInfo(),
275                            settingsValues, latinIme.getCurrentAutoCapsState(),
276                            latinIme.getCurrentRecapitalizeState());
277                }
278                break;
279            case MSG_SHOW_COMMIT_INDICATOR:
280                // Protocol of MSG_SET_COMMIT_INDICATOR_ENABLED:
281                // - what: MSG_SHOW_COMMIT_INDICATOR
282                // - arg1: not used.
283                // - arg2: not used.
284                // - obj:  the Runnable object to be called back.
285                ((Runnable) msg.obj).run();
286                break;
287            case MSG_WAIT_FOR_DICTIONARY_LOAD:
288                Log.i(TAG, "Timeout waiting for dictionary load");
289                break;
290            }
291        }
292
293        public void postUpdateSuggestionStrip(final int inputStyle) {
294            sendMessageDelayed(obtainMessage(MSG_UPDATE_SUGGESTION_STRIP, inputStyle,
295                    0 /* ignored */), mDelayInMillisecondsToUpdateSuggestions);
296        }
297
298        public void postReopenDictionaries() {
299            sendMessage(obtainMessage(MSG_REOPEN_DICTIONARIES));
300        }
301
302        public void postResumeSuggestions(final boolean shouldIncludeResumedWordInSuggestions,
303                final boolean shouldDelay) {
304            final LatinIME latinIme = getOwnerInstance();
305            if (latinIme == null) {
306                return;
307            }
308            if (!latinIme.mSettings.getCurrent().isSuggestionsEnabledPerUserSettings()) {
309                return;
310            }
311            removeMessages(MSG_RESUME_SUGGESTIONS);
312            if (shouldDelay) {
313                sendMessageDelayed(obtainMessage(MSG_RESUME_SUGGESTIONS,
314                        shouldIncludeResumedWordInSuggestions ? ARG1_TRUE : ARG1_FALSE,
315                        0 /* ignored */), mDelayInMillisecondsToUpdateSuggestions);
316            } else {
317                sendMessage(obtainMessage(MSG_RESUME_SUGGESTIONS,
318                        shouldIncludeResumedWordInSuggestions ? ARG1_TRUE : ARG1_FALSE,
319                        0 /* ignored */));
320            }
321        }
322
323        public void postResetCaches(final boolean tryResumeSuggestions, final int remainingTries) {
324            removeMessages(MSG_RESET_CACHES);
325            sendMessage(obtainMessage(MSG_RESET_CACHES, tryResumeSuggestions ? 1 : 0,
326                    remainingTries, null));
327        }
328
329        public void postWaitForDictionaryLoad() {
330            sendMessageDelayed(obtainMessage(MSG_WAIT_FOR_DICTIONARY_LOAD),
331                    DELAY_WAIT_FOR_DICTIONARY_LOAD);
332        }
333
334        public void cancelWaitForDictionaryLoad() {
335            removeMessages(MSG_WAIT_FOR_DICTIONARY_LOAD);
336        }
337
338        public boolean hasPendingWaitForDictionaryLoad() {
339            return hasMessages(MSG_WAIT_FOR_DICTIONARY_LOAD);
340        }
341
342        public void cancelUpdateSuggestionStrip() {
343            removeMessages(MSG_UPDATE_SUGGESTION_STRIP);
344        }
345
346        public boolean hasPendingUpdateSuggestions() {
347            return hasMessages(MSG_UPDATE_SUGGESTION_STRIP);
348        }
349
350        public boolean hasPendingReopenDictionaries() {
351            return hasMessages(MSG_REOPEN_DICTIONARIES);
352        }
353
354        public void postUpdateShiftState() {
355            removeMessages(MSG_UPDATE_SHIFT_STATE);
356            sendMessageDelayed(obtainMessage(MSG_UPDATE_SHIFT_STATE),
357                    mDelayInMillisecondsToUpdateShiftState);
358        }
359
360        @UsedForTesting
361        public void removeAllMessages() {
362            for (int i = 0; i <= MSG_LAST; ++i) {
363                removeMessages(i);
364            }
365        }
366
367        public void showGesturePreviewAndSuggestionStrip(final SuggestedWords suggestedWords,
368                final boolean dismissGestureFloatingPreviewText) {
369            removeMessages(MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP);
370            final int arg1 = dismissGestureFloatingPreviewText
371                    ? ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT
372                    : ARG1_SHOW_GESTURE_FLOATING_PREVIEW_TEXT;
373            obtainMessage(MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP, arg1,
374                    ARG2_UNUSED, suggestedWords).sendToTarget();
375        }
376
377        public void showSuggestionStrip(final SuggestedWords suggestedWords) {
378            removeMessages(MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP);
379            obtainMessage(MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP,
380                    ARG1_NOT_GESTURE_INPUT, ARG2_UNUSED, suggestedWords).sendToTarget();
381        }
382
383        public void showTailBatchInputResult(final SuggestedWords suggestedWords) {
384            obtainMessage(MSG_UPDATE_TAIL_BATCH_INPUT_COMPLETED, suggestedWords).sendToTarget();
385        }
386
387        /**
388         * Posts a delayed task to show the commit indicator.
389         *
390         * <p>Only one task can exist in the queue. When this method is called, any prior task that
391         * has not yet fired will be canceled.</p>
392         * @param task the runnable object that will be fired when the delayed task is dispatched.
393         */
394        public void postShowCommitIndicatorTask(final Runnable task) {
395            removeMessages(MSG_SHOW_COMMIT_INDICATOR);
396            sendMessageDelayed(obtainMessage(MSG_SHOW_COMMIT_INDICATOR, task),
397                    mDelayInMillisecondsToShowCommitIndicator);
398        }
399
400        // Working variables for the following methods.
401        private boolean mIsOrientationChanging;
402        private boolean mPendingSuccessiveImsCallback;
403        private boolean mHasPendingStartInput;
404        private boolean mHasPendingFinishInputView;
405        private boolean mHasPendingFinishInput;
406        private EditorInfo mAppliedEditorInfo;
407
408        public void startOrientationChanging() {
409            removeMessages(MSG_PENDING_IMS_CALLBACK);
410            resetPendingImsCallback();
411            mIsOrientationChanging = true;
412            final LatinIME latinIme = getOwnerInstance();
413            if (latinIme == null) {
414                return;
415            }
416            if (latinIme.isInputViewShown()) {
417                latinIme.mKeyboardSwitcher.saveKeyboardState();
418            }
419        }
420
421        private void resetPendingImsCallback() {
422            mHasPendingFinishInputView = false;
423            mHasPendingFinishInput = false;
424            mHasPendingStartInput = false;
425        }
426
427        private void executePendingImsCallback(final LatinIME latinIme, final EditorInfo editorInfo,
428                boolean restarting) {
429            if (mHasPendingFinishInputView) {
430                latinIme.onFinishInputViewInternal(mHasPendingFinishInput);
431            }
432            if (mHasPendingFinishInput) {
433                latinIme.onFinishInputInternal();
434            }
435            if (mHasPendingStartInput) {
436                latinIme.onStartInputInternal(editorInfo, restarting);
437            }
438            resetPendingImsCallback();
439        }
440
441        public void onStartInput(final EditorInfo editorInfo, final boolean restarting) {
442            if (hasMessages(MSG_PENDING_IMS_CALLBACK)) {
443                // Typically this is the second onStartInput after orientation changed.
444                mHasPendingStartInput = true;
445            } else {
446                if (mIsOrientationChanging && restarting) {
447                    // This is the first onStartInput after orientation changed.
448                    mIsOrientationChanging = false;
449                    mPendingSuccessiveImsCallback = true;
450                }
451                final LatinIME latinIme = getOwnerInstance();
452                if (latinIme != null) {
453                    executePendingImsCallback(latinIme, editorInfo, restarting);
454                    latinIme.onStartInputInternal(editorInfo, restarting);
455                }
456            }
457        }
458
459        public void onStartInputView(final EditorInfo editorInfo, final boolean restarting) {
460            if (hasMessages(MSG_PENDING_IMS_CALLBACK)
461                    && KeyboardId.equivalentEditorInfoForKeyboard(editorInfo, mAppliedEditorInfo)) {
462                // Typically this is the second onStartInputView after orientation changed.
463                resetPendingImsCallback();
464            } else {
465                if (mPendingSuccessiveImsCallback) {
466                    // This is the first onStartInputView after orientation changed.
467                    mPendingSuccessiveImsCallback = false;
468                    resetPendingImsCallback();
469                    sendMessageDelayed(obtainMessage(MSG_PENDING_IMS_CALLBACK),
470                            PENDING_IMS_CALLBACK_DURATION);
471                }
472                final LatinIME latinIme = getOwnerInstance();
473                if (latinIme != null) {
474                    executePendingImsCallback(latinIme, editorInfo, restarting);
475                    latinIme.onStartInputViewInternal(editorInfo, restarting);
476                    mAppliedEditorInfo = editorInfo;
477                }
478            }
479        }
480
481        public void onFinishInputView(final boolean finishingInput) {
482            if (hasMessages(MSG_PENDING_IMS_CALLBACK)) {
483                // Typically this is the first onFinishInputView after orientation changed.
484                mHasPendingFinishInputView = true;
485            } else {
486                final LatinIME latinIme = getOwnerInstance();
487                if (latinIme != null) {
488                    latinIme.onFinishInputViewInternal(finishingInput);
489                    mAppliedEditorInfo = null;
490                }
491            }
492        }
493
494        public void onFinishInput() {
495            if (hasMessages(MSG_PENDING_IMS_CALLBACK)) {
496                // Typically this is the first onFinishInput after orientation changed.
497                mHasPendingFinishInput = true;
498            } else {
499                final LatinIME latinIme = getOwnerInstance();
500                if (latinIme != null) {
501                    executePendingImsCallback(latinIme, null, false);
502                    latinIme.onFinishInputInternal();
503                }
504            }
505        }
506    }
507
508    static final class SubtypeState {
509        private InputMethodSubtype mLastActiveSubtype;
510        private boolean mCurrentSubtypeHasBeenUsed;
511
512        public void setCurrentSubtypeHasBeenUsed() {
513            mCurrentSubtypeHasBeenUsed = true;
514        }
515
516        public void switchSubtype(final IBinder token, final RichInputMethodManager richImm) {
517            final InputMethodSubtype currentSubtype = richImm.getInputMethodManager()
518                    .getCurrentInputMethodSubtype();
519            final InputMethodSubtype lastActiveSubtype = mLastActiveSubtype;
520            final boolean currentSubtypeHasBeenUsed = mCurrentSubtypeHasBeenUsed;
521            if (currentSubtypeHasBeenUsed) {
522                mLastActiveSubtype = currentSubtype;
523                mCurrentSubtypeHasBeenUsed = false;
524            }
525            if (currentSubtypeHasBeenUsed
526                    && richImm.checkIfSubtypeBelongsToThisImeAndEnabled(lastActiveSubtype)
527                    && !currentSubtype.equals(lastActiveSubtype)) {
528                richImm.setInputMethodAndSubtype(token, lastActiveSubtype);
529                return;
530            }
531            richImm.switchToNextInputMethod(token, true /* onlyCurrentIme */);
532        }
533    }
534
535    // Loading the native library eagerly to avoid unexpected UnsatisfiedLinkError at the initial
536    // JNI call as much as possible.
537    static {
538        JniUtils.loadNativeLibrary();
539    }
540
541    public LatinIME() {
542        super();
543        mSettings = Settings.getInstance();
544        mSubtypeSwitcher = SubtypeSwitcher.getInstance();
545        mKeyboardSwitcher = KeyboardSwitcher.getInstance();
546        mSpecialKeyDetector = new SpecialKeyDetector(this);
547        mIsHardwareAcceleratedDrawingEnabled =
548                InputMethodServiceCompatUtils.enableHardwareAcceleration(this);
549        Log.i(TAG, "Hardware accelerated drawing: " + mIsHardwareAcceleratedDrawingEnabled);
550    }
551
552    @Override
553    public void onCreate() {
554        Settings.init(this);
555        DebugFlags.init(PreferenceManager.getDefaultSharedPreferences(this));
556        RichInputMethodManager.init(this);
557        mRichImm = RichInputMethodManager.getInstance();
558        SubtypeSwitcher.init(this);
559        KeyboardSwitcher.init(this);
560        AudioAndHapticFeedbackManager.init(this);
561        AccessibilityUtils.init(this);
562        StatsUtils.init(this);
563
564        super.onCreate();
565
566        mHandler.onCreate();
567        DEBUG = DebugFlags.DEBUG_ENABLED;
568
569        // TODO: Resolve mutual dependencies of {@link #loadSettings()} and {@link #initSuggest()}.
570        loadSettings();
571        resetSuggest();
572
573        // Register to receive ringer mode change and network state change.
574        // Also receive installation and removal of a dictionary pack.
575        final IntentFilter filter = new IntentFilter();
576        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
577        filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION);
578        registerReceiver(mConnectivityAndRingerModeChangeReceiver, filter);
579
580        final IntentFilter packageFilter = new IntentFilter();
581        packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
582        packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
583        packageFilter.addDataScheme(SCHEME_PACKAGE);
584        registerReceiver(mDictionaryPackInstallReceiver, packageFilter);
585
586        final IntentFilter newDictFilter = new IntentFilter();
587        newDictFilter.addAction(DictionaryPackConstants.NEW_DICTIONARY_INTENT_ACTION);
588        registerReceiver(mDictionaryPackInstallReceiver, newDictFilter);
589
590        final IntentFilter dictDumpFilter = new IntentFilter();
591        dictDumpFilter.addAction(DictionaryDumpBroadcastReceiver.DICTIONARY_DUMP_INTENT_ACTION);
592        registerReceiver(mDictionaryDumpBroadcastReceiver, dictDumpFilter);
593
594        DictionaryDecayBroadcastReciever.setUpIntervalAlarmForDictionaryDecaying(this);
595
596        StatsUtils.onCreate(mSettings.getCurrent());
597    }
598
599    // Has to be package-visible for unit tests
600    @UsedForTesting
601    void loadSettings() {
602        final Locale locale = mSubtypeSwitcher.getCurrentSubtypeLocale();
603        final EditorInfo editorInfo = getCurrentInputEditorInfo();
604        final InputAttributes inputAttributes = new InputAttributes(
605                editorInfo, isFullscreenMode(), getPackageName());
606        mSettings.loadSettings(this, locale, inputAttributes);
607        final SettingsValues currentSettingsValues = mSettings.getCurrent();
608        AudioAndHapticFeedbackManager.getInstance().onSettingsChanged(currentSettingsValues);
609        // This method is called on startup and language switch, before the new layout has
610        // been displayed. Opening dictionaries never affects responsivity as dictionaries are
611        // asynchronously loaded.
612        if (!mHandler.hasPendingReopenDictionaries()) {
613            resetSuggestForLocale(locale);
614        }
615        mDictionaryFacilitator.updateEnabledSubtypes(mRichImm.getMyEnabledInputMethodSubtypeList(
616                true /* allowsImplicitlySelectedSubtypes */));
617        refreshPersonalizationDictionarySession(currentSettingsValues);
618        StatsUtils.onLoadSettings(currentSettingsValues);
619    }
620
621    private void refreshPersonalizationDictionarySession(
622            final SettingsValues currentSettingsValues) {
623        mPersonalizationDictionaryUpdater.onLoadSettings(
624                currentSettingsValues.mUsePersonalizedDicts,
625                mSubtypeSwitcher.isSystemLocaleSameAsLocaleOfAllEnabledSubtypesOfEnabledImes());
626        mContextualDictionaryUpdater.onLoadSettings(currentSettingsValues.mUsePersonalizedDicts);
627        final boolean shouldKeepUserHistoryDictionaries;
628        if (currentSettingsValues.mUsePersonalizedDicts) {
629            shouldKeepUserHistoryDictionaries = true;
630        } else {
631            shouldKeepUserHistoryDictionaries = false;
632        }
633        if (!shouldKeepUserHistoryDictionaries) {
634            // Remove user history dictionaries.
635            PersonalizationHelper.removeAllUserHistoryDictionaries(this);
636            mDictionaryFacilitator.clearUserHistoryDictionary();
637        }
638    }
639
640    // Note that this method is called from a non-UI thread.
641    @Override
642    public void onUpdateMainDictionaryAvailability(final boolean isMainDictionaryAvailable) {
643        final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
644        if (mainKeyboardView != null) {
645            mainKeyboardView.setMainDictionaryAvailability(isMainDictionaryAvailable);
646        }
647        if (mHandler.hasPendingWaitForDictionaryLoad()) {
648            mHandler.cancelWaitForDictionaryLoad();
649            mHandler.postResumeSuggestions(true /* shouldIncludeResumedWordInSuggestions */,
650                    false /* shouldDelay */);
651        }
652    }
653
654    private void resetSuggest() {
655        final Locale switcherSubtypeLocale = mSubtypeSwitcher.getCurrentSubtypeLocale();
656        final String switcherLocaleStr = switcherSubtypeLocale.toString();
657        final Locale subtypeLocale;
658        if (TextUtils.isEmpty(switcherLocaleStr)) {
659            // This happens in very rare corner cases - for example, immediately after a switch
660            // to LatinIME has been requested, about a frame later another switch happens. In this
661            // case, we are about to go down but we still don't know it, however the system tells
662            // us there is no current subtype so the locale is the empty string. Take the best
663            // possible guess instead -- it's bound to have no consequences, and we have no way
664            // of knowing anyway.
665            Log.e(TAG, "System is reporting no current subtype.");
666            subtypeLocale = getResources().getConfiguration().locale;
667        } else {
668            subtypeLocale = switcherSubtypeLocale;
669        }
670        resetSuggestForLocale(subtypeLocale);
671    }
672
673    /**
674     * Reset suggest by loading dictionaries for the locale and the current settings values.
675     *
676     * @param locale the locale
677     */
678    private void resetSuggestForLocale(final Locale locale) {
679        final SettingsValues settingsValues = mSettings.getCurrent();
680        mDictionaryFacilitator.resetDictionaries(this /* context */, locale,
681                settingsValues.mUseContactsDict, settingsValues.mUsePersonalizedDicts,
682                false /* forceReloadMainDictionary */, this);
683        if (settingsValues.mAutoCorrectionEnabledPerUserSettings) {
684            mInputLogic.mSuggest.setAutoCorrectionThreshold(
685                    settingsValues.mAutoCorrectionThreshold);
686        }
687    }
688
689    /**
690     * Reset suggest by loading the main dictionary of the current locale.
691     */
692    /* package private */ void resetSuggestMainDict() {
693        final SettingsValues settingsValues = mSettings.getCurrent();
694        mDictionaryFacilitator.resetDictionaries(this /* context */,
695                mDictionaryFacilitator.getLocale(), settingsValues.mUseContactsDict,
696                settingsValues.mUsePersonalizedDicts, true /* forceReloadMainDictionary */, this);
697    }
698
699    @Override
700    public void onDestroy() {
701        mDictionaryFacilitator.closeDictionaries();
702        mPersonalizationDictionaryUpdater.onDestroy();
703        mContextualDictionaryUpdater.onDestroy();
704        mSettings.onDestroy();
705        unregisterReceiver(mConnectivityAndRingerModeChangeReceiver);
706        unregisterReceiver(mDictionaryPackInstallReceiver);
707        unregisterReceiver(mDictionaryDumpBroadcastReceiver);
708        StatsUtils.onDestroy();
709        super.onDestroy();
710    }
711
712    @UsedForTesting
713    public void recycle() {
714        unregisterReceiver(mDictionaryPackInstallReceiver);
715        unregisterReceiver(mDictionaryDumpBroadcastReceiver);
716        unregisterReceiver(mConnectivityAndRingerModeChangeReceiver);
717        mInputLogic.recycle();
718    }
719
720    @Override
721    public void onConfigurationChanged(final Configuration conf) {
722        SettingsValues settingsValues = mSettings.getCurrent();
723        if (settingsValues.mDisplayOrientation != conf.orientation) {
724            mHandler.startOrientationChanging();
725            mInputLogic.onOrientationChange(mSettings.getCurrent());
726        }
727        if (settingsValues.mHasHardwareKeyboard != Settings.readHasHardwareKeyboard(conf)) {
728            // If the state of having a hardware keyboard changed, then we want to reload the
729            // settings to adjust for that.
730            // TODO: we should probably do this unconditionally here, rather than only when we
731            // have a change in hardware keyboard configuration.
732            loadSettings();
733            settingsValues = mSettings.getCurrent();
734            if (settingsValues.mHasHardwareKeyboard) {
735                // We call cleanupInternalStateForFinishInput() because it's the right thing to do;
736                // however, it seems at the moment the framework is passing us a seemingly valid
737                // but actually non-functional InputConnection object. So if this bug ever gets
738                // fixed we'll be able to remove the composition, but until it is this code is
739                // actually not doing much.
740                cleanupInternalStateForFinishInput();
741            }
742        }
743        // TODO: Remove this test.
744        if (!conf.locale.equals(mPersonalizationDictionaryUpdater.getLocale())) {
745            refreshPersonalizationDictionarySession(settingsValues);
746        }
747        super.onConfigurationChanged(conf);
748    }
749
750    @Override
751    public View onCreateInputView() {
752        return mKeyboardSwitcher.onCreateInputView(mIsHardwareAcceleratedDrawingEnabled);
753    }
754
755    @Override
756    public void setInputView(final View view) {
757        super.setInputView(view);
758        mInputView = view;
759        mSuggestionStripView = (SuggestionStripView)view.findViewById(R.id.suggestion_strip_view);
760        if (hasSuggestionStripView()) {
761            mSuggestionStripView.setListener(this, view);
762        }
763        mInputLogic.setTextDecoratorUi(new TextDecoratorUi(this, view));
764    }
765
766    @Override
767    public void setExtractView(final View view) {
768        final TextView prevExtractEditText = mExtractEditText;
769        super.setExtractView(view);
770        TextView nextExtractEditText = null;
771        if (view != null) {
772            final View extractEditText = view.findViewById(android.R.id.inputExtractEditText);
773            if (extractEditText instanceof TextView) {
774                nextExtractEditText = (TextView)extractEditText;
775            }
776        }
777        if (prevExtractEditText == nextExtractEditText) {
778            return;
779        }
780        if (ProductionFlags.ENABLE_CURSOR_ANCHOR_INFO_CALLBACK && prevExtractEditText != null) {
781            prevExtractEditText.getViewTreeObserver().removeOnPreDrawListener(
782                    mExtractTextViewPreDrawListener);
783        }
784        mExtractEditText = nextExtractEditText;
785        if (ProductionFlags.ENABLE_CURSOR_ANCHOR_INFO_CALLBACK && mExtractEditText != null) {
786            mExtractEditText.getViewTreeObserver().addOnPreDrawListener(
787                    mExtractTextViewPreDrawListener);
788        }
789    }
790
791    private final ViewTreeObserver.OnPreDrawListener mExtractTextViewPreDrawListener =
792            new ViewTreeObserver.OnPreDrawListener() {
793                @Override
794                public boolean onPreDraw() {
795                    onExtractTextViewPreDraw();
796                    return true;
797                }
798            };
799
800    private void onExtractTextViewPreDraw() {
801        if (!ProductionFlags.ENABLE_CURSOR_ANCHOR_INFO_CALLBACK || !isFullscreenMode()
802                || mExtractEditText == null) {
803            return;
804        }
805        final CursorAnchorInfo info = CursorAnchorInfoUtils.getCursorAnchorInfo(mExtractEditText);
806        mInputLogic.onUpdateCursorAnchorInfo(CursorAnchorInfoCompatWrapper.fromObject(info));
807    }
808
809    @Override
810    public void setCandidatesView(final View view) {
811        // To ensure that CandidatesView will never be set.
812        return;
813    }
814
815    @Override
816    public void onStartInput(final EditorInfo editorInfo, final boolean restarting) {
817        mHandler.onStartInput(editorInfo, restarting);
818    }
819
820    @Override
821    public void onStartInputView(final EditorInfo editorInfo, final boolean restarting) {
822        mHandler.onStartInputView(editorInfo, restarting);
823    }
824
825    @Override
826    public void onFinishInputView(final boolean finishingInput) {
827        mHandler.onFinishInputView(finishingInput);
828    }
829
830    @Override
831    public void onFinishInput() {
832        mHandler.onFinishInput();
833    }
834
835    @Override
836    public void onCurrentInputMethodSubtypeChanged(final InputMethodSubtype subtype) {
837        // Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged()
838        // is not guaranteed. It may even be called at the same time on a different thread.
839        mSubtypeSwitcher.onSubtypeChanged(subtype);
840        mInputLogic.onSubtypeChanged(SubtypeLocaleUtils.getCombiningRulesExtraValue(subtype),
841                mSettings.getCurrent());
842        loadKeyboard();
843    }
844
845    private void onStartInputInternal(final EditorInfo editorInfo, final boolean restarting) {
846        super.onStartInput(editorInfo, restarting);
847    }
848
849    @SuppressWarnings("deprecation")
850    private void onStartInputViewInternal(final EditorInfo editorInfo, final boolean restarting) {
851        super.onStartInputView(editorInfo, restarting);
852        mRichImm.clearSubtypeCaches();
853        final KeyboardSwitcher switcher = mKeyboardSwitcher;
854        switcher.updateKeyboardTheme();
855        final MainKeyboardView mainKeyboardView = switcher.getMainKeyboardView();
856        // If we are starting input in a different text field from before, we'll have to reload
857        // settings, so currentSettingsValues can't be final.
858        SettingsValues currentSettingsValues = mSettings.getCurrent();
859
860        if (editorInfo == null) {
861            Log.e(TAG, "Null EditorInfo in onStartInputView()");
862            if (DebugFlags.DEBUG_ENABLED) {
863                throw new NullPointerException("Null EditorInfo in onStartInputView()");
864            }
865            return;
866        }
867        if (DEBUG) {
868            Log.d(TAG, "onStartInputView: editorInfo:"
869                    + String.format("inputType=0x%08x imeOptions=0x%08x",
870                            editorInfo.inputType, editorInfo.imeOptions));
871            Log.d(TAG, "All caps = "
872                    + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0)
873                    + ", sentence caps = "
874                    + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0)
875                    + ", word caps = "
876                    + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_WORDS) != 0));
877        }
878        Log.i(TAG, "Starting input. Cursor position = "
879                + editorInfo.initialSelStart + "," + editorInfo.initialSelEnd);
880        // TODO: Consolidate these checks with {@link InputAttributes}.
881        if (InputAttributes.inPrivateImeOptions(null, NO_MICROPHONE_COMPAT, editorInfo)) {
882            Log.w(TAG, "Deprecated private IME option specified: " + editorInfo.privateImeOptions);
883            Log.w(TAG, "Use " + getPackageName() + "." + NO_MICROPHONE + " instead");
884        }
885        if (InputAttributes.inPrivateImeOptions(getPackageName(), FORCE_ASCII, editorInfo)) {
886            Log.w(TAG, "Deprecated private IME option specified: " + editorInfo.privateImeOptions);
887            Log.w(TAG, "Use EditorInfo.IME_FLAG_FORCE_ASCII flag instead");
888        }
889
890        // In landscape mode, this method gets called without the input view being created.
891        if (mainKeyboardView == null) {
892            return;
893        }
894
895        // Forward this event to the accessibility utilities, if enabled.
896        final AccessibilityUtils accessUtils = AccessibilityUtils.getInstance();
897        if (accessUtils.isTouchExplorationEnabled()) {
898            accessUtils.onStartInputViewInternal(mainKeyboardView, editorInfo, restarting);
899        }
900
901        final boolean inputTypeChanged = !currentSettingsValues.isSameInputType(editorInfo);
902        final boolean isDifferentTextField = !restarting || inputTypeChanged;
903        if (isDifferentTextField) {
904            mSubtypeSwitcher.updateParametersOnStartInputView();
905        }
906
907        // The EditorInfo might have a flag that affects fullscreen mode.
908        // Note: This call should be done by InputMethodService?
909        updateFullscreenMode();
910
911        // ALERT: settings have not been reloaded and there is a chance they may be stale.
912        // In the practice, if it is, we should have gotten onConfigurationChanged so it should
913        // be fine, but this is horribly confusing and must be fixed AS SOON AS POSSIBLE.
914
915        // In some cases the input connection has not been reset yet and we can't access it. In
916        // this case we will need to call loadKeyboard() later, when it's accessible, so that we
917        // can go into the correct mode, so we need to do some housekeeping here.
918        final boolean needToCallLoadKeyboardLater;
919        final Suggest suggest = mInputLogic.mSuggest;
920        if (!currentSettingsValues.mHasHardwareKeyboard) {
921            // The app calling setText() has the effect of clearing the composing
922            // span, so we should reset our state unconditionally, even if restarting is true.
923            // We also tell the input logic about the combining rules for the current subtype, so
924            // it can adjust its combiners if needed.
925            mInputLogic.startInput(mSubtypeSwitcher.getCombiningRulesExtraValueOfCurrentSubtype(),
926                    currentSettingsValues);
927
928            // Note: the following does a round-trip IPC on the main thread: be careful
929            final Locale currentLocale = mSubtypeSwitcher.getCurrentSubtypeLocale();
930            if (null != currentLocale && !currentLocale.equals(suggest.getLocale())) {
931                // TODO: Do this automatically.
932                resetSuggest();
933            }
934
935            // TODO[IL]: Can the following be moved to InputLogic#startInput?
936            if (!mInputLogic.mConnection.resetCachesUponCursorMoveAndReturnSuccess(
937                    editorInfo.initialSelStart, editorInfo.initialSelEnd,
938                    false /* shouldFinishComposition */)) {
939                // Sometimes, while rotating, for some reason the framework tells the app we are not
940                // connected to it and that means we can't refresh the cache. In this case, schedule
941                // a refresh later.
942                // We try resetting the caches up to 5 times before giving up.
943                mHandler.postResetCaches(isDifferentTextField, 5 /* remainingTries */);
944                // mLastSelection{Start,End} are reset later in this method, no need to do it here
945                needToCallLoadKeyboardLater = true;
946            } else {
947                // When rotating, initialSelStart and initialSelEnd sometimes are lying. Make a best
948                // effort to work around this bug.
949                mInputLogic.mConnection.tryFixLyingCursorPosition();
950                mHandler.postResumeSuggestions(true /* shouldIncludeResumedWordInSuggestions */,
951                        true /* shouldDelay */);
952                needToCallLoadKeyboardLater = false;
953            }
954        } else {
955            // If we have a hardware keyboard we don't need to call loadKeyboard later anyway.
956            needToCallLoadKeyboardLater = false;
957        }
958
959        if (isDifferentTextField ||
960                !currentSettingsValues.hasSameOrientation(getResources().getConfiguration())) {
961            loadSettings();
962        }
963        if (isDifferentTextField) {
964            mainKeyboardView.closing();
965            currentSettingsValues = mSettings.getCurrent();
966
967            if (currentSettingsValues.mAutoCorrectionEnabledPerUserSettings) {
968                suggest.setAutoCorrectionThreshold(
969                        currentSettingsValues.mAutoCorrectionThreshold);
970            }
971
972            switcher.loadKeyboard(editorInfo, currentSettingsValues, getCurrentAutoCapsState(),
973                    getCurrentRecapitalizeState());
974            if (needToCallLoadKeyboardLater) {
975                // If we need to call loadKeyboard again later, we need to save its state now. The
976                // later call will be done in #retryResetCaches.
977                switcher.saveKeyboardState();
978            }
979        } else if (restarting) {
980            // TODO: Come up with a more comprehensive way to reset the keyboard layout when
981            // a keyboard layout set doesn't get reloaded in this method.
982            switcher.resetKeyboardStateToAlphabet(getCurrentAutoCapsState(),
983                    getCurrentRecapitalizeState());
984            // In apps like Talk, we come here when the text is sent and the field gets emptied and
985            // we need to re-evaluate the shift state, but not the whole layout which would be
986            // disruptive.
987            // Space state must be updated before calling updateShiftState
988            switcher.requestUpdatingShiftState(getCurrentAutoCapsState(),
989                    getCurrentRecapitalizeState());
990        }
991        // This will set the punctuation suggestions if next word suggestion is off;
992        // otherwise it will clear the suggestion strip.
993        setNeutralSuggestionStrip();
994
995        mHandler.cancelUpdateSuggestionStrip();
996
997        mainKeyboardView.setMainDictionaryAvailability(
998                mDictionaryFacilitator.hasInitializedMainDictionary());
999        mainKeyboardView.setKeyPreviewPopupEnabled(currentSettingsValues.mKeyPreviewPopupOn,
1000                currentSettingsValues.mKeyPreviewPopupDismissDelay);
1001        mainKeyboardView.setSlidingKeyInputPreviewEnabled(
1002                currentSettingsValues.mSlidingKeyInputPreviewEnabled);
1003        mainKeyboardView.setGestureHandlingEnabledByUser(
1004                currentSettingsValues.mGestureInputEnabled,
1005                currentSettingsValues.mGestureTrailEnabled,
1006                currentSettingsValues.mGestureFloatingPreviewTextEnabled);
1007
1008        // Contextual dictionary should be updated for the current application.
1009        mContextualDictionaryUpdater.onStartInputView(editorInfo.packageName);
1010        if (TRACE) Debug.startMethodTracing("/data/trace/latinime");
1011    }
1012
1013    @Override
1014    public void onWindowHidden() {
1015        super.onWindowHidden();
1016        final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
1017        if (mainKeyboardView != null) {
1018            mainKeyboardView.closing();
1019        }
1020    }
1021
1022    private void onFinishInputInternal() {
1023        super.onFinishInput();
1024
1025        final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
1026        if (mainKeyboardView != null) {
1027            mainKeyboardView.closing();
1028        }
1029    }
1030
1031    private void onFinishInputViewInternal(final boolean finishingInput) {
1032        super.onFinishInputView(finishingInput);
1033        cleanupInternalStateForFinishInput();
1034    }
1035
1036    private void cleanupInternalStateForFinishInput() {
1037        mKeyboardSwitcher.deallocateMemory();
1038        // Remove pending messages related to update suggestions
1039        mHandler.cancelUpdateSuggestionStrip();
1040        // Should do the following in onFinishInputInternal but until JB MR2 it's not called :(
1041        mInputLogic.finishInput();
1042    }
1043
1044    @Override
1045    public void onUpdateSelection(final int oldSelStart, final int oldSelEnd,
1046            final int newSelStart, final int newSelEnd,
1047            final int composingSpanStart, final int composingSpanEnd) {
1048        super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd,
1049                composingSpanStart, composingSpanEnd);
1050        if (DEBUG) {
1051            Log.i(TAG, "onUpdateSelection: oss=" + oldSelStart + ", ose=" + oldSelEnd
1052                    + ", nss=" + newSelStart + ", nse=" + newSelEnd
1053                    + ", cs=" + composingSpanStart + ", ce=" + composingSpanEnd);
1054        }
1055
1056        // This call happens when we have a hardware keyboard as well as when we don't. While we
1057        // don't support hardware keyboards yet we should avoid doing the processing associated
1058        // with cursor movement when we have a hardware keyboard since we are not in charge.
1059        final SettingsValues settingsValues = mSettings.getCurrent();
1060        if ((!settingsValues.mHasHardwareKeyboard || ProductionFlags.IS_HARDWARE_KEYBOARD_SUPPORTED)
1061                && mInputLogic.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd)) {
1062            mKeyboardSwitcher.requestUpdatingShiftState(getCurrentAutoCapsState(),
1063                    getCurrentRecapitalizeState());
1064        }
1065    }
1066
1067    // We cannot mark this method as @Override until new SDK becomes publicly available.
1068    // @Override
1069    public void onUpdateCursorAnchorInfo(final CursorAnchorInfo info) {
1070        if (!ProductionFlags.ENABLE_CURSOR_ANCHOR_INFO_CALLBACK || isFullscreenMode()) {
1071            return;
1072        }
1073        mInputLogic.onUpdateCursorAnchorInfo(CursorAnchorInfoCompatWrapper.fromObject(info));
1074    }
1075
1076    /**
1077     * This is called when the user has clicked on the extracted text view,
1078     * when running in fullscreen mode.  The default implementation hides
1079     * the suggestions view when this happens, but only if the extracted text
1080     * editor has a vertical scroll bar because its text doesn't fit.
1081     * Here we override the behavior due to the possibility that a re-correction could
1082     * cause the suggestions strip to disappear and re-appear.
1083     */
1084    @Override
1085    public void onExtractedTextClicked() {
1086        if (mSettings.getCurrent().needsToLookupSuggestions()) {
1087            return;
1088        }
1089
1090        super.onExtractedTextClicked();
1091    }
1092
1093    /**
1094     * This is called when the user has performed a cursor movement in the
1095     * extracted text view, when it is running in fullscreen mode.  The default
1096     * implementation hides the suggestions view when a vertical movement
1097     * happens, but only if the extracted text editor has a vertical scroll bar
1098     * because its text doesn't fit.
1099     * Here we override the behavior due to the possibility that a re-correction could
1100     * cause the suggestions strip to disappear and re-appear.
1101     */
1102    @Override
1103    public void onExtractedCursorMovement(final int dx, final int dy) {
1104        if (mSettings.getCurrent().needsToLookupSuggestions()) {
1105            return;
1106        }
1107
1108        super.onExtractedCursorMovement(dx, dy);
1109    }
1110
1111    @Override
1112    public void hideWindow() {
1113        mKeyboardSwitcher.onHideWindow();
1114
1115        if (TRACE) Debug.stopMethodTracing();
1116        if (isShowingOptionDialog()) {
1117            mOptionsDialog.dismiss();
1118            mOptionsDialog = null;
1119        }
1120        super.hideWindow();
1121    }
1122
1123    @Override
1124    public void onDisplayCompletions(final CompletionInfo[] applicationSpecifiedCompletions) {
1125        if (DEBUG) {
1126            Log.i(TAG, "Received completions:");
1127            if (applicationSpecifiedCompletions != null) {
1128                for (int i = 0; i < applicationSpecifiedCompletions.length; i++) {
1129                    Log.i(TAG, "  #" + i + ": " + applicationSpecifiedCompletions[i]);
1130                }
1131            }
1132        }
1133        if (!mSettings.getCurrent().isApplicationSpecifiedCompletionsOn()) {
1134            return;
1135        }
1136        // If we have an update request in flight, we need to cancel it so it does not override
1137        // these completions.
1138        mHandler.cancelUpdateSuggestionStrip();
1139        if (applicationSpecifiedCompletions == null) {
1140            setNeutralSuggestionStrip();
1141            return;
1142        }
1143
1144        final ArrayList<SuggestedWords.SuggestedWordInfo> applicationSuggestedWords =
1145                SuggestedWords.getFromApplicationSpecifiedCompletions(
1146                        applicationSpecifiedCompletions);
1147        final SuggestedWords suggestedWords = new SuggestedWords(applicationSuggestedWords,
1148                null /* rawSuggestions */, false /* typedWordValid */, false /* willAutoCorrect */,
1149                false /* isObsoleteSuggestions */,
1150                SuggestedWords.INPUT_STYLE_APPLICATION_SPECIFIED /* inputStyle */);
1151        // When in fullscreen mode, show completions generated by the application forcibly
1152        setSuggestedWords(suggestedWords);
1153    }
1154
1155    @Override
1156    public void onComputeInsets(final InputMethodService.Insets outInsets) {
1157        super.onComputeInsets(outInsets);
1158        final SettingsValues settingsValues = mSettings.getCurrent();
1159        final View visibleKeyboardView = mKeyboardSwitcher.getVisibleKeyboardView();
1160        if (visibleKeyboardView == null || !hasSuggestionStripView()) {
1161            return;
1162        }
1163        final int inputHeight = mInputView.getHeight();
1164        final boolean hasHardwareKeyboard = settingsValues.mHasHardwareKeyboard;
1165        if (hasHardwareKeyboard && visibleKeyboardView.getVisibility() == View.GONE) {
1166            // If there is a hardware keyboard and a visible software keyboard view has been hidden,
1167            // no visual element will be shown on the screen.
1168            outInsets.touchableInsets = inputHeight;
1169            outInsets.visibleTopInsets = inputHeight;
1170            return;
1171        }
1172        final int suggestionsHeight = (!mKeyboardSwitcher.isShowingEmojiPalettes()
1173                && mSuggestionStripView.getVisibility() == View.VISIBLE)
1174                ? mSuggestionStripView.getHeight() : 0;
1175        final int visibleTopY = inputHeight - visibleKeyboardView.getHeight() - suggestionsHeight;
1176        mSuggestionStripView.setMoreSuggestionsHeight(visibleTopY);
1177        // Need to set touchable region only if a keyboard view is being shown.
1178        if (visibleKeyboardView.isShown()) {
1179            final int touchLeft = 0;
1180            final int touchTop = mKeyboardSwitcher.isShowingMoreKeysPanel() ? 0 : visibleTopY;
1181            final int touchRight = visibleKeyboardView.getWidth();
1182            final int touchBottom = inputHeight
1183                    // Extend touchable region below the keyboard.
1184                    + EXTENDED_TOUCHABLE_REGION_HEIGHT;
1185            outInsets.touchableInsets = InputMethodService.Insets.TOUCHABLE_INSETS_REGION;
1186            outInsets.touchableRegion.set(touchLeft, touchTop, touchRight, touchBottom);
1187        }
1188        outInsets.contentTopInsets = visibleTopY;
1189        outInsets.visibleTopInsets = visibleTopY;
1190    }
1191
1192    public void startShowingInputView() {
1193        mIsExecutingStartShowingInputView = true;
1194        // This {@link #showWindow(boolean)} will eventually call back
1195        // {@link #onEvaluateInputViewShown()}.
1196        showWindow(true /* showInput */);
1197        mIsExecutingStartShowingInputView = false;
1198    }
1199
1200    public void stopShowingInputView() {
1201        showWindow(false /* showInput */);
1202    }
1203
1204    @Override
1205    public boolean onEvaluateInputViewShown() {
1206        if (mIsExecutingStartShowingInputView) {
1207            return true;
1208        }
1209        return super.onEvaluateInputViewShown();
1210    }
1211
1212    @Override
1213    public boolean onEvaluateFullscreenMode() {
1214        final SettingsValues settingsValues = mSettings.getCurrent();
1215        if (settingsValues.mHasHardwareKeyboard) {
1216            // If there is a hardware keyboard, disable full screen mode.
1217            return false;
1218        }
1219        // Reread resource value here, because this method is called by the framework as needed.
1220        final boolean isFullscreenModeAllowed = Settings.readUseFullscreenMode(getResources());
1221        if (super.onEvaluateFullscreenMode() && isFullscreenModeAllowed) {
1222            // TODO: Remove this hack. Actually we should not really assume NO_EXTRACT_UI
1223            // implies NO_FULLSCREEN. However, the framework mistakenly does.  i.e. NO_EXTRACT_UI
1224            // without NO_FULLSCREEN doesn't work as expected. Because of this we need this
1225            // hack for now.  Let's get rid of this once the framework gets fixed.
1226            final EditorInfo ei = getCurrentInputEditorInfo();
1227            return !(ei != null && ((ei.imeOptions & EditorInfo.IME_FLAG_NO_EXTRACT_UI) != 0));
1228        }
1229        return false;
1230    }
1231
1232    @Override
1233    public void updateFullscreenMode() {
1234        // Override layout parameters to expand {@link SoftInputWindow} to the entire screen.
1235        // See {@link InputMethodService#setinputView(View) and
1236        // {@link SoftInputWindow#updateWidthHeight(WindowManager.LayoutParams)}.
1237        final Window window = getWindow().getWindow();
1238        ViewLayoutUtils.updateLayoutHeightOf(window, LayoutParams.MATCH_PARENT);
1239        // This method may be called before {@link #setInputView(View)}.
1240        if (mInputView != null) {
1241            // In non-fullscreen mode, {@link InputView} and its parent inputArea should expand to
1242            // the entire screen and be placed at the bottom of {@link SoftInputWindow}.
1243            // In fullscreen mode, these shouldn't expand to the entire screen and should be
1244            // coexistent with {@link #mExtractedArea} above.
1245            // See {@link InputMethodService#setInputView(View) and
1246            // com.android.internal.R.layout.input_method.xml.
1247            final int layoutHeight = isFullscreenMode()
1248                    ? LayoutParams.WRAP_CONTENT : LayoutParams.MATCH_PARENT;
1249            final View inputArea = window.findViewById(android.R.id.inputArea);
1250            ViewLayoutUtils.updateLayoutHeightOf(inputArea, layoutHeight);
1251            ViewLayoutUtils.updateLayoutGravityOf(inputArea, Gravity.BOTTOM);
1252            ViewLayoutUtils.updateLayoutHeightOf(mInputView, layoutHeight);
1253        }
1254        super.updateFullscreenMode();
1255        mInputLogic.onUpdateFullscreenMode(isFullscreenMode());
1256    }
1257
1258    private int getCurrentAutoCapsState() {
1259        return mInputLogic.getCurrentAutoCapsState(mSettings.getCurrent());
1260    }
1261
1262    private int getCurrentRecapitalizeState() {
1263        return mInputLogic.getCurrentRecapitalizeState();
1264    }
1265
1266    public Locale getCurrentSubtypeLocale() {
1267        return mSubtypeSwitcher.getCurrentSubtypeLocale();
1268    }
1269
1270    /**
1271     * @param codePoints code points to get coordinates for.
1272     * @return x,y coordinates for this keyboard, as a flattened array.
1273     */
1274    public int[] getCoordinatesForCurrentKeyboard(final int[] codePoints) {
1275        final Keyboard keyboard = mKeyboardSwitcher.getKeyboard();
1276        if (null == keyboard) {
1277            return CoordinateUtils.newCoordinateArray(codePoints.length,
1278                    Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE);
1279        }
1280        return keyboard.getCoordinates(codePoints);
1281    }
1282
1283    // Callback for the {@link SuggestionStripView}, to call when the "add to dictionary" hint is
1284    // pressed.
1285    @Override
1286    public void addWordToUserDictionary(final String word) {
1287        if (TextUtils.isEmpty(word)) {
1288            // Probably never supposed to happen, but just in case.
1289            return;
1290        }
1291        final String wordToEdit;
1292        if (CapsModeUtils.isAutoCapsMode(mInputLogic.mLastComposedWord.mCapitalizedMode)) {
1293            wordToEdit = word.toLowerCase(getCurrentSubtypeLocale());
1294        } else {
1295            wordToEdit = word;
1296        }
1297        mDictionaryFacilitator.addWordToUserDictionary(this /* context */, wordToEdit);
1298        mInputLogic.onAddWordToUserDictionary();
1299    }
1300
1301    // Callback for the {@link SuggestionStripView}, to call when the important notice strip is
1302    // pressed.
1303    @Override
1304    public void showImportantNoticeContents() {
1305        showOptionDialog(new ImportantNoticeDialog(this /* context */, this /* listener */));
1306    }
1307
1308    // Implement {@link ImportantNoticeDialog.ImportantNoticeDialogListener}
1309    @Override
1310    public void onClickSettingsOfImportantNoticeDialog(final int nextVersion) {
1311        launchSettings();
1312    }
1313
1314    // Implement {@link ImportantNoticeDialog.ImportantNoticeDialogListener}
1315    @Override
1316    public void onUserAcknowledgmentOfImportantNoticeDialog(final int nextVersion) {
1317        setNeutralSuggestionStrip();
1318    }
1319
1320    public void displaySettingsDialog() {
1321        if (isShowingOptionDialog()) {
1322            return;
1323        }
1324        showSubtypeSelectorAndSettings();
1325    }
1326
1327    @Override
1328    public boolean onCustomRequest(final int requestCode) {
1329        if (isShowingOptionDialog()) return false;
1330        switch (requestCode) {
1331        case Constants.CUSTOM_CODE_SHOW_INPUT_METHOD_PICKER:
1332            if (mRichImm.hasMultipleEnabledIMEsOrSubtypes(true /* include aux subtypes */)) {
1333                mRichImm.getInputMethodManager().showInputMethodPicker();
1334                return true;
1335            }
1336            return false;
1337        }
1338        return false;
1339    }
1340
1341    private boolean isShowingOptionDialog() {
1342        return mOptionsDialog != null && mOptionsDialog.isShowing();
1343    }
1344
1345    // TODO: Revise the language switch key behavior to make it much smarter and more reasonable.
1346    public void switchToNextSubtype() {
1347        final IBinder token = getWindow().getWindow().getAttributes().token;
1348        if (shouldSwitchToOtherInputMethods()) {
1349            mRichImm.switchToNextInputMethod(token, false /* onlyCurrentIme */);
1350            return;
1351        }
1352        mSubtypeState.switchSubtype(token, mRichImm);
1353    }
1354
1355    // Implementation of {@link KeyboardActionListener}.
1356    @Override
1357    public void onCodeInput(final int codePoint, final int x, final int y,
1358            final boolean isKeyRepeat) {
1359        final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
1360        // x and y include some padding, but everything down the line (especially native
1361        // code) needs the coordinates in the keyboard frame.
1362        // TODO: We should reconsider which coordinate system should be used to represent
1363        // keyboard event. Also we should pull this up -- LatinIME has no business doing
1364        // this transformation, it should be done already before calling onCodeInput.
1365        final int keyX = mainKeyboardView.getKeyX(x);
1366        final int keyY = mainKeyboardView.getKeyY(y);
1367        final int codeToSend;
1368        if (Constants.CODE_SHIFT == codePoint) {
1369            // TODO: Instead of checking for alphabetic keyboard here, separate keycodes for
1370            // alphabetic shift and shift while in symbol layout.
1371            final Keyboard currentKeyboard = mKeyboardSwitcher.getKeyboard();
1372            if (null != currentKeyboard && currentKeyboard.mId.isAlphabetKeyboard()) {
1373                codeToSend = codePoint;
1374            } else {
1375                codeToSend = Constants.CODE_SYMBOL_SHIFT;
1376            }
1377        } else {
1378            codeToSend = codePoint;
1379        }
1380        if (Constants.CODE_SHORTCUT == codePoint) {
1381            mSubtypeSwitcher.switchToShortcutIME(this);
1382            // Still call the *#onCodeInput methods for readability.
1383        }
1384        final Event event = createSoftwareKeypressEvent(codeToSend, keyX, keyY, isKeyRepeat);
1385        final InputTransaction completeInputTransaction =
1386                mInputLogic.onCodeInput(mSettings.getCurrent(), event,
1387                        mKeyboardSwitcher.getKeyboardShiftMode(),
1388                        mKeyboardSwitcher.getCurrentKeyboardScriptId(), mHandler);
1389        updateStateAfterInputTransaction(completeInputTransaction);
1390        mKeyboardSwitcher.onCodeInput(codePoint, getCurrentAutoCapsState(),
1391                getCurrentRecapitalizeState());
1392    }
1393
1394    // A helper method to split the code point and the key code. Ultimately, they should not be
1395    // squashed into the same variable, and this method should be removed.
1396    private static Event createSoftwareKeypressEvent(final int keyCodeOrCodePoint, final int keyX,
1397             final int keyY, final boolean isKeyRepeat) {
1398        final int keyCode;
1399        final int codePoint;
1400        if (keyCodeOrCodePoint <= 0) {
1401            keyCode = keyCodeOrCodePoint;
1402            codePoint = Event.NOT_A_CODE_POINT;
1403        } else {
1404            keyCode = Event.NOT_A_KEY_CODE;
1405            codePoint = keyCodeOrCodePoint;
1406        }
1407        return Event.createSoftwareKeypressEvent(codePoint, keyCode, keyX, keyY, isKeyRepeat);
1408    }
1409
1410    // Called from PointerTracker through the KeyboardActionListener interface
1411    @Override
1412    public void onTextInput(final String rawText) {
1413        // TODO: have the keyboard pass the correct key code when we need it.
1414        final Event event = Event.createSoftwareTextEvent(rawText, Event.NOT_A_KEY_CODE);
1415        final InputTransaction completeInputTransaction =
1416                mInputLogic.onTextInput(mSettings.getCurrent(), event,
1417                        mKeyboardSwitcher.getKeyboardShiftMode(), mHandler);
1418        updateStateAfterInputTransaction(completeInputTransaction);
1419        mKeyboardSwitcher.onCodeInput(Constants.CODE_OUTPUT_TEXT, getCurrentAutoCapsState(),
1420                getCurrentRecapitalizeState());
1421    }
1422
1423    @Override
1424    public void onStartBatchInput() {
1425        mInputLogic.onStartBatchInput(mSettings.getCurrent(), mKeyboardSwitcher, mHandler);
1426    }
1427
1428    @Override
1429    public void onUpdateBatchInput(final InputPointers batchPointers) {
1430        mInputLogic.onUpdateBatchInput(mSettings.getCurrent(), batchPointers, mKeyboardSwitcher);
1431    }
1432
1433    @Override
1434    public void onEndBatchInput(final InputPointers batchPointers) {
1435        mInputLogic.onEndBatchInput(batchPointers);
1436    }
1437
1438    @Override
1439    public void onCancelBatchInput() {
1440        mInputLogic.onCancelBatchInput(mHandler);
1441    }
1442
1443    // This method must run on the UI Thread.
1444    private void showGesturePreviewAndSuggestionStrip(final SuggestedWords suggestedWords,
1445            final boolean dismissGestureFloatingPreviewText) {
1446        showSuggestionStrip(suggestedWords);
1447        final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
1448        mainKeyboardView.showGestureFloatingPreviewText(suggestedWords);
1449        if (dismissGestureFloatingPreviewText) {
1450            mainKeyboardView.dismissGestureFloatingPreviewText();
1451        }
1452    }
1453
1454    // Called from PointerTracker through the KeyboardActionListener interface
1455    @Override
1456    public void onFinishSlidingInput() {
1457        // User finished sliding input.
1458        mKeyboardSwitcher.onFinishSlidingInput(getCurrentAutoCapsState(),
1459                getCurrentRecapitalizeState());
1460    }
1461
1462    // Called from PointerTracker through the KeyboardActionListener interface
1463    @Override
1464    public void onCancelInput() {
1465        // User released a finger outside any key
1466        // Nothing to do so far.
1467    }
1468
1469    public boolean hasSuggestionStripView() {
1470        return null != mSuggestionStripView;
1471    }
1472
1473    @Override
1474    public boolean isShowingAddToDictionaryHint() {
1475        return hasSuggestionStripView() && mSuggestionStripView.isShowingAddToDictionaryHint();
1476    }
1477
1478    @Override
1479    public void dismissAddToDictionaryHint() {
1480        if (!hasSuggestionStripView()) {
1481            return;
1482        }
1483        mSuggestionStripView.dismissAddToDictionaryHint();
1484    }
1485
1486    private void setSuggestedWords(final SuggestedWords suggestedWords) {
1487        final SettingsValues currentSettingsValues = mSettings.getCurrent();
1488        mInputLogic.setSuggestedWords(suggestedWords, currentSettingsValues, mHandler);
1489        // TODO: Modify this when we support suggestions with hard keyboard
1490        if (!hasSuggestionStripView()) {
1491            return;
1492        }
1493        if (!onEvaluateInputViewShown()) {
1494            return;
1495        }
1496
1497        final boolean shouldShowImportantNotice =
1498                ImportantNoticeUtils.shouldShowImportantNotice(this);
1499        final boolean shouldShowSuggestionCandidates =
1500                currentSettingsValues.mInputAttributes.mShouldShowSuggestions
1501                && currentSettingsValues.isSuggestionsEnabledPerUserSettings();
1502        final boolean shouldShowSuggestionsStripUnlessPassword = shouldShowImportantNotice
1503                || currentSettingsValues.mShowsVoiceInputKey
1504                || shouldShowSuggestionCandidates
1505                || currentSettingsValues.isApplicationSpecifiedCompletionsOn();
1506        final boolean shouldShowSuggestionsStrip = shouldShowSuggestionsStripUnlessPassword
1507                && !currentSettingsValues.mInputAttributes.mIsPasswordField;
1508        mSuggestionStripView.updateVisibility(shouldShowSuggestionsStrip, isFullscreenMode());
1509        if (!shouldShowSuggestionsStrip) {
1510            return;
1511        }
1512
1513        final boolean isEmptyApplicationSpecifiedCompletions =
1514                currentSettingsValues.isApplicationSpecifiedCompletionsOn()
1515                && suggestedWords.isEmpty();
1516        final boolean noSuggestionsFromDictionaries = (SuggestedWords.EMPTY == suggestedWords)
1517                || suggestedWords.isPunctuationSuggestions()
1518                || isEmptyApplicationSpecifiedCompletions;
1519        final boolean isBeginningOfSentencePrediction = (suggestedWords.mInputStyle
1520                == SuggestedWords.INPUT_STYLE_BEGINNING_OF_SENTENCE_PREDICTION);
1521        final boolean noSuggestionsToOverrideImportantNotice = noSuggestionsFromDictionaries
1522                || isBeginningOfSentencePrediction;
1523        if (shouldShowImportantNotice && noSuggestionsToOverrideImportantNotice) {
1524            if (mSuggestionStripView.maybeShowImportantNoticeTitle()) {
1525                return;
1526            }
1527        }
1528
1529        if (currentSettingsValues.isSuggestionsEnabledPerUserSettings()
1530                || currentSettingsValues.isApplicationSpecifiedCompletionsOn()
1531                // We should clear the contextual strip if there is no suggestion from dictionaries.
1532                || noSuggestionsFromDictionaries) {
1533            mSuggestionStripView.setSuggestions(suggestedWords,
1534                    SubtypeLocaleUtils.isRtlLanguage(mSubtypeSwitcher.getCurrentSubtype()));
1535        }
1536    }
1537
1538    // TODO[IL]: Move this out of LatinIME.
1539    public void getSuggestedWords(final int inputStyle, final int sequenceNumber,
1540            final OnGetSuggestedWordsCallback callback) {
1541        final Keyboard keyboard = mKeyboardSwitcher.getKeyboard();
1542        if (keyboard == null) {
1543            callback.onGetSuggestedWords(SuggestedWords.EMPTY);
1544            return;
1545        }
1546        mInputLogic.getSuggestedWords(mSettings.getCurrent(), keyboard.getProximityInfo(),
1547                mKeyboardSwitcher.getKeyboardShiftMode(), inputStyle, sequenceNumber, callback);
1548    }
1549
1550    @Override
1551    public void showSuggestionStrip(final SuggestedWords sourceSuggestedWords) {
1552        final SuggestedWords suggestedWords =
1553                sourceSuggestedWords.isEmpty() ? SuggestedWords.EMPTY : sourceSuggestedWords;
1554        if (SuggestedWords.EMPTY == suggestedWords) {
1555            setNeutralSuggestionStrip();
1556        } else {
1557            setSuggestedWords(suggestedWords);
1558        }
1559        // Cache the auto-correction in accessibility code so we can speak it if the user
1560        // touches a key that will insert it.
1561        AccessibilityUtils.getInstance().setAutoCorrection(suggestedWords,
1562                sourceSuggestedWords.mTypedWord);
1563    }
1564
1565    // Called from {@link SuggestionStripView} through the {@link SuggestionStripView#Listener}
1566    // interface
1567    @Override
1568    public void pickSuggestionManually(final SuggestedWordInfo suggestionInfo) {
1569        final InputTransaction completeInputTransaction = mInputLogic.onPickSuggestionManually(
1570                mSettings.getCurrent(), suggestionInfo,
1571                mKeyboardSwitcher.getKeyboardShiftMode(),
1572                mKeyboardSwitcher.getCurrentKeyboardScriptId(),
1573                mHandler);
1574        updateStateAfterInputTransaction(completeInputTransaction);
1575    }
1576
1577    @Override
1578    public void showAddToDictionaryHint(final String word) {
1579        if (!hasSuggestionStripView()) {
1580            return;
1581        }
1582        mSuggestionStripView.showAddToDictionaryHint(word);
1583    }
1584
1585    // This will show either an empty suggestion strip (if prediction is enabled) or
1586    // punctuation suggestions (if it's disabled).
1587    @Override
1588    public void setNeutralSuggestionStrip() {
1589        final SettingsValues currentSettings = mSettings.getCurrent();
1590        final SuggestedWords neutralSuggestions = currentSettings.mBigramPredictionEnabled
1591                ? SuggestedWords.EMPTY : currentSettings.mSpacingAndPunctuations.mSuggestPuncList;
1592        setSuggestedWords(neutralSuggestions);
1593    }
1594
1595    // TODO: Make this private
1596    // Outside LatinIME, only used by the {@link InputTestsBase} test suite.
1597    @UsedForTesting
1598    void loadKeyboard() {
1599        // Since we are switching languages, the most urgent thing is to let the keyboard graphics
1600        // update. LoadKeyboard does that, but we need to wait for buffer flip for it to be on
1601        // the screen. Anything we do right now will delay this, so wait until the next frame
1602        // before we do the rest, like reopening dictionaries and updating suggestions. So we
1603        // post a message.
1604        mHandler.postReopenDictionaries();
1605        loadSettings();
1606        if (mKeyboardSwitcher.getMainKeyboardView() != null) {
1607            // Reload keyboard because the current language has been changed.
1608            mKeyboardSwitcher.loadKeyboard(getCurrentInputEditorInfo(), mSettings.getCurrent(),
1609                    getCurrentAutoCapsState(), getCurrentRecapitalizeState());
1610        }
1611    }
1612
1613    /**
1614     * After an input transaction has been executed, some state must be updated. This includes
1615     * the shift state of the keyboard and suggestions. This method looks at the finished
1616     * inputTransaction to find out what is necessary and updates the state accordingly.
1617     * @param inputTransaction The transaction that has been executed.
1618     */
1619    private void updateStateAfterInputTransaction(final InputTransaction inputTransaction) {
1620        switch (inputTransaction.getRequiredShiftUpdate()) {
1621        case InputTransaction.SHIFT_UPDATE_LATER:
1622            mHandler.postUpdateShiftState();
1623            break;
1624        case InputTransaction.SHIFT_UPDATE_NOW:
1625            mKeyboardSwitcher.requestUpdatingShiftState(getCurrentAutoCapsState(),
1626                    getCurrentRecapitalizeState());
1627            break;
1628        default: // SHIFT_NO_UPDATE
1629        }
1630        if (inputTransaction.requiresUpdateSuggestions()) {
1631            final int inputStyle;
1632            if (inputTransaction.mEvent.isSuggestionStripPress()) {
1633                // Suggestion strip press: no input.
1634                inputStyle = SuggestedWords.INPUT_STYLE_NONE;
1635            } else if (inputTransaction.mEvent.isGesture()) {
1636                inputStyle = SuggestedWords.INPUT_STYLE_TAIL_BATCH;
1637            } else {
1638                inputStyle = SuggestedWords.INPUT_STYLE_TYPING;
1639            }
1640            mHandler.postUpdateSuggestionStrip(inputStyle);
1641        }
1642        if (inputTransaction.didAffectContents()) {
1643            mSubtypeState.setCurrentSubtypeHasBeenUsed();
1644        }
1645    }
1646
1647    private void hapticAndAudioFeedback(final int code, final int repeatCount) {
1648        final MainKeyboardView keyboardView = mKeyboardSwitcher.getMainKeyboardView();
1649        if (keyboardView != null && keyboardView.isInDraggingFinger()) {
1650            // No need to feedback while finger is dragging.
1651            return;
1652        }
1653        if (repeatCount > 0) {
1654            if (code == Constants.CODE_DELETE && !mInputLogic.mConnection.canDeleteCharacters()) {
1655                // No need to feedback when repeat delete key will have no effect.
1656                return;
1657            }
1658            // TODO: Use event time that the last feedback has been generated instead of relying on
1659            // a repeat count to thin out feedback.
1660            if (repeatCount % PERIOD_FOR_AUDIO_AND_HAPTIC_FEEDBACK_IN_KEY_REPEAT == 0) {
1661                return;
1662            }
1663        }
1664        final AudioAndHapticFeedbackManager feedbackManager =
1665                AudioAndHapticFeedbackManager.getInstance();
1666        if (repeatCount == 0) {
1667            // TODO: Reconsider how to perform haptic feedback when repeating key.
1668            feedbackManager.performHapticFeedback(keyboardView);
1669        }
1670        feedbackManager.performAudioFeedback(code);
1671    }
1672
1673    // Callback of the {@link KeyboardActionListener}. This is called when a key is depressed;
1674    // release matching call is {@link #onReleaseKey(int,boolean)} below.
1675    @Override
1676    public void onPressKey(final int primaryCode, final int repeatCount,
1677            final boolean isSinglePointer) {
1678        mKeyboardSwitcher.onPressKey(primaryCode, isSinglePointer, getCurrentAutoCapsState(),
1679                getCurrentRecapitalizeState());
1680        hapticAndAudioFeedback(primaryCode, repeatCount);
1681    }
1682
1683    // Callback of the {@link KeyboardActionListener}. This is called when a key is released;
1684    // press matching call is {@link #onPressKey(int,int,boolean)} above.
1685    @Override
1686    public void onReleaseKey(final int primaryCode, final boolean withSliding) {
1687        mKeyboardSwitcher.onReleaseKey(primaryCode, withSliding, getCurrentAutoCapsState(),
1688                getCurrentRecapitalizeState());
1689    }
1690
1691    private HardwareEventDecoder getHardwareKeyEventDecoder(final int deviceId) {
1692        final HardwareEventDecoder decoder = mHardwareEventDecoders.get(deviceId);
1693        if (null != decoder) return decoder;
1694        // TODO: create the decoder according to the specification
1695        final HardwareEventDecoder newDecoder = new HardwareKeyboardEventDecoder(deviceId);
1696        mHardwareEventDecoders.put(deviceId, newDecoder);
1697        return newDecoder;
1698    }
1699
1700    // Hooks for hardware keyboard
1701    @Override
1702    public boolean onKeyDown(final int keyCode, final KeyEvent keyEvent) {
1703        mSpecialKeyDetector.onKeyDown(keyEvent);
1704        if (!ProductionFlags.IS_HARDWARE_KEYBOARD_SUPPORTED) {
1705            return super.onKeyDown(keyCode, keyEvent);
1706        }
1707        final Event event = getHardwareKeyEventDecoder(
1708                keyEvent.getDeviceId()).decodeHardwareKey(keyEvent);
1709        // If the event is not handled by LatinIME, we just pass it to the parent implementation.
1710        // If it's handled, we return true because we did handle it.
1711        if (event.isHandled()) {
1712            mInputLogic.onCodeInput(mSettings.getCurrent(), event,
1713                    mKeyboardSwitcher.getKeyboardShiftMode(),
1714                    // TODO: this is not necessarily correct for a hardware keyboard right now
1715                    mKeyboardSwitcher.getCurrentKeyboardScriptId(),
1716                    mHandler);
1717            return true;
1718        }
1719        return super.onKeyDown(keyCode, keyEvent);
1720    }
1721
1722    @Override
1723    public boolean onKeyUp(final int keyCode, final KeyEvent keyEvent) {
1724        mSpecialKeyDetector.onKeyUp(keyEvent);
1725        if (!ProductionFlags.IS_HARDWARE_KEYBOARD_SUPPORTED) {
1726            return super.onKeyUp(keyCode, keyEvent);
1727        }
1728        final long keyIdentifier = keyEvent.getDeviceId() << 32 + keyEvent.getKeyCode();
1729        if (mInputLogic.mCurrentlyPressedHardwareKeys.remove(keyIdentifier)) {
1730            return true;
1731        }
1732        return super.onKeyUp(keyCode, keyEvent);
1733    }
1734
1735    // onKeyDown and onKeyUp are the main events we are interested in. There are two more events
1736    // related to handling of hardware key events that we may want to implement in the future:
1737    // boolean onKeyLongPress(final int keyCode, final KeyEvent event);
1738    // boolean onKeyMultiple(final int keyCode, final int count, final KeyEvent event);
1739
1740    // receive ringer mode change and network state change.
1741    private final BroadcastReceiver mConnectivityAndRingerModeChangeReceiver =
1742            new BroadcastReceiver() {
1743        @Override
1744        public void onReceive(final Context context, final Intent intent) {
1745            final String action = intent.getAction();
1746            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
1747                mSubtypeSwitcher.onNetworkStateChanged(intent);
1748            } else if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) {
1749                AudioAndHapticFeedbackManager.getInstance().onRingerModeChanged();
1750            }
1751        }
1752    };
1753
1754    private void launchSettings() {
1755        mInputLogic.commitTyped(mSettings.getCurrent(), LastComposedWord.NOT_A_SEPARATOR);
1756        requestHideSelf(0);
1757        final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
1758        if (mainKeyboardView != null) {
1759            mainKeyboardView.closing();
1760        }
1761        final Intent intent = new Intent();
1762        intent.setClass(LatinIME.this, SettingsActivity.class);
1763        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1764                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
1765                | Intent.FLAG_ACTIVITY_CLEAR_TOP);
1766        intent.putExtra(SettingsActivity.EXTRA_SHOW_HOME_AS_UP, false);
1767        startActivity(intent);
1768    }
1769
1770    private void showSubtypeSelectorAndSettings() {
1771        final CharSequence title = getString(R.string.english_ime_input_options);
1772        // TODO: Should use new string "Select active input modes".
1773        final CharSequence languageSelectionTitle = getString(R.string.language_selection_title);
1774        final CharSequence[] items = new CharSequence[] {
1775                languageSelectionTitle,
1776                getString(ApplicationUtils.getActivityTitleResId(this, SettingsActivity.class))
1777        };
1778        final OnClickListener listener = new OnClickListener() {
1779            @Override
1780            public void onClick(DialogInterface di, int position) {
1781                di.dismiss();
1782                switch (position) {
1783                case 0:
1784                    final Intent intent = IntentUtils.getInputLanguageSelectionIntent(
1785                            mRichImm.getInputMethodIdOfThisIme(),
1786                            Intent.FLAG_ACTIVITY_NEW_TASK
1787                                    | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
1788                                    | Intent.FLAG_ACTIVITY_CLEAR_TOP);
1789                    intent.putExtra(Intent.EXTRA_TITLE, languageSelectionTitle);
1790                    startActivity(intent);
1791                    break;
1792                case 1:
1793                    launchSettings();
1794                    break;
1795                }
1796            }
1797        };
1798        final AlertDialog.Builder builder = new AlertDialog.Builder(
1799                DialogUtils.getPlatformDialogThemeContext(this));
1800        builder.setItems(items, listener).setTitle(title);
1801        final AlertDialog dialog = builder.create();
1802        dialog.setCancelable(true /* cancelable */);
1803        dialog.setCanceledOnTouchOutside(true /* cancelable */);
1804        showOptionDialog(dialog);
1805    }
1806
1807    // TODO: Move this method out of {@link LatinIME}.
1808    private void showOptionDialog(final AlertDialog dialog) {
1809        final IBinder windowToken = mKeyboardSwitcher.getMainKeyboardView().getWindowToken();
1810        if (windowToken == null) {
1811            return;
1812        }
1813
1814        final Window window = dialog.getWindow();
1815        final WindowManager.LayoutParams lp = window.getAttributes();
1816        lp.token = windowToken;
1817        lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
1818        window.setAttributes(lp);
1819        window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
1820
1821        mOptionsDialog = dialog;
1822        dialog.show();
1823    }
1824
1825    // TODO: can this be removed somehow without breaking the tests?
1826    @UsedForTesting
1827    /* package for test */ SuggestedWords getSuggestedWordsForTest() {
1828        // You may not use this method for anything else than debug
1829        return DEBUG ? mInputLogic.mSuggestedWords : null;
1830    }
1831
1832    // DO NOT USE THIS for any other purpose than testing. This is information private to LatinIME.
1833    @UsedForTesting
1834    /* package for test */ void waitForLoadingDictionaries(final long timeout, final TimeUnit unit)
1835            throws InterruptedException {
1836        mDictionaryFacilitator.waitForLoadingDictionariesForTesting(timeout, unit);
1837    }
1838
1839    // DO NOT USE THIS for any other purpose than testing. This can break the keyboard badly.
1840    @UsedForTesting
1841    /* package for test */ void replaceDictionariesForTest(final Locale locale) {
1842        final SettingsValues settingsValues = mSettings.getCurrent();
1843        mDictionaryFacilitator.resetDictionaries(this, locale,
1844            settingsValues.mUseContactsDict, settingsValues.mUsePersonalizedDicts,
1845            false /* forceReloadMainDictionary */, this /* listener */);
1846    }
1847
1848    // DO NOT USE THIS for any other purpose than testing.
1849    @UsedForTesting
1850    /* package for test */ void clearPersonalizedDictionariesForTest() {
1851        mDictionaryFacilitator.clearUserHistoryDictionary();
1852        mDictionaryFacilitator.clearPersonalizationDictionary();
1853    }
1854
1855    @UsedForTesting
1856    /* package for test */ List<InputMethodSubtype> getEnabledSubtypesForTest() {
1857        return (mRichImm != null) ? mRichImm.getMyEnabledInputMethodSubtypeList(
1858                true /* allowsImplicitlySelectedSubtypes */) : new ArrayList<InputMethodSubtype>();
1859    }
1860
1861    public void dumpDictionaryForDebug(final String dictName) {
1862        if (mDictionaryFacilitator.getLocale() == null) {
1863            resetSuggest();
1864        }
1865        mDictionaryFacilitator.dumpDictionaryForDebug(dictName);
1866    }
1867
1868    public void debugDumpStateAndCrashWithException(final String context) {
1869        final SettingsValues settingsValues = mSettings.getCurrent();
1870        final StringBuilder s = new StringBuilder(settingsValues.toString());
1871        s.append("\nAttributes : ").append(settingsValues.mInputAttributes)
1872                .append("\nContext : ").append(context);
1873        throw new RuntimeException(s.toString());
1874    }
1875
1876    @Override
1877    protected void dump(final FileDescriptor fd, final PrintWriter fout, final String[] args) {
1878        super.dump(fd, fout, args);
1879
1880        final Printer p = new PrintWriterPrinter(fout);
1881        p.println("LatinIME state :");
1882        p.println("  VersionCode = " + ApplicationUtils.getVersionCode(this));
1883        p.println("  VersionName = " + ApplicationUtils.getVersionName(this));
1884        final Keyboard keyboard = mKeyboardSwitcher.getKeyboard();
1885        final int keyboardMode = keyboard != null ? keyboard.mId.mMode : -1;
1886        p.println("  Keyboard mode = " + keyboardMode);
1887        final SettingsValues settingsValues = mSettings.getCurrent();
1888        p.println(settingsValues.dump());
1889        // TODO: Dump all settings values
1890    }
1891
1892    public boolean shouldSwitchToOtherInputMethods() {
1893        // TODO: Revisit here to reorganize the settings. Probably we can/should use different
1894        // strategy once the implementation of
1895        // {@link InputMethodManager#shouldOfferSwitchingToNextInputMethod} is defined well.
1896        final boolean fallbackValue = mSettings.getCurrent().mIncludesOtherImesInLanguageSwitchList;
1897        final IBinder token = getWindow().getWindow().getAttributes().token;
1898        if (token == null) {
1899            return fallbackValue;
1900        }
1901        return mRichImm.shouldOfferSwitchingToNextInputMethod(token, fallbackValue);
1902    }
1903
1904    public boolean shouldShowLanguageSwitchKey() {
1905        // TODO: Revisit here to reorganize the settings. Probably we can/should use different
1906        // strategy once the implementation of
1907        // {@link InputMethodManager#shouldOfferSwitchingToNextInputMethod} is defined well.
1908        final boolean fallbackValue = mSettings.getCurrent().isLanguageSwitchKeyEnabled();
1909        final IBinder token = getWindow().getWindow().getAttributes().token;
1910        if (token == null) {
1911            return fallbackValue;
1912        }
1913        return mRichImm.shouldOfferSwitchingToNextInputMethod(token, fallbackValue);
1914    }
1915}
1916