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