InputMethodManagerService.java revision 06487a58be22b100daf3f950b9a1d25c3ea42aa2
1/*
2 * Copyright (C) 2006-2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License. You may obtain a copy of
6 * the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations under
14 * the License.
15 */
16
17package com.android.server;
18
19import com.android.internal.content.PackageMonitor;
20import com.android.internal.os.HandlerCaller;
21import com.android.internal.view.IInputContext;
22import com.android.internal.view.IInputMethod;
23import com.android.internal.view.IInputMethodCallback;
24import com.android.internal.view.IInputMethodClient;
25import com.android.internal.view.IInputMethodManager;
26import com.android.internal.view.IInputMethodSession;
27import com.android.internal.view.InputBindResult;
28
29import com.android.server.StatusBarManagerService;
30
31import org.xmlpull.v1.XmlPullParserException;
32
33import android.app.ActivityManagerNative;
34import android.app.AlertDialog;
35import android.app.PendingIntent;
36import android.content.ComponentName;
37import android.content.ContentResolver;
38import android.content.Context;
39import android.content.DialogInterface;
40import android.content.IntentFilter;
41import android.content.DialogInterface.OnCancelListener;
42import android.content.Intent;
43import android.content.ServiceConnection;
44import android.content.pm.ApplicationInfo;
45import android.content.pm.PackageManager;
46import android.content.pm.ResolveInfo;
47import android.content.pm.ServiceInfo;
48import android.content.res.Configuration;
49import android.content.res.Resources;
50import android.content.res.TypedArray;
51import android.database.ContentObserver;
52import android.os.Binder;
53import android.os.Handler;
54import android.os.IBinder;
55import android.os.IInterface;
56import android.os.Message;
57import android.os.Parcel;
58import android.os.RemoteException;
59import android.os.ResultReceiver;
60import android.os.ServiceManager;
61import android.os.SystemClock;
62import android.provider.Settings;
63import android.provider.Settings.Secure;
64import android.provider.Settings.SettingNotFoundException;
65import android.text.TextUtils;
66import android.util.EventLog;
67import android.util.Pair;
68import android.util.Slog;
69import android.util.PrintWriterPrinter;
70import android.util.Printer;
71import android.view.IWindowManager;
72import android.view.WindowManager;
73import android.view.inputmethod.EditorInfo;
74import android.view.inputmethod.InputBinding;
75import android.view.inputmethod.InputMethod;
76import android.view.inputmethod.InputMethodInfo;
77import android.view.inputmethod.InputMethodManager;
78import android.view.inputmethod.InputMethodSubtype;
79
80import java.io.FileDescriptor;
81import java.io.IOException;
82import java.io.PrintWriter;
83import java.text.Collator;
84import java.util.ArrayList;
85import java.util.HashMap;
86import java.util.HashSet;
87import java.util.List;
88import java.util.Map;
89import java.util.TreeMap;
90
91/**
92 * This class provides a system service that manages input methods.
93 */
94public class InputMethodManagerService extends IInputMethodManager.Stub
95        implements ServiceConnection, Handler.Callback {
96    static final boolean DEBUG = false;
97    static final String TAG = "InputManagerService";
98
99    static final int MSG_SHOW_IM_PICKER = 1;
100    static final int MSG_SHOW_IM_SUBTYPE_PICKER = 2;
101    static final int MSG_SHOW_IM_SUBTYPE_ENABLER = 3;
102
103    static final int MSG_UNBIND_INPUT = 1000;
104    static final int MSG_BIND_INPUT = 1010;
105    static final int MSG_SHOW_SOFT_INPUT = 1020;
106    static final int MSG_HIDE_SOFT_INPUT = 1030;
107    static final int MSG_ATTACH_TOKEN = 1040;
108    static final int MSG_CREATE_SESSION = 1050;
109
110    static final int MSG_START_INPUT = 2000;
111    static final int MSG_RESTART_INPUT = 2010;
112
113    static final int MSG_UNBIND_METHOD = 3000;
114    static final int MSG_BIND_METHOD = 3010;
115
116    static final long TIME_TO_RECONNECT = 10*1000;
117
118    private static final int NOT_A_SUBTYPE_ID = -1;
119
120    final Context mContext;
121    final Handler mHandler;
122    final InputMethodSettings mSettings;
123    final SettingsObserver mSettingsObserver;
124    final StatusBarManagerService mStatusBar;
125    final IWindowManager mIWindowManager;
126    final HandlerCaller mCaller;
127
128    final InputBindResult mNoBinding = new InputBindResult(null, null, -1);
129
130    // All known input methods.  mMethodMap also serves as the global
131    // lock for this class.
132    final ArrayList<InputMethodInfo> mMethodList = new ArrayList<InputMethodInfo>();
133    final HashMap<String, InputMethodInfo> mMethodMap = new HashMap<String, InputMethodInfo>();
134
135    class SessionState {
136        final ClientState client;
137        final IInputMethod method;
138        final IInputMethodSession session;
139
140        @Override
141        public String toString() {
142            return "SessionState{uid " + client.uid + " pid " + client.pid
143                    + " method " + Integer.toHexString(
144                            System.identityHashCode(method))
145                    + " session " + Integer.toHexString(
146                            System.identityHashCode(session))
147                    + "}";
148        }
149
150        SessionState(ClientState _client, IInputMethod _method,
151                IInputMethodSession _session) {
152            client = _client;
153            method = _method;
154            session = _session;
155        }
156    }
157
158    class ClientState {
159        final IInputMethodClient client;
160        final IInputContext inputContext;
161        final int uid;
162        final int pid;
163        final InputBinding binding;
164
165        boolean sessionRequested;
166        SessionState curSession;
167
168        @Override
169        public String toString() {
170            return "ClientState{" + Integer.toHexString(
171                    System.identityHashCode(this)) + " uid " + uid
172                    + " pid " + pid + "}";
173        }
174
175        ClientState(IInputMethodClient _client, IInputContext _inputContext,
176                int _uid, int _pid) {
177            client = _client;
178            inputContext = _inputContext;
179            uid = _uid;
180            pid = _pid;
181            binding = new InputBinding(null, inputContext.asBinder(), uid, pid);
182        }
183    }
184
185    final HashMap<IBinder, ClientState> mClients
186            = new HashMap<IBinder, ClientState>();
187
188    /**
189     * Set once the system is ready to run third party code.
190     */
191    boolean mSystemReady;
192
193    /**
194     * Id of the currently selected input method.
195     */
196    String mCurMethodId;
197
198    /**
199     * The current binding sequence number, incremented every time there is
200     * a new bind performed.
201     */
202    int mCurSeq;
203
204    /**
205     * The client that is currently bound to an input method.
206     */
207    ClientState mCurClient;
208
209    /**
210     * The last window token that gained focus.
211     */
212    IBinder mCurFocusedWindow;
213
214    /**
215     * The input context last provided by the current client.
216     */
217    IInputContext mCurInputContext;
218
219    /**
220     * The attributes last provided by the current client.
221     */
222    EditorInfo mCurAttribute;
223
224    /**
225     * The input method ID of the input method service that we are currently
226     * connected to or in the process of connecting to.
227     */
228    String mCurId;
229
230    /**
231     * The current subtype of the current input method.
232     */
233    private InputMethodSubtype mCurrentSubtype;
234
235
236    /**
237     * Set to true if our ServiceConnection is currently actively bound to
238     * a service (whether or not we have gotten its IBinder back yet).
239     */
240    boolean mHaveConnection;
241
242    /**
243     * Set if the client has asked for the input method to be shown.
244     */
245    boolean mShowRequested;
246
247    /**
248     * Set if we were explicitly told to show the input method.
249     */
250    boolean mShowExplicitlyRequested;
251
252    /**
253     * Set if we were forced to be shown.
254     */
255    boolean mShowForced;
256
257    /**
258     * Set if we last told the input method to show itself.
259     */
260    boolean mInputShown;
261
262    /**
263     * The Intent used to connect to the current input method.
264     */
265    Intent mCurIntent;
266
267    /**
268     * The token we have made for the currently active input method, to
269     * identify it in the future.
270     */
271    IBinder mCurToken;
272
273    /**
274     * If non-null, this is the input method service we are currently connected
275     * to.
276     */
277    IInputMethod mCurMethod;
278
279    /**
280     * Time that we last initiated a bind to the input method, to determine
281     * if we should try to disconnect and reconnect to it.
282     */
283    long mLastBindTime;
284
285    /**
286     * Have we called mCurMethod.bindInput()?
287     */
288    boolean mBoundToMethod;
289
290    /**
291     * Currently enabled session.  Only touched by service thread, not
292     * protected by a lock.
293     */
294    SessionState mEnabledSession;
295
296    /**
297     * True if the screen is on.  The value is true initially.
298     */
299    boolean mScreenOn = true;
300
301    AlertDialog.Builder mDialogBuilder;
302    AlertDialog mSwitchingDialog;
303    InputMethodInfo[] mIms;
304    CharSequence[] mItems;
305    int[] mSubtypeIds;
306
307    class SettingsObserver extends ContentObserver {
308        SettingsObserver(Handler handler) {
309            super(handler);
310            ContentResolver resolver = mContext.getContentResolver();
311            resolver.registerContentObserver(Settings.Secure.getUriFor(
312                    Settings.Secure.DEFAULT_INPUT_METHOD), false, this);
313            resolver.registerContentObserver(Settings.Secure.getUriFor(
314                    Settings.Secure.SELECTED_INPUT_METHOD_SUBTYPE), false, this);
315        }
316
317        @Override public void onChange(boolean selfChange) {
318            synchronized (mMethodMap) {
319                updateFromSettingsLocked();
320            }
321        }
322    }
323
324    class ScreenOnOffReceiver extends android.content.BroadcastReceiver {
325        @Override
326        public void onReceive(Context context, Intent intent) {
327            if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
328                mScreenOn = true;
329            } else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
330                mScreenOn = false;
331            } else if (intent.getAction().equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
332                hideInputMethodMenu();
333                return;
334            } else {
335                Slog.w(TAG, "Unexpected intent " + intent);
336            }
337
338            // Inform the current client of the change in active status
339            try {
340                if (mCurClient != null && mCurClient.client != null) {
341                    mCurClient.client.setActive(mScreenOn);
342                }
343            } catch (RemoteException e) {
344                Slog.w(TAG, "Got RemoteException sending 'screen on/off' notification to pid "
345                        + mCurClient.pid + " uid " + mCurClient.uid);
346            }
347        }
348    }
349
350    class MyPackageMonitor extends PackageMonitor {
351
352        @Override
353        public boolean onHandleForceStop(Intent intent, String[] packages, int uid, boolean doit) {
354            synchronized (mMethodMap) {
355                String curInputMethodId = Settings.Secure.getString(mContext
356                        .getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);
357                final int N = mMethodList.size();
358                if (curInputMethodId != null) {
359                    for (int i=0; i<N; i++) {
360                        InputMethodInfo imi = mMethodList.get(i);
361                        if (imi.getId().equals(curInputMethodId)) {
362                            for (String pkg : packages) {
363                                if (imi.getPackageName().equals(pkg)) {
364                                    if (!doit) {
365                                        return true;
366                                    }
367                                    Settings.Secure.putString(mContext.getContentResolver(),
368                                            Settings.Secure.DEFAULT_INPUT_METHOD, "");
369                                    resetSelectedInputMethodSubtype();
370                                    chooseNewDefaultIMELocked();
371                                    return true;
372                                }
373                            }
374                        }
375                    }
376                }
377            }
378            return false;
379        }
380
381        @Override
382        public void onSomePackagesChanged() {
383            synchronized (mMethodMap) {
384                InputMethodInfo curIm = null;
385                String curInputMethodId = Settings.Secure.getString(mContext
386                        .getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);
387                final int N = mMethodList.size();
388                if (curInputMethodId != null) {
389                    for (int i=0; i<N; i++) {
390                        InputMethodInfo imi = mMethodList.get(i);
391                        if (imi.getId().equals(curInputMethodId)) {
392                            curIm = imi;
393                        }
394                        int change = isPackageDisappearing(imi.getPackageName());
395                        if (change == PACKAGE_TEMPORARY_CHANGE
396                                || change == PACKAGE_PERMANENT_CHANGE) {
397                            Slog.i(TAG, "Input method uninstalled, disabling: "
398                                    + imi.getComponent());
399                            setInputMethodEnabledLocked(imi.getId(), false);
400                        }
401                    }
402                }
403
404                buildInputMethodListLocked(mMethodList, mMethodMap);
405
406                boolean changed = false;
407
408                if (curIm != null) {
409                    int change = isPackageDisappearing(curIm.getPackageName());
410                    if (change == PACKAGE_TEMPORARY_CHANGE
411                            || change == PACKAGE_PERMANENT_CHANGE) {
412                        ServiceInfo si = null;
413                        try {
414                            si = mContext.getPackageManager().getServiceInfo(
415                                    curIm.getComponent(), 0);
416                        } catch (PackageManager.NameNotFoundException ex) {
417                        }
418                        if (si == null) {
419                            // Uh oh, current input method is no longer around!
420                            // Pick another one...
421                            Slog.i(TAG, "Current input method removed: " + curInputMethodId);
422                            if (!chooseNewDefaultIMELocked()) {
423                                changed = true;
424                                curIm = null;
425                                Slog.i(TAG, "Unsetting current input method");
426                                Settings.Secure.putString(mContext.getContentResolver(),
427                                        Settings.Secure.DEFAULT_INPUT_METHOD, "");
428                                resetSelectedInputMethodSubtype();
429                            }
430                        }
431                    }
432                }
433
434                if (curIm == null) {
435                    // We currently don't have a default input method... is
436                    // one now available?
437                    changed = chooseNewDefaultIMELocked();
438                }
439
440                if (changed) {
441                    updateFromSettingsLocked();
442                }
443            }
444        }
445    }
446
447    class MethodCallback extends IInputMethodCallback.Stub {
448        final IInputMethod mMethod;
449
450        MethodCallback(IInputMethod method) {
451            mMethod = method;
452        }
453
454        public void finishedEvent(int seq, boolean handled) throws RemoteException {
455        }
456
457        public void sessionCreated(IInputMethodSession session) throws RemoteException {
458            onSessionCreated(mMethod, session);
459        }
460    }
461
462    public InputMethodManagerService(Context context, StatusBarManagerService statusBar) {
463        mContext = context;
464        mHandler = new Handler(this);
465        mIWindowManager = IWindowManager.Stub.asInterface(
466                ServiceManager.getService(Context.WINDOW_SERVICE));
467        mCaller = new HandlerCaller(context, new HandlerCaller.Callback() {
468            public void executeMessage(Message msg) {
469                handleMessage(msg);
470            }
471        });
472
473        (new MyPackageMonitor()).register(mContext, true);
474
475        IntentFilter screenOnOffFilt = new IntentFilter();
476        screenOnOffFilt.addAction(Intent.ACTION_SCREEN_ON);
477        screenOnOffFilt.addAction(Intent.ACTION_SCREEN_OFF);
478        screenOnOffFilt.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
479        mContext.registerReceiver(new ScreenOnOffReceiver(), screenOnOffFilt);
480
481        mStatusBar = statusBar;
482        statusBar.setIconVisibility("ime", false);
483
484        // mSettings should be created before buildInputMethodListLocked
485        mSettings = new InputMethodSettings(context.getContentResolver(), mMethodMap, mMethodList);
486        buildInputMethodListLocked(mMethodList, mMethodMap);
487        mSettings.enableAllIMEsIfThereIsNoEnabledIME();
488
489        if (TextUtils.isEmpty(Settings.Secure.getString(
490                mContext.getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD))) {
491            InputMethodInfo defIm = null;
492            for (InputMethodInfo imi: mMethodList) {
493                if (defIm == null && imi.getIsDefaultResourceId() != 0) {
494                    try {
495                        Resources res = context.createPackageContext(
496                                imi.getPackageName(), 0).getResources();
497                        if (res.getBoolean(imi.getIsDefaultResourceId())) {
498                            defIm = imi;
499                            Slog.i(TAG, "Selected default: " + imi.getId());
500                        }
501                    } catch (PackageManager.NameNotFoundException ex) {
502                    } catch (Resources.NotFoundException ex) {
503                    }
504                }
505            }
506            if (defIm == null && mMethodList.size() > 0) {
507                defIm = mMethodList.get(0);
508                Slog.i(TAG, "No default found, using " + defIm.getId());
509            }
510            if (defIm != null) {
511                Settings.Secure.putString(mContext.getContentResolver(),
512                        Settings.Secure.DEFAULT_INPUT_METHOD, defIm.getId());
513                putSelectedInputMethodSubtype(defIm, NOT_A_SUBTYPE_ID);
514            }
515        }
516
517        mSettingsObserver = new SettingsObserver(mHandler);
518        updateFromSettingsLocked();
519    }
520
521    @Override
522    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
523            throws RemoteException {
524        try {
525            return super.onTransact(code, data, reply, flags);
526        } catch (RuntimeException e) {
527            // The input method manager only throws security exceptions, so let's
528            // log all others.
529            if (!(e instanceof SecurityException)) {
530                Slog.e(TAG, "Input Method Manager Crash", e);
531            }
532            throw e;
533        }
534    }
535
536    public void systemReady() {
537        synchronized (mMethodMap) {
538            if (!mSystemReady) {
539                mSystemReady = true;
540                try {
541                    startInputInnerLocked();
542                } catch (RuntimeException e) {
543                    Slog.w(TAG, "Unexpected exception", e);
544                }
545            }
546        }
547    }
548
549    public List<InputMethodInfo> getInputMethodList() {
550        synchronized (mMethodMap) {
551            return new ArrayList<InputMethodInfo>(mMethodList);
552        }
553    }
554
555    public List<InputMethodInfo> getEnabledInputMethodList() {
556        synchronized (mMethodMap) {
557            return mSettings.getEnabledInputMethodListLocked();
558        }
559    }
560
561    public void addClient(IInputMethodClient client,
562            IInputContext inputContext, int uid, int pid) {
563        synchronized (mMethodMap) {
564            mClients.put(client.asBinder(), new ClientState(client,
565                    inputContext, uid, pid));
566        }
567    }
568
569    public void removeClient(IInputMethodClient client) {
570        synchronized (mMethodMap) {
571            mClients.remove(client.asBinder());
572        }
573    }
574
575    void executeOrSendMessage(IInterface target, Message msg) {
576         if (target.asBinder() instanceof Binder) {
577             mCaller.sendMessage(msg);
578         } else {
579             handleMessage(msg);
580             msg.recycle();
581         }
582    }
583
584    void unbindCurrentClientLocked() {
585        if (mCurClient != null) {
586            if (DEBUG) Slog.v(TAG, "unbindCurrentInputLocked: client = "
587                    + mCurClient.client.asBinder());
588            if (mBoundToMethod) {
589                mBoundToMethod = false;
590                if (mCurMethod != null) {
591                    executeOrSendMessage(mCurMethod, mCaller.obtainMessageO(
592                            MSG_UNBIND_INPUT, mCurMethod));
593                }
594            }
595            executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
596                    MSG_UNBIND_METHOD, mCurSeq, mCurClient.client));
597            mCurClient.sessionRequested = false;
598
599            // Call setActive(false) on the old client
600            try {
601                mCurClient.client.setActive(false);
602            } catch (RemoteException e) {
603                Slog.w(TAG, "Got RemoteException sending setActive(false) notification to pid "
604                        + mCurClient.pid + " uid " + mCurClient.uid);
605            }
606            mCurClient = null;
607
608            hideInputMethodMenuLocked();
609        }
610    }
611
612    private int getImeShowFlags() {
613        int flags = 0;
614        if (mShowForced) {
615            flags |= InputMethod.SHOW_FORCED
616                    | InputMethod.SHOW_EXPLICIT;
617        } else if (mShowExplicitlyRequested) {
618            flags |= InputMethod.SHOW_EXPLICIT;
619        }
620        return flags;
621    }
622
623    private int getAppShowFlags() {
624        int flags = 0;
625        if (mShowForced) {
626            flags |= InputMethodManager.SHOW_FORCED;
627        } else if (!mShowExplicitlyRequested) {
628            flags |= InputMethodManager.SHOW_IMPLICIT;
629        }
630        return flags;
631    }
632
633    InputBindResult attachNewInputLocked(boolean initial, boolean needResult) {
634        if (!mBoundToMethod) {
635            executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
636                    MSG_BIND_INPUT, mCurMethod, mCurClient.binding));
637            mBoundToMethod = true;
638        }
639        final SessionState session = mCurClient.curSession;
640        if (initial) {
641            executeOrSendMessage(session.method, mCaller.obtainMessageOOO(
642                    MSG_START_INPUT, session, mCurInputContext, mCurAttribute));
643        } else {
644            executeOrSendMessage(session.method, mCaller.obtainMessageOOO(
645                    MSG_RESTART_INPUT, session, mCurInputContext, mCurAttribute));
646        }
647        if (mShowRequested) {
648            if (DEBUG) Slog.v(TAG, "Attach new input asks to show input");
649            showCurrentInputLocked(getAppShowFlags(), null);
650        }
651        return needResult
652                ? new InputBindResult(session.session, mCurId, mCurSeq)
653                : null;
654    }
655
656    InputBindResult startInputLocked(IInputMethodClient client,
657            IInputContext inputContext, EditorInfo attribute,
658            boolean initial, boolean needResult) {
659        // If no method is currently selected, do nothing.
660        if (mCurMethodId == null) {
661            return mNoBinding;
662        }
663
664        ClientState cs = mClients.get(client.asBinder());
665        if (cs == null) {
666            throw new IllegalArgumentException("unknown client "
667                    + client.asBinder());
668        }
669
670        try {
671            if (!mIWindowManager.inputMethodClientHasFocus(cs.client)) {
672                // Check with the window manager to make sure this client actually
673                // has a window with focus.  If not, reject.  This is thread safe
674                // because if the focus changes some time before or after, the
675                // next client receiving focus that has any interest in input will
676                // be calling through here after that change happens.
677                Slog.w(TAG, "Starting input on non-focused client " + cs.client
678                        + " (uid=" + cs.uid + " pid=" + cs.pid + ")");
679                return null;
680            }
681        } catch (RemoteException e) {
682        }
683
684        if (mCurClient != cs) {
685            // If the client is changing, we need to switch over to the new
686            // one.
687            unbindCurrentClientLocked();
688            if (DEBUG) Slog.v(TAG, "switching to client: client = "
689                    + cs.client.asBinder());
690
691            // If the screen is on, inform the new client it is active
692            if (mScreenOn) {
693                try {
694                    cs.client.setActive(mScreenOn);
695                } catch (RemoteException e) {
696                    Slog.w(TAG, "Got RemoteException sending setActive notification to pid "
697                            + cs.pid + " uid " + cs.uid);
698                }
699            }
700        }
701
702        // Bump up the sequence for this client and attach it.
703        mCurSeq++;
704        if (mCurSeq <= 0) mCurSeq = 1;
705        mCurClient = cs;
706        mCurInputContext = inputContext;
707        mCurAttribute = attribute;
708
709        // Check if the input method is changing.
710        if (mCurId != null && mCurId.equals(mCurMethodId)) {
711            if (cs.curSession != null) {
712                // Fast case: if we are already connected to the input method,
713                // then just return it.
714                return attachNewInputLocked(initial, needResult);
715            }
716            if (mHaveConnection) {
717                if (mCurMethod != null) {
718                    if (!cs.sessionRequested) {
719                        cs.sessionRequested = true;
720                        if (DEBUG) Slog.v(TAG, "Creating new session for client " + cs);
721                        executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
722                                MSG_CREATE_SESSION, mCurMethod,
723                                new MethodCallback(mCurMethod)));
724                    }
725                    // Return to client, and we will get back with it when
726                    // we have had a session made for it.
727                    return new InputBindResult(null, mCurId, mCurSeq);
728                } else if (SystemClock.uptimeMillis()
729                        < (mLastBindTime+TIME_TO_RECONNECT)) {
730                    // In this case we have connected to the service, but
731                    // don't yet have its interface.  If it hasn't been too
732                    // long since we did the connection, we'll return to
733                    // the client and wait to get the service interface so
734                    // we can report back.  If it has been too long, we want
735                    // to fall through so we can try a disconnect/reconnect
736                    // to see if we can get back in touch with the service.
737                    return new InputBindResult(null, mCurId, mCurSeq);
738                } else {
739                    EventLog.writeEvent(EventLogTags.IMF_FORCE_RECONNECT_IME,
740                            mCurMethodId, SystemClock.uptimeMillis()-mLastBindTime, 0);
741                }
742            }
743        }
744
745        return startInputInnerLocked();
746    }
747
748    InputBindResult startInputInnerLocked() {
749        if (mCurMethodId == null) {
750            return mNoBinding;
751        }
752
753        if (!mSystemReady) {
754            // If the system is not yet ready, we shouldn't be running third
755            // party code.
756            return new InputBindResult(null, mCurMethodId, mCurSeq);
757        }
758
759        InputMethodInfo info = mMethodMap.get(mCurMethodId);
760        if (info == null) {
761            throw new IllegalArgumentException("Unknown id: " + mCurMethodId);
762        }
763
764        unbindCurrentMethodLocked(false);
765
766        mCurIntent = new Intent(InputMethod.SERVICE_INTERFACE);
767        mCurIntent.setComponent(info.getComponent());
768        mCurIntent.putExtra(Intent.EXTRA_CLIENT_LABEL,
769                com.android.internal.R.string.input_method_binding_label);
770        mCurIntent.putExtra(Intent.EXTRA_CLIENT_INTENT, PendingIntent.getActivity(
771                mContext, 0, new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS), 0));
772        if (mContext.bindService(mCurIntent, this, Context.BIND_AUTO_CREATE)) {
773            mLastBindTime = SystemClock.uptimeMillis();
774            mHaveConnection = true;
775            mCurId = info.getId();
776            mCurToken = new Binder();
777            try {
778                if (DEBUG) Slog.v(TAG, "Adding window token: " + mCurToken);
779                mIWindowManager.addWindowToken(mCurToken,
780                        WindowManager.LayoutParams.TYPE_INPUT_METHOD);
781            } catch (RemoteException e) {
782            }
783            return new InputBindResult(null, mCurId, mCurSeq);
784        } else {
785            mCurIntent = null;
786            Slog.w(TAG, "Failure connecting to input method service: "
787                    + mCurIntent);
788        }
789        return null;
790    }
791
792    public InputBindResult startInput(IInputMethodClient client,
793            IInputContext inputContext, EditorInfo attribute,
794            boolean initial, boolean needResult) {
795        synchronized (mMethodMap) {
796            final long ident = Binder.clearCallingIdentity();
797            try {
798                return startInputLocked(client, inputContext, attribute,
799                        initial, needResult);
800            } finally {
801                Binder.restoreCallingIdentity(ident);
802            }
803        }
804    }
805
806    public void finishInput(IInputMethodClient client) {
807    }
808
809    public void onServiceConnected(ComponentName name, IBinder service) {
810        synchronized (mMethodMap) {
811            if (mCurIntent != null && name.equals(mCurIntent.getComponent())) {
812                mCurMethod = IInputMethod.Stub.asInterface(service);
813                if (mCurToken == null) {
814                    Slog.w(TAG, "Service connected without a token!");
815                    unbindCurrentMethodLocked(false);
816                    return;
817                }
818                if (DEBUG) Slog.v(TAG, "Initiating attach with token: " + mCurToken);
819                executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
820                        MSG_ATTACH_TOKEN, mCurMethod, mCurToken));
821                if (mCurClient != null) {
822                    if (DEBUG) Slog.v(TAG, "Creating first session while with client "
823                            + mCurClient);
824                    executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
825                            MSG_CREATE_SESSION, mCurMethod,
826                            new MethodCallback(mCurMethod)));
827                }
828            }
829        }
830    }
831
832    void onSessionCreated(IInputMethod method, IInputMethodSession session) {
833        synchronized (mMethodMap) {
834            if (mCurMethod != null && method != null
835                    && mCurMethod.asBinder() == method.asBinder()) {
836                if (mCurClient != null) {
837                    mCurClient.curSession = new SessionState(mCurClient,
838                            method, session);
839                    mCurClient.sessionRequested = false;
840                    InputBindResult res = attachNewInputLocked(true, true);
841                    if (res.method != null) {
842                        executeOrSendMessage(mCurClient.client, mCaller.obtainMessageOO(
843                                MSG_BIND_METHOD, mCurClient.client, res));
844                    }
845                }
846            }
847        }
848    }
849
850    void unbindCurrentMethodLocked(boolean reportToClient) {
851        if (mHaveConnection) {
852            mContext.unbindService(this);
853            mHaveConnection = false;
854        }
855
856        if (mCurToken != null) {
857            try {
858                if (DEBUG) Slog.v(TAG, "Removing window token: " + mCurToken);
859                mIWindowManager.removeWindowToken(mCurToken);
860            } catch (RemoteException e) {
861            }
862            mCurToken = null;
863        }
864
865        mCurId = null;
866        clearCurMethodLocked();
867
868        if (reportToClient && mCurClient != null) {
869            executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
870                    MSG_UNBIND_METHOD, mCurSeq, mCurClient.client));
871        }
872    }
873
874    private void finishSession(SessionState sessionState) {
875        if (sessionState != null && sessionState.session != null) {
876            try {
877                sessionState.session.finishSession();
878            } catch (RemoteException e) {
879                Slog.w(TAG, "Session failed to close due to remote exception", e);
880            }
881        }
882    }
883
884    void clearCurMethodLocked() {
885        if (mCurMethod != null) {
886            for (ClientState cs : mClients.values()) {
887                cs.sessionRequested = false;
888                finishSession(cs.curSession);
889                cs.curSession = null;
890            }
891
892            finishSession(mEnabledSession);
893            mEnabledSession = null;
894            mCurMethod = null;
895        }
896        mStatusBar.setIconVisibility("ime", false);
897    }
898
899    public void onServiceDisconnected(ComponentName name) {
900        synchronized (mMethodMap) {
901            if (DEBUG) Slog.v(TAG, "Service disconnected: " + name
902                    + " mCurIntent=" + mCurIntent);
903            if (mCurMethod != null && mCurIntent != null
904                    && name.equals(mCurIntent.getComponent())) {
905                clearCurMethodLocked();
906                // We consider this to be a new bind attempt, since the system
907                // should now try to restart the service for us.
908                mLastBindTime = SystemClock.uptimeMillis();
909                mShowRequested = mInputShown;
910                mInputShown = false;
911                if (mCurClient != null) {
912                    executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
913                            MSG_UNBIND_METHOD, mCurSeq, mCurClient.client));
914                }
915            }
916        }
917    }
918
919    public void updateStatusIcon(IBinder token, String packageName, int iconId) {
920        int uid = Binder.getCallingUid();
921        long ident = Binder.clearCallingIdentity();
922        try {
923            if (token == null || mCurToken != token) {
924                Slog.w(TAG, "Ignoring setInputMethod of uid " + uid + " token: " + token);
925                return;
926            }
927
928            synchronized (mMethodMap) {
929                if (iconId == 0) {
930                    if (DEBUG) Slog.d(TAG, "hide the small icon for the input method");
931                    mStatusBar.setIconVisibility("ime", false);
932                } else if (packageName != null) {
933                    if (DEBUG) Slog.d(TAG, "show a small icon for the input method");
934                    mStatusBar.setIcon("ime", packageName, iconId, 0);
935                    mStatusBar.setIconVisibility("ime", true);
936                }
937            }
938        } finally {
939            Binder.restoreCallingIdentity(ident);
940        }
941    }
942
943    public void setIMEButtonVisible(IBinder token, boolean visible) {
944        int uid = Binder.getCallingUid();
945        long ident = Binder.clearCallingIdentity();
946        try {
947            if (token == null || mCurToken != token) {
948                Slog.w(TAG, "Ignoring setIMEButtonVisible of uid " + uid + " token: " + token);
949                return;
950            }
951
952            synchronized (mMethodMap) {
953                mStatusBar.setIMEButtonVisible(visible);
954            }
955        } finally {
956            Binder.restoreCallingIdentity(ident);
957        }
958    }
959
960    void updateFromSettingsLocked() {
961        // We are assuming that whoever is changing DEFAULT_INPUT_METHOD and
962        // ENABLED_INPUT_METHODS is taking care of keeping them correctly in
963        // sync, so we will never have a DEFAULT_INPUT_METHOD that is not
964        // enabled.
965        String id = Settings.Secure.getString(mContext.getContentResolver(),
966                Settings.Secure.DEFAULT_INPUT_METHOD);
967        if (id != null && id.length() > 0) {
968            try {
969                setInputMethodLocked(id, getSelectedInputMethodSubtypeId(id));
970            } catch (IllegalArgumentException e) {
971                Slog.w(TAG, "Unknown input method from prefs: " + id, e);
972                mCurMethodId = null;
973                unbindCurrentMethodLocked(true);
974            }
975        } else {
976            // There is no longer an input method set, so stop any current one.
977            mCurMethodId = null;
978            unbindCurrentMethodLocked(true);
979        }
980    }
981
982    /* package */ void setInputMethodLocked(String id, int subtypeId) {
983        InputMethodInfo info = mMethodMap.get(id);
984        if (info == null) {
985            throw new IllegalArgumentException("Unknown id: " + id);
986        }
987
988        if (id.equals(mCurMethodId)) {
989            if (subtypeId != NOT_A_SUBTYPE_ID) {
990                InputMethodSubtype subtype = info.getSubtypes().get(subtypeId);
991                if (subtype != mCurrentSubtype) {
992                    synchronized (mMethodMap) {
993                        if (mCurMethod != null) {
994                            try {
995                                putSelectedInputMethodSubtype(info, subtypeId);
996                                mCurMethod.changeInputMethodSubtype(subtype);
997                            } catch (RemoteException e) {
998                                return;
999                            }
1000                        }
1001                    }
1002                }
1003            }
1004            return;
1005        }
1006
1007        final long ident = Binder.clearCallingIdentity();
1008        try {
1009            mCurMethodId = id;
1010            // Set a subtype to this input method.
1011            // subtypeId the name of a subtype which will be set.
1012            if (putSelectedInputMethodSubtype(info, subtypeId)) {
1013                mCurrentSubtype = info.getSubtypes().get(subtypeId);
1014            } else {
1015                mCurrentSubtype = null;
1016            }
1017
1018            Settings.Secure.putString(mContext.getContentResolver(),
1019                    Settings.Secure.DEFAULT_INPUT_METHOD, id);
1020
1021            if (ActivityManagerNative.isSystemReady()) {
1022                Intent intent = new Intent(Intent.ACTION_INPUT_METHOD_CHANGED);
1023                intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
1024                intent.putExtra("input_method_id", id);
1025                mContext.sendBroadcast(intent);
1026            }
1027            unbindCurrentClientLocked();
1028        } finally {
1029            Binder.restoreCallingIdentity(ident);
1030        }
1031    }
1032
1033    public boolean showSoftInput(IInputMethodClient client, int flags,
1034            ResultReceiver resultReceiver) {
1035        int uid = Binder.getCallingUid();
1036        long ident = Binder.clearCallingIdentity();
1037        try {
1038            synchronized (mMethodMap) {
1039                if (mCurClient == null || client == null
1040                        || mCurClient.client.asBinder() != client.asBinder()) {
1041                    try {
1042                        // We need to check if this is the current client with
1043                        // focus in the window manager, to allow this call to
1044                        // be made before input is started in it.
1045                        if (!mIWindowManager.inputMethodClientHasFocus(client)) {
1046                            Slog.w(TAG, "Ignoring showSoftInput of uid " + uid + ": " + client);
1047                            return false;
1048                        }
1049                    } catch (RemoteException e) {
1050                        return false;
1051                    }
1052                }
1053
1054                if (DEBUG) Slog.v(TAG, "Client requesting input be shown");
1055                return showCurrentInputLocked(flags, resultReceiver);
1056            }
1057        } finally {
1058            Binder.restoreCallingIdentity(ident);
1059        }
1060    }
1061
1062    boolean showCurrentInputLocked(int flags, ResultReceiver resultReceiver) {
1063        mShowRequested = true;
1064        if ((flags&InputMethodManager.SHOW_IMPLICIT) == 0) {
1065            mShowExplicitlyRequested = true;
1066        }
1067        if ((flags&InputMethodManager.SHOW_FORCED) != 0) {
1068            mShowExplicitlyRequested = true;
1069            mShowForced = true;
1070        }
1071
1072        if (!mSystemReady) {
1073            return false;
1074        }
1075
1076        boolean res = false;
1077        if (mCurMethod != null) {
1078            executeOrSendMessage(mCurMethod, mCaller.obtainMessageIOO(
1079                    MSG_SHOW_SOFT_INPUT, getImeShowFlags(), mCurMethod,
1080                    resultReceiver));
1081            mInputShown = true;
1082            res = true;
1083        } else if (mHaveConnection && SystemClock.uptimeMillis()
1084                < (mLastBindTime+TIME_TO_RECONNECT)) {
1085            // The client has asked to have the input method shown, but
1086            // we have been sitting here too long with a connection to the
1087            // service and no interface received, so let's disconnect/connect
1088            // to try to prod things along.
1089            EventLog.writeEvent(EventLogTags.IMF_FORCE_RECONNECT_IME, mCurMethodId,
1090                    SystemClock.uptimeMillis()-mLastBindTime,1);
1091            mContext.unbindService(this);
1092            mContext.bindService(mCurIntent, this, Context.BIND_AUTO_CREATE);
1093        }
1094
1095        return res;
1096    }
1097
1098    public boolean hideSoftInput(IInputMethodClient client, int flags,
1099            ResultReceiver resultReceiver) {
1100        int uid = Binder.getCallingUid();
1101        long ident = Binder.clearCallingIdentity();
1102        try {
1103            synchronized (mMethodMap) {
1104                if (mCurClient == null || client == null
1105                        || mCurClient.client.asBinder() != client.asBinder()) {
1106                    try {
1107                        // We need to check if this is the current client with
1108                        // focus in the window manager, to allow this call to
1109                        // be made before input is started in it.
1110                        if (!mIWindowManager.inputMethodClientHasFocus(client)) {
1111                            if (DEBUG) Slog.w(TAG, "Ignoring hideSoftInput of uid "
1112                                    + uid + ": " + client);
1113                            return false;
1114                        }
1115                    } catch (RemoteException e) {
1116                        return false;
1117                    }
1118                }
1119
1120                if (DEBUG) Slog.v(TAG, "Client requesting input be hidden");
1121                return hideCurrentInputLocked(flags, resultReceiver);
1122            }
1123        } finally {
1124            Binder.restoreCallingIdentity(ident);
1125        }
1126    }
1127
1128    boolean hideCurrentInputLocked(int flags, ResultReceiver resultReceiver) {
1129        if ((flags&InputMethodManager.HIDE_IMPLICIT_ONLY) != 0
1130                && (mShowExplicitlyRequested || mShowForced)) {
1131            if (DEBUG) Slog.v(TAG,
1132                    "Not hiding: explicit show not cancelled by non-explicit hide");
1133            return false;
1134        }
1135        if (mShowForced && (flags&InputMethodManager.HIDE_NOT_ALWAYS) != 0) {
1136            if (DEBUG) Slog.v(TAG,
1137                    "Not hiding: forced show not cancelled by not-always hide");
1138            return false;
1139        }
1140        boolean res;
1141        if (mInputShown && mCurMethod != null) {
1142            executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
1143                    MSG_HIDE_SOFT_INPUT, mCurMethod, resultReceiver));
1144            res = true;
1145        } else {
1146            res = false;
1147        }
1148        mInputShown = false;
1149        mShowRequested = false;
1150        mShowExplicitlyRequested = false;
1151        mShowForced = false;
1152        return res;
1153    }
1154
1155    public void windowGainedFocus(IInputMethodClient client, IBinder windowToken,
1156            boolean viewHasFocus, boolean isTextEditor, int softInputMode,
1157            boolean first, int windowFlags) {
1158        long ident = Binder.clearCallingIdentity();
1159        try {
1160            synchronized (mMethodMap) {
1161                if (DEBUG) Slog.v(TAG, "windowGainedFocus: " + client.asBinder()
1162                        + " viewHasFocus=" + viewHasFocus
1163                        + " isTextEditor=" + isTextEditor
1164                        + " softInputMode=#" + Integer.toHexString(softInputMode)
1165                        + " first=" + first + " flags=#"
1166                        + Integer.toHexString(windowFlags));
1167
1168                if (mCurClient == null || client == null
1169                        || mCurClient.client.asBinder() != client.asBinder()) {
1170                    try {
1171                        // We need to check if this is the current client with
1172                        // focus in the window manager, to allow this call to
1173                        // be made before input is started in it.
1174                        if (!mIWindowManager.inputMethodClientHasFocus(client)) {
1175                            Slog.w(TAG, "Client not active, ignoring focus gain of: " + client);
1176                            return;
1177                        }
1178                    } catch (RemoteException e) {
1179                    }
1180                }
1181
1182                if (mCurFocusedWindow == windowToken) {
1183                    Slog.w(TAG, "Window already focused, ignoring focus gain of: " + client);
1184                    return;
1185                }
1186                mCurFocusedWindow = windowToken;
1187
1188                switch (softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_STATE) {
1189                    case WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED:
1190                        if (!isTextEditor || (softInputMode &
1191                                WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
1192                                != WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) {
1193                            if (WindowManager.LayoutParams.mayUseInputMethod(windowFlags)) {
1194                                // There is no focus view, and this window will
1195                                // be behind any soft input window, so hide the
1196                                // soft input window if it is shown.
1197                                if (DEBUG) Slog.v(TAG, "Unspecified window will hide input");
1198                                hideCurrentInputLocked(InputMethodManager.HIDE_NOT_ALWAYS, null);
1199                            }
1200                        } else if (isTextEditor && (softInputMode &
1201                                WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
1202                                == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
1203                                && (softInputMode &
1204                                        WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) {
1205                            // There is a focus view, and we are navigating forward
1206                            // into the window, so show the input window for the user.
1207                            if (DEBUG) Slog.v(TAG, "Unspecified window will show input");
1208                            showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
1209                        }
1210                        break;
1211                    case WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED:
1212                        // Do nothing.
1213                        break;
1214                    case WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN:
1215                        if ((softInputMode &
1216                                WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) {
1217                            if (DEBUG) Slog.v(TAG, "Window asks to hide input going forward");
1218                            hideCurrentInputLocked(0, null);
1219                        }
1220                        break;
1221                    case WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN:
1222                        if (DEBUG) Slog.v(TAG, "Window asks to hide input");
1223                        hideCurrentInputLocked(0, null);
1224                        break;
1225                    case WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE:
1226                        if ((softInputMode &
1227                                WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) {
1228                            if (DEBUG) Slog.v(TAG, "Window asks to show input going forward");
1229                            showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
1230                        }
1231                        break;
1232                    case WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE:
1233                        if (DEBUG) Slog.v(TAG, "Window asks to always show input");
1234                        showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
1235                        break;
1236                }
1237            }
1238        } finally {
1239            Binder.restoreCallingIdentity(ident);
1240        }
1241    }
1242
1243    public void showInputMethodPickerFromClient(IInputMethodClient client) {
1244        synchronized (mMethodMap) {
1245            if (mCurClient == null || client == null
1246                    || mCurClient.client.asBinder() != client.asBinder()) {
1247                Slog.w(TAG, "Ignoring showInputMethodPickerFromClient of uid "
1248                        + Binder.getCallingUid() + ": " + client);
1249            }
1250
1251            mHandler.sendEmptyMessage(MSG_SHOW_IM_PICKER);
1252        }
1253    }
1254
1255    public void showInputMethodSubtypePickerFromClient(IInputMethodClient client) {
1256        synchronized (mMethodMap) {
1257            if (mCurClient == null || client == null
1258                    || mCurClient.client.asBinder() != client.asBinder()) {
1259                Slog.w(TAG, "Ignoring showInputMethodSubtypePickerFromClient of: " + client);
1260            }
1261
1262            mHandler.sendEmptyMessage(MSG_SHOW_IM_SUBTYPE_PICKER);
1263        }
1264    }
1265
1266    public void showInputMethodAndSubtypeEnablerFromClient(
1267            IInputMethodClient client, String topId) {
1268        // TODO: Handle topId for setting the top position of the list activity
1269        synchronized (mMethodMap) {
1270            if (mCurClient == null || client == null
1271                    || mCurClient.client.asBinder() != client.asBinder()) {
1272                Slog.w(TAG, "Ignoring showInputMethodAndSubtypeEnablerFromClient of: " + client);
1273            }
1274
1275            mHandler.sendEmptyMessage(MSG_SHOW_IM_SUBTYPE_ENABLER);
1276        }
1277    }
1278
1279    public void setInputMethod(IBinder token, String id) {
1280        setInputMethodWithSubtype(token, id, NOT_A_SUBTYPE_ID);
1281    }
1282
1283    private void setInputMethodWithSubtype(IBinder token, String id, int subtypeId) {
1284        synchronized (mMethodMap) {
1285            if (token == null) {
1286                if (mContext.checkCallingOrSelfPermission(
1287                        android.Manifest.permission.WRITE_SECURE_SETTINGS)
1288                        != PackageManager.PERMISSION_GRANTED) {
1289                    throw new SecurityException(
1290                            "Using null token requires permission "
1291                            + android.Manifest.permission.WRITE_SECURE_SETTINGS);
1292                }
1293            } else if (mCurToken != token) {
1294                Slog.w(TAG, "Ignoring setInputMethod of uid " + Binder.getCallingUid()
1295                        + " token: " + token);
1296                return;
1297            }
1298
1299            long ident = Binder.clearCallingIdentity();
1300            try {
1301                setInputMethodLocked(id, subtypeId);
1302            } finally {
1303                Binder.restoreCallingIdentity(ident);
1304            }
1305        }
1306    }
1307
1308    public void hideMySoftInput(IBinder token, int flags) {
1309        synchronized (mMethodMap) {
1310            if (token == null || mCurToken != token) {
1311                if (DEBUG) Slog.w(TAG, "Ignoring hideInputMethod of uid "
1312                        + Binder.getCallingUid() + " token: " + token);
1313                return;
1314            }
1315            long ident = Binder.clearCallingIdentity();
1316            try {
1317                hideCurrentInputLocked(flags, null);
1318            } finally {
1319                Binder.restoreCallingIdentity(ident);
1320            }
1321        }
1322    }
1323
1324    public void showMySoftInput(IBinder token, int flags) {
1325        synchronized (mMethodMap) {
1326            if (token == null || mCurToken != token) {
1327                Slog.w(TAG, "Ignoring showMySoftInput of uid "
1328                        + Binder.getCallingUid() + " token: " + token);
1329                return;
1330            }
1331            long ident = Binder.clearCallingIdentity();
1332            try {
1333                showCurrentInputLocked(flags, null);
1334            } finally {
1335                Binder.restoreCallingIdentity(ident);
1336            }
1337        }
1338    }
1339
1340    void setEnabledSessionInMainThread(SessionState session) {
1341        if (mEnabledSession != session) {
1342            if (mEnabledSession != null) {
1343                try {
1344                    if (DEBUG) Slog.v(TAG, "Disabling: " + mEnabledSession);
1345                    mEnabledSession.method.setSessionEnabled(
1346                            mEnabledSession.session, false);
1347                } catch (RemoteException e) {
1348                }
1349            }
1350            mEnabledSession = session;
1351            try {
1352                if (DEBUG) Slog.v(TAG, "Enabling: " + mEnabledSession);
1353                session.method.setSessionEnabled(
1354                        session.session, true);
1355            } catch (RemoteException e) {
1356            }
1357        }
1358    }
1359
1360    public boolean handleMessage(Message msg) {
1361        HandlerCaller.SomeArgs args;
1362        switch (msg.what) {
1363            case MSG_SHOW_IM_PICKER:
1364                showInputMethodMenu();
1365                return true;
1366
1367            case MSG_SHOW_IM_SUBTYPE_PICKER:
1368                showInputMethodSubtypeMenu();
1369                return true;
1370
1371            case MSG_SHOW_IM_SUBTYPE_ENABLER:
1372                showInputMethodAndSubtypeEnabler();
1373                return true;
1374
1375            // ---------------------------------------------------------
1376
1377            case MSG_UNBIND_INPUT:
1378                try {
1379                    ((IInputMethod)msg.obj).unbindInput();
1380                } catch (RemoteException e) {
1381                    // There is nothing interesting about the method dying.
1382                }
1383                return true;
1384            case MSG_BIND_INPUT:
1385                args = (HandlerCaller.SomeArgs)msg.obj;
1386                try {
1387                    ((IInputMethod)args.arg1).bindInput((InputBinding)args.arg2);
1388                } catch (RemoteException e) {
1389                }
1390                return true;
1391            case MSG_SHOW_SOFT_INPUT:
1392                args = (HandlerCaller.SomeArgs)msg.obj;
1393                try {
1394                    ((IInputMethod)args.arg1).showSoftInput(msg.arg1,
1395                            (ResultReceiver)args.arg2);
1396                } catch (RemoteException e) {
1397                }
1398                return true;
1399            case MSG_HIDE_SOFT_INPUT:
1400                args = (HandlerCaller.SomeArgs)msg.obj;
1401                try {
1402                    ((IInputMethod)args.arg1).hideSoftInput(0,
1403                            (ResultReceiver)args.arg2);
1404                } catch (RemoteException e) {
1405                }
1406                return true;
1407            case MSG_ATTACH_TOKEN:
1408                args = (HandlerCaller.SomeArgs)msg.obj;
1409                try {
1410                    if (DEBUG) Slog.v(TAG, "Sending attach of token: " + args.arg2);
1411                    ((IInputMethod)args.arg1).attachToken((IBinder)args.arg2);
1412                } catch (RemoteException e) {
1413                }
1414                return true;
1415            case MSG_CREATE_SESSION:
1416                args = (HandlerCaller.SomeArgs)msg.obj;
1417                try {
1418                    ((IInputMethod)args.arg1).createSession(
1419                            (IInputMethodCallback)args.arg2);
1420                } catch (RemoteException e) {
1421                }
1422                return true;
1423            // ---------------------------------------------------------
1424
1425            case MSG_START_INPUT:
1426                args = (HandlerCaller.SomeArgs)msg.obj;
1427                try {
1428                    SessionState session = (SessionState)args.arg1;
1429                    setEnabledSessionInMainThread(session);
1430                    session.method.startInput((IInputContext)args.arg2,
1431                            (EditorInfo)args.arg3);
1432                } catch (RemoteException e) {
1433                }
1434                return true;
1435            case MSG_RESTART_INPUT:
1436                args = (HandlerCaller.SomeArgs)msg.obj;
1437                try {
1438                    SessionState session = (SessionState)args.arg1;
1439                    setEnabledSessionInMainThread(session);
1440                    session.method.restartInput((IInputContext)args.arg2,
1441                            (EditorInfo)args.arg3);
1442                } catch (RemoteException e) {
1443                }
1444                return true;
1445
1446            // ---------------------------------------------------------
1447
1448            case MSG_UNBIND_METHOD:
1449                try {
1450                    ((IInputMethodClient)msg.obj).onUnbindMethod(msg.arg1);
1451                } catch (RemoteException e) {
1452                    // There is nothing interesting about the last client dying.
1453                }
1454                return true;
1455            case MSG_BIND_METHOD:
1456                args = (HandlerCaller.SomeArgs)msg.obj;
1457                try {
1458                    ((IInputMethodClient)args.arg1).onBindMethod(
1459                            (InputBindResult)args.arg2);
1460                } catch (RemoteException e) {
1461                    Slog.w(TAG, "Client died receiving input method " + args.arg2);
1462                }
1463                return true;
1464        }
1465        return false;
1466    }
1467
1468    private boolean isSystemIme(InputMethodInfo inputMethod) {
1469        return (inputMethod.getServiceInfo().applicationInfo.flags
1470                & ApplicationInfo.FLAG_SYSTEM) != 0;
1471    }
1472
1473    private boolean chooseNewDefaultIMELocked() {
1474        List<InputMethodInfo> enabled = mSettings.getEnabledInputMethodListLocked();
1475        if (enabled != null && enabled.size() > 0) {
1476            // We'd prefer to fall back on a system IME, since that is safer.
1477            int i=enabled.size();
1478            while (i > 0) {
1479                i--;
1480                if ((enabled.get(i).getServiceInfo().applicationInfo.flags
1481                        & ApplicationInfo.FLAG_SYSTEM) != 0) {
1482                    break;
1483                }
1484            }
1485            InputMethodInfo imi = enabled.get(i);
1486            Settings.Secure.putString(mContext.getContentResolver(),
1487                    Settings.Secure.DEFAULT_INPUT_METHOD, imi.getId());
1488            putSelectedInputMethodSubtype(imi, NOT_A_SUBTYPE_ID);
1489            return true;
1490        }
1491
1492        return false;
1493    }
1494
1495    void buildInputMethodListLocked(ArrayList<InputMethodInfo> list,
1496            HashMap<String, InputMethodInfo> map) {
1497        list.clear();
1498        map.clear();
1499
1500        PackageManager pm = mContext.getPackageManager();
1501        final Configuration config = mContext.getResources().getConfiguration();
1502        final boolean haveHardKeyboard = config.keyboard == Configuration.KEYBOARD_QWERTY;
1503        String disabledSysImes = Settings.Secure.getString(mContext.getContentResolver(),
1504                Secure.DISABLED_SYSTEM_INPUT_METHODS);
1505        if (disabledSysImes == null) disabledSysImes = "";
1506
1507        List<ResolveInfo> services = pm.queryIntentServices(
1508                new Intent(InputMethod.SERVICE_INTERFACE),
1509                PackageManager.GET_META_DATA);
1510
1511        for (int i = 0; i < services.size(); ++i) {
1512            ResolveInfo ri = services.get(i);
1513            ServiceInfo si = ri.serviceInfo;
1514            ComponentName compName = new ComponentName(si.packageName, si.name);
1515            if (!android.Manifest.permission.BIND_INPUT_METHOD.equals(
1516                    si.permission)) {
1517                Slog.w(TAG, "Skipping input method " + compName
1518                        + ": it does not require the permission "
1519                        + android.Manifest.permission.BIND_INPUT_METHOD);
1520                continue;
1521            }
1522
1523            if (DEBUG) Slog.d(TAG, "Checking " + compName);
1524
1525            try {
1526                InputMethodInfo p = new InputMethodInfo(mContext, ri);
1527                list.add(p);
1528                final String id = p.getId();
1529                map.put(id, p);
1530
1531                // System IMEs are enabled by default, unless there's a hard keyboard
1532                // and the system IME was explicitly disabled
1533                if (isSystemIme(p) && (!haveHardKeyboard || disabledSysImes.indexOf(id) < 0)) {
1534                    setInputMethodEnabledLocked(id, true);
1535                }
1536
1537                if (DEBUG) {
1538                    Slog.d(TAG, "Found a third-party input method " + p);
1539                }
1540
1541            } catch (XmlPullParserException e) {
1542                Slog.w(TAG, "Unable to load input method " + compName, e);
1543            } catch (IOException e) {
1544                Slog.w(TAG, "Unable to load input method " + compName, e);
1545            }
1546        }
1547
1548        String defaultIme = Settings.Secure.getString(mContext
1549                .getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);
1550        if (!TextUtils.isEmpty(defaultIme) && !map.containsKey(defaultIme)) {
1551            if (chooseNewDefaultIMELocked()) {
1552                updateFromSettingsLocked();
1553            }
1554        }
1555    }
1556
1557    // ----------------------------------------------------------------------
1558
1559    private void showInputMethodMenu() {
1560        showInputMethodMenuInternal(false);
1561    }
1562
1563    private void showInputMethodSubtypeMenu() {
1564        showInputMethodMenuInternal(true);
1565    }
1566
1567    private void showInputMethodAndSubtypeEnabler() {
1568        Intent intent = new Intent(Settings.ACTION_INPUT_METHOD_AND_SUBTYPE_ENABLER);
1569        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1570                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
1571                | Intent.FLAG_ACTIVITY_CLEAR_TOP);
1572        mContext.startActivity(intent);
1573    }
1574
1575    private void showInputMethodMenuInternal(boolean showSubtypes) {
1576        if (DEBUG) Slog.v(TAG, "Show switching menu");
1577
1578        final Context context = mContext;
1579
1580        final PackageManager pm = context.getPackageManager();
1581
1582        String lastInputMethodId = Settings.Secure.getString(context
1583                .getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);
1584        int lastInputMethodSubtypeId = getSelectedInputMethodSubtypeId(lastInputMethodId);
1585        if (DEBUG) Slog.v(TAG, "Current IME: " + lastInputMethodId);
1586
1587        synchronized (mMethodMap) {
1588            final List<Pair<InputMethodInfo, ArrayList<String>>> immis =
1589                    mSettings.getEnabledInputMethodAndSubtypeListLocked();
1590            ArrayList<Integer> subtypeIds = new ArrayList<Integer>();
1591
1592            if (immis == null || immis.size() == 0) {
1593                return;
1594            }
1595
1596            hideInputMethodMenuLocked();
1597
1598            int N = immis.size();
1599
1600            final Map<CharSequence, Pair<InputMethodInfo, Integer>> imMap =
1601                new TreeMap<CharSequence, Pair<InputMethodInfo, Integer>>(Collator.getInstance());
1602
1603            for (int i = 0; i < N; ++i) {
1604                InputMethodInfo property = immis.get(i).first;
1605                final ArrayList<String> enabledSubtypeIds = immis.get(i).second;
1606                HashSet<String> enabledSubtypeSet = new HashSet<String>();
1607                for (String s : enabledSubtypeIds) {
1608                    enabledSubtypeSet.add(s);
1609                }
1610                if (property == null) {
1611                    continue;
1612                }
1613                ArrayList<InputMethodSubtype> subtypes = property.getSubtypes();
1614                CharSequence label = property.loadLabel(pm);
1615                if (showSubtypes && enabledSubtypeSet.size() > 0) {
1616                    for (int j = 0; j < subtypes.size(); ++j) {
1617                        InputMethodSubtype subtype = subtypes.get(j);
1618                        if (enabledSubtypeSet.contains(String.valueOf(subtype.hashCode()))) {
1619                            CharSequence title;
1620                            int nameResId = subtype.getNameResId();
1621                            int modeResId = subtype.getModeResId();
1622                            if (nameResId != 0) {
1623                                title = pm.getText(property.getPackageName(), nameResId,
1624                                        property.getServiceInfo().applicationInfo);
1625                            } else {
1626                                CharSequence language = subtype.getLocale();
1627                                CharSequence mode = modeResId == 0 ? null
1628                                        : pm.getText(property.getPackageName(), modeResId,
1629                                                property.getServiceInfo().applicationInfo);
1630                                // TODO: Use more friendly Title and UI
1631                                title = label + "," + (mode == null ? "" : mode) + ","
1632                                        + (language == null ? "" : language);
1633                            }
1634                            imMap.put(title, new Pair<InputMethodInfo, Integer>(property, j));
1635                        }
1636                    }
1637                } else {
1638                    imMap.put(label,
1639                            new Pair<InputMethodInfo, Integer>(property, NOT_A_SUBTYPE_ID));
1640                    subtypeIds.add(0);
1641                }
1642            }
1643
1644            N = imMap.size();
1645            mItems = imMap.keySet().toArray(new CharSequence[N]);
1646            mIms = new InputMethodInfo[N];
1647            mSubtypeIds = new int[N];
1648            int checkedItem = 0;
1649            for (int i = 0; i < N; ++i) {
1650                Pair<InputMethodInfo, Integer> value = imMap.get(mItems[i]);
1651                mIms[i] = value.first;
1652                mSubtypeIds[i] = value.second;
1653                if (mIms[i].getId().equals(lastInputMethodId)) {
1654                    int subtypeId = mSubtypeIds[i];
1655                    if ((subtypeId == NOT_A_SUBTYPE_ID)
1656                            || (lastInputMethodSubtypeId == NOT_A_SUBTYPE_ID && subtypeId == 0)
1657                            || (subtypeId == lastInputMethodSubtypeId)) {
1658                        checkedItem = i;
1659                    }
1660                }
1661            }
1662
1663            AlertDialog.OnClickListener adocl = new AlertDialog.OnClickListener() {
1664                public void onClick(DialogInterface dialog, int which) {
1665                    hideInputMethodMenu();
1666                }
1667            };
1668
1669            TypedArray a = context.obtainStyledAttributes(null,
1670                    com.android.internal.R.styleable.DialogPreference,
1671                    com.android.internal.R.attr.alertDialogStyle, 0);
1672            mDialogBuilder = new AlertDialog.Builder(context)
1673                    .setTitle(com.android.internal.R.string.select_input_method)
1674                    .setOnCancelListener(new OnCancelListener() {
1675                        public void onCancel(DialogInterface dialog) {
1676                            hideInputMethodMenu();
1677                        }
1678                    })
1679                    .setIcon(a.getDrawable(
1680                            com.android.internal.R.styleable.DialogPreference_dialogTitle));
1681            a.recycle();
1682
1683            mDialogBuilder.setSingleChoiceItems(mItems, checkedItem,
1684                    new AlertDialog.OnClickListener() {
1685                        public void onClick(DialogInterface dialog, int which) {
1686                            synchronized (mMethodMap) {
1687                                if (mIms == null || mIms.length <= which
1688                                        || mSubtypeIds == null || mSubtypeIds.length <= which) {
1689                                    return;
1690                                }
1691                                InputMethodInfo im = mIms[which];
1692                                int subtypeId = mSubtypeIds[which];
1693                                hideInputMethodMenu();
1694                                if (im != null) {
1695                                    if ((subtypeId < 0)
1696                                            || (subtypeId >= im.getSubtypes().size())) {
1697                                        subtypeId = NOT_A_SUBTYPE_ID;
1698                                    }
1699                                    setInputMethodLocked(im.getId(), subtypeId);
1700                                }
1701                            }
1702                        }
1703                    });
1704
1705            if (showSubtypes) {
1706                mDialogBuilder.setPositiveButton(com.android.internal.R.string.more_item_label,
1707                        new DialogInterface.OnClickListener() {
1708                            public void onClick(DialogInterface dialog, int whichButton) {
1709                                showInputMethodAndSubtypeEnabler();
1710                            }
1711                        });
1712            }
1713            mDialogBuilder.setNegativeButton(com.android.internal.R.string.cancel,
1714                    new DialogInterface.OnClickListener() {
1715                        public void onClick(DialogInterface dialog, int whichButton) {
1716                            hideInputMethodMenu();
1717                        }
1718                    });
1719            mSwitchingDialog = mDialogBuilder.create();
1720            mSwitchingDialog.getWindow().setType(
1721                    WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG);
1722            mSwitchingDialog.show();
1723        }
1724    }
1725
1726    void hideInputMethodMenu() {
1727        synchronized (mMethodMap) {
1728            hideInputMethodMenuLocked();
1729        }
1730    }
1731
1732    void hideInputMethodMenuLocked() {
1733        if (DEBUG) Slog.v(TAG, "Hide switching menu");
1734
1735        if (mSwitchingDialog != null) {
1736            mSwitchingDialog.dismiss();
1737            mSwitchingDialog = null;
1738        }
1739
1740        mDialogBuilder = null;
1741        mItems = null;
1742        mIms = null;
1743    }
1744
1745    // ----------------------------------------------------------------------
1746
1747    public boolean setInputMethodEnabled(String id, boolean enabled) {
1748        synchronized (mMethodMap) {
1749            if (mContext.checkCallingOrSelfPermission(
1750                    android.Manifest.permission.WRITE_SECURE_SETTINGS)
1751                    != PackageManager.PERMISSION_GRANTED) {
1752                throw new SecurityException(
1753                        "Requires permission "
1754                        + android.Manifest.permission.WRITE_SECURE_SETTINGS);
1755            }
1756
1757            long ident = Binder.clearCallingIdentity();
1758            try {
1759                return setInputMethodEnabledLocked(id, enabled);
1760            } finally {
1761                Binder.restoreCallingIdentity(ident);
1762            }
1763        }
1764    }
1765
1766    boolean setInputMethodEnabledLocked(String id, boolean enabled) {
1767        // Make sure this is a valid input method.
1768        InputMethodInfo imm = mMethodMap.get(id);
1769        if (imm == null) {
1770            throw new IllegalArgumentException("Unknown id: " + mCurMethodId);
1771        }
1772
1773        List<Pair<String, ArrayList<String>>> enabledInputMethodsList = mSettings
1774                .getEnabledInputMethodsAndSubtypeListLocked();
1775
1776        if (enabled) {
1777            for (Pair<String, ArrayList<String>> pair: enabledInputMethodsList) {
1778                if (pair.first.equals(id)) {
1779                    // We are enabling this input method, but it is already enabled.
1780                    // Nothing to do. The previous state was enabled.
1781                    return true;
1782                }
1783            }
1784            mSettings.appendAndPutEnabledInputMethodLocked(id, false);
1785            // Previous state was disabled.
1786            return false;
1787        } else {
1788            StringBuilder builder = new StringBuilder();
1789            if (mSettings.buildAndPutEnabledInputMethodsStrRemovingIdLocked(
1790                    builder, enabledInputMethodsList, id)) {
1791                // Disabled input method is currently selected, switch to another one.
1792                String selId = Settings.Secure.getString(mContext.getContentResolver(),
1793                        Settings.Secure.DEFAULT_INPUT_METHOD);
1794                if (id.equals(selId)) {
1795                    Settings.Secure.putString(
1796                            mContext.getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD,
1797                            enabledInputMethodsList.size() > 0
1798                                    ? enabledInputMethodsList.get(0).first : "");
1799                    resetSelectedInputMethodSubtype();
1800                }
1801                // Previous state was enabled.
1802                return true;
1803            } else {
1804                // We are disabling the input method but it is already disabled.
1805                // Nothing to do.  The previous state was disabled.
1806                return false;
1807            }
1808        }
1809    }
1810
1811    private void resetSelectedInputMethodSubtype() {
1812        Settings.Secure.putInt(mContext.getContentResolver(),
1813                Settings.Secure.SELECTED_INPUT_METHOD_SUBTYPE, NOT_A_SUBTYPE_ID);
1814    }
1815
1816    private boolean putSelectedInputMethodSubtype(InputMethodInfo imi, int subtypeId) {
1817        ArrayList<InputMethodSubtype> subtypes = imi.getSubtypes();
1818        if (subtypeId >= 0 && subtypeId < subtypes.size()) {
1819            Settings.Secure.putInt(mContext.getContentResolver(),
1820                    Settings.Secure.SELECTED_INPUT_METHOD_SUBTYPE,
1821                    subtypes.get(subtypeId).hashCode());
1822            return true;
1823        } else {
1824            resetSelectedInputMethodSubtype();
1825            return false;
1826        }
1827    }
1828
1829    private int getSelectedInputMethodSubtypeId(String id) {
1830        InputMethodInfo imi = mMethodMap.get(id);
1831        if (imi == null) {
1832            return NOT_A_SUBTYPE_ID;
1833        }
1834        ArrayList<InputMethodSubtype> subtypes = imi.getSubtypes();
1835        int subtypeId;
1836        try {
1837            subtypeId = Settings.Secure.getInt(mContext.getContentResolver(),
1838                    Settings.Secure.SELECTED_INPUT_METHOD_SUBTYPE);
1839        } catch (SettingNotFoundException e) {
1840            return NOT_A_SUBTYPE_ID;
1841        }
1842        for (int i = 0; i < subtypes.size(); ++i) {
1843            InputMethodSubtype ims = subtypes.get(i);
1844            if (subtypeId == ims.hashCode()) {
1845                return i;
1846            }
1847        }
1848        return NOT_A_SUBTYPE_ID;
1849    }
1850
1851    /**
1852     * @return Return the current subtype of this input method.
1853     */
1854    public InputMethodSubtype getCurrentInputMethodSubtype() {
1855        return mCurrentSubtype;
1856    }
1857
1858    /**
1859     * Utility class for putting and getting settings for InputMethod
1860     * TODO: Move all putters and getters of settings to this class.
1861     */
1862    private static class InputMethodSettings {
1863        // The string for enabled input method is saved as follows:
1864        // example: ("ime0;subtype0;subtype1;subtype2:ime1:ime2;subtype0")
1865        private static final char INPUT_METHOD_SEPARATER = ':';
1866        private static final char INPUT_METHOD_SUBTYPE_SEPARATER = ';';
1867        private final TextUtils.SimpleStringSplitter mStringColonSplitter =
1868                new TextUtils.SimpleStringSplitter(INPUT_METHOD_SEPARATER);
1869
1870        private final TextUtils.SimpleStringSplitter mStringSemiColonSplitter =
1871                new TextUtils.SimpleStringSplitter(INPUT_METHOD_SUBTYPE_SEPARATER);
1872
1873        private final ContentResolver mResolver;
1874        private final HashMap<String, InputMethodInfo> mMethodMap;
1875        private final ArrayList<InputMethodInfo> mMethodList;
1876
1877        private String mEnabledInputMethodsStrCache;
1878
1879        private static void buildEnabledInputMethodsSettingString(
1880                StringBuilder builder, Pair<String, ArrayList<String>> pair) {
1881            String id = pair.first;
1882            ArrayList<String> subtypes = pair.second;
1883            builder.append(id);
1884            if (subtypes.size() > 0) {
1885                builder.append(subtypes.get(0));
1886                for (int i = 1; i < subtypes.size(); ++i) {
1887                    builder.append(INPUT_METHOD_SUBTYPE_SEPARATER).append(subtypes.get(i));
1888                }
1889            }
1890        }
1891
1892        public InputMethodSettings(
1893                ContentResolver resolver, HashMap<String, InputMethodInfo> methodMap,
1894                ArrayList<InputMethodInfo> methodList) {
1895            mResolver = resolver;
1896            mMethodMap = methodMap;
1897            mMethodList = methodList;
1898        }
1899
1900        public List<InputMethodInfo> getEnabledInputMethodListLocked() {
1901            return createEnabledInputMethodListLocked(
1902                    getEnabledInputMethodsAndSubtypeListLocked());
1903        }
1904
1905        public List<Pair<InputMethodInfo, ArrayList<String>>>
1906                getEnabledInputMethodAndSubtypeListLocked() {
1907            return createEnabledInputMethodAndSubtypeListLocked(
1908                    getEnabledInputMethodsAndSubtypeListLocked());
1909        }
1910
1911        // At the initial boot, the settings for input methods are not set,
1912        // so we need to enable IME in that case.
1913        public void enableAllIMEsIfThereIsNoEnabledIME() {
1914            if (TextUtils.isEmpty(getEnabledInputMethodsStr())) {
1915                StringBuilder sb = new StringBuilder();
1916                final int N = mMethodList.size();
1917                for (int i = 0; i < N; i++) {
1918                    InputMethodInfo imi = mMethodList.get(i);
1919                    Slog.i(TAG, "Adding: " + imi.getId());
1920                    if (i > 0) sb.append(':');
1921                    sb.append(imi.getId());
1922                }
1923                putEnabledInputMethodsStr(sb.toString());
1924            }
1925        }
1926
1927        public List<Pair<String, ArrayList<String>>> getEnabledInputMethodsAndSubtypeListLocked() {
1928            ArrayList<Pair<String, ArrayList<String>>> imsList
1929                    = new ArrayList<Pair<String, ArrayList<String>>>();
1930            final String enabledInputMethodsStr = getEnabledInputMethodsStr();
1931            if (TextUtils.isEmpty(enabledInputMethodsStr)) {
1932                return imsList;
1933            }
1934            mStringColonSplitter.setString(enabledInputMethodsStr);
1935            while (mStringColonSplitter.hasNext()) {
1936                String nextImsStr = mStringColonSplitter.next();
1937                mStringSemiColonSplitter.setString(nextImsStr);
1938                if (mStringSemiColonSplitter.hasNext()) {
1939                    ArrayList<String> subtypeHashes = new ArrayList<String>();
1940                    // The first element is ime id.
1941                    String imeId = mStringSemiColonSplitter.next();
1942                    while (mStringSemiColonSplitter.hasNext()) {
1943                        subtypeHashes.add(mStringSemiColonSplitter.next());
1944                    }
1945                    imsList.add(new Pair<String, ArrayList<String>>(imeId, subtypeHashes));
1946                }
1947            }
1948            return imsList;
1949        }
1950
1951        public void appendAndPutEnabledInputMethodLocked(String id, boolean reloadInputMethodStr) {
1952            if (reloadInputMethodStr) {
1953                getEnabledInputMethodsStr();
1954            }
1955            if (TextUtils.isEmpty(mEnabledInputMethodsStrCache)) {
1956                // Add in the newly enabled input method.
1957                putEnabledInputMethodsStr(id);
1958            } else {
1959                putEnabledInputMethodsStr(
1960                        mEnabledInputMethodsStrCache + INPUT_METHOD_SEPARATER + id);
1961            }
1962        }
1963
1964        /**
1965         * Build and put a string of EnabledInputMethods with removing specified Id.
1966         * @return the specified id was removed or not.
1967         */
1968        public boolean buildAndPutEnabledInputMethodsStrRemovingIdLocked(
1969                StringBuilder builder, List<Pair<String, ArrayList<String>>> imsList, String id) {
1970            boolean isRemoved = false;
1971            boolean needsAppendSeparator = false;
1972            for (Pair<String, ArrayList<String>> ims: imsList) {
1973                String curId = ims.first;
1974                if (curId.equals(id)) {
1975                    // We are disabling this input method, and it is
1976                    // currently enabled.  Skip it to remove from the
1977                    // new list.
1978                    isRemoved = true;
1979                } else {
1980                    if (needsAppendSeparator) {
1981                        builder.append(INPUT_METHOD_SEPARATER);
1982                    } else {
1983                        needsAppendSeparator = true;
1984                    }
1985                    buildEnabledInputMethodsSettingString(builder, ims);
1986                }
1987            }
1988            if (isRemoved) {
1989                // Update the setting with the new list of input methods.
1990                putEnabledInputMethodsStr(builder.toString());
1991            }
1992            return isRemoved;
1993        }
1994
1995        private List<InputMethodInfo> createEnabledInputMethodListLocked(
1996                List<Pair<String, ArrayList<String>>> imsList) {
1997            final ArrayList<InputMethodInfo> res = new ArrayList<InputMethodInfo>();
1998            for (Pair<String, ArrayList<String>> ims: imsList) {
1999                InputMethodInfo info = mMethodMap.get(ims.first);
2000                if (info != null) {
2001                    res.add(info);
2002                }
2003            }
2004            return res;
2005        }
2006
2007        private List<Pair<InputMethodInfo, ArrayList<String>>>
2008                createEnabledInputMethodAndSubtypeListLocked(
2009                        List<Pair<String, ArrayList<String>>> imsList) {
2010            final ArrayList<Pair<InputMethodInfo, ArrayList<String>>> res
2011                    = new ArrayList<Pair<InputMethodInfo, ArrayList<String>>>();
2012            for (Pair<String, ArrayList<String>> ims : imsList) {
2013                InputMethodInfo info = mMethodMap.get(ims.first);
2014                if (info != null) {
2015                    res.add(new Pair<InputMethodInfo, ArrayList<String>>(info, ims.second));
2016                }
2017            }
2018            return res;
2019        }
2020
2021        private void putEnabledInputMethodsStr(String str) {
2022            Settings.Secure.putString(mResolver, Settings.Secure.ENABLED_INPUT_METHODS, str);
2023            mEnabledInputMethodsStrCache = str;
2024        }
2025
2026        private String getEnabledInputMethodsStr() {
2027            mEnabledInputMethodsStrCache = Settings.Secure.getString(
2028                    mResolver, Settings.Secure.ENABLED_INPUT_METHODS);
2029            return mEnabledInputMethodsStrCache;
2030        }
2031    }
2032
2033    // ----------------------------------------------------------------------
2034
2035    @Override
2036    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2037        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2038                != PackageManager.PERMISSION_GRANTED) {
2039
2040            pw.println("Permission Denial: can't dump InputMethodManager from from pid="
2041                    + Binder.getCallingPid()
2042                    + ", uid=" + Binder.getCallingUid());
2043            return;
2044        }
2045
2046        IInputMethod method;
2047        ClientState client;
2048
2049        final Printer p = new PrintWriterPrinter(pw);
2050
2051        synchronized (mMethodMap) {
2052            p.println("Current Input Method Manager state:");
2053            int N = mMethodList.size();
2054            p.println("  Input Methods:");
2055            for (int i=0; i<N; i++) {
2056                InputMethodInfo info = mMethodList.get(i);
2057                p.println("  InputMethod #" + i + ":");
2058                info.dump(p, "    ");
2059            }
2060            p.println("  Clients:");
2061            for (ClientState ci : mClients.values()) {
2062                p.println("  Client " + ci + ":");
2063                p.println("    client=" + ci.client);
2064                p.println("    inputContext=" + ci.inputContext);
2065                p.println("    sessionRequested=" + ci.sessionRequested);
2066                p.println("    curSession=" + ci.curSession);
2067            }
2068            p.println("  mCurMethodId=" + mCurMethodId);
2069            client = mCurClient;
2070            p.println("  mCurClient=" + client + " mCurSeq=" + mCurSeq);
2071            p.println("  mCurFocusedWindow=" + mCurFocusedWindow);
2072            p.println("  mCurId=" + mCurId + " mHaveConnect=" + mHaveConnection
2073                    + " mBoundToMethod=" + mBoundToMethod);
2074            p.println("  mCurToken=" + mCurToken);
2075            p.println("  mCurIntent=" + mCurIntent);
2076            method = mCurMethod;
2077            p.println("  mCurMethod=" + mCurMethod);
2078            p.println("  mEnabledSession=" + mEnabledSession);
2079            p.println("  mShowRequested=" + mShowRequested
2080                    + " mShowExplicitlyRequested=" + mShowExplicitlyRequested
2081                    + " mShowForced=" + mShowForced
2082                    + " mInputShown=" + mInputShown);
2083            p.println("  mSystemReady=" + mSystemReady + " mScreenOn=" + mScreenOn);
2084        }
2085
2086        p.println(" ");
2087        if (client != null) {
2088            pw.flush();
2089            try {
2090                client.client.asBinder().dump(fd, args);
2091            } catch (RemoteException e) {
2092                p.println("Input method client dead: " + e);
2093            }
2094        } else {
2095            p.println("No input method client.");
2096        }
2097
2098        p.println(" ");
2099        if (method != null) {
2100            pw.flush();
2101            try {
2102                method.asBinder().dump(fd, args);
2103            } catch (RemoteException e) {
2104                p.println("Input method service dead: " + e);
2105            }
2106        } else {
2107            p.println("No input method service.");
2108        }
2109    }
2110}
2111