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