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