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