InputMethodManagerService.java revision 4e1ab15b305aac26ad8819fc3b2951e20985944d
1/*
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 * use this file except in compliance with the License. You may obtain a copy of
5 * the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 * License for the specific language governing permissions and limitations under
13 * the License.
14 */
15
16package com.android.server;
17
18import com.android.internal.content.PackageMonitor;
19import com.android.internal.os.HandlerCaller;
20import com.android.internal.os.SomeArgs;
21import com.android.internal.util.FastXmlSerializer;
22import com.android.internal.view.IInputContext;
23import com.android.internal.view.IInputMethod;
24import com.android.internal.view.IInputMethodCallback;
25import com.android.internal.view.IInputMethodClient;
26import com.android.internal.view.IInputMethodManager;
27import com.android.internal.view.IInputMethodSession;
28import com.android.internal.view.InputBindResult;
29import com.android.server.EventLogTags;
30import com.android.server.wm.WindowManagerService;
31
32import org.xmlpull.v1.XmlPullParser;
33import org.xmlpull.v1.XmlPullParserException;
34import org.xmlpull.v1.XmlSerializer;
35
36import android.app.ActivityManagerNative;
37import android.app.AppGlobals;
38import android.app.AlertDialog;
39import android.app.IUserSwitchObserver;
40import android.app.KeyguardManager;
41import android.app.Notification;
42import android.app.NotificationManager;
43import android.app.PendingIntent;
44import android.content.BroadcastReceiver;
45import android.content.ComponentName;
46import android.content.ContentResolver;
47import android.content.Context;
48import android.content.DialogInterface;
49import android.content.DialogInterface.OnCancelListener;
50import android.content.Intent;
51import android.content.IntentFilter;
52import android.content.ServiceConnection;
53import android.content.pm.ApplicationInfo;
54import android.content.pm.IPackageManager;
55import android.content.pm.PackageManager;
56import android.content.pm.PackageManager.NameNotFoundException;
57import android.content.pm.ResolveInfo;
58import android.content.pm.ServiceInfo;
59import android.content.res.Configuration;
60import android.content.res.Resources;
61import android.content.res.TypedArray;
62import android.database.ContentObserver;
63import android.inputmethodservice.InputMethodService;
64import android.os.Binder;
65import android.os.Environment;
66import android.os.Handler;
67import android.os.IBinder;
68import android.os.IInterface;
69import android.os.IRemoteCallback;
70import android.os.Message;
71import android.os.Process;
72import android.os.Parcel;
73import android.os.RemoteException;
74import android.os.ResultReceiver;
75import android.os.ServiceManager;
76import android.os.SystemClock;
77import android.os.UserHandle;
78import android.provider.Settings;
79import android.provider.Settings.Secure;
80import android.provider.Settings.SettingNotFoundException;
81import android.text.TextUtils;
82import android.text.style.SuggestionSpan;
83import android.util.AtomicFile;
84import android.util.EventLog;
85import android.util.LruCache;
86import android.util.Pair;
87import android.util.PrintWriterPrinter;
88import android.util.Printer;
89import android.util.Slog;
90import android.util.Xml;
91import android.view.IWindowManager;
92import android.view.LayoutInflater;
93import android.view.View;
94import android.view.ViewGroup;
95import android.view.WindowManager;
96import android.view.inputmethod.EditorInfo;
97import android.view.inputmethod.InputBinding;
98import android.view.inputmethod.InputMethod;
99import android.view.inputmethod.InputMethodInfo;
100import android.view.inputmethod.InputMethodManager;
101import android.view.inputmethod.InputMethodSubtype;
102import android.widget.ArrayAdapter;
103import android.widget.CompoundButton;
104import android.widget.CompoundButton.OnCheckedChangeListener;
105import android.widget.RadioButton;
106import android.widget.Switch;
107import android.widget.TextView;
108
109import java.io.File;
110import java.io.FileDescriptor;
111import java.io.FileInputStream;
112import java.io.FileOutputStream;
113import java.io.IOException;
114import java.io.PrintWriter;
115import java.util.ArrayList;
116import java.util.Collections;
117import java.util.Comparator;
118import java.util.HashMap;
119import java.util.HashSet;
120import java.util.List;
121import java.util.Locale;
122import java.util.TreeMap;
123
124/**
125 * This class provides a system service that manages input methods.
126 */
127public class InputMethodManagerService extends IInputMethodManager.Stub
128        implements ServiceConnection, Handler.Callback {
129    static final boolean DEBUG = false;
130    static final String TAG = "InputMethodManagerService";
131
132    static final int MSG_SHOW_IM_PICKER = 1;
133    static final int MSG_SHOW_IM_SUBTYPE_PICKER = 2;
134    static final int MSG_SHOW_IM_SUBTYPE_ENABLER = 3;
135    static final int MSG_SHOW_IM_CONFIG = 4;
136
137    static final int MSG_UNBIND_INPUT = 1000;
138    static final int MSG_BIND_INPUT = 1010;
139    static final int MSG_SHOW_SOFT_INPUT = 1020;
140    static final int MSG_HIDE_SOFT_INPUT = 1030;
141    static final int MSG_ATTACH_TOKEN = 1040;
142    static final int MSG_CREATE_SESSION = 1050;
143
144    static final int MSG_START_INPUT = 2000;
145    static final int MSG_RESTART_INPUT = 2010;
146
147    static final int MSG_UNBIND_METHOD = 3000;
148    static final int MSG_BIND_METHOD = 3010;
149    static final int MSG_SET_ACTIVE = 3020;
150
151    static final int MSG_HARD_KEYBOARD_SWITCH_CHANGED = 4000;
152
153    static final long TIME_TO_RECONNECT = 10*1000;
154
155    static final int SECURE_SUGGESTION_SPANS_MAX_SIZE = 20;
156
157    private static final int NOT_A_SUBTYPE_ID = -1;
158    private static final String NOT_A_SUBTYPE_ID_STR = String.valueOf(NOT_A_SUBTYPE_ID);
159    private static final String SUBTYPE_MODE_KEYBOARD = "keyboard";
160    private static final String SUBTYPE_MODE_VOICE = "voice";
161    private static final String TAG_TRY_SUPPRESSING_IME_SWITCHER = "TrySuppressingImeSwitcher";
162    private static final String TAG_ENABLED_WHEN_DEFAULT_IS_NOT_ASCII_CAPABLE =
163            "EnabledWhenDefaultIsNotAsciiCapable";
164    private static final String TAG_ASCII_CAPABLE = "AsciiCapable";
165    private static final Locale ENGLISH_LOCALE = new Locale("en");
166
167    final Context mContext;
168    final Resources mRes;
169    final Handler mHandler;
170    final InputMethodSettings mSettings;
171    final SettingsObserver mSettingsObserver;
172    final IWindowManager mIWindowManager;
173    final HandlerCaller mCaller;
174    private final InputMethodFileManager mFileManager;
175    private final InputMethodAndSubtypeListManager mImListManager;
176    private final HardKeyboardListener mHardKeyboardListener;
177    private final WindowManagerService mWindowManagerService;
178
179    final InputBindResult mNoBinding = new InputBindResult(null, null, -1);
180
181    // All known input methods.  mMethodMap also serves as the global
182    // lock for this class.
183    final ArrayList<InputMethodInfo> mMethodList = new ArrayList<InputMethodInfo>();
184    final HashMap<String, InputMethodInfo> mMethodMap = new HashMap<String, InputMethodInfo>();
185    private final LruCache<SuggestionSpan, InputMethodInfo> mSecureSuggestionSpans =
186            new LruCache<SuggestionSpan, InputMethodInfo>(SECURE_SUGGESTION_SPANS_MAX_SIZE);
187
188    // Used to bring IME service up to visible adjustment while it is being shown.
189    final ServiceConnection mVisibleConnection = new ServiceConnection() {
190        @Override public void onServiceConnected(ComponentName name, IBinder service) {
191        }
192
193        @Override public void onServiceDisconnected(ComponentName name) {
194        }
195    };
196    boolean mVisibleBound = false;
197
198    // Ongoing notification
199    private NotificationManager mNotificationManager;
200    private KeyguardManager mKeyguardManager;
201    private StatusBarManagerService mStatusBar;
202    private Notification mImeSwitcherNotification;
203    private PendingIntent mImeSwitchPendingIntent;
204    private boolean mShowOngoingImeSwitcherForPhones;
205    private boolean mNotificationShown;
206    private final boolean mImeSelectedOnBoot;
207
208    class SessionState {
209        final ClientState client;
210        final IInputMethod method;
211        final IInputMethodSession session;
212
213        @Override
214        public String toString() {
215            return "SessionState{uid " + client.uid + " pid " + client.pid
216                    + " method " + Integer.toHexString(
217                            System.identityHashCode(method))
218                    + " session " + Integer.toHexString(
219                            System.identityHashCode(session))
220                    + "}";
221        }
222
223        SessionState(ClientState _client, IInputMethod _method,
224                IInputMethodSession _session) {
225            client = _client;
226            method = _method;
227            session = _session;
228        }
229    }
230
231    class ClientState {
232        final IInputMethodClient client;
233        final IInputContext inputContext;
234        final int uid;
235        final int pid;
236        final InputBinding binding;
237
238        boolean sessionRequested;
239        SessionState curSession;
240
241        @Override
242        public String toString() {
243            return "ClientState{" + Integer.toHexString(
244                    System.identityHashCode(this)) + " uid " + uid
245                    + " pid " + pid + "}";
246        }
247
248        ClientState(IInputMethodClient _client, IInputContext _inputContext,
249                int _uid, int _pid) {
250            client = _client;
251            inputContext = _inputContext;
252            uid = _uid;
253            pid = _pid;
254            binding = new InputBinding(null, inputContext.asBinder(), uid, pid);
255        }
256    }
257
258    final HashMap<IBinder, ClientState> mClients
259            = new HashMap<IBinder, ClientState>();
260
261    /**
262     * Set once the system is ready to run third party code.
263     */
264    boolean mSystemReady;
265
266    /**
267     * Id of the currently selected input method.
268     */
269    String mCurMethodId;
270
271    /**
272     * The current binding sequence number, incremented every time there is
273     * a new bind performed.
274     */
275    int mCurSeq;
276
277    /**
278     * The client that is currently bound to an input method.
279     */
280    ClientState mCurClient;
281
282    /**
283     * The last window token that gained focus.
284     */
285    IBinder mCurFocusedWindow;
286
287    /**
288     * The input context last provided by the current client.
289     */
290    IInputContext mCurInputContext;
291
292    /**
293     * The attributes last provided by the current client.
294     */
295    EditorInfo mCurAttribute;
296
297    /**
298     * The input method ID of the input method service that we are currently
299     * connected to or in the process of connecting to.
300     */
301    String mCurId;
302
303    /**
304     * The current subtype of the current input method.
305     */
306    private InputMethodSubtype mCurrentSubtype;
307
308    // This list contains the pairs of InputMethodInfo and InputMethodSubtype.
309    private final HashMap<InputMethodInfo, ArrayList<InputMethodSubtype>>
310            mShortcutInputMethodsAndSubtypes =
311                new HashMap<InputMethodInfo, ArrayList<InputMethodSubtype>>();
312
313    /**
314     * Set to true if our ServiceConnection is currently actively bound to
315     * a service (whether or not we have gotten its IBinder back yet).
316     */
317    boolean mHaveConnection;
318
319    /**
320     * Set if the client has asked for the input method to be shown.
321     */
322    boolean mShowRequested;
323
324    /**
325     * Set if we were explicitly told to show the input method.
326     */
327    boolean mShowExplicitlyRequested;
328
329    /**
330     * Set if we were forced to be shown.
331     */
332    boolean mShowForced;
333
334    /**
335     * Set if we last told the input method to show itself.
336     */
337    boolean mInputShown;
338
339    /**
340     * The Intent used to connect to the current input method.
341     */
342    Intent mCurIntent;
343
344    /**
345     * The token we have made for the currently active input method, to
346     * identify it in the future.
347     */
348    IBinder mCurToken;
349
350    /**
351     * If non-null, this is the input method service we are currently connected
352     * to.
353     */
354    IInputMethod mCurMethod;
355
356    /**
357     * Time that we last initiated a bind to the input method, to determine
358     * if we should try to disconnect and reconnect to it.
359     */
360    long mLastBindTime;
361
362    /**
363     * Have we called mCurMethod.bindInput()?
364     */
365    boolean mBoundToMethod;
366
367    /**
368     * Currently enabled session.  Only touched by service thread, not
369     * protected by a lock.
370     */
371    SessionState mEnabledSession;
372
373    /**
374     * True if the screen is on.  The value is true initially.
375     */
376    boolean mScreenOn = true;
377
378    int mBackDisposition = InputMethodService.BACK_DISPOSITION_DEFAULT;
379    int mImeWindowVis;
380
381    private AlertDialog.Builder mDialogBuilder;
382    private AlertDialog mSwitchingDialog;
383    private View mSwitchingDialogTitleView;
384    private InputMethodInfo[] mIms;
385    private int[] mSubtypeIds;
386    private Locale mLastSystemLocale;
387    private final MyPackageMonitor mMyPackageMonitor = new MyPackageMonitor();
388    private final IPackageManager mIPackageManager;
389
390    class SettingsObserver extends ContentObserver {
391        SettingsObserver(Handler handler) {
392            super(handler);
393            ContentResolver resolver = mContext.getContentResolver();
394            resolver.registerContentObserver(Settings.Secure.getUriFor(
395                    Settings.Secure.DEFAULT_INPUT_METHOD), false, this);
396            resolver.registerContentObserver(Settings.Secure.getUriFor(
397                    Settings.Secure.ENABLED_INPUT_METHODS), false, this);
398            resolver.registerContentObserver(Settings.Secure.getUriFor(
399                    Settings.Secure.SELECTED_INPUT_METHOD_SUBTYPE), false, this);
400        }
401
402        @Override public void onChange(boolean selfChange) {
403            synchronized (mMethodMap) {
404                updateFromSettingsLocked();
405            }
406        }
407    }
408
409    class ImmsBroadcastReceiver extends android.content.BroadcastReceiver {
410        private void updateActive() {
411            // Inform the current client of the change in active status
412            if (mCurClient != null && mCurClient.client != null) {
413                executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
414                        MSG_SET_ACTIVE, mScreenOn ? 1 : 0, mCurClient));
415            }
416        }
417
418        @Override
419        public void onReceive(Context context, Intent intent) {
420            final String action = intent.getAction();
421            if (Intent.ACTION_SCREEN_ON.equals(action)) {
422                mScreenOn = true;
423                refreshImeWindowVisibilityLocked();
424                updateActive();
425                return;
426            } else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
427                mScreenOn = false;
428                setImeWindowVisibilityStatusHiddenLocked();
429                updateActive();
430                return;
431            } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
432                hideInputMethodMenu();
433                // No need to updateActive
434                return;
435            } else {
436                Slog.w(TAG, "Unexpected intent " + intent);
437            }
438        }
439    }
440
441    class MyPackageMonitor extends PackageMonitor {
442        private boolean isChangingPackagesOfCurrentUser() {
443            final int userId = getChangingUserId();
444            final boolean retval = userId == mSettings.getCurrentUserId();
445            if (DEBUG) {
446                Slog.d(TAG, "--- ignore this call back from a background user: " + userId);
447            }
448            return retval;
449        }
450
451        @Override
452        public boolean onHandleForceStop(Intent intent, String[] packages, int uid, boolean doit) {
453            if (!isChangingPackagesOfCurrentUser()) {
454                return false;
455            }
456            synchronized (mMethodMap) {
457                String curInputMethodId = mSettings.getSelectedInputMethod();
458                final int N = mMethodList.size();
459                if (curInputMethodId != null) {
460                    for (int i=0; i<N; i++) {
461                        InputMethodInfo imi = mMethodList.get(i);
462                        if (imi.getId().equals(curInputMethodId)) {
463                            for (String pkg : packages) {
464                                if (imi.getPackageName().equals(pkg)) {
465                                    if (!doit) {
466                                        return true;
467                                    }
468                                    resetSelectedInputMethodAndSubtypeLocked("");
469                                    chooseNewDefaultIMELocked();
470                                    return true;
471                                }
472                            }
473                        }
474                    }
475                }
476            }
477            return false;
478        }
479
480        @Override
481        public void onSomePackagesChanged() {
482            if (!isChangingPackagesOfCurrentUser()) {
483                return;
484            }
485            synchronized (mMethodMap) {
486                InputMethodInfo curIm = null;
487                String curInputMethodId = mSettings.getSelectedInputMethod();
488                final int N = mMethodList.size();
489                if (curInputMethodId != null) {
490                    for (int i=0; i<N; i++) {
491                        InputMethodInfo imi = mMethodList.get(i);
492                        final String imiId = imi.getId();
493                        if (imiId.equals(curInputMethodId)) {
494                            curIm = imi;
495                        }
496
497                        int change = isPackageDisappearing(imi.getPackageName());
498                        if (isPackageModified(imi.getPackageName())) {
499                            mFileManager.deleteAllInputMethodSubtypes(imiId);
500                        }
501                        if (change == PACKAGE_TEMPORARY_CHANGE
502                                || change == PACKAGE_PERMANENT_CHANGE) {
503                            Slog.i(TAG, "Input method uninstalled, disabling: "
504                                    + imi.getComponent());
505                            setInputMethodEnabledLocked(imi.getId(), false);
506                        }
507                    }
508                }
509
510                buildInputMethodListLocked(mMethodList, mMethodMap);
511
512                boolean changed = false;
513
514                if (curIm != null) {
515                    int change = isPackageDisappearing(curIm.getPackageName());
516                    if (change == PACKAGE_TEMPORARY_CHANGE
517                            || change == PACKAGE_PERMANENT_CHANGE) {
518                        ServiceInfo si = null;
519                        try {
520                            si = mIPackageManager.getServiceInfo(
521                                    curIm.getComponent(), 0, mSettings.getCurrentUserId());
522                        } catch (RemoteException ex) {
523                        }
524                        if (si == null) {
525                            // Uh oh, current input method is no longer around!
526                            // Pick another one...
527                            Slog.i(TAG, "Current input method removed: " + curInputMethodId);
528                            setImeWindowVisibilityStatusHiddenLocked();
529                            if (!chooseNewDefaultIMELocked()) {
530                                changed = true;
531                                curIm = null;
532                                Slog.i(TAG, "Unsetting current input method");
533                                resetSelectedInputMethodAndSubtypeLocked("");
534                            }
535                        }
536                    }
537                }
538
539                if (curIm == null) {
540                    // We currently don't have a default input method... is
541                    // one now available?
542                    changed = chooseNewDefaultIMELocked();
543                }
544
545                if (changed) {
546                    updateFromSettingsLocked();
547                }
548            }
549        }
550    }
551
552    private static class MethodCallback extends IInputMethodCallback.Stub {
553        private final IInputMethod mMethod;
554        private final InputMethodManagerService mParentIMMS;
555
556        MethodCallback(final IInputMethod method, final InputMethodManagerService imms) {
557            mMethod = method;
558            mParentIMMS = imms;
559        }
560
561        @Override
562        public void finishedEvent(int seq, boolean handled) throws RemoteException {
563        }
564
565        @Override
566        public void sessionCreated(IInputMethodSession session) throws RemoteException {
567            mParentIMMS.onSessionCreated(mMethod, session);
568        }
569    }
570
571    private class HardKeyboardListener
572            implements WindowManagerService.OnHardKeyboardStatusChangeListener {
573        @Override
574        public void onHardKeyboardStatusChange(boolean available, boolean enabled) {
575            mHandler.sendMessage(mHandler.obtainMessage(
576                    MSG_HARD_KEYBOARD_SWITCH_CHANGED, available ? 1 : 0, enabled ? 1 : 0));
577        }
578
579        public void handleHardKeyboardStatusChange(boolean available, boolean enabled) {
580            if (DEBUG) {
581                Slog.w(TAG, "HardKeyboardStatusChanged: available = " + available + ", enabled = "
582                        + enabled);
583            }
584            synchronized(mMethodMap) {
585                if (mSwitchingDialog != null && mSwitchingDialogTitleView != null
586                        && mSwitchingDialog.isShowing()) {
587                    mSwitchingDialogTitleView.findViewById(
588                            com.android.internal.R.id.hard_keyboard_section).setVisibility(
589                                    available ? View.VISIBLE : View.GONE);
590                }
591            }
592        }
593    }
594
595    public InputMethodManagerService(Context context, WindowManagerService windowManager) {
596        mIPackageManager = AppGlobals.getPackageManager();
597        mContext = context;
598        mRes = context.getResources();
599        mHandler = new Handler(this);
600        mIWindowManager = IWindowManager.Stub.asInterface(
601                ServiceManager.getService(Context.WINDOW_SERVICE));
602        mCaller = new HandlerCaller(context, new HandlerCaller.Callback() {
603            @Override
604            public void executeMessage(Message msg) {
605                handleMessage(msg);
606            }
607        });
608        mWindowManagerService = windowManager;
609        mHardKeyboardListener = new HardKeyboardListener();
610
611        mImeSwitcherNotification = new Notification();
612        mImeSwitcherNotification.icon = com.android.internal.R.drawable.ic_notification_ime_default;
613        mImeSwitcherNotification.when = 0;
614        mImeSwitcherNotification.flags = Notification.FLAG_ONGOING_EVENT;
615        mImeSwitcherNotification.tickerText = null;
616        mImeSwitcherNotification.defaults = 0; // please be quiet
617        mImeSwitcherNotification.sound = null;
618        mImeSwitcherNotification.vibrate = null;
619
620        // Tag this notification specially so SystemUI knows it's important
621        mImeSwitcherNotification.kind = new String[] { "android.system.imeswitcher" };
622
623        Intent intent = new Intent(Settings.ACTION_SHOW_INPUT_METHOD_PICKER);
624        mImeSwitchPendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
625
626        mShowOngoingImeSwitcherForPhones = false;
627
628        synchronized (mMethodMap) {
629            mFileManager = new InputMethodFileManager(mMethodMap);
630        }
631        mImListManager = new InputMethodAndSubtypeListManager(context, this);
632
633        final IntentFilter broadcastFilter = new IntentFilter();
634        broadcastFilter.addAction(Intent.ACTION_SCREEN_ON);
635        broadcastFilter.addAction(Intent.ACTION_SCREEN_OFF);
636        broadcastFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
637        mContext.registerReceiver(new ImmsBroadcastReceiver(), broadcastFilter);
638
639        mNotificationShown = false;
640        int userId = 0;
641        try {
642            ActivityManagerNative.getDefault().registerUserSwitchObserver(
643                    new IUserSwitchObserver.Stub() {
644                        @Override
645                        public void onUserSwitching(int newUserId, IRemoteCallback reply) {
646                            switchUser(newUserId);
647                            if (reply != null) {
648                                try {
649                                    reply.sendResult(null);
650                                } catch (RemoteException e) {
651                                }
652                            }
653                        }
654
655                        @Override
656                        public void onUserSwitchComplete(int newUserId) throws RemoteException {
657                        }
658                    });
659            userId = ActivityManagerNative.getDefault().getCurrentUser().id;
660        } catch (RemoteException e) {
661            Slog.w(TAG, "Couldn't get current user ID; guessing it's 0", e);
662        }
663        mMyPackageMonitor.register(mContext, null, true);
664
665        // mSettings should be created before buildInputMethodListLocked
666        mSettings = new InputMethodSettings(
667                mRes, context.getContentResolver(), mMethodMap, mMethodList, userId);
668
669        // Just checking if defaultImiId is empty or not
670        final String defaultImiId = mSettings.getSelectedInputMethod();
671        mImeSelectedOnBoot = !TextUtils.isEmpty(defaultImiId);
672
673        buildInputMethodListLocked(mMethodList, mMethodMap);
674        mSettings.enableAllIMEsIfThereIsNoEnabledIME();
675
676        if (!mImeSelectedOnBoot) {
677            Slog.w(TAG, "No IME selected. Choose the most applicable IME.");
678            resetDefaultImeLocked(context);
679        }
680
681        mSettingsObserver = new SettingsObserver(mHandler);
682        updateFromSettingsLocked();
683
684        // IMMS wants to receive Intent.ACTION_LOCALE_CHANGED in order to update the current IME
685        // according to the new system locale.
686        final IntentFilter filter = new IntentFilter();
687        filter.addAction(Intent.ACTION_LOCALE_CHANGED);
688        mContext.registerReceiver(
689                new BroadcastReceiver() {
690                    @Override
691                    public void onReceive(Context context, Intent intent) {
692                        synchronized(mMethodMap) {
693                            checkCurrentLocaleChangedLocked();
694                        }
695                    }
696                }, filter);
697    }
698
699    private void resetDefaultImeLocked(Context context) {
700        // Do not reset the default (current) IME when it is a 3rd-party IME
701        if (mCurMethodId != null && !isSystemIme(mMethodMap.get(mCurMethodId))) {
702            return;
703        }
704
705        InputMethodInfo defIm = null;
706        for (InputMethodInfo imi : mMethodList) {
707            if (defIm == null) {
708                if (isValidSystemDefaultIme(imi, context)) {
709                    defIm = imi;
710                    Slog.i(TAG, "Selected default: " + imi.getId());
711                }
712            }
713        }
714        if (defIm == null && mMethodList.size() > 0) {
715            defIm = getMostApplicableDefaultIMELocked();
716            Slog.i(TAG, "No default found, using " + defIm.getId());
717        }
718        if (defIm != null) {
719            setSelectedInputMethodAndSubtypeLocked(defIm, NOT_A_SUBTYPE_ID, false);
720        }
721    }
722
723    private void resetAllInternalStateLocked(boolean updateOnlyWhenLocaleChanged) {
724        if (!mSystemReady) {
725            // not system ready
726            return;
727        }
728        final Locale newLocale = mRes.getConfiguration().locale;
729        if (!updateOnlyWhenLocaleChanged
730                || (newLocale != null && !newLocale.equals(mLastSystemLocale))) {
731            if (!updateOnlyWhenLocaleChanged) {
732                hideCurrentInputLocked(0, null);
733                mCurMethodId = null;
734                unbindCurrentMethodLocked(true);
735            }
736            if (DEBUG) {
737                Slog.i(TAG, "Locale has been changed to " + newLocale);
738            }
739            buildInputMethodListLocked(mMethodList, mMethodMap);
740            if (!updateOnlyWhenLocaleChanged) {
741                final String selectedImiId = mSettings.getSelectedInputMethod();
742                if (TextUtils.isEmpty(selectedImiId)) {
743                    // This is the first time of the user switch and
744                    // set the current ime to the proper one.
745                    resetDefaultImeLocked(mContext);
746                }
747            }
748            updateFromSettingsLocked();
749            mLastSystemLocale = newLocale;
750            if (!updateOnlyWhenLocaleChanged) {
751                try {
752                    startInputInnerLocked();
753                } catch (RuntimeException e) {
754                    Slog.w(TAG, "Unexpected exception", e);
755                }
756            }
757        }
758    }
759
760    private void checkCurrentLocaleChangedLocked() {
761        resetAllInternalStateLocked(true);
762    }
763
764    private void switchUser(int newUserId) {
765        mSettings.setCurrentUserId(newUserId);
766        resetAllInternalStateLocked(false);
767    }
768
769    private boolean isValidSystemDefaultIme(InputMethodInfo imi, Context context) {
770        if (!mSystemReady) {
771            return false;
772        }
773        if (!isSystemIme(imi)) {
774            return false;
775        }
776        if (imi.getIsDefaultResourceId() != 0) {
777            try {
778                Resources res = context.createPackageContext(
779                        imi.getPackageName(), 0).getResources();
780                if (res.getBoolean(imi.getIsDefaultResourceId())
781                        && containsSubtypeOf(imi, context.getResources().getConfiguration().
782                                locale.getLanguage())) {
783                    return true;
784                }
785            } catch (PackageManager.NameNotFoundException ex) {
786            } catch (Resources.NotFoundException ex) {
787            }
788        }
789        if (imi.getSubtypeCount() == 0) {
790            Slog.w(TAG, "Found no subtypes in a system IME: " + imi.getPackageName());
791        }
792        return false;
793    }
794
795    private static boolean isSystemImeThatHasEnglishSubtype(InputMethodInfo imi) {
796        if (!isSystemIme(imi)) {
797            return false;
798        }
799        return containsSubtypeOf(imi, ENGLISH_LOCALE.getLanguage());
800    }
801
802    private static boolean containsSubtypeOf(InputMethodInfo imi, String language) {
803        final int N = imi.getSubtypeCount();
804        for (int i = 0; i < N; ++i) {
805            if (imi.getSubtypeAt(i).getLocale().startsWith(language)) {
806                return true;
807            }
808        }
809        return false;
810    }
811
812    @Override
813    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
814            throws RemoteException {
815        try {
816            return super.onTransact(code, data, reply, flags);
817        } catch (RuntimeException e) {
818            // The input method manager only throws security exceptions, so let's
819            // log all others.
820            if (!(e instanceof SecurityException)) {
821                Slog.e(TAG, "Input Method Manager Crash", e);
822            }
823            throw e;
824        }
825    }
826
827    public void systemReady(StatusBarManagerService statusBar) {
828        synchronized (mMethodMap) {
829            if (DEBUG) {
830                Slog.d(TAG, "--- systemReady");
831            }
832            if (!mSystemReady) {
833                mSystemReady = true;
834                mKeyguardManager =
835                        (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
836                mNotificationManager = (NotificationManager)
837                        mContext.getSystemService(Context.NOTIFICATION_SERVICE);
838                mStatusBar = statusBar;
839                statusBar.setIconVisibility("ime", false);
840                updateImeWindowStatusLocked();
841                mShowOngoingImeSwitcherForPhones = mRes.getBoolean(
842                        com.android.internal.R.bool.show_ongoing_ime_switcher);
843                if (mShowOngoingImeSwitcherForPhones) {
844                    mWindowManagerService.setOnHardKeyboardStatusChangeListener(
845                            mHardKeyboardListener);
846                }
847                buildInputMethodListLocked(mMethodList, mMethodMap);
848                if (!mImeSelectedOnBoot) {
849                    Slog.w(TAG, "Reset the default IME as \"Resource\" is ready here.");
850                    checkCurrentLocaleChangedLocked();
851                }
852                mLastSystemLocale = mRes.getConfiguration().locale;
853                try {
854                    startInputInnerLocked();
855                } catch (RuntimeException e) {
856                    Slog.w(TAG, "Unexpected exception", e);
857                }
858            }
859        }
860    }
861
862    private void setImeWindowVisibilityStatusHiddenLocked() {
863        mImeWindowVis = 0;
864        updateImeWindowStatusLocked();
865    }
866
867    private void refreshImeWindowVisibilityLocked() {
868        final Configuration conf = mRes.getConfiguration();
869        final boolean haveHardKeyboard = conf.keyboard
870                != Configuration.KEYBOARD_NOKEYS;
871        final boolean hardKeyShown = haveHardKeyboard
872                && conf.hardKeyboardHidden
873                        != Configuration.HARDKEYBOARDHIDDEN_YES;
874        final boolean isScreenLocked = mKeyguardManager != null
875                && mKeyguardManager.isKeyguardLocked()
876                && mKeyguardManager.isKeyguardSecure();
877        mImeWindowVis = (!isScreenLocked && (mInputShown || hardKeyShown)) ?
878                (InputMethodService.IME_ACTIVE | InputMethodService.IME_VISIBLE) : 0;
879        updateImeWindowStatusLocked();
880    }
881
882    private void updateImeWindowStatusLocked() {
883        setImeWindowStatus(mCurToken, mImeWindowVis, mBackDisposition);
884    }
885
886    // ---------------------------------------------------------------------------------------
887    // Check whether or not this is a valid IPC. Assumes an IPC is valid when either
888    // 1) it comes from the system process
889    // 2) the calling process' user id is identical to the current user id IMMS thinks.
890    private boolean calledFromValidUser() {
891        final int uid = Binder.getCallingUid();
892        final int userId = UserHandle.getUserId(uid);
893        if (DEBUG) {
894            Slog.d(TAG, "--- calledFromForegroundUserOrSystemProcess ? "
895                    + "calling uid = " + uid + " system uid = " + Process.SYSTEM_UID
896                    + " calling userId = " + userId + ", foreground user id = "
897                    + mSettings.getCurrentUserId());
898        }
899        if (uid == Process.SYSTEM_UID || userId == mSettings.getCurrentUserId()) {
900            return true;
901        } else {
902            Slog.w(TAG, "--- IPC called from background users. Ignore. \n" + getStackTrace());
903            return false;
904        }
905    }
906
907    private boolean bindCurrentInputMethodService(
908            Intent service, ServiceConnection conn, int flags) {
909        if (service == null || conn == null) {
910            Slog.e(TAG, "--- bind failed: service = " + service + ", conn = " + conn);
911            return false;
912        }
913        return mContext.bindService(service, conn, flags, mSettings.getCurrentUserId());
914    }
915
916    @Override
917    public List<InputMethodInfo> getInputMethodList() {
918        // TODO: Make this work even for non-current users?
919        if (!calledFromValidUser()) {
920            return Collections.emptyList();
921        }
922        synchronized (mMethodMap) {
923            return new ArrayList<InputMethodInfo>(mMethodList);
924        }
925    }
926
927    @Override
928    public List<InputMethodInfo> getEnabledInputMethodList() {
929        // TODO: Make this work even for non-current users?
930        if (!calledFromValidUser()) {
931            return Collections.emptyList();
932        }
933        synchronized (mMethodMap) {
934            return mSettings.getEnabledInputMethodListLocked();
935        }
936    }
937
938    private HashMap<InputMethodInfo, List<InputMethodSubtype>>
939            getExplicitlyOrImplicitlyEnabledInputMethodsAndSubtypeListLocked() {
940        HashMap<InputMethodInfo, List<InputMethodSubtype>> enabledInputMethodAndSubtypes =
941                new HashMap<InputMethodInfo, List<InputMethodSubtype>>();
942        for (InputMethodInfo imi: mSettings.getEnabledInputMethodListLocked()) {
943            enabledInputMethodAndSubtypes.put(
944                    imi, getEnabledInputMethodSubtypeListLocked(imi, true));
945        }
946        return enabledInputMethodAndSubtypes;
947    }
948
949    public List<InputMethodSubtype> getEnabledInputMethodSubtypeListLocked(InputMethodInfo imi,
950            boolean allowsImplicitlySelectedSubtypes) {
951        if (imi == null && mCurMethodId != null) {
952            imi = mMethodMap.get(mCurMethodId);
953        }
954        List<InputMethodSubtype> enabledSubtypes =
955                mSettings.getEnabledInputMethodSubtypeListLocked(imi);
956        if (allowsImplicitlySelectedSubtypes && enabledSubtypes.isEmpty()) {
957            enabledSubtypes = getImplicitlyApplicableSubtypesLocked(mRes, imi);
958        }
959        return InputMethodSubtype.sort(mContext, 0, imi, enabledSubtypes);
960    }
961
962    @Override
963    public List<InputMethodSubtype> getEnabledInputMethodSubtypeList(InputMethodInfo imi,
964            boolean allowsImplicitlySelectedSubtypes) {
965        // TODO: Make this work even for non-current users?
966        if (!calledFromValidUser()) {
967            return Collections.emptyList();
968        }
969        synchronized (mMethodMap) {
970            return getEnabledInputMethodSubtypeListLocked(imi, allowsImplicitlySelectedSubtypes);
971        }
972    }
973
974    @Override
975    public void addClient(IInputMethodClient client,
976            IInputContext inputContext, int uid, int pid) {
977        if (!calledFromValidUser()) {
978            return;
979        }
980        synchronized (mMethodMap) {
981            mClients.put(client.asBinder(), new ClientState(client,
982                    inputContext, uid, pid));
983        }
984    }
985
986    @Override
987    public void removeClient(IInputMethodClient client) {
988        if (!calledFromValidUser()) {
989            return;
990        }
991        synchronized (mMethodMap) {
992            mClients.remove(client.asBinder());
993        }
994    }
995
996    void executeOrSendMessage(IInterface target, Message msg) {
997         if (target.asBinder() instanceof Binder) {
998             mCaller.sendMessage(msg);
999         } else {
1000             handleMessage(msg);
1001             msg.recycle();
1002         }
1003    }
1004
1005    void unbindCurrentClientLocked() {
1006        if (mCurClient != null) {
1007            if (DEBUG) Slog.v(TAG, "unbindCurrentInputLocked: client = "
1008                    + mCurClient.client.asBinder());
1009            if (mBoundToMethod) {
1010                mBoundToMethod = false;
1011                if (mCurMethod != null) {
1012                    executeOrSendMessage(mCurMethod, mCaller.obtainMessageO(
1013                            MSG_UNBIND_INPUT, mCurMethod));
1014                }
1015            }
1016
1017            executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
1018                    MSG_SET_ACTIVE, 0, mCurClient));
1019            executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
1020                    MSG_UNBIND_METHOD, mCurSeq, mCurClient.client));
1021            mCurClient.sessionRequested = false;
1022            mCurClient = null;
1023
1024            hideInputMethodMenuLocked();
1025        }
1026    }
1027
1028    private int getImeShowFlags() {
1029        int flags = 0;
1030        if (mShowForced) {
1031            flags |= InputMethod.SHOW_FORCED
1032                    | InputMethod.SHOW_EXPLICIT;
1033        } else if (mShowExplicitlyRequested) {
1034            flags |= InputMethod.SHOW_EXPLICIT;
1035        }
1036        return flags;
1037    }
1038
1039    private int getAppShowFlags() {
1040        int flags = 0;
1041        if (mShowForced) {
1042            flags |= InputMethodManager.SHOW_FORCED;
1043        } else if (!mShowExplicitlyRequested) {
1044            flags |= InputMethodManager.SHOW_IMPLICIT;
1045        }
1046        return flags;
1047    }
1048
1049    InputBindResult attachNewInputLocked(boolean initial) {
1050        if (!mBoundToMethod) {
1051            executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
1052                    MSG_BIND_INPUT, mCurMethod, mCurClient.binding));
1053            mBoundToMethod = true;
1054        }
1055        final SessionState session = mCurClient.curSession;
1056        if (initial) {
1057            executeOrSendMessage(session.method, mCaller.obtainMessageOOO(
1058                    MSG_START_INPUT, session, mCurInputContext, mCurAttribute));
1059        } else {
1060            executeOrSendMessage(session.method, mCaller.obtainMessageOOO(
1061                    MSG_RESTART_INPUT, session, mCurInputContext, mCurAttribute));
1062        }
1063        if (mShowRequested) {
1064            if (DEBUG) Slog.v(TAG, "Attach new input asks to show input");
1065            showCurrentInputLocked(getAppShowFlags(), null);
1066        }
1067        return new InputBindResult(session.session, mCurId, mCurSeq);
1068    }
1069
1070    InputBindResult startInputLocked(IInputMethodClient client,
1071            IInputContext inputContext, EditorInfo attribute, int controlFlags) {
1072        // If no method is currently selected, do nothing.
1073        if (mCurMethodId == null) {
1074            return mNoBinding;
1075        }
1076
1077        ClientState cs = mClients.get(client.asBinder());
1078        if (cs == null) {
1079            throw new IllegalArgumentException("unknown client "
1080                    + client.asBinder());
1081        }
1082
1083        try {
1084            if (!mIWindowManager.inputMethodClientHasFocus(cs.client)) {
1085                // Check with the window manager to make sure this client actually
1086                // has a window with focus.  If not, reject.  This is thread safe
1087                // because if the focus changes some time before or after, the
1088                // next client receiving focus that has any interest in input will
1089                // be calling through here after that change happens.
1090                Slog.w(TAG, "Starting input on non-focused client " + cs.client
1091                        + " (uid=" + cs.uid + " pid=" + cs.pid + ")");
1092                return null;
1093            }
1094        } catch (RemoteException e) {
1095        }
1096
1097        return startInputUncheckedLocked(cs, inputContext, attribute, controlFlags);
1098    }
1099
1100    InputBindResult startInputUncheckedLocked(ClientState cs,
1101            IInputContext inputContext, EditorInfo attribute, int controlFlags) {
1102        // If no method is currently selected, do nothing.
1103        if (mCurMethodId == null) {
1104            return mNoBinding;
1105        }
1106
1107        if (mCurClient != cs) {
1108            // If the client is changing, we need to switch over to the new
1109            // one.
1110            unbindCurrentClientLocked();
1111            if (DEBUG) Slog.v(TAG, "switching to client: client = "
1112                    + cs.client.asBinder());
1113
1114            // If the screen is on, inform the new client it is active
1115            if (mScreenOn) {
1116                executeOrSendMessage(cs.client, mCaller.obtainMessageIO(
1117                        MSG_SET_ACTIVE, mScreenOn ? 1 : 0, cs));
1118            }
1119        }
1120
1121        // Bump up the sequence for this client and attach it.
1122        mCurSeq++;
1123        if (mCurSeq <= 0) mCurSeq = 1;
1124        mCurClient = cs;
1125        mCurInputContext = inputContext;
1126        mCurAttribute = attribute;
1127
1128        // Check if the input method is changing.
1129        if (mCurId != null && mCurId.equals(mCurMethodId)) {
1130            if (cs.curSession != null) {
1131                // Fast case: if we are already connected to the input method,
1132                // then just return it.
1133                return attachNewInputLocked(
1134                        (controlFlags&InputMethodManager.CONTROL_START_INITIAL) != 0);
1135            }
1136            if (mHaveConnection) {
1137                if (mCurMethod != null) {
1138                    if (!cs.sessionRequested) {
1139                        cs.sessionRequested = true;
1140                        if (DEBUG) Slog.v(TAG, "Creating new session for client " + cs);
1141                        executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
1142                                MSG_CREATE_SESSION, mCurMethod,
1143                                new MethodCallback(mCurMethod, this)));
1144                    }
1145                    // Return to client, and we will get back with it when
1146                    // we have had a session made for it.
1147                    return new InputBindResult(null, mCurId, mCurSeq);
1148                } else if (SystemClock.uptimeMillis()
1149                        < (mLastBindTime+TIME_TO_RECONNECT)) {
1150                    // In this case we have connected to the service, but
1151                    // don't yet have its interface.  If it hasn't been too
1152                    // long since we did the connection, we'll return to
1153                    // the client and wait to get the service interface so
1154                    // we can report back.  If it has been too long, we want
1155                    // to fall through so we can try a disconnect/reconnect
1156                    // to see if we can get back in touch with the service.
1157                    return new InputBindResult(null, mCurId, mCurSeq);
1158                } else {
1159                    EventLog.writeEvent(EventLogTags.IMF_FORCE_RECONNECT_IME,
1160                            mCurMethodId, SystemClock.uptimeMillis()-mLastBindTime, 0);
1161                }
1162            }
1163        }
1164
1165        return startInputInnerLocked();
1166    }
1167
1168    InputBindResult startInputInnerLocked() {
1169        if (mCurMethodId == null) {
1170            return mNoBinding;
1171        }
1172
1173        if (!mSystemReady) {
1174            // If the system is not yet ready, we shouldn't be running third
1175            // party code.
1176            return new InputBindResult(null, mCurMethodId, mCurSeq);
1177        }
1178
1179        InputMethodInfo info = mMethodMap.get(mCurMethodId);
1180        if (info == null) {
1181            throw new IllegalArgumentException("Unknown id: " + mCurMethodId);
1182        }
1183
1184        unbindCurrentMethodLocked(false);
1185
1186        mCurIntent = new Intent(InputMethod.SERVICE_INTERFACE);
1187        mCurIntent.setComponent(info.getComponent());
1188        mCurIntent.putExtra(Intent.EXTRA_CLIENT_LABEL,
1189                com.android.internal.R.string.input_method_binding_label);
1190        mCurIntent.putExtra(Intent.EXTRA_CLIENT_INTENT, PendingIntent.getActivity(
1191                mContext, 0, new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS), 0));
1192        if (bindCurrentInputMethodService(mCurIntent, this, Context.BIND_AUTO_CREATE
1193                | Context.BIND_NOT_VISIBLE)) {
1194            mLastBindTime = SystemClock.uptimeMillis();
1195            mHaveConnection = true;
1196            mCurId = info.getId();
1197            mCurToken = new Binder();
1198            try {
1199                if (DEBUG) Slog.v(TAG, "Adding window token: " + mCurToken);
1200                mIWindowManager.addWindowToken(mCurToken,
1201                        WindowManager.LayoutParams.TYPE_INPUT_METHOD);
1202            } catch (RemoteException e) {
1203            }
1204            return new InputBindResult(null, mCurId, mCurSeq);
1205        } else {
1206            mCurIntent = null;
1207            Slog.w(TAG, "Failure connecting to input method service: "
1208                    + mCurIntent);
1209        }
1210        return null;
1211    }
1212
1213    @Override
1214    public InputBindResult startInput(IInputMethodClient client,
1215            IInputContext inputContext, EditorInfo attribute, int controlFlags) {
1216        if (!calledFromValidUser()) {
1217            return null;
1218        }
1219        synchronized (mMethodMap) {
1220            final long ident = Binder.clearCallingIdentity();
1221            try {
1222                return startInputLocked(client, inputContext, attribute, controlFlags);
1223            } finally {
1224                Binder.restoreCallingIdentity(ident);
1225            }
1226        }
1227    }
1228
1229    @Override
1230    public void finishInput(IInputMethodClient client) {
1231    }
1232
1233    @Override
1234    public void onServiceConnected(ComponentName name, IBinder service) {
1235        synchronized (mMethodMap) {
1236            if (mCurIntent != null && name.equals(mCurIntent.getComponent())) {
1237                mCurMethod = IInputMethod.Stub.asInterface(service);
1238                if (mCurToken == null) {
1239                    Slog.w(TAG, "Service connected without a token!");
1240                    unbindCurrentMethodLocked(false);
1241                    return;
1242                }
1243                if (DEBUG) Slog.v(TAG, "Initiating attach with token: " + mCurToken);
1244                executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
1245                        MSG_ATTACH_TOKEN, mCurMethod, mCurToken));
1246                if (mCurClient != null) {
1247                    if (DEBUG) Slog.v(TAG, "Creating first session while with client "
1248                            + mCurClient);
1249                    executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
1250                            MSG_CREATE_SESSION, mCurMethod,
1251                            new MethodCallback(mCurMethod, this)));
1252                }
1253            }
1254        }
1255    }
1256
1257    void onSessionCreated(IInputMethod method, IInputMethodSession session) {
1258        synchronized (mMethodMap) {
1259            if (mCurMethod != null && method != null
1260                    && mCurMethod.asBinder() == method.asBinder()) {
1261                if (mCurClient != null) {
1262                    mCurClient.curSession = new SessionState(mCurClient,
1263                            method, session);
1264                    mCurClient.sessionRequested = false;
1265                    InputBindResult res = attachNewInputLocked(true);
1266                    if (res.method != null) {
1267                        executeOrSendMessage(mCurClient.client, mCaller.obtainMessageOO(
1268                                MSG_BIND_METHOD, mCurClient.client, res));
1269                    }
1270                }
1271            }
1272        }
1273    }
1274
1275    void unbindCurrentMethodLocked(boolean reportToClient) {
1276        if (mVisibleBound) {
1277            mContext.unbindService(mVisibleConnection);
1278            mVisibleBound = false;
1279        }
1280
1281        if (mHaveConnection) {
1282            mContext.unbindService(this);
1283            mHaveConnection = false;
1284        }
1285
1286        if (mCurToken != null) {
1287            try {
1288                if (DEBUG) Slog.v(TAG, "Removing window token: " + mCurToken);
1289                if ((mImeWindowVis & InputMethodService.IME_ACTIVE) != 0) {
1290                    // The current IME is shown. Hence an IME switch (transition) is happening.
1291                    mWindowManagerService.saveLastInputMethodWindowForTransition();
1292                }
1293                mIWindowManager.removeWindowToken(mCurToken);
1294            } catch (RemoteException e) {
1295            }
1296            mCurToken = null;
1297        }
1298
1299        mCurId = null;
1300        clearCurMethodLocked();
1301
1302        if (reportToClient && mCurClient != null) {
1303            executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
1304                    MSG_UNBIND_METHOD, mCurSeq, mCurClient.client));
1305        }
1306    }
1307
1308    private void finishSession(SessionState sessionState) {
1309        if (sessionState != null && sessionState.session != null) {
1310            try {
1311                sessionState.session.finishSession();
1312            } catch (RemoteException e) {
1313                Slog.w(TAG, "Session failed to close due to remote exception", e);
1314                setImeWindowVisibilityStatusHiddenLocked();
1315            }
1316        }
1317    }
1318
1319    void clearCurMethodLocked() {
1320        if (mCurMethod != null) {
1321            for (ClientState cs : mClients.values()) {
1322                cs.sessionRequested = false;
1323                finishSession(cs.curSession);
1324                cs.curSession = null;
1325            }
1326
1327            finishSession(mEnabledSession);
1328            mEnabledSession = null;
1329            mCurMethod = null;
1330        }
1331        if (mStatusBar != null) {
1332            mStatusBar.setIconVisibility("ime", false);
1333        }
1334    }
1335
1336    @Override
1337    public void onServiceDisconnected(ComponentName name) {
1338        synchronized (mMethodMap) {
1339            if (DEBUG) Slog.v(TAG, "Service disconnected: " + name
1340                    + " mCurIntent=" + mCurIntent);
1341            if (mCurMethod != null && mCurIntent != null
1342                    && name.equals(mCurIntent.getComponent())) {
1343                clearCurMethodLocked();
1344                // We consider this to be a new bind attempt, since the system
1345                // should now try to restart the service for us.
1346                mLastBindTime = SystemClock.uptimeMillis();
1347                mShowRequested = mInputShown;
1348                mInputShown = false;
1349                if (mCurClient != null) {
1350                    executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
1351                            MSG_UNBIND_METHOD, mCurSeq, mCurClient.client));
1352                }
1353            }
1354        }
1355    }
1356
1357    @Override
1358    public void updateStatusIcon(IBinder token, String packageName, int iconId) {
1359        int uid = Binder.getCallingUid();
1360        long ident = Binder.clearCallingIdentity();
1361        try {
1362            if (token == null || mCurToken != token) {
1363                Slog.w(TAG, "Ignoring setInputMethod of uid " + uid + " token: " + token);
1364                return;
1365            }
1366
1367            synchronized (mMethodMap) {
1368                if (iconId == 0) {
1369                    if (DEBUG) Slog.d(TAG, "hide the small icon for the input method");
1370                    if (mStatusBar != null) {
1371                        mStatusBar.setIconVisibility("ime", false);
1372                    }
1373                } else if (packageName != null) {
1374                    if (DEBUG) Slog.d(TAG, "show a small icon for the input method");
1375                    CharSequence contentDescription = null;
1376                    try {
1377                        // Use PackageManager to load label
1378                        final PackageManager packageManager = mContext.getPackageManager();
1379                        contentDescription = packageManager.getApplicationLabel(
1380                                mIPackageManager.getApplicationInfo(packageName, 0,
1381                                        mSettings.getCurrentUserId()));
1382                    } catch (RemoteException e) {
1383                        /* ignore */
1384                    }
1385                    if (mStatusBar != null) {
1386                        mStatusBar.setIcon("ime", packageName, iconId, 0,
1387                                contentDescription  != null
1388                                        ? contentDescription.toString() : null);
1389                        mStatusBar.setIconVisibility("ime", true);
1390                    }
1391                }
1392            }
1393        } finally {
1394            Binder.restoreCallingIdentity(ident);
1395        }
1396    }
1397
1398    private boolean needsToShowImeSwitchOngoingNotification() {
1399        if (!mShowOngoingImeSwitcherForPhones) return false;
1400        if (isScreenLocked()) return false;
1401        synchronized (mMethodMap) {
1402            List<InputMethodInfo> imis = mSettings.getEnabledInputMethodListLocked();
1403            final int N = imis.size();
1404            if (N > 2) return true;
1405            if (N < 1) return false;
1406            int nonAuxCount = 0;
1407            int auxCount = 0;
1408            InputMethodSubtype nonAuxSubtype = null;
1409            InputMethodSubtype auxSubtype = null;
1410            for(int i = 0; i < N; ++i) {
1411                final InputMethodInfo imi = imis.get(i);
1412                final List<InputMethodSubtype> subtypes = getEnabledInputMethodSubtypeListLocked(
1413                        imi, true);
1414                final int subtypeCount = subtypes.size();
1415                if (subtypeCount == 0) {
1416                    ++nonAuxCount;
1417                } else {
1418                    for (int j = 0; j < subtypeCount; ++j) {
1419                        final InputMethodSubtype subtype = subtypes.get(j);
1420                        if (!subtype.isAuxiliary()) {
1421                            ++nonAuxCount;
1422                            nonAuxSubtype = subtype;
1423                        } else {
1424                            ++auxCount;
1425                            auxSubtype = subtype;
1426                        }
1427                    }
1428                }
1429            }
1430            if (nonAuxCount > 1 || auxCount > 1) {
1431                return true;
1432            } else if (nonAuxCount == 1 && auxCount == 1) {
1433                if (nonAuxSubtype != null && auxSubtype != null
1434                        && (nonAuxSubtype.getLocale().equals(auxSubtype.getLocale())
1435                                || auxSubtype.overridesImplicitlyEnabledSubtype()
1436                                || nonAuxSubtype.overridesImplicitlyEnabledSubtype())
1437                        && nonAuxSubtype.containsExtraValueKey(TAG_TRY_SUPPRESSING_IME_SWITCHER)) {
1438                    return false;
1439                }
1440                return true;
1441            }
1442            return false;
1443        }
1444    }
1445
1446    // Caution! This method is called in this class. Handle multi-user carefully
1447    @SuppressWarnings("deprecation")
1448    @Override
1449    public void setImeWindowStatus(IBinder token, int vis, int backDisposition) {
1450        final long ident = Binder.clearCallingIdentity();
1451        try {
1452            if (token == null || mCurToken != token) {
1453                int uid = Binder.getCallingUid();
1454                Slog.w(TAG, "Ignoring setImeWindowStatus of uid " + uid + " token: " + token);
1455                return;
1456            }
1457
1458            synchronized (mMethodMap) {
1459                mImeWindowVis = vis;
1460                mBackDisposition = backDisposition;
1461                if (mStatusBar != null) {
1462                    mStatusBar.setImeWindowStatus(token, vis, backDisposition);
1463                }
1464                final boolean iconVisibility = (vis & InputMethodService.IME_ACTIVE) != 0;
1465                final InputMethodInfo imi = mMethodMap.get(mCurMethodId);
1466                if (imi != null && iconVisibility && needsToShowImeSwitchOngoingNotification()) {
1467                    // Used to load label
1468                    final PackageManager pm = mContext.getPackageManager();
1469                    final CharSequence title = mRes.getText(
1470                            com.android.internal.R.string.select_input_method);
1471                    final CharSequence imiLabel = imi.loadLabel(pm);
1472                    if (DEBUG) {
1473                        Slog.d(TAG, "--- imiLabel = " + imiLabel);
1474                    }
1475                    final CharSequence summary = mCurrentSubtype != null
1476                            ? TextUtils.concat(mCurrentSubtype.getDisplayName(mContext,
1477                                        imi.getPackageName(), imi.getServiceInfo().applicationInfo),
1478                                                (TextUtils.isEmpty(imiLabel) ?
1479                                                        "" : " - " + imiLabel))
1480                            : imiLabel;
1481
1482                    mImeSwitcherNotification.setLatestEventInfo(
1483                            mContext, title, summary, mImeSwitchPendingIntent);
1484                    if (mNotificationManager != null) {
1485                        mNotificationManager.notify(
1486                                com.android.internal.R.string.select_input_method,
1487                                mImeSwitcherNotification);
1488                        mNotificationShown = true;
1489                    }
1490                } else {
1491                    if (mNotificationShown && mNotificationManager != null) {
1492                        mNotificationManager.cancel(
1493                                com.android.internal.R.string.select_input_method);
1494                        mNotificationShown = false;
1495                    }
1496                }
1497            }
1498        } finally {
1499            Binder.restoreCallingIdentity(ident);
1500        }
1501    }
1502
1503    @Override
1504    public void registerSuggestionSpansForNotification(SuggestionSpan[] spans) {
1505        if (!calledFromValidUser()) {
1506            return;
1507        }
1508        synchronized (mMethodMap) {
1509            final InputMethodInfo currentImi = mMethodMap.get(mCurMethodId);
1510            for (int i = 0; i < spans.length; ++i) {
1511                SuggestionSpan ss = spans[i];
1512                if (!TextUtils.isEmpty(ss.getNotificationTargetClassName())) {
1513                    mSecureSuggestionSpans.put(ss, currentImi);
1514                    final InputMethodInfo targetImi = mSecureSuggestionSpans.get(ss);
1515                }
1516            }
1517        }
1518    }
1519
1520    @Override
1521    public boolean notifySuggestionPicked(SuggestionSpan span, String originalString, int index) {
1522        if (!calledFromValidUser()) {
1523            return false;
1524        }
1525        synchronized (mMethodMap) {
1526            final InputMethodInfo targetImi = mSecureSuggestionSpans.get(span);
1527            // TODO: Do not send the intent if the process of the targetImi is already dead.
1528            if (targetImi != null) {
1529                final String[] suggestions = span.getSuggestions();
1530                if (index < 0 || index >= suggestions.length) return false;
1531                final String className = span.getNotificationTargetClassName();
1532                final Intent intent = new Intent();
1533                // Ensures that only a class in the original IME package will receive the
1534                // notification.
1535                intent.setClassName(targetImi.getPackageName(), className);
1536                intent.setAction(SuggestionSpan.ACTION_SUGGESTION_PICKED);
1537                intent.putExtra(SuggestionSpan.SUGGESTION_SPAN_PICKED_BEFORE, originalString);
1538                intent.putExtra(SuggestionSpan.SUGGESTION_SPAN_PICKED_AFTER, suggestions[index]);
1539                intent.putExtra(SuggestionSpan.SUGGESTION_SPAN_PICKED_HASHCODE, span.hashCode());
1540                mContext.sendBroadcast(intent);
1541                return true;
1542            }
1543        }
1544        return false;
1545    }
1546
1547    void updateFromSettingsLocked() {
1548        // We are assuming that whoever is changing DEFAULT_INPUT_METHOD and
1549        // ENABLED_INPUT_METHODS is taking care of keeping them correctly in
1550        // sync, so we will never have a DEFAULT_INPUT_METHOD that is not
1551        // enabled.
1552        String id = mSettings.getSelectedInputMethod();
1553        // There is no input method selected, try to choose new applicable input method.
1554        if (TextUtils.isEmpty(id) && chooseNewDefaultIMELocked()) {
1555            id = mSettings.getSelectedInputMethod();
1556        }
1557        if (!TextUtils.isEmpty(id)) {
1558            try {
1559                setInputMethodLocked(id, getSelectedInputMethodSubtypeId(id));
1560            } catch (IllegalArgumentException e) {
1561                Slog.w(TAG, "Unknown input method from prefs: " + id, e);
1562                mCurMethodId = null;
1563                unbindCurrentMethodLocked(true);
1564            }
1565            mShortcutInputMethodsAndSubtypes.clear();
1566        } else {
1567            // There is no longer an input method set, so stop any current one.
1568            mCurMethodId = null;
1569            unbindCurrentMethodLocked(true);
1570        }
1571    }
1572
1573    /* package */ void setInputMethodLocked(String id, int subtypeId) {
1574        InputMethodInfo info = mMethodMap.get(id);
1575        if (info == null) {
1576            throw new IllegalArgumentException("Unknown id: " + id);
1577        }
1578
1579        // See if we need to notify a subtype change within the same IME.
1580        if (id.equals(mCurMethodId)) {
1581            final int subtypeCount = info.getSubtypeCount();
1582            if (subtypeCount <= 0) {
1583                return;
1584            }
1585            final InputMethodSubtype oldSubtype = mCurrentSubtype;
1586            final InputMethodSubtype newSubtype;
1587            if (subtypeId >= 0 && subtypeId < subtypeCount) {
1588                newSubtype = info.getSubtypeAt(subtypeId);
1589            } else {
1590                // If subtype is null, try to find the most applicable one from
1591                // getCurrentInputMethodSubtype.
1592                newSubtype = getCurrentInputMethodSubtypeLocked();
1593            }
1594            if (newSubtype == null || oldSubtype == null) {
1595                Slog.w(TAG, "Illegal subtype state: old subtype = " + oldSubtype
1596                        + ", new subtype = " + newSubtype);
1597                return;
1598            }
1599            if (newSubtype != oldSubtype) {
1600                setSelectedInputMethodAndSubtypeLocked(info, subtypeId, true);
1601                if (mCurMethod != null) {
1602                    try {
1603                        refreshImeWindowVisibilityLocked();
1604                        mCurMethod.changeInputMethodSubtype(newSubtype);
1605                    } catch (RemoteException e) {
1606                        Slog.w(TAG, "Failed to call changeInputMethodSubtype");
1607                    }
1608                }
1609            }
1610            return;
1611        }
1612
1613        // Changing to a different IME.
1614        final long ident = Binder.clearCallingIdentity();
1615        try {
1616            // Set a subtype to this input method.
1617            // subtypeId the name of a subtype which will be set.
1618            setSelectedInputMethodAndSubtypeLocked(info, subtypeId, false);
1619            // mCurMethodId should be updated after setSelectedInputMethodAndSubtypeLocked()
1620            // because mCurMethodId is stored as a history in
1621            // setSelectedInputMethodAndSubtypeLocked().
1622            mCurMethodId = id;
1623
1624            if (ActivityManagerNative.isSystemReady()) {
1625                Intent intent = new Intent(Intent.ACTION_INPUT_METHOD_CHANGED);
1626                intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
1627                intent.putExtra("input_method_id", id);
1628                mContext.sendBroadcast(intent);
1629            }
1630            unbindCurrentClientLocked();
1631        } finally {
1632            Binder.restoreCallingIdentity(ident);
1633        }
1634    }
1635
1636    @Override
1637    public boolean showSoftInput(IInputMethodClient client, int flags,
1638            ResultReceiver resultReceiver) {
1639        if (!calledFromValidUser()) {
1640            return false;
1641        }
1642        int uid = Binder.getCallingUid();
1643        long ident = Binder.clearCallingIdentity();
1644        try {
1645            synchronized (mMethodMap) {
1646                if (mCurClient == null || client == null
1647                        || mCurClient.client.asBinder() != client.asBinder()) {
1648                    try {
1649                        // We need to check if this is the current client with
1650                        // focus in the window manager, to allow this call to
1651                        // be made before input is started in it.
1652                        if (!mIWindowManager.inputMethodClientHasFocus(client)) {
1653                            Slog.w(TAG, "Ignoring showSoftInput of uid " + uid + ": " + client);
1654                            return false;
1655                        }
1656                    } catch (RemoteException e) {
1657                        return false;
1658                    }
1659                }
1660
1661                if (DEBUG) Slog.v(TAG, "Client requesting input be shown");
1662                return showCurrentInputLocked(flags, resultReceiver);
1663            }
1664        } finally {
1665            Binder.restoreCallingIdentity(ident);
1666        }
1667    }
1668
1669    boolean showCurrentInputLocked(int flags, ResultReceiver resultReceiver) {
1670        mShowRequested = true;
1671        if ((flags&InputMethodManager.SHOW_IMPLICIT) == 0) {
1672            mShowExplicitlyRequested = true;
1673        }
1674        if ((flags&InputMethodManager.SHOW_FORCED) != 0) {
1675            mShowExplicitlyRequested = true;
1676            mShowForced = true;
1677        }
1678
1679        if (!mSystemReady) {
1680            return false;
1681        }
1682
1683        boolean res = false;
1684        if (mCurMethod != null) {
1685            executeOrSendMessage(mCurMethod, mCaller.obtainMessageIOO(
1686                    MSG_SHOW_SOFT_INPUT, getImeShowFlags(), mCurMethod,
1687                    resultReceiver));
1688            mInputShown = true;
1689            if (mHaveConnection && !mVisibleBound) {
1690                bindCurrentInputMethodService(
1691                        mCurIntent, mVisibleConnection, Context.BIND_AUTO_CREATE);
1692                mVisibleBound = true;
1693            }
1694            res = true;
1695        } else if (mHaveConnection && SystemClock.uptimeMillis()
1696                >= (mLastBindTime+TIME_TO_RECONNECT)) {
1697            // The client has asked to have the input method shown, but
1698            // we have been sitting here too long with a connection to the
1699            // service and no interface received, so let's disconnect/connect
1700            // to try to prod things along.
1701            EventLog.writeEvent(EventLogTags.IMF_FORCE_RECONNECT_IME, mCurMethodId,
1702                    SystemClock.uptimeMillis()-mLastBindTime,1);
1703            Slog.w(TAG, "Force disconnect/connect to the IME in showCurrentInputLocked()");
1704            mContext.unbindService(this);
1705            bindCurrentInputMethodService(mCurIntent, this, Context.BIND_AUTO_CREATE
1706                    | Context.BIND_NOT_VISIBLE);
1707        } else {
1708            if (DEBUG) {
1709                Slog.d(TAG, "Can't show input: connection = " + mHaveConnection + ", time = "
1710                        + ((mLastBindTime+TIME_TO_RECONNECT) - SystemClock.uptimeMillis()));
1711            }
1712        }
1713
1714        return res;
1715    }
1716
1717    @Override
1718    public boolean hideSoftInput(IInputMethodClient client, int flags,
1719            ResultReceiver resultReceiver) {
1720        if (!calledFromValidUser()) {
1721            return false;
1722        }
1723        int uid = Binder.getCallingUid();
1724        long ident = Binder.clearCallingIdentity();
1725        try {
1726            synchronized (mMethodMap) {
1727                if (mCurClient == null || client == null
1728                        || mCurClient.client.asBinder() != client.asBinder()) {
1729                    try {
1730                        // We need to check if this is the current client with
1731                        // focus in the window manager, to allow this call to
1732                        // be made before input is started in it.
1733                        if (!mIWindowManager.inputMethodClientHasFocus(client)) {
1734                            if (DEBUG) Slog.w(TAG, "Ignoring hideSoftInput of uid "
1735                                    + uid + ": " + client);
1736                            setImeWindowVisibilityStatusHiddenLocked();
1737                            return false;
1738                        }
1739                    } catch (RemoteException e) {
1740                        setImeWindowVisibilityStatusHiddenLocked();
1741                        return false;
1742                    }
1743                }
1744
1745                if (DEBUG) Slog.v(TAG, "Client requesting input be hidden");
1746                return hideCurrentInputLocked(flags, resultReceiver);
1747            }
1748        } finally {
1749            Binder.restoreCallingIdentity(ident);
1750        }
1751    }
1752
1753    boolean hideCurrentInputLocked(int flags, ResultReceiver resultReceiver) {
1754        if ((flags&InputMethodManager.HIDE_IMPLICIT_ONLY) != 0
1755                && (mShowExplicitlyRequested || mShowForced)) {
1756            if (DEBUG) Slog.v(TAG,
1757                    "Not hiding: explicit show not cancelled by non-explicit hide");
1758            return false;
1759        }
1760        if (mShowForced && (flags&InputMethodManager.HIDE_NOT_ALWAYS) != 0) {
1761            if (DEBUG) Slog.v(TAG,
1762                    "Not hiding: forced show not cancelled by not-always hide");
1763            return false;
1764        }
1765        boolean res;
1766        if (mInputShown && mCurMethod != null) {
1767            executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
1768                    MSG_HIDE_SOFT_INPUT, mCurMethod, resultReceiver));
1769            res = true;
1770        } else {
1771            res = false;
1772        }
1773        if (mHaveConnection && mVisibleBound) {
1774            mContext.unbindService(mVisibleConnection);
1775            mVisibleBound = false;
1776        }
1777        mInputShown = false;
1778        mShowRequested = false;
1779        mShowExplicitlyRequested = false;
1780        mShowForced = false;
1781        return res;
1782    }
1783
1784    @Override
1785    public InputBindResult windowGainedFocus(IInputMethodClient client, IBinder windowToken,
1786            int controlFlags, int softInputMode, int windowFlags,
1787            EditorInfo attribute, IInputContext inputContext) {
1788        if (!calledFromValidUser()) {
1789            return null;
1790        }
1791        InputBindResult res = null;
1792        long ident = Binder.clearCallingIdentity();
1793        try {
1794            synchronized (mMethodMap) {
1795                if (DEBUG) Slog.v(TAG, "windowGainedFocus: " + client.asBinder()
1796                        + " controlFlags=#" + Integer.toHexString(controlFlags)
1797                        + " softInputMode=#" + Integer.toHexString(softInputMode)
1798                        + " windowFlags=#" + Integer.toHexString(windowFlags));
1799
1800                ClientState cs = mClients.get(client.asBinder());
1801                if (cs == null) {
1802                    throw new IllegalArgumentException("unknown client "
1803                            + client.asBinder());
1804                }
1805
1806                try {
1807                    if (!mIWindowManager.inputMethodClientHasFocus(cs.client)) {
1808                        // Check with the window manager to make sure this client actually
1809                        // has a window with focus.  If not, reject.  This is thread safe
1810                        // because if the focus changes some time before or after, the
1811                        // next client receiving focus that has any interest in input will
1812                        // be calling through here after that change happens.
1813                        Slog.w(TAG, "Focus gain on non-focused client " + cs.client
1814                                + " (uid=" + cs.uid + " pid=" + cs.pid + ")");
1815                        return null;
1816                    }
1817                } catch (RemoteException e) {
1818                }
1819
1820                if (mCurFocusedWindow == windowToken) {
1821                    Slog.w(TAG, "Window already focused, ignoring focus gain of: " + client
1822                            + " attribute=" + attribute);
1823                    if (attribute != null) {
1824                        return startInputUncheckedLocked(cs, inputContext, attribute,
1825                                controlFlags);
1826                    }
1827                    return null;
1828                }
1829                mCurFocusedWindow = windowToken;
1830
1831                // Should we auto-show the IME even if the caller has not
1832                // specified what should be done with it?
1833                // We only do this automatically if the window can resize
1834                // to accommodate the IME (so what the user sees will give
1835                // them good context without input information being obscured
1836                // by the IME) or if running on a large screen where there
1837                // is more room for the target window + IME.
1838                final boolean doAutoShow =
1839                        (softInputMode & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
1840                                == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
1841                        || mRes.getConfiguration().isLayoutSizeAtLeast(
1842                                Configuration.SCREENLAYOUT_SIZE_LARGE);
1843                final boolean isTextEditor =
1844                        (controlFlags&InputMethodManager.CONTROL_WINDOW_IS_TEXT_EDITOR) != 0;
1845
1846                // We want to start input before showing the IME, but after closing
1847                // it.  We want to do this after closing it to help the IME disappear
1848                // more quickly (not get stuck behind it initializing itself for the
1849                // new focused input, even if its window wants to hide the IME).
1850                boolean didStart = false;
1851
1852                switch (softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_STATE) {
1853                    case WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED:
1854                        if (!isTextEditor || !doAutoShow) {
1855                            if (WindowManager.LayoutParams.mayUseInputMethod(windowFlags)) {
1856                                // There is no focus view, and this window will
1857                                // be behind any soft input window, so hide the
1858                                // soft input window if it is shown.
1859                                if (DEBUG) Slog.v(TAG, "Unspecified window will hide input");
1860                                hideCurrentInputLocked(InputMethodManager.HIDE_NOT_ALWAYS, null);
1861                            }
1862                        } else if (isTextEditor && doAutoShow && (softInputMode &
1863                                WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) {
1864                            // There is a focus view, and we are navigating forward
1865                            // into the window, so show the input window for the user.
1866                            // We only do this automatically if the window can resize
1867                            // to accommodate the IME (so what the user sees will give
1868                            // them good context without input information being obscured
1869                            // by the IME) or if running on a large screen where there
1870                            // is more room for the target window + IME.
1871                            if (DEBUG) Slog.v(TAG, "Unspecified window will show input");
1872                            if (attribute != null) {
1873                                res = startInputUncheckedLocked(cs, inputContext, attribute,
1874                                        controlFlags);
1875                                didStart = true;
1876                            }
1877                            showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
1878                        }
1879                        break;
1880                    case WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED:
1881                        // Do nothing.
1882                        break;
1883                    case WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN:
1884                        if ((softInputMode &
1885                                WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) {
1886                            if (DEBUG) Slog.v(TAG, "Window asks to hide input going forward");
1887                            hideCurrentInputLocked(0, null);
1888                        }
1889                        break;
1890                    case WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN:
1891                        if (DEBUG) Slog.v(TAG, "Window asks to hide input");
1892                        hideCurrentInputLocked(0, null);
1893                        break;
1894                    case WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE:
1895                        if ((softInputMode &
1896                                WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) {
1897                            if (DEBUG) Slog.v(TAG, "Window asks to show input going forward");
1898                            if (attribute != null) {
1899                                res = startInputUncheckedLocked(cs, inputContext, attribute,
1900                                        controlFlags);
1901                                didStart = true;
1902                            }
1903                            showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
1904                        }
1905                        break;
1906                    case WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE:
1907                        if (DEBUG) Slog.v(TAG, "Window asks to always show input");
1908                        if (attribute != null) {
1909                            res = startInputUncheckedLocked(cs, inputContext, attribute,
1910                                    controlFlags);
1911                            didStart = true;
1912                        }
1913                        showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
1914                        break;
1915                }
1916
1917                if (!didStart && attribute != null) {
1918                    res = startInputUncheckedLocked(cs, inputContext, attribute,
1919                            controlFlags);
1920                }
1921            }
1922        } finally {
1923            Binder.restoreCallingIdentity(ident);
1924        }
1925
1926        return res;
1927    }
1928
1929    @Override
1930    public void showInputMethodPickerFromClient(IInputMethodClient client) {
1931        if (!calledFromValidUser()) {
1932            return;
1933        }
1934        synchronized (mMethodMap) {
1935            if (mCurClient == null || client == null
1936                    || mCurClient.client.asBinder() != client.asBinder()) {
1937                Slog.w(TAG, "Ignoring showInputMethodPickerFromClient of uid "
1938                        + Binder.getCallingUid() + ": " + client);
1939            }
1940
1941            // Always call subtype picker, because subtype picker is a superset of input method
1942            // picker.
1943            mHandler.sendEmptyMessage(MSG_SHOW_IM_SUBTYPE_PICKER);
1944        }
1945    }
1946
1947    @Override
1948    public void setInputMethod(IBinder token, String id) {
1949        if (!calledFromValidUser()) {
1950            return;
1951        }
1952        setInputMethodWithSubtypeId(token, id, NOT_A_SUBTYPE_ID);
1953    }
1954
1955    @Override
1956    public void setInputMethodAndSubtype(IBinder token, String id, InputMethodSubtype subtype) {
1957        if (!calledFromValidUser()) {
1958            return;
1959        }
1960        synchronized (mMethodMap) {
1961            if (subtype != null) {
1962                setInputMethodWithSubtypeId(token, id, getSubtypeIdFromHashCode(
1963                        mMethodMap.get(id), subtype.hashCode()));
1964            } else {
1965                setInputMethod(token, id);
1966            }
1967        }
1968    }
1969
1970    @Override
1971    public void showInputMethodAndSubtypeEnablerFromClient(
1972            IInputMethodClient client, String inputMethodId) {
1973        if (!calledFromValidUser()) {
1974            return;
1975        }
1976        synchronized (mMethodMap) {
1977            if (mCurClient == null || client == null
1978                || mCurClient.client.asBinder() != client.asBinder()) {
1979                Slog.w(TAG, "Ignoring showInputMethodAndSubtypeEnablerFromClient of: " + client);
1980            }
1981            executeOrSendMessage(mCurMethod, mCaller.obtainMessageO(
1982                    MSG_SHOW_IM_SUBTYPE_ENABLER, inputMethodId));
1983        }
1984    }
1985
1986    @Override
1987    public boolean switchToLastInputMethod(IBinder token) {
1988        if (!calledFromValidUser()) {
1989            return false;
1990        }
1991        synchronized (mMethodMap) {
1992            final Pair<String, String> lastIme = mSettings.getLastInputMethodAndSubtypeLocked();
1993            final InputMethodInfo lastImi;
1994            if (lastIme != null) {
1995                lastImi = mMethodMap.get(lastIme.first);
1996            } else {
1997                lastImi = null;
1998            }
1999            String targetLastImiId = null;
2000            int subtypeId = NOT_A_SUBTYPE_ID;
2001            if (lastIme != null && lastImi != null) {
2002                final boolean imiIdIsSame = lastImi.getId().equals(mCurMethodId);
2003                final int lastSubtypeHash = Integer.valueOf(lastIme.second);
2004                final int currentSubtypeHash = mCurrentSubtype == null ? NOT_A_SUBTYPE_ID
2005                        : mCurrentSubtype.hashCode();
2006                // If the last IME is the same as the current IME and the last subtype is not
2007                // defined, there is no need to switch to the last IME.
2008                if (!imiIdIsSame || lastSubtypeHash != currentSubtypeHash) {
2009                    targetLastImiId = lastIme.first;
2010                    subtypeId = getSubtypeIdFromHashCode(lastImi, lastSubtypeHash);
2011                }
2012            }
2013
2014            if (TextUtils.isEmpty(targetLastImiId) && !canAddToLastInputMethod(mCurrentSubtype)) {
2015                // This is a safety net. If the currentSubtype can't be added to the history
2016                // and the framework couldn't find the last ime, we will make the last ime be
2017                // the most applicable enabled keyboard subtype of the system imes.
2018                final List<InputMethodInfo> enabled = mSettings.getEnabledInputMethodListLocked();
2019                if (enabled != null) {
2020                    final int N = enabled.size();
2021                    final String locale = mCurrentSubtype == null
2022                            ? mRes.getConfiguration().locale.toString()
2023                            : mCurrentSubtype.getLocale();
2024                    for (int i = 0; i < N; ++i) {
2025                        final InputMethodInfo imi = enabled.get(i);
2026                        if (imi.getSubtypeCount() > 0 && isSystemIme(imi)) {
2027                            InputMethodSubtype keyboardSubtype =
2028                                    findLastResortApplicableSubtypeLocked(mRes, getSubtypes(imi),
2029                                            SUBTYPE_MODE_KEYBOARD, locale, true);
2030                            if (keyboardSubtype != null) {
2031                                targetLastImiId = imi.getId();
2032                                subtypeId = getSubtypeIdFromHashCode(
2033                                        imi, keyboardSubtype.hashCode());
2034                                if(keyboardSubtype.getLocale().equals(locale)) {
2035                                    break;
2036                                }
2037                            }
2038                        }
2039                    }
2040                }
2041            }
2042
2043            if (!TextUtils.isEmpty(targetLastImiId)) {
2044                if (DEBUG) {
2045                    Slog.d(TAG, "Switch to: " + lastImi.getId() + ", " + lastIme.second
2046                            + ", from: " + mCurMethodId + ", " + subtypeId);
2047                }
2048                setInputMethodWithSubtypeId(token, targetLastImiId, subtypeId);
2049                return true;
2050            } else {
2051                return false;
2052            }
2053        }
2054    }
2055
2056    @Override
2057    public boolean switchToNextInputMethod(IBinder token, boolean onlyCurrentIme) {
2058        if (!calledFromValidUser()) {
2059            return false;
2060        }
2061        synchronized (mMethodMap) {
2062            final ImeSubtypeListItem nextSubtype = mImListManager.getNextInputMethod(
2063                    onlyCurrentIme, mMethodMap.get(mCurMethodId), mCurrentSubtype);
2064            if (nextSubtype == null) {
2065                return false;
2066            }
2067            setInputMethodWithSubtypeId(token, nextSubtype.mImi.getId(), nextSubtype.mSubtypeId);
2068            return true;
2069        }
2070    }
2071
2072    @Override
2073    public InputMethodSubtype getLastInputMethodSubtype() {
2074        if (!calledFromValidUser()) {
2075            return null;
2076        }
2077        synchronized (mMethodMap) {
2078            final Pair<String, String> lastIme = mSettings.getLastInputMethodAndSubtypeLocked();
2079            // TODO: Handle the case of the last IME with no subtypes
2080            if (lastIme == null || TextUtils.isEmpty(lastIme.first)
2081                    || TextUtils.isEmpty(lastIme.second)) return null;
2082            final InputMethodInfo lastImi = mMethodMap.get(lastIme.first);
2083            if (lastImi == null) return null;
2084            try {
2085                final int lastSubtypeHash = Integer.valueOf(lastIme.second);
2086                final int lastSubtypeId = getSubtypeIdFromHashCode(lastImi, lastSubtypeHash);
2087                if (lastSubtypeId < 0 || lastSubtypeId >= lastImi.getSubtypeCount()) {
2088                    return null;
2089                }
2090                return lastImi.getSubtypeAt(lastSubtypeId);
2091            } catch (NumberFormatException e) {
2092                return null;
2093            }
2094        }
2095    }
2096
2097    @Override
2098    public void setAdditionalInputMethodSubtypes(String imiId, InputMethodSubtype[] subtypes) {
2099        if (!calledFromValidUser()) {
2100            return;
2101        }
2102        // By this IPC call, only a process which shares the same uid with the IME can add
2103        // additional input method subtypes to the IME.
2104        if (TextUtils.isEmpty(imiId) || subtypes == null || subtypes.length == 0) return;
2105        synchronized (mMethodMap) {
2106            final InputMethodInfo imi = mMethodMap.get(imiId);
2107            if (imi == null) return;
2108            final String[] packageInfos;
2109            try {
2110                packageInfos = mIPackageManager.getPackagesForUid(Binder.getCallingUid());
2111            } catch (RemoteException e) {
2112                Slog.e(TAG, "Failed to get package infos");
2113                return;
2114            }
2115            if (packageInfos != null) {
2116                final int packageNum = packageInfos.length;
2117                for (int i = 0; i < packageNum; ++i) {
2118                    if (packageInfos[i].equals(imi.getPackageName())) {
2119                        mFileManager.addInputMethodSubtypes(imi, subtypes);
2120                        final long ident = Binder.clearCallingIdentity();
2121                        try {
2122                            buildInputMethodListLocked(mMethodList, mMethodMap);
2123                        } finally {
2124                            Binder.restoreCallingIdentity(ident);
2125                        }
2126                        return;
2127                    }
2128                }
2129            }
2130        }
2131        return;
2132    }
2133
2134    private void setInputMethodWithSubtypeId(IBinder token, String id, int subtypeId) {
2135        synchronized (mMethodMap) {
2136            if (token == null) {
2137                if (mContext.checkCallingOrSelfPermission(
2138                        android.Manifest.permission.WRITE_SECURE_SETTINGS)
2139                        != PackageManager.PERMISSION_GRANTED) {
2140                    throw new SecurityException(
2141                            "Using null token requires permission "
2142                            + android.Manifest.permission.WRITE_SECURE_SETTINGS);
2143                }
2144            } else if (mCurToken != token) {
2145                Slog.w(TAG, "Ignoring setInputMethod of uid " + Binder.getCallingUid()
2146                        + " token: " + token);
2147                return;
2148            }
2149
2150            final long ident = Binder.clearCallingIdentity();
2151            try {
2152                setInputMethodLocked(id, subtypeId);
2153            } finally {
2154                Binder.restoreCallingIdentity(ident);
2155            }
2156        }
2157    }
2158
2159    @Override
2160    public void hideMySoftInput(IBinder token, int flags) {
2161        if (!calledFromValidUser()) {
2162            return;
2163        }
2164        synchronized (mMethodMap) {
2165            if (token == null || mCurToken != token) {
2166                if (DEBUG) Slog.w(TAG, "Ignoring hideInputMethod of uid "
2167                        + Binder.getCallingUid() + " token: " + token);
2168                return;
2169            }
2170            long ident = Binder.clearCallingIdentity();
2171            try {
2172                hideCurrentInputLocked(flags, null);
2173            } finally {
2174                Binder.restoreCallingIdentity(ident);
2175            }
2176        }
2177    }
2178
2179    @Override
2180    public void showMySoftInput(IBinder token, int flags) {
2181        if (!calledFromValidUser()) {
2182            return;
2183        }
2184        synchronized (mMethodMap) {
2185            if (token == null || mCurToken != token) {
2186                Slog.w(TAG, "Ignoring showMySoftInput of uid "
2187                        + Binder.getCallingUid() + " token: " + token);
2188                return;
2189            }
2190            long ident = Binder.clearCallingIdentity();
2191            try {
2192                showCurrentInputLocked(flags, null);
2193            } finally {
2194                Binder.restoreCallingIdentity(ident);
2195            }
2196        }
2197    }
2198
2199    void setEnabledSessionInMainThread(SessionState session) {
2200        if (mEnabledSession != session) {
2201            if (mEnabledSession != null) {
2202                try {
2203                    if (DEBUG) Slog.v(TAG, "Disabling: " + mEnabledSession);
2204                    mEnabledSession.method.setSessionEnabled(
2205                            mEnabledSession.session, false);
2206                } catch (RemoteException e) {
2207                }
2208            }
2209            mEnabledSession = session;
2210            try {
2211                if (DEBUG) Slog.v(TAG, "Enabling: " + mEnabledSession);
2212                session.method.setSessionEnabled(
2213                        session.session, true);
2214            } catch (RemoteException e) {
2215            }
2216        }
2217    }
2218
2219    @Override
2220    public boolean handleMessage(Message msg) {
2221        SomeArgs args;
2222        switch (msg.what) {
2223            case MSG_SHOW_IM_PICKER:
2224                showInputMethodMenu();
2225                return true;
2226
2227            case MSG_SHOW_IM_SUBTYPE_PICKER:
2228                showInputMethodSubtypeMenu();
2229                return true;
2230
2231            case MSG_SHOW_IM_SUBTYPE_ENABLER:
2232                args = (SomeArgs)msg.obj;
2233                showInputMethodAndSubtypeEnabler((String)args.arg1);
2234                args.recycle();
2235                return true;
2236
2237            case MSG_SHOW_IM_CONFIG:
2238                showConfigureInputMethods();
2239                return true;
2240
2241            // ---------------------------------------------------------
2242
2243            case MSG_UNBIND_INPUT:
2244                try {
2245                    ((IInputMethod)msg.obj).unbindInput();
2246                } catch (RemoteException e) {
2247                    // There is nothing interesting about the method dying.
2248                }
2249                return true;
2250            case MSG_BIND_INPUT:
2251                args = (SomeArgs)msg.obj;
2252                try {
2253                    ((IInputMethod)args.arg1).bindInput((InputBinding)args.arg2);
2254                } catch (RemoteException e) {
2255                }
2256                args.recycle();
2257                return true;
2258            case MSG_SHOW_SOFT_INPUT:
2259                args = (SomeArgs)msg.obj;
2260                try {
2261                    ((IInputMethod)args.arg1).showSoftInput(msg.arg1,
2262                            (ResultReceiver)args.arg2);
2263                } catch (RemoteException e) {
2264                }
2265                args.recycle();
2266                return true;
2267            case MSG_HIDE_SOFT_INPUT:
2268                args = (SomeArgs)msg.obj;
2269                try {
2270                    ((IInputMethod)args.arg1).hideSoftInput(0,
2271                            (ResultReceiver)args.arg2);
2272                } catch (RemoteException e) {
2273                }
2274                args.recycle();
2275                return true;
2276            case MSG_ATTACH_TOKEN:
2277                args = (SomeArgs)msg.obj;
2278                try {
2279                    if (DEBUG) Slog.v(TAG, "Sending attach of token: " + args.arg2);
2280                    ((IInputMethod)args.arg1).attachToken((IBinder)args.arg2);
2281                } catch (RemoteException e) {
2282                }
2283                args.recycle();
2284                return true;
2285            case MSG_CREATE_SESSION:
2286                args = (SomeArgs)msg.obj;
2287                try {
2288                    ((IInputMethod)args.arg1).createSession(
2289                            (IInputMethodCallback)args.arg2);
2290                } catch (RemoteException e) {
2291                }
2292                args.recycle();
2293                return true;
2294            // ---------------------------------------------------------
2295
2296            case MSG_START_INPUT:
2297                args = (SomeArgs)msg.obj;
2298                try {
2299                    SessionState session = (SessionState)args.arg1;
2300                    setEnabledSessionInMainThread(session);
2301                    session.method.startInput((IInputContext)args.arg2,
2302                            (EditorInfo)args.arg3);
2303                } catch (RemoteException e) {
2304                }
2305                args.recycle();
2306                return true;
2307            case MSG_RESTART_INPUT:
2308                args = (SomeArgs)msg.obj;
2309                try {
2310                    SessionState session = (SessionState)args.arg1;
2311                    setEnabledSessionInMainThread(session);
2312                    session.method.restartInput((IInputContext)args.arg2,
2313                            (EditorInfo)args.arg3);
2314                } catch (RemoteException e) {
2315                }
2316                args.recycle();
2317                return true;
2318
2319            // ---------------------------------------------------------
2320
2321            case MSG_UNBIND_METHOD:
2322                try {
2323                    ((IInputMethodClient)msg.obj).onUnbindMethod(msg.arg1);
2324                } catch (RemoteException e) {
2325                    // There is nothing interesting about the last client dying.
2326                }
2327                return true;
2328            case MSG_BIND_METHOD:
2329                args = (SomeArgs)msg.obj;
2330                try {
2331                    ((IInputMethodClient)args.arg1).onBindMethod(
2332                            (InputBindResult)args.arg2);
2333                } catch (RemoteException e) {
2334                    Slog.w(TAG, "Client died receiving input method " + args.arg2);
2335                }
2336                args.recycle();
2337                return true;
2338            case MSG_SET_ACTIVE:
2339                try {
2340                    ((ClientState)msg.obj).client.setActive(msg.arg1 != 0);
2341                } catch (RemoteException e) {
2342                    Slog.w(TAG, "Got RemoteException sending setActive(false) notification to pid "
2343                            + ((ClientState)msg.obj).pid + " uid "
2344                            + ((ClientState)msg.obj).uid);
2345                }
2346                return true;
2347
2348            // --------------------------------------------------------------
2349            case MSG_HARD_KEYBOARD_SWITCH_CHANGED:
2350                mHardKeyboardListener.handleHardKeyboardStatusChange(
2351                        msg.arg1 == 1, msg.arg2 == 1);
2352                return true;
2353        }
2354        return false;
2355    }
2356
2357    private static boolean isSystemIme(InputMethodInfo inputMethod) {
2358        return (inputMethod.getServiceInfo().applicationInfo.flags
2359                & ApplicationInfo.FLAG_SYSTEM) != 0;
2360    }
2361
2362    private static ArrayList<InputMethodSubtype> getSubtypes(InputMethodInfo imi) {
2363        ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
2364        final int subtypeCount = imi.getSubtypeCount();
2365        for (int i = 0; i < subtypeCount; ++i) {
2366            subtypes.add(imi.getSubtypeAt(i));
2367        }
2368        return subtypes;
2369    }
2370
2371    private static ArrayList<InputMethodSubtype> getOverridingImplicitlyEnabledSubtypes(
2372            InputMethodInfo imi, String mode) {
2373        ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
2374        final int subtypeCount = imi.getSubtypeCount();
2375        for (int i = 0; i < subtypeCount; ++i) {
2376            final InputMethodSubtype subtype = imi.getSubtypeAt(i);
2377            if (subtype.overridesImplicitlyEnabledSubtype() && subtype.getMode().equals(mode)) {
2378                subtypes.add(subtype);
2379            }
2380        }
2381        return subtypes;
2382    }
2383
2384    private InputMethodInfo getMostApplicableDefaultIMELocked() {
2385        List<InputMethodInfo> enabled = mSettings.getEnabledInputMethodListLocked();
2386        if (enabled != null && enabled.size() > 0) {
2387            // We'd prefer to fall back on a system IME, since that is safer.
2388            int i = enabled.size();
2389            int firstFoundSystemIme = -1;
2390            while (i > 0) {
2391                i--;
2392                final InputMethodInfo imi = enabled.get(i);
2393                if (isSystemImeThatHasEnglishSubtype(imi) && !imi.isAuxiliaryIme()) {
2394                    return imi;
2395                }
2396                if (firstFoundSystemIme < 0 && isSystemIme(imi) && !imi.isAuxiliaryIme()) {
2397                    firstFoundSystemIme = i;
2398                }
2399            }
2400            return enabled.get(Math.max(firstFoundSystemIme, 0));
2401        }
2402        return null;
2403    }
2404
2405    private boolean chooseNewDefaultIMELocked() {
2406        final InputMethodInfo imi = getMostApplicableDefaultIMELocked();
2407        if (imi != null) {
2408            if (DEBUG) {
2409                Slog.d(TAG, "New default IME was selected: " + imi.getId());
2410            }
2411            resetSelectedInputMethodAndSubtypeLocked(imi.getId());
2412            return true;
2413        }
2414
2415        return false;
2416    }
2417
2418    void buildInputMethodListLocked(ArrayList<InputMethodInfo> list,
2419            HashMap<String, InputMethodInfo> map) {
2420        if (DEBUG) {
2421            Slog.d(TAG, "--- re-buildInputMethodList " + ", \n ------ \n" + getStackTrace());
2422        }
2423        list.clear();
2424        map.clear();
2425
2426        // Use for queryIntentServicesAsUser
2427        final PackageManager pm = mContext.getPackageManager();
2428        final Configuration config = mRes.getConfiguration();
2429        final boolean haveHardKeyboard = config.keyboard == Configuration.KEYBOARD_QWERTY;
2430        String disabledSysImes = mSettings.getDisabledSystemInputMethods();
2431        if (disabledSysImes == null) disabledSysImes = "";
2432
2433        final List<ResolveInfo> services = pm.queryIntentServicesAsUser(
2434                new Intent(InputMethod.SERVICE_INTERFACE),
2435                PackageManager.GET_META_DATA, mSettings.getCurrentUserId());
2436
2437        final HashMap<String, List<InputMethodSubtype>> additionalSubtypes =
2438                mFileManager.getAllAdditionalInputMethodSubtypes();
2439        for (int i = 0; i < services.size(); ++i) {
2440            ResolveInfo ri = services.get(i);
2441            ServiceInfo si = ri.serviceInfo;
2442            ComponentName compName = new ComponentName(si.packageName, si.name);
2443            if (!android.Manifest.permission.BIND_INPUT_METHOD.equals(
2444                    si.permission)) {
2445                Slog.w(TAG, "Skipping input method " + compName
2446                        + ": it does not require the permission "
2447                        + android.Manifest.permission.BIND_INPUT_METHOD);
2448                continue;
2449            }
2450
2451            if (DEBUG) Slog.d(TAG, "Checking " + compName);
2452
2453            try {
2454                InputMethodInfo p = new InputMethodInfo(mContext, ri, additionalSubtypes);
2455                list.add(p);
2456                final String id = p.getId();
2457                map.put(id, p);
2458
2459                // Valid system default IMEs and IMEs that have English subtypes are enabled
2460                // by default, unless there's a hard keyboard and the system IME was explicitly
2461                // disabled
2462                if ((isValidSystemDefaultIme(p, mContext) || isSystemImeThatHasEnglishSubtype(p))
2463                        && (!haveHardKeyboard || disabledSysImes.indexOf(id) < 0)) {
2464                    setInputMethodEnabledLocked(id, true);
2465                }
2466
2467                if (DEBUG) {
2468                    Slog.d(TAG, "Found a third-party input method " + p);
2469                }
2470
2471            } catch (XmlPullParserException e) {
2472                Slog.w(TAG, "Unable to load input method " + compName, e);
2473            } catch (IOException e) {
2474                Slog.w(TAG, "Unable to load input method " + compName, e);
2475            }
2476        }
2477
2478        final String defaultImiId = mSettings.getSelectedInputMethod();
2479        if (!TextUtils.isEmpty(defaultImiId)) {
2480            if (!map.containsKey(defaultImiId)) {
2481                Slog.w(TAG, "Default IME is uninstalled. Choose new default IME.");
2482                if (chooseNewDefaultIMELocked()) {
2483                    updateFromSettingsLocked();
2484                }
2485            } else {
2486                // Double check that the default IME is certainly enabled.
2487                setInputMethodEnabledLocked(defaultImiId, true);
2488            }
2489        }
2490    }
2491
2492    // ----------------------------------------------------------------------
2493
2494    private void showInputMethodMenu() {
2495        showInputMethodMenuInternal(false);
2496    }
2497
2498    private void showInputMethodSubtypeMenu() {
2499        showInputMethodMenuInternal(true);
2500    }
2501
2502    private void showInputMethodAndSubtypeEnabler(String inputMethodId) {
2503        Intent intent = new Intent(Settings.ACTION_INPUT_METHOD_SUBTYPE_SETTINGS);
2504        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
2505                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
2506                | Intent.FLAG_ACTIVITY_CLEAR_TOP);
2507        if (!TextUtils.isEmpty(inputMethodId)) {
2508            intent.putExtra(Settings.EXTRA_INPUT_METHOD_ID, inputMethodId);
2509        }
2510        mContext.startActivity(intent);
2511    }
2512
2513    private void showConfigureInputMethods() {
2514        Intent intent = new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS);
2515        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
2516                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
2517                | Intent.FLAG_ACTIVITY_CLEAR_TOP);
2518        mContext.startActivity(intent);
2519    }
2520
2521    private boolean isScreenLocked() {
2522        return mKeyguardManager != null
2523                && mKeyguardManager.isKeyguardLocked() && mKeyguardManager.isKeyguardSecure();
2524    }
2525    private void showInputMethodMenuInternal(boolean showSubtypes) {
2526        if (DEBUG) Slog.v(TAG, "Show switching menu");
2527
2528        final Context context = mContext;
2529        final boolean isScreenLocked = isScreenLocked();
2530
2531        final String lastInputMethodId = mSettings.getSelectedInputMethod();
2532        int lastInputMethodSubtypeId = getSelectedInputMethodSubtypeId(lastInputMethodId);
2533        if (DEBUG) Slog.v(TAG, "Current IME: " + lastInputMethodId);
2534
2535        synchronized (mMethodMap) {
2536            final HashMap<InputMethodInfo, List<InputMethodSubtype>> immis =
2537                    getExplicitlyOrImplicitlyEnabledInputMethodsAndSubtypeListLocked();
2538            if (immis == null || immis.size() == 0) {
2539                return;
2540            }
2541
2542            hideInputMethodMenuLocked();
2543
2544            final List<ImeSubtypeListItem> imList =
2545                    mImListManager.getSortedInputMethodAndSubtypeList(
2546                            showSubtypes, mInputShown, isScreenLocked);
2547
2548            if (lastInputMethodSubtypeId == NOT_A_SUBTYPE_ID) {
2549                final InputMethodSubtype currentSubtype = getCurrentInputMethodSubtypeLocked();
2550                if (currentSubtype != null) {
2551                    final InputMethodInfo currentImi = mMethodMap.get(mCurMethodId);
2552                    lastInputMethodSubtypeId =
2553                            getSubtypeIdFromHashCode(currentImi, currentSubtype.hashCode());
2554                }
2555            }
2556
2557            final int N = imList.size();
2558            mIms = new InputMethodInfo[N];
2559            mSubtypeIds = new int[N];
2560            int checkedItem = 0;
2561            for (int i = 0; i < N; ++i) {
2562                final ImeSubtypeListItem item = imList.get(i);
2563                mIms[i] = item.mImi;
2564                mSubtypeIds[i] = item.mSubtypeId;
2565                if (mIms[i].getId().equals(lastInputMethodId)) {
2566                    int subtypeId = mSubtypeIds[i];
2567                    if ((subtypeId == NOT_A_SUBTYPE_ID)
2568                            || (lastInputMethodSubtypeId == NOT_A_SUBTYPE_ID && subtypeId == 0)
2569                            || (subtypeId == lastInputMethodSubtypeId)) {
2570                        checkedItem = i;
2571                    }
2572                }
2573            }
2574            final TypedArray a = context.obtainStyledAttributes(null,
2575                    com.android.internal.R.styleable.DialogPreference,
2576                    com.android.internal.R.attr.alertDialogStyle, 0);
2577            mDialogBuilder = new AlertDialog.Builder(context)
2578                    .setOnCancelListener(new OnCancelListener() {
2579                        @Override
2580                        public void onCancel(DialogInterface dialog) {
2581                            hideInputMethodMenu();
2582                        }
2583                    })
2584                    .setIcon(a.getDrawable(
2585                            com.android.internal.R.styleable.DialogPreference_dialogTitle));
2586            a.recycle();
2587            final LayoutInflater inflater =
2588                    (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
2589            final View tv = inflater.inflate(
2590                    com.android.internal.R.layout.input_method_switch_dialog_title, null);
2591            mDialogBuilder.setCustomTitle(tv);
2592
2593            // Setup layout for a toggle switch of the hardware keyboard
2594            mSwitchingDialogTitleView = tv;
2595            mSwitchingDialogTitleView.findViewById(
2596                    com.android.internal.R.id.hard_keyboard_section).setVisibility(
2597                            mWindowManagerService.isHardKeyboardAvailable() ?
2598                                    View.VISIBLE : View.GONE);
2599            final Switch hardKeySwitch =  ((Switch)mSwitchingDialogTitleView.findViewById(
2600                    com.android.internal.R.id.hard_keyboard_switch));
2601            hardKeySwitch.setChecked(mWindowManagerService.isHardKeyboardEnabled());
2602            hardKeySwitch.setOnCheckedChangeListener(
2603                    new OnCheckedChangeListener() {
2604                        @Override
2605                        public void onCheckedChanged(
2606                                CompoundButton buttonView, boolean isChecked) {
2607                            mWindowManagerService.setHardKeyboardEnabled(isChecked);
2608                        }
2609                    });
2610
2611            final ImeSubtypeListAdapter adapter = new ImeSubtypeListAdapter(context,
2612                    com.android.internal.R.layout.simple_list_item_2_single_choice, imList,
2613                    checkedItem);
2614
2615            mDialogBuilder.setSingleChoiceItems(adapter, checkedItem,
2616                    new AlertDialog.OnClickListener() {
2617                        @Override
2618                        public void onClick(DialogInterface dialog, int which) {
2619                            synchronized (mMethodMap) {
2620                                if (mIms == null || mIms.length <= which
2621                                        || mSubtypeIds == null || mSubtypeIds.length <= which) {
2622                                    return;
2623                                }
2624                                InputMethodInfo im = mIms[which];
2625                                int subtypeId = mSubtypeIds[which];
2626                                hideInputMethodMenu();
2627                                if (im != null) {
2628                                    if ((subtypeId < 0)
2629                                            || (subtypeId >= im.getSubtypeCount())) {
2630                                        subtypeId = NOT_A_SUBTYPE_ID;
2631                                    }
2632                                    setInputMethodLocked(im.getId(), subtypeId);
2633                                }
2634                            }
2635                        }
2636                    });
2637
2638            if (showSubtypes && !isScreenLocked) {
2639                mDialogBuilder.setPositiveButton(
2640                        com.android.internal.R.string.configure_input_methods,
2641                        new DialogInterface.OnClickListener() {
2642                            @Override
2643                            public void onClick(DialogInterface dialog, int whichButton) {
2644                                showConfigureInputMethods();
2645                            }
2646                        });
2647            }
2648            mSwitchingDialog = mDialogBuilder.create();
2649            mSwitchingDialog.setCanceledOnTouchOutside(true);
2650            mSwitchingDialog.getWindow().setType(
2651                    WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG);
2652            mSwitchingDialog.getWindow().getAttributes().setTitle("Select input method");
2653            mSwitchingDialog.show();
2654        }
2655    }
2656
2657    private static class ImeSubtypeListItem implements Comparable<ImeSubtypeListItem> {
2658        public final CharSequence mImeName;
2659        public final CharSequence mSubtypeName;
2660        public final InputMethodInfo mImi;
2661        public final int mSubtypeId;
2662        private final boolean mIsSystemLocale;
2663        private final boolean mIsSystemLanguage;
2664
2665        public ImeSubtypeListItem(CharSequence imeName, CharSequence subtypeName,
2666                InputMethodInfo imi, int subtypeId, String subtypeLocale, String systemLocale) {
2667            mImeName = imeName;
2668            mSubtypeName = subtypeName;
2669            mImi = imi;
2670            mSubtypeId = subtypeId;
2671            if (TextUtils.isEmpty(subtypeLocale)) {
2672                mIsSystemLocale = false;
2673                mIsSystemLanguage = false;
2674            } else {
2675                mIsSystemLocale = subtypeLocale.equals(systemLocale);
2676                mIsSystemLanguage = mIsSystemLocale
2677                        || subtypeLocale.startsWith(systemLocale.substring(0, 2));
2678            }
2679        }
2680
2681        @Override
2682        public int compareTo(ImeSubtypeListItem other) {
2683            if (TextUtils.isEmpty(mImeName)) {
2684                return 1;
2685            }
2686            if (TextUtils.isEmpty(other.mImeName)) {
2687                return -1;
2688            }
2689            if (!TextUtils.equals(mImeName, other.mImeName)) {
2690                return mImeName.toString().compareTo(other.mImeName.toString());
2691            }
2692            if (TextUtils.equals(mSubtypeName, other.mSubtypeName)) {
2693                return 0;
2694            }
2695            if (mIsSystemLocale) {
2696                return -1;
2697            }
2698            if (other.mIsSystemLocale) {
2699                return 1;
2700            }
2701            if (mIsSystemLanguage) {
2702                return -1;
2703            }
2704            if (other.mIsSystemLanguage) {
2705                return 1;
2706            }
2707            if (TextUtils.isEmpty(mSubtypeName)) {
2708                return 1;
2709            }
2710            if (TextUtils.isEmpty(other.mSubtypeName)) {
2711                return -1;
2712            }
2713            return mSubtypeName.toString().compareTo(other.mSubtypeName.toString());
2714        }
2715    }
2716
2717    private static class ImeSubtypeListAdapter extends ArrayAdapter<ImeSubtypeListItem> {
2718        private final LayoutInflater mInflater;
2719        private final int mTextViewResourceId;
2720        private final List<ImeSubtypeListItem> mItemsList;
2721        private final int mCheckedItem;
2722        public ImeSubtypeListAdapter(Context context, int textViewResourceId,
2723                List<ImeSubtypeListItem> itemsList, int checkedItem) {
2724            super(context, textViewResourceId, itemsList);
2725            mTextViewResourceId = textViewResourceId;
2726            mItemsList = itemsList;
2727            mCheckedItem = checkedItem;
2728            mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
2729        }
2730
2731        @Override
2732        public View getView(int position, View convertView, ViewGroup parent) {
2733            final View view = convertView != null ? convertView
2734                    : mInflater.inflate(mTextViewResourceId, null);
2735            if (position < 0 || position >= mItemsList.size()) return view;
2736            final ImeSubtypeListItem item = mItemsList.get(position);
2737            final CharSequence imeName = item.mImeName;
2738            final CharSequence subtypeName = item.mSubtypeName;
2739            final TextView firstTextView = (TextView)view.findViewById(android.R.id.text1);
2740            final TextView secondTextView = (TextView)view.findViewById(android.R.id.text2);
2741            if (TextUtils.isEmpty(subtypeName)) {
2742                firstTextView.setText(imeName);
2743                secondTextView.setVisibility(View.GONE);
2744            } else {
2745                firstTextView.setText(subtypeName);
2746                secondTextView.setText(imeName);
2747                secondTextView.setVisibility(View.VISIBLE);
2748            }
2749            final RadioButton radioButton =
2750                    (RadioButton)view.findViewById(com.android.internal.R.id.radio);
2751            radioButton.setChecked(position == mCheckedItem);
2752            return view;
2753        }
2754    }
2755
2756    void hideInputMethodMenu() {
2757        synchronized (mMethodMap) {
2758            hideInputMethodMenuLocked();
2759        }
2760    }
2761
2762    void hideInputMethodMenuLocked() {
2763        if (DEBUG) Slog.v(TAG, "Hide switching menu");
2764
2765        if (mSwitchingDialog != null) {
2766            mSwitchingDialog.dismiss();
2767            mSwitchingDialog = null;
2768        }
2769
2770        mDialogBuilder = null;
2771        mIms = null;
2772    }
2773
2774    // ----------------------------------------------------------------------
2775
2776    @Override
2777    public boolean setInputMethodEnabled(String id, boolean enabled) {
2778        // TODO: Make this work even for non-current users?
2779        if (!calledFromValidUser()) {
2780            return false;
2781        }
2782        synchronized (mMethodMap) {
2783            if (mContext.checkCallingOrSelfPermission(
2784                    android.Manifest.permission.WRITE_SECURE_SETTINGS)
2785                    != PackageManager.PERMISSION_GRANTED) {
2786                throw new SecurityException(
2787                        "Requires permission "
2788                        + android.Manifest.permission.WRITE_SECURE_SETTINGS);
2789            }
2790
2791            long ident = Binder.clearCallingIdentity();
2792            try {
2793                return setInputMethodEnabledLocked(id, enabled);
2794            } finally {
2795                Binder.restoreCallingIdentity(ident);
2796            }
2797        }
2798    }
2799
2800    boolean setInputMethodEnabledLocked(String id, boolean enabled) {
2801        // Make sure this is a valid input method.
2802        InputMethodInfo imm = mMethodMap.get(id);
2803        if (imm == null) {
2804            throw new IllegalArgumentException("Unknown id: " + mCurMethodId);
2805        }
2806
2807        List<Pair<String, ArrayList<String>>> enabledInputMethodsList = mSettings
2808                .getEnabledInputMethodsAndSubtypeListLocked();
2809
2810        if (enabled) {
2811            for (Pair<String, ArrayList<String>> pair: enabledInputMethodsList) {
2812                if (pair.first.equals(id)) {
2813                    // We are enabling this input method, but it is already enabled.
2814                    // Nothing to do. The previous state was enabled.
2815                    return true;
2816                }
2817            }
2818            mSettings.appendAndPutEnabledInputMethodLocked(id, false);
2819            // Previous state was disabled.
2820            return false;
2821        } else {
2822            StringBuilder builder = new StringBuilder();
2823            if (mSettings.buildAndPutEnabledInputMethodsStrRemovingIdLocked(
2824                    builder, enabledInputMethodsList, id)) {
2825                // Disabled input method is currently selected, switch to another one.
2826                final String selId = mSettings.getSelectedInputMethod();
2827                if (id.equals(selId) && !chooseNewDefaultIMELocked()) {
2828                    Slog.i(TAG, "Can't find new IME, unsetting the current input method.");
2829                    resetSelectedInputMethodAndSubtypeLocked("");
2830                }
2831                // Previous state was enabled.
2832                return true;
2833            } else {
2834                // We are disabling the input method but it is already disabled.
2835                // Nothing to do.  The previous state was disabled.
2836                return false;
2837            }
2838        }
2839    }
2840
2841    private boolean canAddToLastInputMethod(InputMethodSubtype subtype) {
2842        if (subtype == null) return true;
2843        return !subtype.isAuxiliary();
2844    }
2845
2846    private void saveCurrentInputMethodAndSubtypeToHistory() {
2847        String subtypeId = NOT_A_SUBTYPE_ID_STR;
2848        if (mCurrentSubtype != null) {
2849            subtypeId = String.valueOf(mCurrentSubtype.hashCode());
2850        }
2851        if (canAddToLastInputMethod(mCurrentSubtype)) {
2852            mSettings.addSubtypeToHistory(mCurMethodId, subtypeId);
2853        }
2854    }
2855
2856    private void setSelectedInputMethodAndSubtypeLocked(InputMethodInfo imi, int subtypeId,
2857            boolean setSubtypeOnly) {
2858        // Update the history of InputMethod and Subtype
2859        saveCurrentInputMethodAndSubtypeToHistory();
2860
2861        // Set Subtype here
2862        if (imi == null || subtypeId < 0) {
2863            mSettings.putSelectedSubtype(NOT_A_SUBTYPE_ID);
2864            mCurrentSubtype = null;
2865        } else {
2866            if (subtypeId < imi.getSubtypeCount()) {
2867                InputMethodSubtype subtype = imi.getSubtypeAt(subtypeId);
2868                mSettings.putSelectedSubtype(subtype.hashCode());
2869                mCurrentSubtype = subtype;
2870            } else {
2871                mSettings.putSelectedSubtype(NOT_A_SUBTYPE_ID);
2872                // If the subtype is not specified, choose the most applicable one
2873                mCurrentSubtype = getCurrentInputMethodSubtypeLocked();
2874            }
2875        }
2876
2877        // Workaround.
2878        // ASEC is not ready in the IMMS constructor. Accordingly, forward-locked
2879        // IMEs are not recognized and considered uninstalled.
2880        // Actually, we can't move everything after SystemReady because
2881        // IMMS needs to run in the encryption lock screen. So, we just skip changing
2882        // the default IME here and try cheking the default IME again in systemReady().
2883        // TODO: Do nothing before system ready and implement a separated logic for
2884        // the encryption lock screen.
2885        // TODO: ASEC should be ready before IMMS is instantiated.
2886        if (mSystemReady && !setSubtypeOnly) {
2887            // Set InputMethod here
2888            mSettings.putSelectedInputMethod(imi != null ? imi.getId() : "");
2889        }
2890    }
2891
2892    private void resetSelectedInputMethodAndSubtypeLocked(String newDefaultIme) {
2893        InputMethodInfo imi = mMethodMap.get(newDefaultIme);
2894        int lastSubtypeId = NOT_A_SUBTYPE_ID;
2895        // newDefaultIme is empty when there is no candidate for the selected IME.
2896        if (imi != null && !TextUtils.isEmpty(newDefaultIme)) {
2897            String subtypeHashCode = mSettings.getLastSubtypeForInputMethodLocked(newDefaultIme);
2898            if (subtypeHashCode != null) {
2899                try {
2900                    lastSubtypeId = getSubtypeIdFromHashCode(
2901                            imi, Integer.valueOf(subtypeHashCode));
2902                } catch (NumberFormatException e) {
2903                    Slog.w(TAG, "HashCode for subtype looks broken: " + subtypeHashCode, e);
2904                }
2905            }
2906        }
2907        setSelectedInputMethodAndSubtypeLocked(imi, lastSubtypeId, false);
2908    }
2909
2910    private int getSelectedInputMethodSubtypeId(String id) {
2911        InputMethodInfo imi = mMethodMap.get(id);
2912        if (imi == null) {
2913            return NOT_A_SUBTYPE_ID;
2914        }
2915        final int subtypeHashCode = mSettings.getSelectedInputMethodSubtypeHashCode();
2916        return getSubtypeIdFromHashCode(imi, subtypeHashCode);
2917    }
2918
2919    private static boolean isValidSubtypeId(InputMethodInfo imi, int subtypeHashCode) {
2920        return getSubtypeIdFromHashCode(imi, subtypeHashCode) != NOT_A_SUBTYPE_ID;
2921    }
2922
2923    private static int getSubtypeIdFromHashCode(InputMethodInfo imi, int subtypeHashCode) {
2924        if (imi != null) {
2925            final int subtypeCount = imi.getSubtypeCount();
2926            for (int i = 0; i < subtypeCount; ++i) {
2927                InputMethodSubtype ims = imi.getSubtypeAt(i);
2928                if (subtypeHashCode == ims.hashCode()) {
2929                    return i;
2930                }
2931            }
2932        }
2933        return NOT_A_SUBTYPE_ID;
2934    }
2935
2936    private static ArrayList<InputMethodSubtype> getImplicitlyApplicableSubtypesLocked(
2937            Resources res, InputMethodInfo imi) {
2938        final List<InputMethodSubtype> subtypes = getSubtypes(imi);
2939        final String systemLocale = res.getConfiguration().locale.toString();
2940        if (TextUtils.isEmpty(systemLocale)) return new ArrayList<InputMethodSubtype>();
2941        final HashMap<String, InputMethodSubtype> applicableModeAndSubtypesMap =
2942                new HashMap<String, InputMethodSubtype>();
2943        final int N = subtypes.size();
2944        for (int i = 0; i < N; ++i) {
2945            // scan overriding implicitly enabled subtypes.
2946            InputMethodSubtype subtype = subtypes.get(i);
2947            if (subtype.overridesImplicitlyEnabledSubtype()) {
2948                final String mode = subtype.getMode();
2949                if (!applicableModeAndSubtypesMap.containsKey(mode)) {
2950                    applicableModeAndSubtypesMap.put(mode, subtype);
2951                }
2952            }
2953        }
2954        if (applicableModeAndSubtypesMap.size() > 0) {
2955            return new ArrayList<InputMethodSubtype>(applicableModeAndSubtypesMap.values());
2956        }
2957        for (int i = 0; i < N; ++i) {
2958            final InputMethodSubtype subtype = subtypes.get(i);
2959            final String locale = subtype.getLocale();
2960            final String mode = subtype.getMode();
2961            // When system locale starts with subtype's locale, that subtype will be applicable
2962            // for system locale
2963            // For instance, it's clearly applicable for cases like system locale = en_US and
2964            // subtype = en, but it is not necessarily considered applicable for cases like system
2965            // locale = en and subtype = en_US.
2966            // We just call systemLocale.startsWith(locale) in this function because there is no
2967            // need to find applicable subtypes aggressively unlike
2968            // findLastResortApplicableSubtypeLocked.
2969            if (systemLocale.startsWith(locale)) {
2970                final InputMethodSubtype applicableSubtype = applicableModeAndSubtypesMap.get(mode);
2971                // If more applicable subtypes are contained, skip.
2972                if (applicableSubtype != null) {
2973                    if (systemLocale.equals(applicableSubtype.getLocale())) continue;
2974                    if (!systemLocale.equals(locale)) continue;
2975                }
2976                applicableModeAndSubtypesMap.put(mode, subtype);
2977            }
2978        }
2979        final InputMethodSubtype keyboardSubtype
2980                = applicableModeAndSubtypesMap.get(SUBTYPE_MODE_KEYBOARD);
2981        final ArrayList<InputMethodSubtype> applicableSubtypes = new ArrayList<InputMethodSubtype>(
2982                applicableModeAndSubtypesMap.values());
2983        if (keyboardSubtype != null && !keyboardSubtype.containsExtraValueKey(TAG_ASCII_CAPABLE)) {
2984            for (int i = 0; i < N; ++i) {
2985                final InputMethodSubtype subtype = subtypes.get(i);
2986                final String mode = subtype.getMode();
2987                if (SUBTYPE_MODE_KEYBOARD.equals(mode) && subtype.containsExtraValueKey(
2988                        TAG_ENABLED_WHEN_DEFAULT_IS_NOT_ASCII_CAPABLE)) {
2989                    applicableSubtypes.add(subtype);
2990                }
2991            }
2992        }
2993        if (keyboardSubtype == null) {
2994            InputMethodSubtype lastResortKeyboardSubtype = findLastResortApplicableSubtypeLocked(
2995                    res, subtypes, SUBTYPE_MODE_KEYBOARD, systemLocale, true);
2996            if (lastResortKeyboardSubtype != null) {
2997                applicableSubtypes.add(lastResortKeyboardSubtype);
2998            }
2999        }
3000        return applicableSubtypes;
3001    }
3002
3003    /**
3004     * If there are no selected subtypes, tries finding the most applicable one according to the
3005     * given locale.
3006     * @param subtypes this function will search the most applicable subtype in subtypes
3007     * @param mode subtypes will be filtered by mode
3008     * @param locale subtypes will be filtered by locale
3009     * @param canIgnoreLocaleAsLastResort if this function can't find the most applicable subtype,
3010     * it will return the first subtype matched with mode
3011     * @return the most applicable subtypeId
3012     */
3013    private static InputMethodSubtype findLastResortApplicableSubtypeLocked(
3014            Resources res, List<InputMethodSubtype> subtypes, String mode, String locale,
3015            boolean canIgnoreLocaleAsLastResort) {
3016        if (subtypes == null || subtypes.size() == 0) {
3017            return null;
3018        }
3019        if (TextUtils.isEmpty(locale)) {
3020            locale = res.getConfiguration().locale.toString();
3021        }
3022        final String language = locale.substring(0, 2);
3023        boolean partialMatchFound = false;
3024        InputMethodSubtype applicableSubtype = null;
3025        InputMethodSubtype firstMatchedModeSubtype = null;
3026        final int N = subtypes.size();
3027        for (int i = 0; i < N; ++i) {
3028            InputMethodSubtype subtype = subtypes.get(i);
3029            final String subtypeLocale = subtype.getLocale();
3030            // An applicable subtype should match "mode". If mode is null, mode will be ignored,
3031            // and all subtypes with all modes can be candidates.
3032            if (mode == null || subtypes.get(i).getMode().equalsIgnoreCase(mode)) {
3033                if (firstMatchedModeSubtype == null) {
3034                    firstMatchedModeSubtype = subtype;
3035                }
3036                if (locale.equals(subtypeLocale)) {
3037                    // Exact match (e.g. system locale is "en_US" and subtype locale is "en_US")
3038                    applicableSubtype = subtype;
3039                    break;
3040                } else if (!partialMatchFound && subtypeLocale.startsWith(language)) {
3041                    // Partial match (e.g. system locale is "en_US" and subtype locale is "en")
3042                    applicableSubtype = subtype;
3043                    partialMatchFound = true;
3044                }
3045            }
3046        }
3047
3048        if (applicableSubtype == null && canIgnoreLocaleAsLastResort) {
3049            return firstMatchedModeSubtype;
3050        }
3051
3052        // The first subtype applicable to the system locale will be defined as the most applicable
3053        // subtype.
3054        if (DEBUG) {
3055            if (applicableSubtype != null) {
3056                Slog.d(TAG, "Applicable InputMethodSubtype was found: "
3057                        + applicableSubtype.getMode() + "," + applicableSubtype.getLocale());
3058            }
3059        }
3060        return applicableSubtype;
3061    }
3062
3063    // If there are no selected shortcuts, tries finding the most applicable ones.
3064    private Pair<InputMethodInfo, InputMethodSubtype>
3065            findLastResortApplicableShortcutInputMethodAndSubtypeLocked(String mode) {
3066        List<InputMethodInfo> imis = mSettings.getEnabledInputMethodListLocked();
3067        InputMethodInfo mostApplicableIMI = null;
3068        InputMethodSubtype mostApplicableSubtype = null;
3069        boolean foundInSystemIME = false;
3070
3071        // Search applicable subtype for each InputMethodInfo
3072        for (InputMethodInfo imi: imis) {
3073            final String imiId = imi.getId();
3074            if (foundInSystemIME && !imiId.equals(mCurMethodId)) {
3075                continue;
3076            }
3077            InputMethodSubtype subtype = null;
3078            final List<InputMethodSubtype> enabledSubtypes =
3079                    getEnabledInputMethodSubtypeListLocked(imi, true);
3080            // 1. Search by the current subtype's locale from enabledSubtypes.
3081            if (mCurrentSubtype != null) {
3082                subtype = findLastResortApplicableSubtypeLocked(
3083                        mRes, enabledSubtypes, mode, mCurrentSubtype.getLocale(), false);
3084            }
3085            // 2. Search by the system locale from enabledSubtypes.
3086            // 3. Search the first enabled subtype matched with mode from enabledSubtypes.
3087            if (subtype == null) {
3088                subtype = findLastResortApplicableSubtypeLocked(
3089                        mRes, enabledSubtypes, mode, null, true);
3090            }
3091            final ArrayList<InputMethodSubtype> overridingImplicitlyEnabledSubtypes =
3092                    getOverridingImplicitlyEnabledSubtypes(imi, mode);
3093            final ArrayList<InputMethodSubtype> subtypesForSearch =
3094                    overridingImplicitlyEnabledSubtypes.isEmpty()
3095                            ? getSubtypes(imi) : overridingImplicitlyEnabledSubtypes;
3096            // 4. Search by the current subtype's locale from all subtypes.
3097            if (subtype == null && mCurrentSubtype != null) {
3098                subtype = findLastResortApplicableSubtypeLocked(
3099                        mRes, subtypesForSearch, mode, mCurrentSubtype.getLocale(), false);
3100            }
3101            // 5. Search by the system locale from all subtypes.
3102            // 6. Search the first enabled subtype matched with mode from all subtypes.
3103            if (subtype == null) {
3104                subtype = findLastResortApplicableSubtypeLocked(
3105                        mRes, subtypesForSearch, mode, null, true);
3106            }
3107            if (subtype != null) {
3108                if (imiId.equals(mCurMethodId)) {
3109                    // The current input method is the most applicable IME.
3110                    mostApplicableIMI = imi;
3111                    mostApplicableSubtype = subtype;
3112                    break;
3113                } else if (!foundInSystemIME) {
3114                    // The system input method is 2nd applicable IME.
3115                    mostApplicableIMI = imi;
3116                    mostApplicableSubtype = subtype;
3117                    if ((imi.getServiceInfo().applicationInfo.flags
3118                            & ApplicationInfo.FLAG_SYSTEM) != 0) {
3119                        foundInSystemIME = true;
3120                    }
3121                }
3122            }
3123        }
3124        if (DEBUG) {
3125            if (mostApplicableIMI != null) {
3126                Slog.w(TAG, "Most applicable shortcut input method was:"
3127                        + mostApplicableIMI.getId());
3128                if (mostApplicableSubtype != null) {
3129                    Slog.w(TAG, "Most applicable shortcut input method subtype was:"
3130                            + "," + mostApplicableSubtype.getMode() + ","
3131                            + mostApplicableSubtype.getLocale());
3132                }
3133            }
3134        }
3135        if (mostApplicableIMI != null) {
3136            return new Pair<InputMethodInfo, InputMethodSubtype> (mostApplicableIMI,
3137                    mostApplicableSubtype);
3138        } else {
3139            return null;
3140        }
3141    }
3142
3143    /**
3144     * @return Return the current subtype of this input method.
3145     */
3146    @Override
3147    public InputMethodSubtype getCurrentInputMethodSubtype() {
3148        // TODO: Make this work even for non-current users?
3149        if (!calledFromValidUser()) {
3150            return null;
3151        }
3152        synchronized (mMethodMap) {
3153            return getCurrentInputMethodSubtypeLocked();
3154        }
3155    }
3156
3157    private InputMethodSubtype getCurrentInputMethodSubtypeLocked() {
3158        if (mCurMethodId == null) {
3159            return null;
3160        }
3161        final boolean subtypeIsSelected =
3162                mSettings.getSelectedInputMethodSubtypeHashCode() != NOT_A_SUBTYPE_ID;
3163        final InputMethodInfo imi = mMethodMap.get(mCurMethodId);
3164        if (imi == null || imi.getSubtypeCount() == 0) {
3165            return null;
3166        }
3167        if (!subtypeIsSelected || mCurrentSubtype == null
3168                || !isValidSubtypeId(imi, mCurrentSubtype.hashCode())) {
3169            int subtypeId = getSelectedInputMethodSubtypeId(mCurMethodId);
3170            if (subtypeId == NOT_A_SUBTYPE_ID) {
3171                // If there are no selected subtypes, the framework will try to find
3172                // the most applicable subtype from explicitly or implicitly enabled
3173                // subtypes.
3174                List<InputMethodSubtype> explicitlyOrImplicitlyEnabledSubtypes =
3175                        getEnabledInputMethodSubtypeListLocked(imi, true);
3176                // If there is only one explicitly or implicitly enabled subtype,
3177                // just returns it.
3178                if (explicitlyOrImplicitlyEnabledSubtypes.size() == 1) {
3179                    mCurrentSubtype = explicitlyOrImplicitlyEnabledSubtypes.get(0);
3180                } else if (explicitlyOrImplicitlyEnabledSubtypes.size() > 1) {
3181                    mCurrentSubtype = findLastResortApplicableSubtypeLocked(
3182                            mRes, explicitlyOrImplicitlyEnabledSubtypes,
3183                            SUBTYPE_MODE_KEYBOARD, null, true);
3184                    if (mCurrentSubtype == null) {
3185                        mCurrentSubtype = findLastResortApplicableSubtypeLocked(
3186                                mRes, explicitlyOrImplicitlyEnabledSubtypes, null, null,
3187                                true);
3188                    }
3189                }
3190            } else {
3191                mCurrentSubtype = getSubtypes(imi).get(subtypeId);
3192            }
3193        }
3194        return mCurrentSubtype;
3195    }
3196
3197    private void addShortcutInputMethodAndSubtypes(InputMethodInfo imi,
3198            InputMethodSubtype subtype) {
3199        if (mShortcutInputMethodsAndSubtypes.containsKey(imi)) {
3200            mShortcutInputMethodsAndSubtypes.get(imi).add(subtype);
3201        } else {
3202            ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
3203            subtypes.add(subtype);
3204            mShortcutInputMethodsAndSubtypes.put(imi, subtypes);
3205        }
3206    }
3207
3208    // TODO: We should change the return type from List to List<Parcelable>
3209    @SuppressWarnings("rawtypes")
3210    @Override
3211    public List getShortcutInputMethodsAndSubtypes() {
3212        synchronized (mMethodMap) {
3213            ArrayList<Object> ret = new ArrayList<Object>();
3214            if (mShortcutInputMethodsAndSubtypes.size() == 0) {
3215                // If there are no selected shortcut subtypes, the framework will try to find
3216                // the most applicable subtype from all subtypes whose mode is
3217                // SUBTYPE_MODE_VOICE. This is an exceptional case, so we will hardcode the mode.
3218                Pair<InputMethodInfo, InputMethodSubtype> info =
3219                    findLastResortApplicableShortcutInputMethodAndSubtypeLocked(
3220                            SUBTYPE_MODE_VOICE);
3221                if (info != null) {
3222                    ret.add(info.first);
3223                    ret.add(info.second);
3224                }
3225                return ret;
3226            }
3227            for (InputMethodInfo imi: mShortcutInputMethodsAndSubtypes.keySet()) {
3228                ret.add(imi);
3229                for (InputMethodSubtype subtype: mShortcutInputMethodsAndSubtypes.get(imi)) {
3230                    ret.add(subtype);
3231                }
3232            }
3233            return ret;
3234        }
3235    }
3236
3237    @Override
3238    public boolean setCurrentInputMethodSubtype(InputMethodSubtype subtype) {
3239        // TODO: Make this work even for non-current users?
3240        if (!calledFromValidUser()) {
3241            return false;
3242        }
3243        synchronized (mMethodMap) {
3244            if (subtype != null && mCurMethodId != null) {
3245                InputMethodInfo imi = mMethodMap.get(mCurMethodId);
3246                int subtypeId = getSubtypeIdFromHashCode(imi, subtype.hashCode());
3247                if (subtypeId != NOT_A_SUBTYPE_ID) {
3248                    setInputMethodLocked(mCurMethodId, subtypeId);
3249                    return true;
3250                }
3251            }
3252            return false;
3253        }
3254    }
3255
3256    private static class InputMethodAndSubtypeListManager {
3257        private final Context mContext;
3258        // Used to load label
3259        private final PackageManager mPm;
3260        private final InputMethodManagerService mImms;
3261        private final String mSystemLocaleStr;
3262        public InputMethodAndSubtypeListManager(Context context, InputMethodManagerService imms) {
3263            mContext = context;
3264            mPm = context.getPackageManager();
3265            mImms = imms;
3266            final Locale locale = context.getResources().getConfiguration().locale;
3267            mSystemLocaleStr = locale != null ? locale.toString() : "";
3268        }
3269
3270        private final TreeMap<InputMethodInfo, List<InputMethodSubtype>> mSortedImmis =
3271                new TreeMap<InputMethodInfo, List<InputMethodSubtype>>(
3272                        new Comparator<InputMethodInfo>() {
3273                            @Override
3274                            public int compare(InputMethodInfo imi1, InputMethodInfo imi2) {
3275                                if (imi2 == null) return 0;
3276                                if (imi1 == null) return 1;
3277                                if (mPm == null) {
3278                                    return imi1.getId().compareTo(imi2.getId());
3279                                }
3280                                CharSequence imiId1 = imi1.loadLabel(mPm) + "/" + imi1.getId();
3281                                CharSequence imiId2 = imi2.loadLabel(mPm) + "/" + imi2.getId();
3282                                return imiId1.toString().compareTo(imiId2.toString());
3283                            }
3284                        });
3285
3286        public ImeSubtypeListItem getNextInputMethod(
3287                boolean onlyCurrentIme, InputMethodInfo imi, InputMethodSubtype subtype) {
3288            if (imi == null) {
3289                return null;
3290            }
3291            final List<ImeSubtypeListItem> imList = getSortedInputMethodAndSubtypeList();
3292            if (imList.size() <= 1) {
3293                return null;
3294            }
3295            final int N = imList.size();
3296            final int currentSubtypeId = subtype != null
3297                    ? getSubtypeIdFromHashCode(imi, subtype.hashCode())
3298                    : NOT_A_SUBTYPE_ID;
3299            for (int i = 0; i < N; ++i) {
3300                final ImeSubtypeListItem isli = imList.get(i);
3301                if (isli.mImi.equals(imi) && isli.mSubtypeId == currentSubtypeId) {
3302                    if (!onlyCurrentIme) {
3303                        return imList.get((i + 1) % N);
3304                    }
3305                    for (int j = 0; j < N - 1; ++j) {
3306                        final ImeSubtypeListItem candidate = imList.get((i + j + 1) % N);
3307                        if (candidate.mImi.equals(imi)) {
3308                            return candidate;
3309                        }
3310                    }
3311                    return null;
3312                }
3313            }
3314            return null;
3315        }
3316
3317        public List<ImeSubtypeListItem> getSortedInputMethodAndSubtypeList() {
3318            return getSortedInputMethodAndSubtypeList(true, false, false);
3319        }
3320
3321        public List<ImeSubtypeListItem> getSortedInputMethodAndSubtypeList(boolean showSubtypes,
3322                boolean inputShown, boolean isScreenLocked) {
3323            final ArrayList<ImeSubtypeListItem> imList = new ArrayList<ImeSubtypeListItem>();
3324            final HashMap<InputMethodInfo, List<InputMethodSubtype>> immis =
3325                    mImms.getExplicitlyOrImplicitlyEnabledInputMethodsAndSubtypeListLocked();
3326            if (immis == null || immis.size() == 0) {
3327                return Collections.emptyList();
3328            }
3329            mSortedImmis.clear();
3330            mSortedImmis.putAll(immis);
3331            for (InputMethodInfo imi : mSortedImmis.keySet()) {
3332                if (imi == null) continue;
3333                List<InputMethodSubtype> explicitlyOrImplicitlyEnabledSubtypeList = immis.get(imi);
3334                HashSet<String> enabledSubtypeSet = new HashSet<String>();
3335                for (InputMethodSubtype subtype: explicitlyOrImplicitlyEnabledSubtypeList) {
3336                    enabledSubtypeSet.add(String.valueOf(subtype.hashCode()));
3337                }
3338                ArrayList<InputMethodSubtype> subtypes = getSubtypes(imi);
3339                final CharSequence imeLabel = imi.loadLabel(mPm);
3340                if (showSubtypes && enabledSubtypeSet.size() > 0) {
3341                    final int subtypeCount = imi.getSubtypeCount();
3342                    if (DEBUG) {
3343                        Slog.v(TAG, "Add subtypes: " + subtypeCount + ", " + imi.getId());
3344                    }
3345                    for (int j = 0; j < subtypeCount; ++j) {
3346                        final InputMethodSubtype subtype = imi.getSubtypeAt(j);
3347                        final String subtypeHashCode = String.valueOf(subtype.hashCode());
3348                        // We show all enabled IMEs and subtypes when an IME is shown.
3349                        if (enabledSubtypeSet.contains(subtypeHashCode)
3350                                && ((inputShown && !isScreenLocked) || !subtype.isAuxiliary())) {
3351                            final CharSequence subtypeLabel =
3352                                    subtype.overridesImplicitlyEnabledSubtype() ? null
3353                                            : subtype.getDisplayName(mContext, imi.getPackageName(),
3354                                                    imi.getServiceInfo().applicationInfo);
3355                            imList.add(new ImeSubtypeListItem(imeLabel, subtypeLabel, imi, j,
3356                                    subtype.getLocale(), mSystemLocaleStr));
3357
3358                            // Removing this subtype from enabledSubtypeSet because we no longer
3359                            // need to add an entry of this subtype to imList to avoid duplicated
3360                            // entries.
3361                            enabledSubtypeSet.remove(subtypeHashCode);
3362                        }
3363                    }
3364                } else {
3365                    imList.add(new ImeSubtypeListItem(imeLabel, null, imi, NOT_A_SUBTYPE_ID,
3366                            null, mSystemLocaleStr));
3367                }
3368            }
3369            Collections.sort(imList);
3370            return imList;
3371        }
3372    }
3373
3374    /**
3375     * Utility class for putting and getting settings for InputMethod
3376     * TODO: Move all putters and getters of settings to this class.
3377     */
3378    private static class InputMethodSettings {
3379        // The string for enabled input method is saved as follows:
3380        // example: ("ime0;subtype0;subtype1;subtype2:ime1:ime2;subtype0")
3381        private static final char INPUT_METHOD_SEPARATER = ':';
3382        private static final char INPUT_METHOD_SUBTYPE_SEPARATER = ';';
3383        private final TextUtils.SimpleStringSplitter mInputMethodSplitter =
3384                new TextUtils.SimpleStringSplitter(INPUT_METHOD_SEPARATER);
3385
3386        private final TextUtils.SimpleStringSplitter mSubtypeSplitter =
3387                new TextUtils.SimpleStringSplitter(INPUT_METHOD_SUBTYPE_SEPARATER);
3388
3389        private final Resources mRes;
3390        private final ContentResolver mResolver;
3391        private final HashMap<String, InputMethodInfo> mMethodMap;
3392        private final ArrayList<InputMethodInfo> mMethodList;
3393
3394        private String mEnabledInputMethodsStrCache;
3395        private int mCurrentUserId;
3396
3397        private static void buildEnabledInputMethodsSettingString(
3398                StringBuilder builder, Pair<String, ArrayList<String>> pair) {
3399            String id = pair.first;
3400            ArrayList<String> subtypes = pair.second;
3401            builder.append(id);
3402            // Inputmethod and subtypes are saved in the settings as follows:
3403            // ime0;subtype0;subtype1:ime1;subtype0:ime2:ime3;subtype0;subtype1
3404            for (String subtypeId: subtypes) {
3405                builder.append(INPUT_METHOD_SUBTYPE_SEPARATER).append(subtypeId);
3406            }
3407        }
3408
3409        public InputMethodSettings(
3410                Resources res, ContentResolver resolver,
3411                HashMap<String, InputMethodInfo> methodMap, ArrayList<InputMethodInfo> methodList,
3412                int userId) {
3413            setCurrentUserId(userId);
3414            mRes = res;
3415            mResolver = resolver;
3416            mMethodMap = methodMap;
3417            mMethodList = methodList;
3418        }
3419
3420        public void setCurrentUserId(int userId) {
3421            if (DEBUG) {
3422                Slog.d(TAG, "--- Swtich the current user from " + mCurrentUserId + " to "
3423                        + userId + ", new ime = " + getSelectedInputMethod());
3424            }
3425            // IMMS settings are kept per user, so keep track of current user
3426            mCurrentUserId = userId;
3427        }
3428
3429        public List<InputMethodInfo> getEnabledInputMethodListLocked() {
3430            return createEnabledInputMethodListLocked(
3431                    getEnabledInputMethodsAndSubtypeListLocked());
3432        }
3433
3434        public List<Pair<InputMethodInfo, ArrayList<String>>>
3435                getEnabledInputMethodAndSubtypeHashCodeListLocked() {
3436            return createEnabledInputMethodAndSubtypeHashCodeListLocked(
3437                    getEnabledInputMethodsAndSubtypeListLocked());
3438        }
3439
3440        public List<InputMethodSubtype> getEnabledInputMethodSubtypeListLocked(
3441                InputMethodInfo imi) {
3442            List<Pair<String, ArrayList<String>>> imsList =
3443                    getEnabledInputMethodsAndSubtypeListLocked();
3444            ArrayList<InputMethodSubtype> enabledSubtypes =
3445                    new ArrayList<InputMethodSubtype>();
3446            if (imi != null) {
3447                for (Pair<String, ArrayList<String>> imsPair : imsList) {
3448                    InputMethodInfo info = mMethodMap.get(imsPair.first);
3449                    if (info != null && info.getId().equals(imi.getId())) {
3450                        final int subtypeCount = info.getSubtypeCount();
3451                        for (int i = 0; i < subtypeCount; ++i) {
3452                            InputMethodSubtype ims = info.getSubtypeAt(i);
3453                            for (String s: imsPair.second) {
3454                                if (String.valueOf(ims.hashCode()).equals(s)) {
3455                                    enabledSubtypes.add(ims);
3456                                }
3457                            }
3458                        }
3459                        break;
3460                    }
3461                }
3462            }
3463            return enabledSubtypes;
3464        }
3465
3466        // At the initial boot, the settings for input methods are not set,
3467        // so we need to enable IME in that case.
3468        public void enableAllIMEsIfThereIsNoEnabledIME() {
3469            if (TextUtils.isEmpty(getEnabledInputMethodsStr())) {
3470                StringBuilder sb = new StringBuilder();
3471                final int N = mMethodList.size();
3472                for (int i = 0; i < N; i++) {
3473                    InputMethodInfo imi = mMethodList.get(i);
3474                    Slog.i(TAG, "Adding: " + imi.getId());
3475                    if (i > 0) sb.append(':');
3476                    sb.append(imi.getId());
3477                }
3478                putEnabledInputMethodsStr(sb.toString());
3479            }
3480        }
3481
3482        private List<Pair<String, ArrayList<String>>> getEnabledInputMethodsAndSubtypeListLocked() {
3483            ArrayList<Pair<String, ArrayList<String>>> imsList
3484                    = new ArrayList<Pair<String, ArrayList<String>>>();
3485            final String enabledInputMethodsStr = getEnabledInputMethodsStr();
3486            if (TextUtils.isEmpty(enabledInputMethodsStr)) {
3487                return imsList;
3488            }
3489            mInputMethodSplitter.setString(enabledInputMethodsStr);
3490            while (mInputMethodSplitter.hasNext()) {
3491                String nextImsStr = mInputMethodSplitter.next();
3492                mSubtypeSplitter.setString(nextImsStr);
3493                if (mSubtypeSplitter.hasNext()) {
3494                    ArrayList<String> subtypeHashes = new ArrayList<String>();
3495                    // The first element is ime id.
3496                    String imeId = mSubtypeSplitter.next();
3497                    while (mSubtypeSplitter.hasNext()) {
3498                        subtypeHashes.add(mSubtypeSplitter.next());
3499                    }
3500                    imsList.add(new Pair<String, ArrayList<String>>(imeId, subtypeHashes));
3501                }
3502            }
3503            return imsList;
3504        }
3505
3506        public void appendAndPutEnabledInputMethodLocked(String id, boolean reloadInputMethodStr) {
3507            if (reloadInputMethodStr) {
3508                getEnabledInputMethodsStr();
3509            }
3510            if (TextUtils.isEmpty(mEnabledInputMethodsStrCache)) {
3511                // Add in the newly enabled input method.
3512                putEnabledInputMethodsStr(id);
3513            } else {
3514                putEnabledInputMethodsStr(
3515                        mEnabledInputMethodsStrCache + INPUT_METHOD_SEPARATER + id);
3516            }
3517        }
3518
3519        /**
3520         * Build and put a string of EnabledInputMethods with removing specified Id.
3521         * @return the specified id was removed or not.
3522         */
3523        public boolean buildAndPutEnabledInputMethodsStrRemovingIdLocked(
3524                StringBuilder builder, List<Pair<String, ArrayList<String>>> imsList, String id) {
3525            boolean isRemoved = false;
3526            boolean needsAppendSeparator = false;
3527            for (Pair<String, ArrayList<String>> ims: imsList) {
3528                String curId = ims.first;
3529                if (curId.equals(id)) {
3530                    // We are disabling this input method, and it is
3531                    // currently enabled.  Skip it to remove from the
3532                    // new list.
3533                    isRemoved = true;
3534                } else {
3535                    if (needsAppendSeparator) {
3536                        builder.append(INPUT_METHOD_SEPARATER);
3537                    } else {
3538                        needsAppendSeparator = true;
3539                    }
3540                    buildEnabledInputMethodsSettingString(builder, ims);
3541                }
3542            }
3543            if (isRemoved) {
3544                // Update the setting with the new list of input methods.
3545                putEnabledInputMethodsStr(builder.toString());
3546            }
3547            return isRemoved;
3548        }
3549
3550        private List<InputMethodInfo> createEnabledInputMethodListLocked(
3551                List<Pair<String, ArrayList<String>>> imsList) {
3552            final ArrayList<InputMethodInfo> res = new ArrayList<InputMethodInfo>();
3553            for (Pair<String, ArrayList<String>> ims: imsList) {
3554                InputMethodInfo info = mMethodMap.get(ims.first);
3555                if (info != null) {
3556                    res.add(info);
3557                }
3558            }
3559            return res;
3560        }
3561
3562        private List<Pair<InputMethodInfo, ArrayList<String>>>
3563                createEnabledInputMethodAndSubtypeHashCodeListLocked(
3564                        List<Pair<String, ArrayList<String>>> imsList) {
3565            final ArrayList<Pair<InputMethodInfo, ArrayList<String>>> res
3566                    = new ArrayList<Pair<InputMethodInfo, ArrayList<String>>>();
3567            for (Pair<String, ArrayList<String>> ims : imsList) {
3568                InputMethodInfo info = mMethodMap.get(ims.first);
3569                if (info != null) {
3570                    res.add(new Pair<InputMethodInfo, ArrayList<String>>(info, ims.second));
3571                }
3572            }
3573            return res;
3574        }
3575
3576        private void putEnabledInputMethodsStr(String str) {
3577            Settings.Secure.putStringForUser(
3578                    mResolver, Settings.Secure.ENABLED_INPUT_METHODS, str, mCurrentUserId);
3579            mEnabledInputMethodsStrCache = str;
3580            if (DEBUG) {
3581                Slog.d(TAG, "putEnabledInputMethodStr: " + str);
3582            }
3583        }
3584
3585        private String getEnabledInputMethodsStr() {
3586            mEnabledInputMethodsStrCache = Settings.Secure.getStringForUser(
3587                    mResolver, Settings.Secure.ENABLED_INPUT_METHODS, mCurrentUserId);
3588            if (DEBUG) {
3589                Slog.d(TAG, "getEnabledInputMethodsStr: " + mEnabledInputMethodsStrCache
3590                        + ", " + mCurrentUserId);
3591            }
3592            return mEnabledInputMethodsStrCache;
3593        }
3594
3595        private void saveSubtypeHistory(
3596                List<Pair<String, String>> savedImes, String newImeId, String newSubtypeId) {
3597            StringBuilder builder = new StringBuilder();
3598            boolean isImeAdded = false;
3599            if (!TextUtils.isEmpty(newImeId) && !TextUtils.isEmpty(newSubtypeId)) {
3600                builder.append(newImeId).append(INPUT_METHOD_SUBTYPE_SEPARATER).append(
3601                        newSubtypeId);
3602                isImeAdded = true;
3603            }
3604            for (Pair<String, String> ime: savedImes) {
3605                String imeId = ime.first;
3606                String subtypeId = ime.second;
3607                if (TextUtils.isEmpty(subtypeId)) {
3608                    subtypeId = NOT_A_SUBTYPE_ID_STR;
3609                }
3610                if (isImeAdded) {
3611                    builder.append(INPUT_METHOD_SEPARATER);
3612                } else {
3613                    isImeAdded = true;
3614                }
3615                builder.append(imeId).append(INPUT_METHOD_SUBTYPE_SEPARATER).append(
3616                        subtypeId);
3617            }
3618            // Remove the last INPUT_METHOD_SEPARATER
3619            putSubtypeHistoryStr(builder.toString());
3620        }
3621
3622        public void addSubtypeToHistory(String imeId, String subtypeId) {
3623            List<Pair<String, String>> subtypeHistory = loadInputMethodAndSubtypeHistoryLocked();
3624            for (Pair<String, String> ime: subtypeHistory) {
3625                if (ime.first.equals(imeId)) {
3626                    if (DEBUG) {
3627                        Slog.v(TAG, "Subtype found in the history: " + imeId + ", "
3628                                + ime.second);
3629                    }
3630                    // We should break here
3631                    subtypeHistory.remove(ime);
3632                    break;
3633                }
3634            }
3635            if (DEBUG) {
3636                Slog.v(TAG, "Add subtype to the history: " + imeId + ", " + subtypeId);
3637            }
3638            saveSubtypeHistory(subtypeHistory, imeId, subtypeId);
3639        }
3640
3641        private void putSubtypeHistoryStr(String str) {
3642            if (DEBUG) {
3643                Slog.d(TAG, "putSubtypeHistoryStr: " + str);
3644            }
3645            Settings.Secure.putStringForUser(
3646                    mResolver, Settings.Secure.INPUT_METHODS_SUBTYPE_HISTORY, str, mCurrentUserId);
3647        }
3648
3649        public Pair<String, String> getLastInputMethodAndSubtypeLocked() {
3650            // Gets the first one from the history
3651            return getLastSubtypeForInputMethodLockedInternal(null);
3652        }
3653
3654        public String getLastSubtypeForInputMethodLocked(String imeId) {
3655            Pair<String, String> ime = getLastSubtypeForInputMethodLockedInternal(imeId);
3656            if (ime != null) {
3657                return ime.second;
3658            } else {
3659                return null;
3660            }
3661        }
3662
3663        private Pair<String, String> getLastSubtypeForInputMethodLockedInternal(String imeId) {
3664            List<Pair<String, ArrayList<String>>> enabledImes =
3665                    getEnabledInputMethodsAndSubtypeListLocked();
3666            List<Pair<String, String>> subtypeHistory = loadInputMethodAndSubtypeHistoryLocked();
3667            for (Pair<String, String> imeAndSubtype : subtypeHistory) {
3668                final String imeInTheHistory = imeAndSubtype.first;
3669                // If imeId is empty, returns the first IME and subtype in the history
3670                if (TextUtils.isEmpty(imeId) || imeInTheHistory.equals(imeId)) {
3671                    final String subtypeInTheHistory = imeAndSubtype.second;
3672                    final String subtypeHashCode =
3673                            getEnabledSubtypeHashCodeForInputMethodAndSubtypeLocked(
3674                                    enabledImes, imeInTheHistory, subtypeInTheHistory);
3675                    if (!TextUtils.isEmpty(subtypeHashCode)) {
3676                        if (DEBUG) {
3677                            Slog.d(TAG, "Enabled subtype found in the history: " + subtypeHashCode);
3678                        }
3679                        return new Pair<String, String>(imeInTheHistory, subtypeHashCode);
3680                    }
3681                }
3682            }
3683            if (DEBUG) {
3684                Slog.d(TAG, "No enabled IME found in the history");
3685            }
3686            return null;
3687        }
3688
3689        private String getEnabledSubtypeHashCodeForInputMethodAndSubtypeLocked(List<Pair<String,
3690                ArrayList<String>>> enabledImes, String imeId, String subtypeHashCode) {
3691            for (Pair<String, ArrayList<String>> enabledIme: enabledImes) {
3692                if (enabledIme.first.equals(imeId)) {
3693                    final ArrayList<String> explicitlyEnabledSubtypes = enabledIme.second;
3694                    final InputMethodInfo imi = mMethodMap.get(imeId);
3695                    if (explicitlyEnabledSubtypes.size() == 0) {
3696                        // If there are no explicitly enabled subtypes, applicable subtypes are
3697                        // enabled implicitly.
3698                        // If IME is enabled and no subtypes are enabled, applicable subtypes
3699                        // are enabled implicitly, so needs to treat them to be enabled.
3700                        if (imi != null && imi.getSubtypeCount() > 0) {
3701                            List<InputMethodSubtype> implicitlySelectedSubtypes =
3702                                    getImplicitlyApplicableSubtypesLocked(mRes, imi);
3703                            if (implicitlySelectedSubtypes != null) {
3704                                final int N = implicitlySelectedSubtypes.size();
3705                                for (int i = 0; i < N; ++i) {
3706                                    final InputMethodSubtype st = implicitlySelectedSubtypes.get(i);
3707                                    if (String.valueOf(st.hashCode()).equals(subtypeHashCode)) {
3708                                        return subtypeHashCode;
3709                                    }
3710                                }
3711                            }
3712                        }
3713                    } else {
3714                        for (String s: explicitlyEnabledSubtypes) {
3715                            if (s.equals(subtypeHashCode)) {
3716                                // If both imeId and subtypeId are enabled, return subtypeId.
3717                                try {
3718                                    final int hashCode = Integer.valueOf(subtypeHashCode);
3719                                    // Check whether the subtype id is valid or not
3720                                    if (isValidSubtypeId(imi, hashCode)) {
3721                                        return s;
3722                                    } else {
3723                                        return NOT_A_SUBTYPE_ID_STR;
3724                                    }
3725                                } catch (NumberFormatException e) {
3726                                    return NOT_A_SUBTYPE_ID_STR;
3727                                }
3728                            }
3729                        }
3730                    }
3731                    // If imeId was enabled but subtypeId was disabled.
3732                    return NOT_A_SUBTYPE_ID_STR;
3733                }
3734            }
3735            // If both imeId and subtypeId are disabled, return null
3736            return null;
3737        }
3738
3739        private List<Pair<String, String>> loadInputMethodAndSubtypeHistoryLocked() {
3740            ArrayList<Pair<String, String>> imsList = new ArrayList<Pair<String, String>>();
3741            final String subtypeHistoryStr = getSubtypeHistoryStr();
3742            if (TextUtils.isEmpty(subtypeHistoryStr)) {
3743                return imsList;
3744            }
3745            mInputMethodSplitter.setString(subtypeHistoryStr);
3746            while (mInputMethodSplitter.hasNext()) {
3747                String nextImsStr = mInputMethodSplitter.next();
3748                mSubtypeSplitter.setString(nextImsStr);
3749                if (mSubtypeSplitter.hasNext()) {
3750                    String subtypeId = NOT_A_SUBTYPE_ID_STR;
3751                    // The first element is ime id.
3752                    String imeId = mSubtypeSplitter.next();
3753                    while (mSubtypeSplitter.hasNext()) {
3754                        subtypeId = mSubtypeSplitter.next();
3755                        break;
3756                    }
3757                    imsList.add(new Pair<String, String>(imeId, subtypeId));
3758                }
3759            }
3760            return imsList;
3761        }
3762
3763        private String getSubtypeHistoryStr() {
3764            if (DEBUG) {
3765                Slog.d(TAG, "getSubtypeHistoryStr: " + Settings.Secure.getStringForUser(
3766                        mResolver, Settings.Secure.INPUT_METHODS_SUBTYPE_HISTORY, mCurrentUserId));
3767            }
3768            return Settings.Secure.getStringForUser(
3769                    mResolver, Settings.Secure.INPUT_METHODS_SUBTYPE_HISTORY, mCurrentUserId);
3770        }
3771
3772        public void putSelectedInputMethod(String imeId) {
3773            if (DEBUG) {
3774                Slog.d(TAG, "putSelectedInputMethodStr: " + imeId + ", "
3775                        + mCurrentUserId);
3776            }
3777            Settings.Secure.putStringForUser(
3778                    mResolver, Settings.Secure.DEFAULT_INPUT_METHOD, imeId, mCurrentUserId);
3779        }
3780
3781        public void putSelectedSubtype(int subtypeId) {
3782            if (DEBUG) {
3783                Slog.d(TAG, "putSelectedInputMethodSubtypeStr: " + subtypeId + ", "
3784                        + mCurrentUserId);
3785            }
3786            Settings.Secure.putIntForUser(mResolver, Settings.Secure.SELECTED_INPUT_METHOD_SUBTYPE,
3787                    subtypeId, mCurrentUserId);
3788        }
3789
3790        public String getDisabledSystemInputMethods() {
3791            return Settings.Secure.getStringForUser(
3792                    mResolver, Settings.Secure.DISABLED_SYSTEM_INPUT_METHODS, mCurrentUserId);
3793        }
3794
3795        public String getSelectedInputMethod() {
3796            if (DEBUG) {
3797                Slog.d(TAG, "getSelectedInputMethodStr: " + Settings.Secure.getStringForUser(
3798                        mResolver, Settings.Secure.DEFAULT_INPUT_METHOD, mCurrentUserId)
3799                        + ", " + mCurrentUserId);
3800            }
3801            return Settings.Secure.getStringForUser(
3802                    mResolver, Settings.Secure.DEFAULT_INPUT_METHOD, mCurrentUserId);
3803        }
3804
3805        public int getSelectedInputMethodSubtypeHashCode() {
3806            try {
3807                return Settings.Secure.getIntForUser(
3808                        mResolver, Settings.Secure.SELECTED_INPUT_METHOD_SUBTYPE, mCurrentUserId);
3809            } catch (SettingNotFoundException e) {
3810                return NOT_A_SUBTYPE_ID;
3811            }
3812        }
3813
3814        public int getCurrentUserId() {
3815            return mCurrentUserId;
3816        }
3817    }
3818
3819    private static class InputMethodFileManager {
3820        private static final String SYSTEM_PATH = "system";
3821        private static final String INPUT_METHOD_PATH = "inputmethod";
3822        private static final String ADDITIONAL_SUBTYPES_FILE_NAME = "subtypes.xml";
3823        private static final String NODE_SUBTYPES = "subtypes";
3824        private static final String NODE_SUBTYPE = "subtype";
3825        private static final String NODE_IMI = "imi";
3826        private static final String ATTR_ID = "id";
3827        private static final String ATTR_LABEL = "label";
3828        private static final String ATTR_ICON = "icon";
3829        private static final String ATTR_IME_SUBTYPE_LOCALE = "imeSubtypeLocale";
3830        private static final String ATTR_IME_SUBTYPE_MODE = "imeSubtypeMode";
3831        private static final String ATTR_IME_SUBTYPE_EXTRA_VALUE = "imeSubtypeExtraValue";
3832        private static final String ATTR_IS_AUXILIARY = "isAuxiliary";
3833        private final AtomicFile mAdditionalInputMethodSubtypeFile;
3834        private final HashMap<String, InputMethodInfo> mMethodMap;
3835        private final HashMap<String, List<InputMethodSubtype>> mAdditionalSubtypesMap =
3836                new HashMap<String, List<InputMethodSubtype>>();
3837        public InputMethodFileManager(HashMap<String, InputMethodInfo> methodMap) {
3838            if (methodMap == null) {
3839                throw new NullPointerException("methodMap is null");
3840            }
3841            mMethodMap = methodMap;
3842            final File systemDir = new File(Environment.getDataDirectory(), SYSTEM_PATH);
3843            final File inputMethodDir = new File(systemDir, INPUT_METHOD_PATH);
3844            if (!inputMethodDir.mkdirs()) {
3845                Slog.w(TAG, "Couldn't create dir.: " + inputMethodDir.getAbsolutePath());
3846            }
3847            final File subtypeFile = new File(inputMethodDir, ADDITIONAL_SUBTYPES_FILE_NAME);
3848            mAdditionalInputMethodSubtypeFile = new AtomicFile(subtypeFile);
3849            if (!subtypeFile.exists()) {
3850                // If "subtypes.xml" doesn't exist, create a blank file.
3851                writeAdditionalInputMethodSubtypes(
3852                        mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile, methodMap);
3853            } else {
3854                readAdditionalInputMethodSubtypes(
3855                        mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile);
3856            }
3857        }
3858
3859        private void deleteAllInputMethodSubtypes(String imiId) {
3860            synchronized (mMethodMap) {
3861                mAdditionalSubtypesMap.remove(imiId);
3862                writeAdditionalInputMethodSubtypes(
3863                        mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile, mMethodMap);
3864            }
3865        }
3866
3867        public void addInputMethodSubtypes(
3868                InputMethodInfo imi, InputMethodSubtype[] additionalSubtypes) {
3869            synchronized (mMethodMap) {
3870                final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>();
3871                final int N = additionalSubtypes.length;
3872                for (int i = 0; i < N; ++i) {
3873                    final InputMethodSubtype subtype = additionalSubtypes[i];
3874                    if (!subtypes.contains(subtype)) {
3875                        subtypes.add(subtype);
3876                    } else {
3877                        Slog.w(TAG, "Duplicated subtype definition found: "
3878                                + subtype.getLocale() + ", " + subtype.getMode());
3879                    }
3880                }
3881                mAdditionalSubtypesMap.put(imi.getId(), subtypes);
3882                writeAdditionalInputMethodSubtypes(
3883                        mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile, mMethodMap);
3884            }
3885        }
3886
3887        public HashMap<String, List<InputMethodSubtype>> getAllAdditionalInputMethodSubtypes() {
3888            synchronized (mMethodMap) {
3889                return mAdditionalSubtypesMap;
3890            }
3891        }
3892
3893        private static void writeAdditionalInputMethodSubtypes(
3894                HashMap<String, List<InputMethodSubtype>> allSubtypes, AtomicFile subtypesFile,
3895                HashMap<String, InputMethodInfo> methodMap) {
3896            // Safety net for the case that this function is called before methodMap is set.
3897            final boolean isSetMethodMap = methodMap != null && methodMap.size() > 0;
3898            FileOutputStream fos = null;
3899            try {
3900                fos = subtypesFile.startWrite();
3901                final XmlSerializer out = new FastXmlSerializer();
3902                out.setOutput(fos, "utf-8");
3903                out.startDocument(null, true);
3904                out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
3905                out.startTag(null, NODE_SUBTYPES);
3906                for (String imiId : allSubtypes.keySet()) {
3907                    if (isSetMethodMap && !methodMap.containsKey(imiId)) {
3908                        Slog.w(TAG, "IME uninstalled or not valid.: " + imiId);
3909                        continue;
3910                    }
3911                    out.startTag(null, NODE_IMI);
3912                    out.attribute(null, ATTR_ID, imiId);
3913                    final List<InputMethodSubtype> subtypesList = allSubtypes.get(imiId);
3914                    final int N = subtypesList.size();
3915                    for (int i = 0; i < N; ++i) {
3916                        final InputMethodSubtype subtype = subtypesList.get(i);
3917                        out.startTag(null, NODE_SUBTYPE);
3918                        out.attribute(null, ATTR_ICON, String.valueOf(subtype.getIconResId()));
3919                        out.attribute(null, ATTR_LABEL, String.valueOf(subtype.getNameResId()));
3920                        out.attribute(null, ATTR_IME_SUBTYPE_LOCALE, subtype.getLocale());
3921                        out.attribute(null, ATTR_IME_SUBTYPE_MODE, subtype.getMode());
3922                        out.attribute(null, ATTR_IME_SUBTYPE_EXTRA_VALUE, subtype.getExtraValue());
3923                        out.attribute(null, ATTR_IS_AUXILIARY,
3924                                String.valueOf(subtype.isAuxiliary() ? 1 : 0));
3925                        out.endTag(null, NODE_SUBTYPE);
3926                    }
3927                    out.endTag(null, NODE_IMI);
3928                }
3929                out.endTag(null, NODE_SUBTYPES);
3930                out.endDocument();
3931                subtypesFile.finishWrite(fos);
3932            } catch (java.io.IOException e) {
3933                Slog.w(TAG, "Error writing subtypes", e);
3934                if (fos != null) {
3935                    subtypesFile.failWrite(fos);
3936                }
3937            }
3938        }
3939
3940        private static void readAdditionalInputMethodSubtypes(
3941                HashMap<String, List<InputMethodSubtype>> allSubtypes, AtomicFile subtypesFile) {
3942            if (allSubtypes == null || subtypesFile == null) return;
3943            allSubtypes.clear();
3944            FileInputStream fis = null;
3945            try {
3946                fis = subtypesFile.openRead();
3947                final XmlPullParser parser = Xml.newPullParser();
3948                parser.setInput(fis, null);
3949                int type = parser.getEventType();
3950                // Skip parsing until START_TAG
3951                while ((type = parser.next()) != XmlPullParser.START_TAG
3952                        && type != XmlPullParser.END_DOCUMENT) {}
3953                String firstNodeName = parser.getName();
3954                if (!NODE_SUBTYPES.equals(firstNodeName)) {
3955                    throw new XmlPullParserException("Xml doesn't start with subtypes");
3956                }
3957                final int depth =parser.getDepth();
3958                String currentImiId = null;
3959                ArrayList<InputMethodSubtype> tempSubtypesArray = null;
3960                while (((type = parser.next()) != XmlPullParser.END_TAG
3961                        || parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
3962                    if (type != XmlPullParser.START_TAG)
3963                        continue;
3964                    final String nodeName = parser.getName();
3965                    if (NODE_IMI.equals(nodeName)) {
3966                        currentImiId = parser.getAttributeValue(null, ATTR_ID);
3967                        if (TextUtils.isEmpty(currentImiId)) {
3968                            Slog.w(TAG, "Invalid imi id found in subtypes.xml");
3969                            continue;
3970                        }
3971                        tempSubtypesArray = new ArrayList<InputMethodSubtype>();
3972                        allSubtypes.put(currentImiId, tempSubtypesArray);
3973                    } else if (NODE_SUBTYPE.equals(nodeName)) {
3974                        if (TextUtils.isEmpty(currentImiId) || tempSubtypesArray == null) {
3975                            Slog.w(TAG, "IME uninstalled or not valid.: " + currentImiId);
3976                            continue;
3977                        }
3978                        final int icon = Integer.valueOf(
3979                                parser.getAttributeValue(null, ATTR_ICON));
3980                        final int label = Integer.valueOf(
3981                                parser.getAttributeValue(null, ATTR_LABEL));
3982                        final String imeSubtypeLocale =
3983                                parser.getAttributeValue(null, ATTR_IME_SUBTYPE_LOCALE);
3984                        final String imeSubtypeMode =
3985                                parser.getAttributeValue(null, ATTR_IME_SUBTYPE_MODE);
3986                        final String imeSubtypeExtraValue =
3987                                parser.getAttributeValue(null, ATTR_IME_SUBTYPE_EXTRA_VALUE);
3988                        final boolean isAuxiliary = "1".equals(String.valueOf(
3989                                parser.getAttributeValue(null, ATTR_IS_AUXILIARY)));
3990                        final InputMethodSubtype subtype =
3991                                new InputMethodSubtype(label, icon, imeSubtypeLocale,
3992                                        imeSubtypeMode, imeSubtypeExtraValue, isAuxiliary);
3993                        tempSubtypesArray.add(subtype);
3994                    }
3995                }
3996            } catch (XmlPullParserException e) {
3997                Slog.w(TAG, "Error reading subtypes: " + e);
3998                return;
3999            } catch (java.io.IOException e) {
4000                Slog.w(TAG, "Error reading subtypes: " + e);
4001                return;
4002            } catch (NumberFormatException e) {
4003                Slog.w(TAG, "Error reading subtypes: " + e);
4004                return;
4005            } finally {
4006                if (fis != null) {
4007                    try {
4008                        fis.close();
4009                    } catch (java.io.IOException e1) {
4010                        Slog.w(TAG, "Failed to close.");
4011                    }
4012                }
4013            }
4014        }
4015    }
4016
4017    // ----------------------------------------------------------------------
4018    // Utilities for debug
4019    private static String getStackTrace() {
4020        final StringBuilder sb = new StringBuilder();
4021        try {
4022            throw new RuntimeException();
4023        } catch (RuntimeException e) {
4024            final StackTraceElement[] frames = e.getStackTrace();
4025            // Start at 1 because the first frame is here and we don't care about it
4026            for (int j = 1; j < frames.length; ++j) {
4027                sb.append(frames[j].toString() + "\n");
4028            }
4029        }
4030        return sb.toString();
4031    }
4032
4033    @Override
4034    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
4035        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
4036                != PackageManager.PERMISSION_GRANTED) {
4037
4038            pw.println("Permission Denial: can't dump InputMethodManager from from pid="
4039                    + Binder.getCallingPid()
4040                    + ", uid=" + Binder.getCallingUid());
4041            return;
4042        }
4043
4044        IInputMethod method;
4045        ClientState client;
4046
4047        final Printer p = new PrintWriterPrinter(pw);
4048
4049        synchronized (mMethodMap) {
4050            p.println("Current Input Method Manager state:");
4051            int N = mMethodList.size();
4052            p.println("  Input Methods:");
4053            for (int i=0; i<N; i++) {
4054                InputMethodInfo info = mMethodList.get(i);
4055                p.println("  InputMethod #" + i + ":");
4056                info.dump(p, "    ");
4057            }
4058            p.println("  Clients:");
4059            for (ClientState ci : mClients.values()) {
4060                p.println("  Client " + ci + ":");
4061                p.println("    client=" + ci.client);
4062                p.println("    inputContext=" + ci.inputContext);
4063                p.println("    sessionRequested=" + ci.sessionRequested);
4064                p.println("    curSession=" + ci.curSession);
4065            }
4066            p.println("  mCurMethodId=" + mCurMethodId);
4067            client = mCurClient;
4068            p.println("  mCurClient=" + client + " mCurSeq=" + mCurSeq);
4069            p.println("  mCurFocusedWindow=" + mCurFocusedWindow);
4070            p.println("  mCurId=" + mCurId + " mHaveConnect=" + mHaveConnection
4071                    + " mBoundToMethod=" + mBoundToMethod);
4072            p.println("  mCurToken=" + mCurToken);
4073            p.println("  mCurIntent=" + mCurIntent);
4074            method = mCurMethod;
4075            p.println("  mCurMethod=" + mCurMethod);
4076            p.println("  mEnabledSession=" + mEnabledSession);
4077            p.println("  mShowRequested=" + mShowRequested
4078                    + " mShowExplicitlyRequested=" + mShowExplicitlyRequested
4079                    + " mShowForced=" + mShowForced
4080                    + " mInputShown=" + mInputShown);
4081            p.println("  mSystemReady=" + mSystemReady + " mScreenOn=" + mScreenOn);
4082        }
4083
4084        p.println(" ");
4085        if (client != null) {
4086            pw.flush();
4087            try {
4088                client.client.asBinder().dump(fd, args);
4089            } catch (RemoteException e) {
4090                p.println("Input method client dead: " + e);
4091            }
4092        } else {
4093            p.println("No input method client.");
4094        }
4095
4096        p.println(" ");
4097        if (method != null) {
4098            pw.flush();
4099            try {
4100                method.asBinder().dump(fd, args);
4101            } catch (RemoteException e) {
4102                p.println("Input method service dead: " + e);
4103            }
4104        } else {
4105            p.println("No input method service.");
4106        }
4107    }
4108}
4109