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