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