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