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