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