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