InputMethodManagerService.java revision 97106ab5af0fdba00d6dbda4767b953e0a5829f4
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.status.IconData;
30import com.android.server.status.StatusBarService;
31
32import org.xmlpull.v1.XmlPullParserException;
33
34import android.app.ActivityManagerNative;
35import android.app.AlertDialog;
36import android.app.PendingIntent;
37import android.content.ComponentName;
38import android.content.ContentResolver;
39import android.content.Context;
40import android.content.DialogInterface;
41import android.content.IntentFilter;
42import android.content.DialogInterface.OnCancelListener;
43import android.content.Intent;
44import android.content.ServiceConnection;
45import android.content.pm.ApplicationInfo;
46import android.content.pm.PackageManager;
47import android.content.pm.ResolveInfo;
48import android.content.pm.ServiceInfo;
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.text.TextUtils;
64import android.util.EventLog;
65import android.util.Slog;
66import android.util.PrintWriterPrinter;
67import android.util.Printer;
68import android.view.IWindowManager;
69import android.view.WindowManager;
70import android.view.inputmethod.InputBinding;
71import android.view.inputmethod.InputMethod;
72import android.view.inputmethod.InputMethodInfo;
73import android.view.inputmethod.InputMethodManager;
74import android.view.inputmethod.EditorInfo;
75
76import java.io.FileDescriptor;
77import java.io.IOException;
78import java.io.PrintWriter;
79import java.util.ArrayList;
80import java.util.HashMap;
81import java.util.List;
82
83/**
84 * This class provides a system service that manages input methods.
85 */
86public class InputMethodManagerService extends IInputMethodManager.Stub
87        implements ServiceConnection, Handler.Callback {
88    static final boolean DEBUG = false;
89    static final String TAG = "InputManagerService";
90
91    static final int MSG_SHOW_IM_PICKER = 1;
92
93    static final int MSG_UNBIND_INPUT = 1000;
94    static final int MSG_BIND_INPUT = 1010;
95    static final int MSG_SHOW_SOFT_INPUT = 1020;
96    static final int MSG_HIDE_SOFT_INPUT = 1030;
97    static final int MSG_ATTACH_TOKEN = 1040;
98    static final int MSG_CREATE_SESSION = 1050;
99
100    static final int MSG_START_INPUT = 2000;
101    static final int MSG_RESTART_INPUT = 2010;
102
103    static final int MSG_UNBIND_METHOD = 3000;
104    static final int MSG_BIND_METHOD = 3010;
105
106    static final long TIME_TO_RECONNECT = 10*1000;
107
108    final Context mContext;
109    final Handler mHandler;
110    final SettingsObserver mSettingsObserver;
111    final StatusBarService mStatusBar;
112    final IBinder mInputMethodIcon;
113    final IconData mInputMethodData;
114    final IWindowManager mIWindowManager;
115    final HandlerCaller mCaller;
116
117    final InputBindResult mNoBinding = new InputBindResult(null, null, -1);
118
119    // All known input methods.  mMethodMap also serves as the global
120    // lock for this class.
121    final ArrayList<InputMethodInfo> mMethodList
122            = new ArrayList<InputMethodInfo>();
123    final HashMap<String, InputMethodInfo> mMethodMap
124            = new HashMap<String, InputMethodInfo>();
125
126    final TextUtils.SimpleStringSplitter mStringColonSplitter
127            = new TextUtils.SimpleStringSplitter(':');
128
129    class SessionState {
130        final ClientState client;
131        final IInputMethod method;
132        final IInputMethodSession session;
133
134        @Override
135        public String toString() {
136            return "SessionState{uid " + client.uid + " pid " + client.pid
137                    + " method " + Integer.toHexString(
138                            System.identityHashCode(method))
139                    + " session " + Integer.toHexString(
140                            System.identityHashCode(session))
141                    + "}";
142        }
143
144        SessionState(ClientState _client, IInputMethod _method,
145                IInputMethodSession _session) {
146            client = _client;
147            method = _method;
148            session = _session;
149        }
150    }
151
152    class ClientState {
153        final IInputMethodClient client;
154        final IInputContext inputContext;
155        final int uid;
156        final int pid;
157        final InputBinding binding;
158
159        boolean sessionRequested;
160        SessionState curSession;
161
162        @Override
163        public String toString() {
164            return "ClientState{" + Integer.toHexString(
165                    System.identityHashCode(this)) + " uid " + uid
166                    + " pid " + pid + "}";
167        }
168
169        ClientState(IInputMethodClient _client, IInputContext _inputContext,
170                int _uid, int _pid) {
171            client = _client;
172            inputContext = _inputContext;
173            uid = _uid;
174            pid = _pid;
175            binding = new InputBinding(null, inputContext.asBinder(), uid, pid);
176        }
177    }
178
179    final HashMap<IBinder, ClientState> mClients
180            = new HashMap<IBinder, ClientState>();
181
182    /**
183     * Set once the system is ready to run third party code.
184     */
185    boolean mSystemReady;
186
187    /**
188     * Id of the currently selected input method.
189     */
190    String mCurMethodId;
191
192    /**
193     * The current binding sequence number, incremented every time there is
194     * a new bind performed.
195     */
196    int mCurSeq;
197
198    /**
199     * The client that is currently bound to an input method.
200     */
201    ClientState mCurClient;
202
203    /**
204     * The last window token that gained focus.
205     */
206    IBinder mCurFocusedWindow;
207
208    /**
209     * The input context last provided by the current client.
210     */
211    IInputContext mCurInputContext;
212
213    /**
214     * The attributes last provided by the current client.
215     */
216    EditorInfo mCurAttribute;
217
218    /**
219     * The input method ID of the input method service that we are currently
220     * connected to or in the process of connecting to.
221     */
222    String mCurId;
223
224    /**
225     * Set to true if our ServiceConnection is currently actively bound to
226     * a service (whether or not we have gotten its IBinder back yet).
227     */
228    boolean mHaveConnection;
229
230    /**
231     * Set if the client has asked for the input method to be shown.
232     */
233    boolean mShowRequested;
234
235    /**
236     * Set if we were explicitly told to show the input method.
237     */
238    boolean mShowExplicitlyRequested;
239
240    /**
241     * Set if we were forced to be shown.
242     */
243    boolean mShowForced;
244
245    /**
246     * Set if we last told the input method to show itself.
247     */
248    boolean mInputShown;
249
250    /**
251     * The Intent used to connect to the current input method.
252     */
253    Intent mCurIntent;
254
255    /**
256     * The token we have made for the currently active input method, to
257     * identify it in the future.
258     */
259    IBinder mCurToken;
260
261    /**
262     * If non-null, this is the input method service we are currently connected
263     * to.
264     */
265    IInputMethod mCurMethod;
266
267    /**
268     * Time that we last initiated a bind to the input method, to determine
269     * if we should try to disconnect and reconnect to it.
270     */
271    long mLastBindTime;
272
273    /**
274     * Have we called mCurMethod.bindInput()?
275     */
276    boolean mBoundToMethod;
277
278    /**
279     * Currently enabled session.  Only touched by service thread, not
280     * protected by a lock.
281     */
282    SessionState mEnabledSession;
283
284    /**
285     * True if the screen is on.  The value is true initially.
286     */
287    boolean mScreenOn = true;
288
289    AlertDialog.Builder mDialogBuilder;
290    AlertDialog mSwitchingDialog;
291    InputMethodInfo[] mIms;
292    CharSequence[] mItems;
293
294    class SettingsObserver extends ContentObserver {
295        SettingsObserver(Handler handler) {
296            super(handler);
297            ContentResolver resolver = mContext.getContentResolver();
298            resolver.registerContentObserver(Settings.Secure.getUriFor(
299                    Settings.Secure.DEFAULT_INPUT_METHOD), false, this);
300        }
301
302        @Override public void onChange(boolean selfChange) {
303            synchronized (mMethodMap) {
304                updateFromSettingsLocked();
305            }
306        }
307    }
308
309    class ScreenOnOffReceiver extends android.content.BroadcastReceiver {
310        @Override
311        public void onReceive(Context context, Intent intent) {
312            if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
313                mScreenOn = true;
314            } else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
315                mScreenOn = false;
316            } else if (intent.getAction().equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
317                hideInputMethodMenu();
318                return;
319            } else {
320                Slog.w(TAG, "Unexpected intent " + intent);
321            }
322
323            // Inform the current client of the change in active status
324            try {
325                if (mCurClient != null && mCurClient.client != null) {
326                    mCurClient.client.setActive(mScreenOn);
327                }
328            } catch (RemoteException e) {
329                Slog.w(TAG, "Got RemoteException sending 'screen on/off' notification to pid "
330                        + mCurClient.pid + " uid " + mCurClient.uid);
331            }
332        }
333    }
334
335    class MyPackageMonitor extends PackageMonitor {
336
337        @Override
338        public boolean onHandleForceStop(Intent intent, String[] packages, int uid, boolean doit) {
339            synchronized (mMethodMap) {
340                String curInputMethodId = Settings.Secure.getString(mContext
341                        .getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);
342                final int N = mMethodList.size();
343                if (curInputMethodId != null) {
344                    for (int i=0; i<N; i++) {
345                        InputMethodInfo imi = mMethodList.get(i);
346                        if (imi.getId().equals(curInputMethodId)) {
347                            for (String pkg : packages) {
348                                if (imi.getPackageName().equals(pkg)) {
349                                    if (!doit) {
350                                        return true;
351                                    }
352
353                                    Settings.Secure.putString(mContext.getContentResolver(),
354                                            Settings.Secure.DEFAULT_INPUT_METHOD, "");
355                                    chooseNewDefaultIMELocked();
356                                    return true;
357                                }
358                            }
359                        }
360                    }
361                }
362            }
363            return false;
364        }
365
366        @Override
367        public void onSomePackagesChanged() {
368            synchronized (mMethodMap) {
369                InputMethodInfo curIm = null;
370                String curInputMethodId = Settings.Secure.getString(mContext
371                        .getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);
372                final int N = mMethodList.size();
373                if (curInputMethodId != null) {
374                    for (int i=0; i<N; i++) {
375                        InputMethodInfo imi = mMethodList.get(i);
376                        if (imi.getId().equals(curInputMethodId)) {
377                            curIm = imi;
378                        }
379                        int change = isPackageDisappearing(imi.getPackageName());
380                        if (change == PACKAGE_TEMPORARY_CHANGE
381                                || change == PACKAGE_PERMANENT_CHANGE) {
382                            Slog.i(TAG, "Input method uninstalled, disabling: "
383                                    + imi.getComponent());
384                            setInputMethodEnabledLocked(imi.getId(), false);
385                        }
386                    }
387                }
388
389                buildInputMethodListLocked(mMethodList, mMethodMap);
390
391                boolean changed = false;
392
393                if (curIm != null) {
394                    int change = isPackageDisappearing(curIm.getPackageName());
395                    if (change == PACKAGE_TEMPORARY_CHANGE
396                            || change == PACKAGE_PERMANENT_CHANGE) {
397                        ServiceInfo si = null;
398                        try {
399                            si = mContext.getPackageManager().getServiceInfo(
400                                    curIm.getComponent(), 0);
401                        } catch (PackageManager.NameNotFoundException ex) {
402                        }
403                        if (si == null) {
404                            // Uh oh, current input method is no longer around!
405                            // Pick another one...
406                            Slog.i(TAG, "Current input method removed: " + curInputMethodId);
407                            if (!chooseNewDefaultIMELocked()) {
408                                changed = true;
409                                curIm = null;
410                                curInputMethodId = "";
411                                Slog.i(TAG, "Unsetting current input method");
412                                Settings.Secure.putString(mContext.getContentResolver(),
413                                        Settings.Secure.DEFAULT_INPUT_METHOD,
414                                        curInputMethodId);
415                            }
416                        }
417                    }
418                }
419
420                if (curIm == null) {
421                    // We currently don't have a default input method... is
422                    // one now available?
423                    changed = chooseNewDefaultIMELocked();
424                }
425
426                if (changed) {
427                    updateFromSettingsLocked();
428                }
429            }
430        }
431    }
432
433    class MethodCallback extends IInputMethodCallback.Stub {
434        final IInputMethod mMethod;
435
436        MethodCallback(IInputMethod method) {
437            mMethod = method;
438        }
439
440        public void finishedEvent(int seq, boolean handled) throws RemoteException {
441        }
442
443        public void sessionCreated(IInputMethodSession session) throws RemoteException {
444            onSessionCreated(mMethod, session);
445        }
446    }
447
448    public InputMethodManagerService(Context context, StatusBarService statusBar) {
449        mContext = context;
450        mHandler = new Handler(this);
451        mIWindowManager = IWindowManager.Stub.asInterface(
452                ServiceManager.getService(Context.WINDOW_SERVICE));
453        mCaller = new HandlerCaller(context, new HandlerCaller.Callback() {
454            public void executeMessage(Message msg) {
455                handleMessage(msg);
456            }
457        });
458
459        (new MyPackageMonitor()).register(mContext, true);
460
461        IntentFilter screenOnOffFilt = new IntentFilter();
462        screenOnOffFilt.addAction(Intent.ACTION_SCREEN_ON);
463        screenOnOffFilt.addAction(Intent.ACTION_SCREEN_OFF);
464        screenOnOffFilt.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
465        mContext.registerReceiver(new ScreenOnOffReceiver(), screenOnOffFilt);
466
467        buildInputMethodListLocked(mMethodList, mMethodMap);
468
469        final String enabledStr = Settings.Secure.getString(
470                mContext.getContentResolver(),
471                Settings.Secure.ENABLED_INPUT_METHODS);
472        Slog.i(TAG, "Enabled input methods: " + enabledStr);
473        if (enabledStr == null) {
474            Slog.i(TAG, "Enabled input methods has not been set, enabling all");
475            InputMethodInfo defIm = null;
476            StringBuilder sb = new StringBuilder(256);
477            final int N = mMethodList.size();
478            for (int i=0; i<N; i++) {
479                InputMethodInfo imi = mMethodList.get(i);
480                Slog.i(TAG, "Adding: " + imi.getId());
481                if (i > 0) sb.append(':');
482                sb.append(imi.getId());
483                if (defIm == null && imi.getIsDefaultResourceId() != 0) {
484                    try {
485                        Resources res = mContext.createPackageContext(
486                                imi.getPackageName(), 0).getResources();
487                        if (res.getBoolean(imi.getIsDefaultResourceId())) {
488                            defIm = imi;
489                            Slog.i(TAG, "Selected default: " + imi.getId());
490                        }
491                    } catch (PackageManager.NameNotFoundException ex) {
492                    } catch (Resources.NotFoundException ex) {
493                    }
494                }
495            }
496            if (defIm == null && N > 0) {
497                defIm = mMethodList.get(0);
498                Slog.i(TAG, "No default found, using " + defIm.getId());
499            }
500            Settings.Secure.putString(mContext.getContentResolver(),
501                    Settings.Secure.ENABLED_INPUT_METHODS, sb.toString());
502            if (defIm != null) {
503                Settings.Secure.putString(mContext.getContentResolver(),
504                        Settings.Secure.DEFAULT_INPUT_METHOD, defIm.getId());
505            }
506        }
507
508        mStatusBar = statusBar;
509        mInputMethodData = IconData.makeIcon("ime", null, 0, 0, 0);
510        mInputMethodIcon = statusBar.addIcon(mInputMethodData, null);
511        statusBar.setIconVisibility(mInputMethodIcon, false);
512
513        mSettingsObserver = new SettingsObserver(mHandler);
514        updateFromSettingsLocked();
515    }
516
517    @Override
518    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
519            throws RemoteException {
520        try {
521            return super.onTransact(code, data, reply, flags);
522        } catch (RuntimeException e) {
523            // The input method manager only throws security exceptions, so let's
524            // log all others.
525            if (!(e instanceof SecurityException)) {
526                Slog.e(TAG, "Input Method Manager Crash", e);
527            }
528            throw e;
529        }
530    }
531
532    public void systemReady() {
533        synchronized (mMethodMap) {
534            if (!mSystemReady) {
535                mSystemReady = true;
536                try {
537                    startInputInnerLocked();
538                } catch (RuntimeException e) {
539                    Slog.w(TAG, "Unexpected exception", e);
540                }
541            }
542        }
543    }
544
545    public List<InputMethodInfo> getInputMethodList() {
546        synchronized (mMethodMap) {
547            return new ArrayList<InputMethodInfo>(mMethodList);
548        }
549    }
550
551    public List<InputMethodInfo> getEnabledInputMethodList() {
552        synchronized (mMethodMap) {
553            return getEnabledInputMethodListLocked();
554        }
555    }
556
557    List<InputMethodInfo> getEnabledInputMethodListLocked() {
558        final ArrayList<InputMethodInfo> res = new ArrayList<InputMethodInfo>();
559
560        final String enabledStr = Settings.Secure.getString(
561                mContext.getContentResolver(),
562                Settings.Secure.ENABLED_INPUT_METHODS);
563        if (enabledStr != null) {
564            final TextUtils.SimpleStringSplitter splitter = mStringColonSplitter;
565            splitter.setString(enabledStr);
566
567            while (splitter.hasNext()) {
568                InputMethodInfo info = mMethodMap.get(splitter.next());
569                if (info != null) {
570                    res.add(info);
571                }
572            }
573        }
574
575        return res;
576    }
577
578    public void addClient(IInputMethodClient client,
579            IInputContext inputContext, int uid, int pid) {
580        synchronized (mMethodMap) {
581            mClients.put(client.asBinder(), new ClientState(client,
582                    inputContext, uid, pid));
583        }
584    }
585
586    public void removeClient(IInputMethodClient client) {
587        synchronized (mMethodMap) {
588            mClients.remove(client.asBinder());
589        }
590    }
591
592    void executeOrSendMessage(IInterface target, Message msg) {
593         if (target.asBinder() instanceof Binder) {
594             mCaller.sendMessage(msg);
595         } else {
596             handleMessage(msg);
597             msg.recycle();
598         }
599    }
600
601    void unbindCurrentClientLocked() {
602        if (mCurClient != null) {
603            if (DEBUG) Slog.v(TAG, "unbindCurrentInputLocked: client = "
604                    + mCurClient.client.asBinder());
605            if (mBoundToMethod) {
606                mBoundToMethod = false;
607                if (mCurMethod != null) {
608                    executeOrSendMessage(mCurMethod, mCaller.obtainMessageO(
609                            MSG_UNBIND_INPUT, mCurMethod));
610                }
611            }
612            executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
613                    MSG_UNBIND_METHOD, mCurSeq, mCurClient.client));
614            mCurClient.sessionRequested = false;
615
616            // Call setActive(false) on the old client
617            try {
618                mCurClient.client.setActive(false);
619            } catch (RemoteException e) {
620                Slog.w(TAG, "Got RemoteException sending setActive(false) notification to pid "
621                        + mCurClient.pid + " uid " + mCurClient.uid);
622            }
623            mCurClient = null;
624
625            hideInputMethodMenuLocked();
626        }
627    }
628
629    private int getImeShowFlags() {
630        int flags = 0;
631        if (mShowForced) {
632            flags |= InputMethod.SHOW_FORCED
633                    | InputMethod.SHOW_EXPLICIT;
634        } else if (mShowExplicitlyRequested) {
635            flags |= InputMethod.SHOW_EXPLICIT;
636        }
637        return flags;
638    }
639
640    private int getAppShowFlags() {
641        int flags = 0;
642        if (mShowForced) {
643            flags |= InputMethodManager.SHOW_FORCED;
644        } else if (!mShowExplicitlyRequested) {
645            flags |= InputMethodManager.SHOW_IMPLICIT;
646        }
647        return flags;
648    }
649
650    InputBindResult attachNewInputLocked(boolean initial, boolean needResult) {
651        if (!mBoundToMethod) {
652            executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
653                    MSG_BIND_INPUT, mCurMethod, mCurClient.binding));
654            mBoundToMethod = true;
655        }
656        final SessionState session = mCurClient.curSession;
657        if (initial) {
658            executeOrSendMessage(session.method, mCaller.obtainMessageOOO(
659                    MSG_START_INPUT, session, mCurInputContext, mCurAttribute));
660        } else {
661            executeOrSendMessage(session.method, mCaller.obtainMessageOOO(
662                    MSG_RESTART_INPUT, session, mCurInputContext, mCurAttribute));
663        }
664        if (mShowRequested) {
665            if (DEBUG) Slog.v(TAG, "Attach new input asks to show input");
666            showCurrentInputLocked(getAppShowFlags(), null);
667        }
668        return needResult
669                ? new InputBindResult(session.session, mCurId, mCurSeq)
670                : null;
671    }
672
673    InputBindResult startInputLocked(IInputMethodClient client,
674            IInputContext inputContext, EditorInfo attribute,
675            boolean initial, boolean needResult) {
676        // If no method is currently selected, do nothing.
677        if (mCurMethodId == null) {
678            return mNoBinding;
679        }
680
681        ClientState cs = mClients.get(client.asBinder());
682        if (cs == null) {
683            throw new IllegalArgumentException("unknown client "
684                    + client.asBinder());
685        }
686
687        try {
688            if (!mIWindowManager.inputMethodClientHasFocus(cs.client)) {
689                // Check with the window manager to make sure this client actually
690                // has a window with focus.  If not, reject.  This is thread safe
691                // because if the focus changes some time before or after, the
692                // next client receiving focus that has any interest in input will
693                // be calling through here after that change happens.
694                Slog.w(TAG, "Starting input on non-focused client " + cs.client
695                        + " (uid=" + cs.uid + " pid=" + cs.pid + ")");
696                return null;
697            }
698        } catch (RemoteException e) {
699        }
700
701        if (mCurClient != cs) {
702            // If the client is changing, we need to switch over to the new
703            // one.
704            unbindCurrentClientLocked();
705            if (DEBUG) Slog.v(TAG, "switching to client: client = "
706                    + cs.client.asBinder());
707
708            // If the screen is on, inform the new client it is active
709            if (mScreenOn) {
710                try {
711                    cs.client.setActive(mScreenOn);
712                } catch (RemoteException e) {
713                    Slog.w(TAG, "Got RemoteException sending setActive notification to pid "
714                            + cs.pid + " uid " + cs.uid);
715                }
716            }
717        }
718
719        // Bump up the sequence for this client and attach it.
720        mCurSeq++;
721        if (mCurSeq <= 0) mCurSeq = 1;
722        mCurClient = cs;
723        mCurInputContext = inputContext;
724        mCurAttribute = attribute;
725
726        // Check if the input method is changing.
727        if (mCurId != null && mCurId.equals(mCurMethodId)) {
728            if (cs.curSession != null) {
729                // Fast case: if we are already connected to the input method,
730                // then just return it.
731                return attachNewInputLocked(initial, needResult);
732            }
733            if (mHaveConnection) {
734                if (mCurMethod != null) {
735                    if (!cs.sessionRequested) {
736                        cs.sessionRequested = true;
737                        if (DEBUG) Slog.v(TAG, "Creating new session for client " + cs);
738                        executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
739                                MSG_CREATE_SESSION, mCurMethod,
740                                new MethodCallback(mCurMethod)));
741                    }
742                    // Return to client, and we will get back with it when
743                    // we have had a session made for it.
744                    return new InputBindResult(null, mCurId, mCurSeq);
745                } else if (SystemClock.uptimeMillis()
746                        < (mLastBindTime+TIME_TO_RECONNECT)) {
747                    // In this case we have connected to the service, but
748                    // don't yet have its interface.  If it hasn't been too
749                    // long since we did the connection, we'll return to
750                    // the client and wait to get the service interface so
751                    // we can report back.  If it has been too long, we want
752                    // to fall through so we can try a disconnect/reconnect
753                    // to see if we can get back in touch with the service.
754                    return new InputBindResult(null, mCurId, mCurSeq);
755                } else {
756                    EventLog.writeEvent(EventLogTags.IMF_FORCE_RECONNECT_IME,
757                            mCurMethodId, SystemClock.uptimeMillis()-mLastBindTime, 0);
758                }
759            }
760        }
761
762        return startInputInnerLocked();
763    }
764
765    InputBindResult startInputInnerLocked() {
766        if (mCurMethodId == null) {
767            return mNoBinding;
768        }
769
770        if (!mSystemReady) {
771            // If the system is not yet ready, we shouldn't be running third
772            // party code.
773            return new InputBindResult(null, mCurMethodId, mCurSeq);
774        }
775
776        InputMethodInfo info = mMethodMap.get(mCurMethodId);
777        if (info == null) {
778            throw new IllegalArgumentException("Unknown id: " + mCurMethodId);
779        }
780
781        unbindCurrentMethodLocked(false);
782
783        mCurIntent = new Intent(InputMethod.SERVICE_INTERFACE);
784        mCurIntent.setComponent(info.getComponent());
785        mCurIntent.putExtra(Intent.EXTRA_CLIENT_LABEL,
786                com.android.internal.R.string.input_method_binding_label);
787        mCurIntent.putExtra(Intent.EXTRA_CLIENT_INTENT, PendingIntent.getActivity(
788                mContext, 0, new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS), 0));
789        if (mContext.bindService(mCurIntent, this, Context.BIND_AUTO_CREATE)) {
790            mLastBindTime = SystemClock.uptimeMillis();
791            mHaveConnection = true;
792            mCurId = info.getId();
793            mCurToken = new Binder();
794            try {
795                if (DEBUG) Slog.v(TAG, "Adding window token: " + mCurToken);
796                mIWindowManager.addWindowToken(mCurToken,
797                        WindowManager.LayoutParams.TYPE_INPUT_METHOD);
798            } catch (RemoteException e) {
799            }
800            return new InputBindResult(null, mCurId, mCurSeq);
801        } else {
802            mCurIntent = null;
803            Slog.w(TAG, "Failure connecting to input method service: "
804                    + mCurIntent);
805        }
806        return null;
807    }
808
809    public InputBindResult startInput(IInputMethodClient client,
810            IInputContext inputContext, EditorInfo attribute,
811            boolean initial, boolean needResult) {
812        synchronized (mMethodMap) {
813            final long ident = Binder.clearCallingIdentity();
814            try {
815                return startInputLocked(client, inputContext, attribute,
816                        initial, needResult);
817            } finally {
818                Binder.restoreCallingIdentity(ident);
819            }
820        }
821    }
822
823    public void finishInput(IInputMethodClient client) {
824    }
825
826    public void onServiceConnected(ComponentName name, IBinder service) {
827        synchronized (mMethodMap) {
828            if (mCurIntent != null && name.equals(mCurIntent.getComponent())) {
829                mCurMethod = IInputMethod.Stub.asInterface(service);
830                if (mCurToken == null) {
831                    Slog.w(TAG, "Service connected without a token!");
832                    unbindCurrentMethodLocked(false);
833                    return;
834                }
835                if (DEBUG) Slog.v(TAG, "Initiating attach with token: " + mCurToken);
836                executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
837                        MSG_ATTACH_TOKEN, mCurMethod, mCurToken));
838                if (mCurClient != null) {
839                    if (DEBUG) Slog.v(TAG, "Creating first session while with client "
840                            + mCurClient);
841                    executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
842                            MSG_CREATE_SESSION, mCurMethod,
843                            new MethodCallback(mCurMethod)));
844                }
845            }
846        }
847    }
848
849    void onSessionCreated(IInputMethod method, IInputMethodSession session) {
850        synchronized (mMethodMap) {
851            if (mCurMethod != null && method != null
852                    && mCurMethod.asBinder() == method.asBinder()) {
853                if (mCurClient != null) {
854                    mCurClient.curSession = new SessionState(mCurClient,
855                            method, session);
856                    mCurClient.sessionRequested = false;
857                    InputBindResult res = attachNewInputLocked(true, true);
858                    if (res.method != null) {
859                        executeOrSendMessage(mCurClient.client, mCaller.obtainMessageOO(
860                                MSG_BIND_METHOD, mCurClient.client, res));
861                    }
862                }
863            }
864        }
865    }
866
867    void unbindCurrentMethodLocked(boolean reportToClient) {
868        if (mHaveConnection) {
869            mContext.unbindService(this);
870            mHaveConnection = false;
871        }
872
873        if (mCurToken != null) {
874            try {
875                if (DEBUG) Slog.v(TAG, "Removing window token: " + mCurToken);
876                mIWindowManager.removeWindowToken(mCurToken);
877            } catch (RemoteException e) {
878            }
879            mCurToken = null;
880        }
881
882        mCurId = null;
883        clearCurMethodLocked();
884
885        if (reportToClient && mCurClient != null) {
886            executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
887                    MSG_UNBIND_METHOD, mCurSeq, mCurClient.client));
888        }
889    }
890
891    void clearCurMethodLocked() {
892        if (mCurMethod != null) {
893            for (ClientState cs : mClients.values()) {
894                cs.sessionRequested = false;
895                cs.curSession = null;
896            }
897            mCurMethod = null;
898        }
899        mStatusBar.setIconVisibility(mInputMethodIcon, false);
900    }
901
902    public void onServiceDisconnected(ComponentName name) {
903        synchronized (mMethodMap) {
904            if (DEBUG) Slog.v(TAG, "Service disconnected: " + name
905                    + " mCurIntent=" + mCurIntent);
906            if (mCurMethod != null && mCurIntent != null
907                    && name.equals(mCurIntent.getComponent())) {
908                clearCurMethodLocked();
909                // We consider this to be a new bind attempt, since the system
910                // should now try to restart the service for us.
911                mLastBindTime = SystemClock.uptimeMillis();
912                mShowRequested = mInputShown;
913                mInputShown = false;
914                if (mCurClient != null) {
915                    executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
916                            MSG_UNBIND_METHOD, mCurSeq, mCurClient.client));
917                }
918            }
919        }
920    }
921
922    public void updateStatusIcon(IBinder token, String packageName, int iconId) {
923        long ident = Binder.clearCallingIdentity();
924        try {
925            if (token == null || mCurToken != token) {
926                Slog.w(TAG, "Ignoring setInputMethod of token: " + token);
927                return;
928            }
929
930            synchronized (mMethodMap) {
931                if (iconId == 0) {
932                    if (DEBUG) Slog.d(TAG, "hide the small icon for the input method");
933                    mStatusBar.setIconVisibility(mInputMethodIcon, false);
934                } else if (packageName != null) {
935                    if (DEBUG) Slog.d(TAG, "show a small icon for the input method");
936                    mInputMethodData.iconId = iconId;
937                    mInputMethodData.iconPackage = packageName;
938                    mStatusBar.updateIcon(mInputMethodIcon, mInputMethodData, null);
939                    mStatusBar.setIconVisibility(mInputMethodIcon, true);
940                }
941            }
942        } finally {
943            Binder.restoreCallingIdentity(ident);
944        }
945    }
946
947    void updateFromSettingsLocked() {
948        // We are assuming that whoever is changing DEFAULT_INPUT_METHOD and
949        // ENABLED_INPUT_METHODS is taking care of keeping them correctly in
950        // sync, so we will never have a DEFAULT_INPUT_METHOD that is not
951        // enabled.
952        String id = Settings.Secure.getString(mContext.getContentResolver(),
953            Settings.Secure.DEFAULT_INPUT_METHOD);
954        if (id != null && id.length() > 0) {
955            try {
956                setInputMethodLocked(id);
957            } catch (IllegalArgumentException e) {
958                Slog.w(TAG, "Unknown input method from prefs: " + id, e);
959                mCurMethodId = null;
960                unbindCurrentMethodLocked(true);
961            }
962        } else {
963            // There is no longer an input method set, so stop any current one.
964            mCurMethodId = null;
965            unbindCurrentMethodLocked(true);
966        }
967    }
968
969    void setInputMethodLocked(String id) {
970        InputMethodInfo info = mMethodMap.get(id);
971        if (info == null) {
972            throw new IllegalArgumentException("Unknown id: " + mCurMethodId);
973        }
974
975        if (id.equals(mCurMethodId)) {
976            return;
977        }
978
979        final long ident = Binder.clearCallingIdentity();
980        try {
981            mCurMethodId = id;
982            Settings.Secure.putString(mContext.getContentResolver(),
983                Settings.Secure.DEFAULT_INPUT_METHOD, id);
984
985            if (ActivityManagerNative.isSystemReady()) {
986                Intent intent = new Intent(Intent.ACTION_INPUT_METHOD_CHANGED);
987                intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
988                intent.putExtra("input_method_id", id);
989                mContext.sendBroadcast(intent);
990            }
991            unbindCurrentClientLocked();
992        } finally {
993            Binder.restoreCallingIdentity(ident);
994        }
995    }
996
997    public boolean showSoftInput(IInputMethodClient client, int flags,
998            ResultReceiver resultReceiver) {
999        long ident = Binder.clearCallingIdentity();
1000        try {
1001            synchronized (mMethodMap) {
1002                if (mCurClient == null || client == null
1003                        || mCurClient.client.asBinder() != client.asBinder()) {
1004                    try {
1005                        // We need to check if this is the current client with
1006                        // focus in the window manager, to allow this call to
1007                        // be made before input is started in it.
1008                        if (!mIWindowManager.inputMethodClientHasFocus(client)) {
1009                            Slog.w(TAG, "Ignoring showSoftInput of: " + client);
1010                            return false;
1011                        }
1012                    } catch (RemoteException e) {
1013                        return false;
1014                    }
1015                }
1016
1017                if (DEBUG) Slog.v(TAG, "Client requesting input be shown");
1018                return showCurrentInputLocked(flags, resultReceiver);
1019            }
1020        } finally {
1021            Binder.restoreCallingIdentity(ident);
1022        }
1023    }
1024
1025    boolean showCurrentInputLocked(int flags, ResultReceiver resultReceiver) {
1026        mShowRequested = true;
1027        if ((flags&InputMethodManager.SHOW_IMPLICIT) == 0) {
1028            mShowExplicitlyRequested = true;
1029        }
1030        if ((flags&InputMethodManager.SHOW_FORCED) != 0) {
1031            mShowExplicitlyRequested = true;
1032            mShowForced = true;
1033        }
1034
1035        if (!mSystemReady) {
1036            return false;
1037        }
1038
1039        boolean res = false;
1040        if (mCurMethod != null) {
1041            executeOrSendMessage(mCurMethod, mCaller.obtainMessageIOO(
1042                    MSG_SHOW_SOFT_INPUT, getImeShowFlags(), mCurMethod,
1043                    resultReceiver));
1044            mInputShown = true;
1045            res = true;
1046        } else if (mHaveConnection && SystemClock.uptimeMillis()
1047                < (mLastBindTime+TIME_TO_RECONNECT)) {
1048            // The client has asked to have the input method shown, but
1049            // we have been sitting here too long with a connection to the
1050            // service and no interface received, so let's disconnect/connect
1051            // to try to prod things along.
1052            EventLog.writeEvent(EventLogTags.IMF_FORCE_RECONNECT_IME, mCurMethodId,
1053                    SystemClock.uptimeMillis()-mLastBindTime,1);
1054            mContext.unbindService(this);
1055            mContext.bindService(mCurIntent, this, Context.BIND_AUTO_CREATE);
1056        }
1057
1058        return res;
1059    }
1060
1061    public boolean hideSoftInput(IInputMethodClient client, int flags,
1062            ResultReceiver resultReceiver) {
1063        long ident = Binder.clearCallingIdentity();
1064        try {
1065            synchronized (mMethodMap) {
1066                if (mCurClient == null || client == null
1067                        || mCurClient.client.asBinder() != client.asBinder()) {
1068                    try {
1069                        // We need to check if this is the current client with
1070                        // focus in the window manager, to allow this call to
1071                        // be made before input is started in it.
1072                        if (!mIWindowManager.inputMethodClientHasFocus(client)) {
1073                            Slog.w(TAG, "Ignoring hideSoftInput of: " + client);
1074                            return false;
1075                        }
1076                    } catch (RemoteException e) {
1077                        return false;
1078                    }
1079                }
1080
1081                if (DEBUG) Slog.v(TAG, "Client requesting input be hidden");
1082                return hideCurrentInputLocked(flags, resultReceiver);
1083            }
1084        } finally {
1085            Binder.restoreCallingIdentity(ident);
1086        }
1087    }
1088
1089    boolean hideCurrentInputLocked(int flags, ResultReceiver resultReceiver) {
1090        if ((flags&InputMethodManager.HIDE_IMPLICIT_ONLY) != 0
1091                && (mShowExplicitlyRequested || mShowForced)) {
1092            if (DEBUG) Slog.v(TAG,
1093                    "Not hiding: explicit show not cancelled by non-explicit hide");
1094            return false;
1095        }
1096        if (mShowForced && (flags&InputMethodManager.HIDE_NOT_ALWAYS) != 0) {
1097            if (DEBUG) Slog.v(TAG,
1098                    "Not hiding: forced show not cancelled by not-always hide");
1099            return false;
1100        }
1101        boolean res;
1102        if (mInputShown && mCurMethod != null) {
1103            executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
1104                    MSG_HIDE_SOFT_INPUT, mCurMethod, resultReceiver));
1105            res = true;
1106        } else {
1107            res = false;
1108        }
1109        mInputShown = false;
1110        mShowRequested = false;
1111        mShowExplicitlyRequested = false;
1112        mShowForced = false;
1113        return res;
1114    }
1115
1116    public void windowGainedFocus(IInputMethodClient client, IBinder windowToken,
1117            boolean viewHasFocus, boolean isTextEditor, int softInputMode,
1118            boolean first, int windowFlags) {
1119        long ident = Binder.clearCallingIdentity();
1120        try {
1121            synchronized (mMethodMap) {
1122                if (DEBUG) Slog.v(TAG, "windowGainedFocus: " + client.asBinder()
1123                        + " viewHasFocus=" + viewHasFocus
1124                        + " isTextEditor=" + isTextEditor
1125                        + " softInputMode=#" + Integer.toHexString(softInputMode)
1126                        + " first=" + first + " flags=#"
1127                        + Integer.toHexString(windowFlags));
1128
1129                if (mCurClient == null || client == null
1130                        || mCurClient.client.asBinder() != client.asBinder()) {
1131                    try {
1132                        // We need to check if this is the current client with
1133                        // focus in the window manager, to allow this call to
1134                        // be made before input is started in it.
1135                        if (!mIWindowManager.inputMethodClientHasFocus(client)) {
1136                            Slog.w(TAG, "Client not active, ignoring focus gain of: " + client);
1137                            return;
1138                        }
1139                    } catch (RemoteException e) {
1140                    }
1141                }
1142
1143                if (mCurFocusedWindow == windowToken) {
1144                    Slog.w(TAG, "Window already focused, ignoring focus gain of: " + client);
1145                    return;
1146                }
1147                mCurFocusedWindow = windowToken;
1148
1149                switch (softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_STATE) {
1150                    case WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED:
1151                        if (!isTextEditor || (softInputMode &
1152                                WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
1153                                != WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) {
1154                            if (WindowManager.LayoutParams.mayUseInputMethod(windowFlags)) {
1155                                // There is no focus view, and this window will
1156                                // be behind any soft input window, so hide the
1157                                // soft input window if it is shown.
1158                                if (DEBUG) Slog.v(TAG, "Unspecified window will hide input");
1159                                hideCurrentInputLocked(InputMethodManager.HIDE_NOT_ALWAYS, null);
1160                            }
1161                        } else if (isTextEditor && (softInputMode &
1162                                WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
1163                                == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
1164                                && (softInputMode &
1165                                        WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) {
1166                            // There is a focus view, and we are navigating forward
1167                            // into the window, so show the input window for the user.
1168                            if (DEBUG) Slog.v(TAG, "Unspecified window will show input");
1169                            showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
1170                        }
1171                        break;
1172                    case WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED:
1173                        // Do nothing.
1174                        break;
1175                    case WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN:
1176                        if ((softInputMode &
1177                                WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) {
1178                            if (DEBUG) Slog.v(TAG, "Window asks to hide input going forward");
1179                            hideCurrentInputLocked(0, null);
1180                        }
1181                        break;
1182                    case WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN:
1183                        if (DEBUG) Slog.v(TAG, "Window asks to hide input");
1184                        hideCurrentInputLocked(0, null);
1185                        break;
1186                    case WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE:
1187                        if ((softInputMode &
1188                                WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) {
1189                            if (DEBUG) Slog.v(TAG, "Window asks to show input going forward");
1190                            showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
1191                        }
1192                        break;
1193                    case WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE:
1194                        if (DEBUG) Slog.v(TAG, "Window asks to always show input");
1195                        showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
1196                        break;
1197                }
1198            }
1199        } finally {
1200            Binder.restoreCallingIdentity(ident);
1201        }
1202    }
1203
1204    public void showInputMethodPickerFromClient(IInputMethodClient client) {
1205        synchronized (mMethodMap) {
1206            if (mCurClient == null || client == null
1207                    || mCurClient.client.asBinder() != client.asBinder()) {
1208                Slog.w(TAG, "Ignoring showInputMethodDialogFromClient of: " + client);
1209            }
1210
1211            mHandler.sendEmptyMessage(MSG_SHOW_IM_PICKER);
1212        }
1213    }
1214
1215    public void setInputMethod(IBinder token, String id) {
1216        synchronized (mMethodMap) {
1217            if (token == null) {
1218                if (mContext.checkCallingOrSelfPermission(
1219                        android.Manifest.permission.WRITE_SECURE_SETTINGS)
1220                        != PackageManager.PERMISSION_GRANTED) {
1221                    throw new SecurityException(
1222                            "Using null token requires permission "
1223                            + android.Manifest.permission.WRITE_SECURE_SETTINGS);
1224                }
1225            } else if (mCurToken != token) {
1226                Slog.w(TAG, "Ignoring setInputMethod of token: " + token);
1227                return;
1228            }
1229
1230            long ident = Binder.clearCallingIdentity();
1231            try {
1232                setInputMethodLocked(id);
1233            } finally {
1234                Binder.restoreCallingIdentity(ident);
1235            }
1236        }
1237    }
1238
1239    public void hideMySoftInput(IBinder token, int flags) {
1240        synchronized (mMethodMap) {
1241            if (token == null || mCurToken != token) {
1242                Slog.w(TAG, "Ignoring hideInputMethod of token: " + token);
1243                return;
1244            }
1245            long ident = Binder.clearCallingIdentity();
1246            try {
1247                hideCurrentInputLocked(flags, null);
1248            } finally {
1249                Binder.restoreCallingIdentity(ident);
1250            }
1251        }
1252    }
1253
1254    public void showMySoftInput(IBinder token, int flags) {
1255        synchronized (mMethodMap) {
1256            if (token == null || mCurToken != token) {
1257                Slog.w(TAG, "Ignoring hideInputMethod of token: " + token);
1258                return;
1259            }
1260            long ident = Binder.clearCallingIdentity();
1261            try {
1262                showCurrentInputLocked(flags, null);
1263            } finally {
1264                Binder.restoreCallingIdentity(ident);
1265            }
1266        }
1267    }
1268
1269    void setEnabledSessionInMainThread(SessionState session) {
1270        if (mEnabledSession != session) {
1271            if (mEnabledSession != null) {
1272                try {
1273                    if (DEBUG) Slog.v(TAG, "Disabling: " + mEnabledSession);
1274                    mEnabledSession.method.setSessionEnabled(
1275                            mEnabledSession.session, false);
1276                } catch (RemoteException e) {
1277                }
1278            }
1279            mEnabledSession = session;
1280            try {
1281                if (DEBUG) Slog.v(TAG, "Enabling: " + mEnabledSession);
1282                session.method.setSessionEnabled(
1283                        session.session, true);
1284            } catch (RemoteException e) {
1285            }
1286        }
1287    }
1288
1289    public boolean handleMessage(Message msg) {
1290        HandlerCaller.SomeArgs args;
1291        switch (msg.what) {
1292            case MSG_SHOW_IM_PICKER:
1293                showInputMethodMenu();
1294                return true;
1295
1296            // ---------------------------------------------------------
1297
1298            case MSG_UNBIND_INPUT:
1299                try {
1300                    ((IInputMethod)msg.obj).unbindInput();
1301                } catch (RemoteException e) {
1302                    // There is nothing interesting about the method dying.
1303                }
1304                return true;
1305            case MSG_BIND_INPUT:
1306                args = (HandlerCaller.SomeArgs)msg.obj;
1307                try {
1308                    ((IInputMethod)args.arg1).bindInput((InputBinding)args.arg2);
1309                } catch (RemoteException e) {
1310                }
1311                return true;
1312            case MSG_SHOW_SOFT_INPUT:
1313                args = (HandlerCaller.SomeArgs)msg.obj;
1314                try {
1315                    ((IInputMethod)args.arg1).showSoftInput(msg.arg1,
1316                            (ResultReceiver)args.arg2);
1317                } catch (RemoteException e) {
1318                }
1319                return true;
1320            case MSG_HIDE_SOFT_INPUT:
1321                args = (HandlerCaller.SomeArgs)msg.obj;
1322                try {
1323                    ((IInputMethod)args.arg1).hideSoftInput(0,
1324                            (ResultReceiver)args.arg2);
1325                } catch (RemoteException e) {
1326                }
1327                return true;
1328            case MSG_ATTACH_TOKEN:
1329                args = (HandlerCaller.SomeArgs)msg.obj;
1330                try {
1331                    if (DEBUG) Slog.v(TAG, "Sending attach of token: " + args.arg2);
1332                    ((IInputMethod)args.arg1).attachToken((IBinder)args.arg2);
1333                } catch (RemoteException e) {
1334                }
1335                return true;
1336            case MSG_CREATE_SESSION:
1337                args = (HandlerCaller.SomeArgs)msg.obj;
1338                try {
1339                    ((IInputMethod)args.arg1).createSession(
1340                            (IInputMethodCallback)args.arg2);
1341                } catch (RemoteException e) {
1342                }
1343                return true;
1344            // ---------------------------------------------------------
1345
1346            case MSG_START_INPUT:
1347                args = (HandlerCaller.SomeArgs)msg.obj;
1348                try {
1349                    SessionState session = (SessionState)args.arg1;
1350                    setEnabledSessionInMainThread(session);
1351                    session.method.startInput((IInputContext)args.arg2,
1352                            (EditorInfo)args.arg3);
1353                } catch (RemoteException e) {
1354                }
1355                return true;
1356            case MSG_RESTART_INPUT:
1357                args = (HandlerCaller.SomeArgs)msg.obj;
1358                try {
1359                    SessionState session = (SessionState)args.arg1;
1360                    setEnabledSessionInMainThread(session);
1361                    session.method.restartInput((IInputContext)args.arg2,
1362                            (EditorInfo)args.arg3);
1363                } catch (RemoteException e) {
1364                }
1365                return true;
1366
1367            // ---------------------------------------------------------
1368
1369            case MSG_UNBIND_METHOD:
1370                try {
1371                    ((IInputMethodClient)msg.obj).onUnbindMethod(msg.arg1);
1372                } catch (RemoteException e) {
1373                    // There is nothing interesting about the last client dying.
1374                }
1375                return true;
1376            case MSG_BIND_METHOD:
1377                args = (HandlerCaller.SomeArgs)msg.obj;
1378                try {
1379                    ((IInputMethodClient)args.arg1).onBindMethod(
1380                            (InputBindResult)args.arg2);
1381                } catch (RemoteException e) {
1382                    Slog.w(TAG, "Client died receiving input method " + args.arg2);
1383                }
1384                return true;
1385        }
1386        return false;
1387    }
1388
1389    private boolean isSystemIme(InputMethodInfo inputMethod) {
1390        return (inputMethod.getServiceInfo().applicationInfo.flags
1391                & ApplicationInfo.FLAG_SYSTEM) != 0;
1392    }
1393
1394    private boolean chooseNewDefaultIMELocked() {
1395        List<InputMethodInfo> enabled = getEnabledInputMethodListLocked();
1396        if (enabled != null && enabled.size() > 0) {
1397            Settings.Secure.putString(mContext.getContentResolver(),
1398                    Settings.Secure.DEFAULT_INPUT_METHOD,
1399                    enabled.get(0).getId());
1400            return true;
1401        }
1402
1403        return false;
1404    }
1405
1406    void buildInputMethodListLocked(ArrayList<InputMethodInfo> list,
1407            HashMap<String, InputMethodInfo> map) {
1408        list.clear();
1409        map.clear();
1410
1411        PackageManager pm = mContext.getPackageManager();
1412
1413        List<ResolveInfo> services = pm.queryIntentServices(
1414                new Intent(InputMethod.SERVICE_INTERFACE),
1415                PackageManager.GET_META_DATA);
1416
1417        for (int i = 0; i < services.size(); ++i) {
1418            ResolveInfo ri = services.get(i);
1419            ServiceInfo si = ri.serviceInfo;
1420            ComponentName compName = new ComponentName(si.packageName, si.name);
1421            if (!android.Manifest.permission.BIND_INPUT_METHOD.equals(
1422                    si.permission)) {
1423                Slog.w(TAG, "Skipping input method " + compName
1424                        + ": it does not require the permission "
1425                        + android.Manifest.permission.BIND_INPUT_METHOD);
1426                continue;
1427            }
1428
1429            if (DEBUG) Slog.d(TAG, "Checking " + compName);
1430
1431            try {
1432                InputMethodInfo p = new InputMethodInfo(mContext, ri);
1433                list.add(p);
1434                map.put(p.getId(), p);
1435
1436                // System IMEs are enabled by default
1437                if (isSystemIme(p)) {
1438                    setInputMethodEnabled(p.getId(), true);
1439                }
1440
1441                if (DEBUG) {
1442                    Slog.d(TAG, "Found a third-party input method " + p);
1443                }
1444
1445            } catch (XmlPullParserException e) {
1446                Slog.w(TAG, "Unable to load input method " + compName, e);
1447            } catch (IOException e) {
1448                Slog.w(TAG, "Unable to load input method " + compName, e);
1449            }
1450        }
1451
1452        String defaultIme = Settings.Secure.getString(mContext
1453                .getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);
1454        if (!map.containsKey(defaultIme)) {
1455            if (chooseNewDefaultIMELocked()) {
1456                updateFromSettingsLocked();
1457            }
1458        }
1459    }
1460
1461    // ----------------------------------------------------------------------
1462
1463    void showInputMethodMenu() {
1464        if (DEBUG) Slog.v(TAG, "Show switching menu");
1465
1466        hideInputMethodMenu();
1467
1468        final Context context = mContext;
1469
1470        final PackageManager pm = context.getPackageManager();
1471
1472        String lastInputMethodId = Settings.Secure.getString(context
1473                .getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);
1474        if (DEBUG) Slog.v(TAG, "Current IME: " + lastInputMethodId);
1475
1476        final List<InputMethodInfo> immis = getEnabledInputMethodList();
1477
1478        if (immis == null) {
1479            return;
1480        }
1481
1482        int N = immis.size();
1483
1484        mItems = new CharSequence[N];
1485        mIms = new InputMethodInfo[N];
1486
1487        for (int i = 0; i < N; ++i) {
1488            InputMethodInfo property = immis.get(i);
1489            if (property == null) {
1490                i--;
1491                N--;
1492                continue;
1493            }
1494            mItems[i] = property.loadLabel(pm);
1495            mIms[i] = property;
1496        }
1497
1498        int checkedItem = 0;
1499        for (int i = 0; i < N; ++i) {
1500            if (mIms[i].getId().equals(lastInputMethodId)) {
1501                checkedItem = i;
1502                break;
1503            }
1504        }
1505
1506        AlertDialog.OnClickListener adocl = new AlertDialog.OnClickListener() {
1507            public void onClick(DialogInterface dialog, int which) {
1508                hideInputMethodMenu();
1509            }
1510        };
1511
1512        TypedArray a = context.obtainStyledAttributes(null,
1513                com.android.internal.R.styleable.DialogPreference,
1514                com.android.internal.R.attr.alertDialogStyle, 0);
1515        mDialogBuilder = new AlertDialog.Builder(context)
1516                .setTitle(com.android.internal.R.string.select_input_method)
1517                .setOnCancelListener(new OnCancelListener() {
1518                    public void onCancel(DialogInterface dialog) {
1519                        hideInputMethodMenu();
1520                    }
1521                })
1522                .setIcon(a.getDrawable(
1523                        com.android.internal.R.styleable.DialogPreference_dialogTitle));
1524        a.recycle();
1525
1526        mDialogBuilder.setSingleChoiceItems(mItems, checkedItem,
1527                new AlertDialog.OnClickListener() {
1528                    public void onClick(DialogInterface dialog, int which) {
1529                        synchronized (mMethodMap) {
1530                            InputMethodInfo im = mIms[which];
1531                            hideInputMethodMenu();
1532                            setInputMethodLocked(im.getId());
1533                        }
1534                    }
1535                });
1536
1537        synchronized (mMethodMap) {
1538            mSwitchingDialog = mDialogBuilder.create();
1539            mSwitchingDialog.getWindow().setType(
1540                    WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG);
1541            mSwitchingDialog.show();
1542        }
1543    }
1544
1545    void hideInputMethodMenu() {
1546        synchronized (mMethodMap) {
1547            hideInputMethodMenuLocked();
1548        }
1549    }
1550
1551    void hideInputMethodMenuLocked() {
1552        if (DEBUG) Slog.v(TAG, "Hide switching menu");
1553
1554        if (mSwitchingDialog != null) {
1555            mSwitchingDialog.dismiss();
1556            mSwitchingDialog = null;
1557        }
1558
1559        mDialogBuilder = null;
1560        mItems = null;
1561        mIms = null;
1562    }
1563
1564    // ----------------------------------------------------------------------
1565
1566    public boolean setInputMethodEnabled(String id, boolean enabled) {
1567        synchronized (mMethodMap) {
1568            if (mContext.checkCallingOrSelfPermission(
1569                    android.Manifest.permission.WRITE_SECURE_SETTINGS)
1570                    != PackageManager.PERMISSION_GRANTED) {
1571                throw new SecurityException(
1572                        "Requires permission "
1573                        + android.Manifest.permission.WRITE_SECURE_SETTINGS);
1574            }
1575
1576            long ident = Binder.clearCallingIdentity();
1577            try {
1578                return setInputMethodEnabledLocked(id, enabled);
1579            } finally {
1580                Binder.restoreCallingIdentity(ident);
1581            }
1582        }
1583    }
1584
1585    boolean setInputMethodEnabledLocked(String id, boolean enabled) {
1586        // Make sure this is a valid input method.
1587        InputMethodInfo imm = mMethodMap.get(id);
1588        if (imm == null) {
1589            if (imm == null) {
1590                throw new IllegalArgumentException("Unknown id: " + mCurMethodId);
1591            }
1592        }
1593
1594        StringBuilder builder = new StringBuilder(256);
1595
1596        boolean removed = false;
1597        String firstId = null;
1598
1599        // Look through the currently enabled input methods.
1600        String enabledStr = Settings.Secure.getString(mContext.getContentResolver(),
1601                Settings.Secure.ENABLED_INPUT_METHODS);
1602        if (enabledStr != null) {
1603            final TextUtils.SimpleStringSplitter splitter = mStringColonSplitter;
1604            splitter.setString(enabledStr);
1605            while (splitter.hasNext()) {
1606                String curId = splitter.next();
1607                if (curId.equals(id)) {
1608                    if (enabled) {
1609                        // We are enabling this input method, but it is
1610                        // already enabled.  Nothing to do.  The previous
1611                        // state was enabled.
1612                        return true;
1613                    }
1614                    // We are disabling this input method, and it is
1615                    // currently enabled.  Skip it to remove from the
1616                    // new list.
1617                    removed = true;
1618                } else if (!enabled) {
1619                    // We are building a new list of input methods that
1620                    // doesn't contain the given one.
1621                    if (firstId == null) firstId = curId;
1622                    if (builder.length() > 0) builder.append(':');
1623                    builder.append(curId);
1624                }
1625            }
1626        }
1627
1628        if (!enabled) {
1629            if (!removed) {
1630                // We are disabling the input method but it is already
1631                // disabled.  Nothing to do.  The previous state was
1632                // disabled.
1633                return false;
1634            }
1635            // Update the setting with the new list of input methods.
1636            Settings.Secure.putString(mContext.getContentResolver(),
1637                    Settings.Secure.ENABLED_INPUT_METHODS, builder.toString());
1638            // We the disabled input method is currently selected, switch
1639            // to another one.
1640            String selId = Settings.Secure.getString(mContext.getContentResolver(),
1641                    Settings.Secure.DEFAULT_INPUT_METHOD);
1642            if (id.equals(selId)) {
1643                Settings.Secure.putString(mContext.getContentResolver(),
1644                        Settings.Secure.DEFAULT_INPUT_METHOD,
1645                        firstId != null ? firstId : "");
1646            }
1647            // Previous state was enabled.
1648            return true;
1649        }
1650
1651        // Add in the newly enabled input method.
1652        if (enabledStr == null || enabledStr.length() == 0) {
1653            enabledStr = id;
1654        } else {
1655            enabledStr = enabledStr + ':' + id;
1656        }
1657
1658        Settings.Secure.putString(mContext.getContentResolver(),
1659                Settings.Secure.ENABLED_INPUT_METHODS, enabledStr);
1660
1661        // Previous state was disabled.
1662        return false;
1663    }
1664
1665    // ----------------------------------------------------------------------
1666
1667    @Override
1668    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1669        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1670                != PackageManager.PERMISSION_GRANTED) {
1671
1672            pw.println("Permission Denial: can't dump InputMethodManager from from pid="
1673                    + Binder.getCallingPid()
1674                    + ", uid=" + Binder.getCallingUid());
1675            return;
1676        }
1677
1678        IInputMethod method;
1679        ClientState client;
1680
1681        final Printer p = new PrintWriterPrinter(pw);
1682
1683        synchronized (mMethodMap) {
1684            p.println("Current Input Method Manager state:");
1685            int N = mMethodList.size();
1686            p.println("  Input Methods:");
1687            for (int i=0; i<N; i++) {
1688                InputMethodInfo info = mMethodList.get(i);
1689                p.println("  InputMethod #" + i + ":");
1690                info.dump(p, "    ");
1691            }
1692            p.println("  Clients:");
1693            for (ClientState ci : mClients.values()) {
1694                p.println("  Client " + ci + ":");
1695                p.println("    client=" + ci.client);
1696                p.println("    inputContext=" + ci.inputContext);
1697                p.println("    sessionRequested=" + ci.sessionRequested);
1698                p.println("    curSession=" + ci.curSession);
1699            }
1700            p.println("  mInputMethodIcon=" + mInputMethodIcon);
1701            p.println("  mInputMethodData=" + mInputMethodData);
1702            p.println("  mCurMethodId=" + mCurMethodId);
1703            client = mCurClient;
1704            p.println("  mCurClient=" + client + " mCurSeq=" + mCurSeq);
1705            p.println("  mCurFocusedWindow=" + mCurFocusedWindow);
1706            p.println("  mCurId=" + mCurId + " mHaveConnect=" + mHaveConnection
1707                    + " mBoundToMethod=" + mBoundToMethod);
1708            p.println("  mCurToken=" + mCurToken);
1709            p.println("  mCurIntent=" + mCurIntent);
1710            method = mCurMethod;
1711            p.println("  mCurMethod=" + mCurMethod);
1712            p.println("  mEnabledSession=" + mEnabledSession);
1713            p.println("  mShowRequested=" + mShowRequested
1714                    + " mShowExplicitlyRequested=" + mShowExplicitlyRequested
1715                    + " mShowForced=" + mShowForced
1716                    + " mInputShown=" + mInputShown);
1717            p.println("  mSystemReady=" + mSystemReady + " mScreenOn=" + mScreenOn);
1718        }
1719
1720        if (client != null) {
1721            p.println(" ");
1722            pw.flush();
1723            try {
1724                client.client.asBinder().dump(fd, args);
1725            } catch (RemoteException e) {
1726                p.println("Input method client dead: " + e);
1727            }
1728        }
1729
1730        if (method != null) {
1731            p.println(" ");
1732            pw.flush();
1733            try {
1734                method.asBinder().dump(fd, args);
1735            } catch (RemoteException e) {
1736                p.println("Input method service dead: " + e);
1737            }
1738        }
1739    }
1740}
1741