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