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