blob: 3c37b4991a9e34c8d79f512aa0cad1f277d467ce [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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.os.HandlerCaller;
20import com.android.internal.view.IInputContext;
21import com.android.internal.view.IInputMethod;
22import com.android.internal.view.IInputMethodCallback;
23import com.android.internal.view.IInputMethodClient;
24import com.android.internal.view.IInputMethodManager;
25import com.android.internal.view.IInputMethodSession;
26import com.android.internal.view.InputBindResult;
27
28import com.android.server.status.IconData;
29import com.android.server.status.StatusBarService;
30
31import org.xmlpull.v1.XmlPullParserException;
32
33import android.app.ActivityManagerNative;
34import android.app.AlertDialog;
35import android.content.ComponentName;
36import android.content.ContentResolver;
37import android.content.Context;
38import android.content.DialogInterface;
39import android.content.IntentFilter;
40import android.content.DialogInterface.OnCancelListener;
41import android.content.Intent;
42import android.content.ServiceConnection;
43import android.content.pm.PackageManager;
44import android.content.pm.ResolveInfo;
45import android.content.pm.ServiceInfo;
46import android.content.res.Resources;
47import android.content.res.TypedArray;
48import android.database.ContentObserver;
49import android.net.Uri;
50import android.os.Binder;
51import android.os.Handler;
52import android.os.IBinder;
53import android.os.IInterface;
54import android.os.Message;
55import android.os.Parcel;
56import android.os.RemoteException;
The Android Open Source Project4df24232009-03-05 14:34:35 -080057import android.os.ResultReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.os.ServiceManager;
59import android.os.SystemClock;
60import android.provider.Settings;
61import android.text.TextUtils;
62import android.util.EventLog;
63import android.util.Log;
64import android.util.PrintWriterPrinter;
65import android.util.Printer;
66import android.view.IWindowManager;
67import android.view.WindowManager;
68import android.view.inputmethod.InputBinding;
69import android.view.inputmethod.InputMethod;
70import android.view.inputmethod.InputMethodInfo;
71import android.view.inputmethod.InputMethodManager;
72import android.view.inputmethod.EditorInfo;
73
74import java.io.FileDescriptor;
75import java.io.IOException;
76import java.io.PrintWriter;
77import java.util.ArrayList;
78import java.util.HashMap;
79import java.util.List;
80
81/**
82 * This class provides a system service that manages input methods.
83 */
84public class InputMethodManagerService extends IInputMethodManager.Stub
85 implements ServiceConnection, Handler.Callback {
86 static final boolean DEBUG = false;
87 static final String TAG = "InputManagerService";
88
89 static final int MSG_SHOW_IM_PICKER = 1;
90
91 static final int MSG_UNBIND_INPUT = 1000;
92 static final int MSG_BIND_INPUT = 1010;
93 static final int MSG_SHOW_SOFT_INPUT = 1020;
94 static final int MSG_HIDE_SOFT_INPUT = 1030;
95 static final int MSG_ATTACH_TOKEN = 1040;
96 static final int MSG_CREATE_SESSION = 1050;
97
98 static final int MSG_START_INPUT = 2000;
99 static final int MSG_RESTART_INPUT = 2010;
100
101 static final int MSG_UNBIND_METHOD = 3000;
102 static final int MSG_BIND_METHOD = 3010;
103
104 static final long TIME_TO_RECONNECT = 10*1000;
105
106 static final int LOG_IMF_FORCE_RECONNECT_IME = 32000;
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 /**
Dianne Hackborna34f1ad2009-09-02 13:26:28 -0700183 * Set once the system is ready to run third party code.
184 */
185 boolean mSystemReady;
186
187 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 * 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 /**
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700204 * The last window token that gained focus.
205 */
206 IBinder mCurFocusedWindow;
207
208 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 * 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;
The Android Open Source Project10592532009-03-18 17:39:46 -0700316 } else if (intent.getAction().equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
317 hideInputMethodMenu();
318 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 } else {
320 Log.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 Log.w(TAG, "Got RemoteException sending 'screen on/off' notification to pid "
330 + mCurClient.pid + " uid " + mCurClient.uid);
331 }
332 }
333 }
334
335 class PackageReceiver extends android.content.BroadcastReceiver {
336 @Override
337 public void onReceive(Context context, Intent intent) {
338 synchronized (mMethodMap) {
339 buildInputMethodListLocked(mMethodList, mMethodMap);
340
341 InputMethodInfo curIm = null;
342 String curInputMethodId = Settings.Secure.getString(context
343 .getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);
344 final int N = mMethodList.size();
345 if (curInputMethodId != null) {
346 for (int i=0; i<N; i++) {
347 if (mMethodList.get(i).getId().equals(curInputMethodId)) {
348 curIm = mMethodList.get(i);
349 }
350 }
351 }
352
353 boolean changed = false;
354
355 Uri uri = intent.getData();
356 String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
357 if (curIm != null && curIm.getPackageName().equals(pkg)) {
358 ServiceInfo si = null;
359 try {
360 si = mContext.getPackageManager().getServiceInfo(
361 curIm.getComponent(), 0);
362 } catch (PackageManager.NameNotFoundException ex) {
363 }
364 if (si == null) {
365 // Uh oh, current input method is no longer around!
366 // Pick another one...
367 Log.i(TAG, "Current input method removed: " + curInputMethodId);
368 List<InputMethodInfo> enabled = getEnabledInputMethodListLocked();
369 if (enabled != null && enabled.size() > 0) {
370 changed = true;
371 curIm = enabled.get(0);
372 curInputMethodId = curIm.getId();
373 Log.i(TAG, "Switching to: " + curInputMethodId);
374 Settings.Secure.putString(mContext.getContentResolver(),
375 Settings.Secure.DEFAULT_INPUT_METHOD,
376 curInputMethodId);
377 } else if (curIm != null) {
378 changed = true;
379 curIm = null;
380 curInputMethodId = "";
381 Log.i(TAG, "Unsetting current input method");
382 Settings.Secure.putString(mContext.getContentResolver(),
383 Settings.Secure.DEFAULT_INPUT_METHOD,
384 curInputMethodId);
385 }
386 }
387
388 } else if (curIm == null) {
389 // We currently don't have a default input method... is
390 // one now available?
391 List<InputMethodInfo> enabled = getEnabledInputMethodListLocked();
392 if (enabled != null && enabled.size() > 0) {
393 changed = true;
394 curIm = enabled.get(0);
395 curInputMethodId = curIm.getId();
396 Log.i(TAG, "New default input method: " + curInputMethodId);
397 Settings.Secure.putString(mContext.getContentResolver(),
398 Settings.Secure.DEFAULT_INPUT_METHOD,
399 curInputMethodId);
400 }
401 }
402
403 if (changed) {
404 updateFromSettingsLocked();
405 }
406 }
407 }
408 }
409
410 class MethodCallback extends IInputMethodCallback.Stub {
411 final IInputMethod mMethod;
412
413 MethodCallback(IInputMethod method) {
414 mMethod = method;
415 }
416
417 public void finishedEvent(int seq, boolean handled) throws RemoteException {
418 }
419
420 public void sessionCreated(IInputMethodSession session) throws RemoteException {
421 onSessionCreated(mMethod, session);
422 }
423 }
424
425 public InputMethodManagerService(Context context, StatusBarService statusBar) {
426 mContext = context;
427 mHandler = new Handler(this);
428 mIWindowManager = IWindowManager.Stub.asInterface(
429 ServiceManager.getService(Context.WINDOW_SERVICE));
430 mCaller = new HandlerCaller(context, new HandlerCaller.Callback() {
431 public void executeMessage(Message msg) {
432 handleMessage(msg);
433 }
434 });
435
436 IntentFilter packageFilt = new IntentFilter();
437 packageFilt.addAction(Intent.ACTION_PACKAGE_ADDED);
438 packageFilt.addAction(Intent.ACTION_PACKAGE_CHANGED);
439 packageFilt.addAction(Intent.ACTION_PACKAGE_REMOVED);
440 packageFilt.addAction(Intent.ACTION_PACKAGE_RESTARTED);
441 packageFilt.addDataScheme("package");
442 mContext.registerReceiver(new PackageReceiver(), packageFilt);
443
444 IntentFilter screenOnOffFilt = new IntentFilter();
445 screenOnOffFilt.addAction(Intent.ACTION_SCREEN_ON);
446 screenOnOffFilt.addAction(Intent.ACTION_SCREEN_OFF);
The Android Open Source Project10592532009-03-18 17:39:46 -0700447 screenOnOffFilt.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800448 mContext.registerReceiver(new ScreenOnOffReceiver(), screenOnOffFilt);
449
450 buildInputMethodListLocked(mMethodList, mMethodMap);
451
452 final String enabledStr = Settings.Secure.getString(
453 mContext.getContentResolver(),
454 Settings.Secure.ENABLED_INPUT_METHODS);
455 Log.i(TAG, "Enabled input methods: " + enabledStr);
456 if (enabledStr == null) {
457 Log.i(TAG, "Enabled input methods has not been set, enabling all");
458 InputMethodInfo defIm = null;
459 StringBuilder sb = new StringBuilder(256);
460 final int N = mMethodList.size();
461 for (int i=0; i<N; i++) {
462 InputMethodInfo imi = mMethodList.get(i);
463 Log.i(TAG, "Adding: " + imi.getId());
464 if (i > 0) sb.append(':');
465 sb.append(imi.getId());
466 if (defIm == null && imi.getIsDefaultResourceId() != 0) {
467 try {
468 Resources res = mContext.createPackageContext(
469 imi.getPackageName(), 0).getResources();
470 if (res.getBoolean(imi.getIsDefaultResourceId())) {
471 defIm = imi;
472 Log.i(TAG, "Selected default: " + imi.getId());
473 }
474 } catch (PackageManager.NameNotFoundException ex) {
475 } catch (Resources.NotFoundException ex) {
476 }
477 }
478 }
479 if (defIm == null && N > 0) {
480 defIm = mMethodList.get(0);
481 Log.i(TAG, "No default found, using " + defIm.getId());
482 }
483 Settings.Secure.putString(mContext.getContentResolver(),
484 Settings.Secure.ENABLED_INPUT_METHODS, sb.toString());
485 if (defIm != null) {
486 Settings.Secure.putString(mContext.getContentResolver(),
487 Settings.Secure.DEFAULT_INPUT_METHOD, defIm.getId());
488 }
489 }
490
491 mStatusBar = statusBar;
492 mInputMethodData = IconData.makeIcon("ime", null, 0, 0, 0);
493 mInputMethodIcon = statusBar.addIcon(mInputMethodData, null);
494 statusBar.setIconVisibility(mInputMethodIcon, false);
495
496 mSettingsObserver = new SettingsObserver(mHandler);
497 updateFromSettingsLocked();
498 }
499
500 @Override
501 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
502 throws RemoteException {
503 try {
504 return super.onTransact(code, data, reply, flags);
505 } catch (RuntimeException e) {
506 // The input method manager only throws security exceptions, so let's
507 // log all others.
508 if (!(e instanceof SecurityException)) {
509 Log.e(TAG, "Input Method Manager Crash", e);
510 }
511 throw e;
512 }
513 }
514
515 public void systemReady() {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -0700516 synchronized (mMethodMap) {
517 if (!mSystemReady) {
518 mSystemReady = true;
519 startInputInnerLocked();
520 }
521 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 }
523
524 public List<InputMethodInfo> getInputMethodList() {
525 synchronized (mMethodMap) {
526 return new ArrayList<InputMethodInfo>(mMethodList);
527 }
528 }
529
530 public List<InputMethodInfo> getEnabledInputMethodList() {
531 synchronized (mMethodMap) {
532 return getEnabledInputMethodListLocked();
533 }
534 }
535
536 List<InputMethodInfo> getEnabledInputMethodListLocked() {
537 final ArrayList<InputMethodInfo> res = new ArrayList<InputMethodInfo>();
538
539 final String enabledStr = Settings.Secure.getString(
540 mContext.getContentResolver(),
541 Settings.Secure.ENABLED_INPUT_METHODS);
542 if (enabledStr != null) {
543 final TextUtils.SimpleStringSplitter splitter = mStringColonSplitter;
544 splitter.setString(enabledStr);
545
546 while (splitter.hasNext()) {
547 InputMethodInfo info = mMethodMap.get(splitter.next());
548 if (info != null) {
549 res.add(info);
550 }
551 }
552 }
553
554 return res;
555 }
556
557 public void addClient(IInputMethodClient client,
558 IInputContext inputContext, int uid, int pid) {
559 synchronized (mMethodMap) {
560 mClients.put(client.asBinder(), new ClientState(client,
561 inputContext, uid, pid));
562 }
563 }
564
565 public void removeClient(IInputMethodClient client) {
566 synchronized (mMethodMap) {
567 mClients.remove(client.asBinder());
568 }
569 }
570
571 void executeOrSendMessage(IInterface target, Message msg) {
572 if (target.asBinder() instanceof Binder) {
573 mCaller.sendMessage(msg);
574 } else {
575 handleMessage(msg);
576 msg.recycle();
577 }
578 }
579
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700580 void unbindCurrentClientLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 if (mCurClient != null) {
582 if (DEBUG) Log.v(TAG, "unbindCurrentInputLocked: client = "
583 + mCurClient.client.asBinder());
584 if (mBoundToMethod) {
585 mBoundToMethod = false;
586 if (mCurMethod != null) {
587 executeOrSendMessage(mCurMethod, mCaller.obtainMessageO(
588 MSG_UNBIND_INPUT, mCurMethod));
589 }
590 }
591 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
592 MSG_UNBIND_METHOD, mCurSeq, mCurClient.client));
593 mCurClient.sessionRequested = false;
594
595 // Call setActive(false) on the old client
596 try {
597 mCurClient.client.setActive(false);
598 } catch (RemoteException e) {
599 Log.w(TAG, "Got RemoteException sending setActive(false) notification to pid "
600 + mCurClient.pid + " uid " + mCurClient.uid);
601 }
602 mCurClient = null;
The Android Open Source Project10592532009-03-18 17:39:46 -0700603
604 hideInputMethodMenuLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 }
606 }
607
608 private int getImeShowFlags() {
609 int flags = 0;
610 if (mShowForced) {
611 flags |= InputMethod.SHOW_FORCED
612 | InputMethod.SHOW_EXPLICIT;
613 } else if (mShowExplicitlyRequested) {
614 flags |= InputMethod.SHOW_EXPLICIT;
615 }
616 return flags;
617 }
618
619 private int getAppShowFlags() {
620 int flags = 0;
621 if (mShowForced) {
622 flags |= InputMethodManager.SHOW_FORCED;
623 } else if (!mShowExplicitlyRequested) {
624 flags |= InputMethodManager.SHOW_IMPLICIT;
625 }
626 return flags;
627 }
628
629 InputBindResult attachNewInputLocked(boolean initial, boolean needResult) {
630 if (!mBoundToMethod) {
631 executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
632 MSG_BIND_INPUT, mCurMethod, mCurClient.binding));
633 mBoundToMethod = true;
634 }
635 final SessionState session = mCurClient.curSession;
636 if (initial) {
637 executeOrSendMessage(session.method, mCaller.obtainMessageOOO(
638 MSG_START_INPUT, session, mCurInputContext, mCurAttribute));
639 } else {
640 executeOrSendMessage(session.method, mCaller.obtainMessageOOO(
641 MSG_RESTART_INPUT, session, mCurInputContext, mCurAttribute));
642 }
643 if (mShowRequested) {
644 if (DEBUG) Log.v(TAG, "Attach new input asks to show input");
The Android Open Source Project4df24232009-03-05 14:34:35 -0800645 showCurrentInputLocked(getAppShowFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 }
647 return needResult
648 ? new InputBindResult(session.session, mCurId, mCurSeq)
649 : null;
650 }
651
652 InputBindResult startInputLocked(IInputMethodClient client,
653 IInputContext inputContext, EditorInfo attribute,
654 boolean initial, boolean needResult) {
655 // If no method is currently selected, do nothing.
656 if (mCurMethodId == null) {
657 return mNoBinding;
658 }
659
660 ClientState cs = mClients.get(client.asBinder());
661 if (cs == null) {
662 throw new IllegalArgumentException("unknown client "
663 + client.asBinder());
664 }
665
666 try {
667 if (!mIWindowManager.inputMethodClientHasFocus(cs.client)) {
668 // Check with the window manager to make sure this client actually
669 // has a window with focus. If not, reject. This is thread safe
670 // because if the focus changes some time before or after, the
671 // next client receiving focus that has any interest in input will
672 // be calling through here after that change happens.
673 Log.w(TAG, "Starting input on non-focused client " + cs.client
674 + " (uid=" + cs.uid + " pid=" + cs.pid + ")");
675 return null;
676 }
677 } catch (RemoteException e) {
678 }
679
680 if (mCurClient != cs) {
681 // If the client is changing, we need to switch over to the new
682 // one.
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700683 unbindCurrentClientLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 if (DEBUG) Log.v(TAG, "switching to client: client = "
685 + cs.client.asBinder());
686
687 // If the screen is on, inform the new client it is active
688 if (mScreenOn) {
689 try {
690 cs.client.setActive(mScreenOn);
691 } catch (RemoteException e) {
692 Log.w(TAG, "Got RemoteException sending setActive notification to pid "
693 + cs.pid + " uid " + cs.uid);
694 }
695 }
696 }
697
698 // Bump up the sequence for this client and attach it.
699 mCurSeq++;
700 if (mCurSeq <= 0) mCurSeq = 1;
701 mCurClient = cs;
702 mCurInputContext = inputContext;
703 mCurAttribute = attribute;
704
705 // Check if the input method is changing.
706 if (mCurId != null && mCurId.equals(mCurMethodId)) {
707 if (cs.curSession != null) {
708 // Fast case: if we are already connected to the input method,
709 // then just return it.
710 return attachNewInputLocked(initial, needResult);
711 }
712 if (mHaveConnection) {
713 if (mCurMethod != null) {
714 if (!cs.sessionRequested) {
715 cs.sessionRequested = true;
716 if (DEBUG) Log.v(TAG, "Creating new session for client " + cs);
717 executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
718 MSG_CREATE_SESSION, mCurMethod,
719 new MethodCallback(mCurMethod)));
720 }
721 // Return to client, and we will get back with it when
722 // we have had a session made for it.
723 return new InputBindResult(null, mCurId, mCurSeq);
724 } else if (SystemClock.uptimeMillis()
725 < (mLastBindTime+TIME_TO_RECONNECT)) {
726 // In this case we have connected to the service, but
727 // don't yet have its interface. If it hasn't been too
728 // long since we did the connection, we'll return to
729 // the client and wait to get the service interface so
730 // we can report back. If it has been too long, we want
731 // to fall through so we can try a disconnect/reconnect
732 // to see if we can get back in touch with the service.
733 return new InputBindResult(null, mCurId, mCurSeq);
734 } else {
735 EventLog.writeEvent(LOG_IMF_FORCE_RECONNECT_IME, mCurMethodId,
736 SystemClock.uptimeMillis()-mLastBindTime, 0);
737 }
738 }
739 }
740
Dianne Hackborna34f1ad2009-09-02 13:26:28 -0700741 return startInputInnerLocked();
742 }
743
744 InputBindResult startInputInnerLocked() {
745 if (mCurMethodId == null) {
746 return mNoBinding;
747 }
748
749 if (!mSystemReady) {
750 // If the system is not yet ready, we shouldn't be running third
751 // party code.
752 return new InputBindResult(null, mCurId, mCurSeq);
753 }
754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 InputMethodInfo info = mMethodMap.get(mCurMethodId);
756 if (info == null) {
757 throw new IllegalArgumentException("Unknown id: " + mCurMethodId);
758 }
759
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700760 unbindCurrentMethodLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761
762 mCurIntent = new Intent(InputMethod.SERVICE_INTERFACE);
763 mCurIntent.setComponent(info.getComponent());
764 if (mContext.bindService(mCurIntent, this, Context.BIND_AUTO_CREATE)) {
765 mLastBindTime = SystemClock.uptimeMillis();
766 mHaveConnection = true;
767 mCurId = info.getId();
768 mCurToken = new Binder();
769 try {
770 if (DEBUG) Log.v(TAG, "Adding window token: " + mCurToken);
771 mIWindowManager.addWindowToken(mCurToken,
772 WindowManager.LayoutParams.TYPE_INPUT_METHOD);
773 } catch (RemoteException e) {
774 }
775 return new InputBindResult(null, mCurId, mCurSeq);
776 } else {
777 mCurIntent = null;
778 Log.w(TAG, "Failure connecting to input method service: "
779 + mCurIntent);
780 }
781 return null;
782 }
783
784 public InputBindResult startInput(IInputMethodClient client,
785 IInputContext inputContext, EditorInfo attribute,
786 boolean initial, boolean needResult) {
787 synchronized (mMethodMap) {
788 final long ident = Binder.clearCallingIdentity();
789 try {
790 return startInputLocked(client, inputContext, attribute,
791 initial, needResult);
792 } finally {
793 Binder.restoreCallingIdentity(ident);
794 }
795 }
796 }
797
798 public void finishInput(IInputMethodClient client) {
799 }
800
801 public void onServiceConnected(ComponentName name, IBinder service) {
802 synchronized (mMethodMap) {
803 if (mCurIntent != null && name.equals(mCurIntent.getComponent())) {
804 mCurMethod = IInputMethod.Stub.asInterface(service);
805 if (mCurClient != null) {
806 if (DEBUG) Log.v(TAG, "Initiating attach with token: " + mCurToken);
807 executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
808 MSG_ATTACH_TOKEN, mCurMethod, mCurToken));
809 if (mCurClient != null) {
810 if (DEBUG) Log.v(TAG, "Creating first session while with client "
811 + mCurClient);
812 executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
813 MSG_CREATE_SESSION, mCurMethod,
814 new MethodCallback(mCurMethod)));
815 }
816 }
817 }
818 }
819 }
820
821 void onSessionCreated(IInputMethod method, IInputMethodSession session) {
822 synchronized (mMethodMap) {
823 if (mCurMethod != null && method != null
824 && mCurMethod.asBinder() == method.asBinder()) {
825 if (mCurClient != null) {
826 mCurClient.curSession = new SessionState(mCurClient,
827 method, session);
828 mCurClient.sessionRequested = false;
829 InputBindResult res = attachNewInputLocked(true, true);
830 if (res.method != null) {
831 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageOO(
832 MSG_BIND_METHOD, mCurClient.client, res));
833 }
834 }
835 }
836 }
837 }
838
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700839 void unbindCurrentMethodLocked(boolean reportToClient) {
840 if (mHaveConnection) {
841 mContext.unbindService(this);
842 mHaveConnection = false;
843 }
844
845 if (mCurToken != null) {
846 try {
847 if (DEBUG) Log.v(TAG, "Removing window token: " + mCurToken);
848 mIWindowManager.removeWindowToken(mCurToken);
849 } catch (RemoteException e) {
850 }
851 mCurToken = null;
852 }
853
The Android Open Source Project10592532009-03-18 17:39:46 -0700854 mCurId = null;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700855 clearCurMethodLocked();
856
857 if (reportToClient && mCurClient != null) {
858 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
859 MSG_UNBIND_METHOD, mCurSeq, mCurClient.client));
860 }
861 }
862
863 void clearCurMethodLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 if (mCurMethod != null) {
865 for (ClientState cs : mClients.values()) {
866 cs.sessionRequested = false;
867 cs.curSession = null;
868 }
869 mCurMethod = null;
870 }
871 mStatusBar.setIconVisibility(mInputMethodIcon, false);
872 }
873
874 public void onServiceDisconnected(ComponentName name) {
875 synchronized (mMethodMap) {
876 if (DEBUG) Log.v(TAG, "Service disconnected: " + name
877 + " mCurIntent=" + mCurIntent);
878 if (mCurMethod != null && mCurIntent != null
879 && name.equals(mCurIntent.getComponent())) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700880 clearCurMethodLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 // We consider this to be a new bind attempt, since the system
882 // should now try to restart the service for us.
883 mLastBindTime = SystemClock.uptimeMillis();
884 mShowRequested = mInputShown;
885 mInputShown = false;
886 if (mCurClient != null) {
887 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
888 MSG_UNBIND_METHOD, mCurSeq, mCurClient.client));
889 }
890 }
891 }
892 }
893
894 public void updateStatusIcon(IBinder token, String packageName, int iconId) {
895 long ident = Binder.clearCallingIdentity();
896 try {
897 if (token == null || mCurToken != token) {
898 Log.w(TAG, "Ignoring setInputMethod of token: " + token);
899 return;
900 }
901
902 synchronized (mMethodMap) {
903 if (iconId == 0) {
904 if (DEBUG) Log.d(TAG, "hide the small icon for the input method");
905 mStatusBar.setIconVisibility(mInputMethodIcon, false);
906 } else if (packageName != null) {
907 if (DEBUG) Log.d(TAG, "show a small icon for the input method");
908 mInputMethodData.iconId = iconId;
909 mInputMethodData.iconPackage = packageName;
910 mStatusBar.updateIcon(mInputMethodIcon, mInputMethodData, null);
911 mStatusBar.setIconVisibility(mInputMethodIcon, true);
912 }
913 }
914 } finally {
915 Binder.restoreCallingIdentity(ident);
916 }
917 }
918
919 void updateFromSettingsLocked() {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700920 // We are assuming that whoever is changing DEFAULT_INPUT_METHOD and
921 // ENABLED_INPUT_METHODS is taking care of keeping them correctly in
922 // sync, so we will never have a DEFAULT_INPUT_METHOD that is not
923 // enabled.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 String id = Settings.Secure.getString(mContext.getContentResolver(),
925 Settings.Secure.DEFAULT_INPUT_METHOD);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700926 if (id != null && id.length() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 try {
928 setInputMethodLocked(id);
929 } catch (IllegalArgumentException e) {
930 Log.w(TAG, "Unknown input method from prefs: " + id, e);
The Android Open Source Project10592532009-03-18 17:39:46 -0700931 mCurMethodId = null;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700932 unbindCurrentMethodLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700934 } else {
935 // There is no longer an input method set, so stop any current one.
The Android Open Source Project10592532009-03-18 17:39:46 -0700936 mCurMethodId = null;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700937 unbindCurrentMethodLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938 }
939 }
940
941 void setInputMethodLocked(String id) {
942 InputMethodInfo info = mMethodMap.get(id);
943 if (info == null) {
944 throw new IllegalArgumentException("Unknown id: " + mCurMethodId);
945 }
946
947 if (id.equals(mCurMethodId)) {
948 return;
949 }
950
951 final long ident = Binder.clearCallingIdentity();
952 try {
953 mCurMethodId = id;
954 Settings.Secure.putString(mContext.getContentResolver(),
955 Settings.Secure.DEFAULT_INPUT_METHOD, id);
956
957 if (ActivityManagerNative.isSystemReady()) {
958 Intent intent = new Intent(Intent.ACTION_INPUT_METHOD_CHANGED);
959 intent.putExtra("input_method_id", id);
960 mContext.sendBroadcast(intent);
961 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700962 unbindCurrentClientLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 } finally {
964 Binder.restoreCallingIdentity(ident);
965 }
966 }
967
The Android Open Source Project4df24232009-03-05 14:34:35 -0800968 public boolean showSoftInput(IInputMethodClient client, int flags,
969 ResultReceiver resultReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 long ident = Binder.clearCallingIdentity();
971 try {
972 synchronized (mMethodMap) {
973 if (mCurClient == null || client == null
974 || mCurClient.client.asBinder() != client.asBinder()) {
975 try {
976 // We need to check if this is the current client with
977 // focus in the window manager, to allow this call to
978 // be made before input is started in it.
979 if (!mIWindowManager.inputMethodClientHasFocus(client)) {
980 Log.w(TAG, "Ignoring showSoftInput of: " + client);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800981 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 }
983 } catch (RemoteException e) {
The Android Open Source Project4df24232009-03-05 14:34:35 -0800984 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 }
986 }
987
988 if (DEBUG) Log.v(TAG, "Client requesting input be shown");
The Android Open Source Project4df24232009-03-05 14:34:35 -0800989 return showCurrentInputLocked(flags, resultReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 }
991 } finally {
992 Binder.restoreCallingIdentity(ident);
993 }
994 }
995
The Android Open Source Project4df24232009-03-05 14:34:35 -0800996 boolean showCurrentInputLocked(int flags, ResultReceiver resultReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 mShowRequested = true;
998 if ((flags&InputMethodManager.SHOW_IMPLICIT) == 0) {
999 mShowExplicitlyRequested = true;
1000 }
1001 if ((flags&InputMethodManager.SHOW_FORCED) != 0) {
1002 mShowExplicitlyRequested = true;
1003 mShowForced = true;
1004 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08001005 boolean res = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 if (mCurMethod != null) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08001007 executeOrSendMessage(mCurMethod, mCaller.obtainMessageIOO(
1008 MSG_SHOW_SOFT_INPUT, getImeShowFlags(), mCurMethod,
1009 resultReceiver));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 mInputShown = true;
The Android Open Source Project4df24232009-03-05 14:34:35 -08001011 res = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 } else if (mHaveConnection && SystemClock.uptimeMillis()
1013 < (mLastBindTime+TIME_TO_RECONNECT)) {
1014 // The client has asked to have the input method shown, but
1015 // we have been sitting here too long with a connection to the
1016 // service and no interface received, so let's disconnect/connect
1017 // to try to prod things along.
1018 EventLog.writeEvent(LOG_IMF_FORCE_RECONNECT_IME, mCurMethodId,
1019 SystemClock.uptimeMillis()-mLastBindTime,1);
1020 mContext.unbindService(this);
1021 mContext.bindService(mCurIntent, this, Context.BIND_AUTO_CREATE);
1022 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08001023
1024 return res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 }
1026
The Android Open Source Project4df24232009-03-05 14:34:35 -08001027 public boolean hideSoftInput(IInputMethodClient client, int flags,
1028 ResultReceiver resultReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 long ident = Binder.clearCallingIdentity();
1030 try {
1031 synchronized (mMethodMap) {
1032 if (mCurClient == null || client == null
1033 || mCurClient.client.asBinder() != client.asBinder()) {
1034 try {
1035 // We need to check if this is the current client with
1036 // focus in the window manager, to allow this call to
1037 // be made before input is started in it.
1038 if (!mIWindowManager.inputMethodClientHasFocus(client)) {
1039 Log.w(TAG, "Ignoring hideSoftInput of: " + client);
The Android Open Source Project4df24232009-03-05 14:34:35 -08001040 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 }
1042 } catch (RemoteException e) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08001043 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 }
1045 }
1046
1047 if (DEBUG) Log.v(TAG, "Client requesting input be hidden");
The Android Open Source Project4df24232009-03-05 14:34:35 -08001048 return hideCurrentInputLocked(flags, resultReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 }
1050 } finally {
1051 Binder.restoreCallingIdentity(ident);
1052 }
1053 }
1054
The Android Open Source Project4df24232009-03-05 14:34:35 -08001055 boolean hideCurrentInputLocked(int flags, ResultReceiver resultReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 if ((flags&InputMethodManager.HIDE_IMPLICIT_ONLY) != 0
1057 && (mShowExplicitlyRequested || mShowForced)) {
1058 if (DEBUG) Log.v(TAG,
1059 "Not hiding: explicit show not cancelled by non-explicit hide");
The Android Open Source Project4df24232009-03-05 14:34:35 -08001060 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 }
1062 if (mShowForced && (flags&InputMethodManager.HIDE_NOT_ALWAYS) != 0) {
1063 if (DEBUG) Log.v(TAG,
1064 "Not hiding: forced show not cancelled by not-always hide");
The Android Open Source Project4df24232009-03-05 14:34:35 -08001065 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08001067 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 if (mInputShown && mCurMethod != null) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08001069 executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO(
1070 MSG_HIDE_SOFT_INPUT, mCurMethod, resultReceiver));
1071 res = true;
1072 } else {
1073 res = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 }
1075 mInputShown = false;
1076 mShowRequested = false;
1077 mShowExplicitlyRequested = false;
1078 mShowForced = false;
The Android Open Source Project4df24232009-03-05 14:34:35 -08001079 return res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 }
1081
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001082 public void windowGainedFocus(IInputMethodClient client, IBinder windowToken,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 boolean viewHasFocus, boolean isTextEditor, int softInputMode,
1084 boolean first, int windowFlags) {
1085 long ident = Binder.clearCallingIdentity();
1086 try {
1087 synchronized (mMethodMap) {
1088 if (DEBUG) Log.v(TAG, "windowGainedFocus: " + client.asBinder()
1089 + " viewHasFocus=" + viewHasFocus
1090 + " isTextEditor=" + isTextEditor
1091 + " softInputMode=#" + Integer.toHexString(softInputMode)
1092 + " first=" + first + " flags=#"
1093 + Integer.toHexString(windowFlags));
1094
1095 if (mCurClient == null || client == null
1096 || mCurClient.client.asBinder() != client.asBinder()) {
1097 try {
1098 // We need to check if this is the current client with
1099 // focus in the window manager, to allow this call to
1100 // be made before input is started in it.
1101 if (!mIWindowManager.inputMethodClientHasFocus(client)) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001102 Log.w(TAG, "Client not active, ignoring focus gain of: " + client);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 return;
1104 }
1105 } catch (RemoteException e) {
1106 }
1107 }
1108
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001109 if (mCurFocusedWindow == windowToken) {
1110 Log.w(TAG, "Window already focused, ignoring focus gain of: " + client);
1111 return;
1112 }
1113 mCurFocusedWindow = windowToken;
1114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 switch (softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_STATE) {
1116 case WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED:
1117 if (!isTextEditor || (softInputMode &
1118 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
1119 != WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) {
1120 if (WindowManager.LayoutParams.mayUseInputMethod(windowFlags)) {
1121 // There is no focus view, and this window will
1122 // be behind any soft input window, so hide the
1123 // soft input window if it is shown.
1124 if (DEBUG) Log.v(TAG, "Unspecified window will hide input");
The Android Open Source Project4df24232009-03-05 14:34:35 -08001125 hideCurrentInputLocked(InputMethodManager.HIDE_NOT_ALWAYS, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 }
1127 } else if (isTextEditor && (softInputMode &
1128 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
1129 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
1130 && (softInputMode &
1131 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) {
1132 // There is a focus view, and we are navigating forward
1133 // into the window, so show the input window for the user.
1134 if (DEBUG) Log.v(TAG, "Unspecified window will show input");
The Android Open Source Project4df24232009-03-05 14:34:35 -08001135 showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 }
1137 break;
1138 case WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED:
1139 // Do nothing.
1140 break;
1141 case WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN:
1142 if ((softInputMode &
1143 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) {
1144 if (DEBUG) Log.v(TAG, "Window asks to hide input going forward");
The Android Open Source Project4df24232009-03-05 14:34:35 -08001145 hideCurrentInputLocked(0, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 }
1147 break;
1148 case WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN:
1149 if (DEBUG) Log.v(TAG, "Window asks to hide input");
The Android Open Source Project4df24232009-03-05 14:34:35 -08001150 hideCurrentInputLocked(0, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 break;
1152 case WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE:
1153 if ((softInputMode &
1154 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) {
1155 if (DEBUG) Log.v(TAG, "Window asks to show input going forward");
The Android Open Source Project4df24232009-03-05 14:34:35 -08001156 showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 }
1158 break;
1159 case WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE:
1160 if (DEBUG) Log.v(TAG, "Window asks to always show input");
The Android Open Source Project4df24232009-03-05 14:34:35 -08001161 showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 break;
1163 }
1164 }
1165 } finally {
1166 Binder.restoreCallingIdentity(ident);
1167 }
1168 }
1169
1170 public void showInputMethodPickerFromClient(IInputMethodClient client) {
1171 synchronized (mMethodMap) {
1172 if (mCurClient == null || client == null
1173 || mCurClient.client.asBinder() != client.asBinder()) {
1174 Log.w(TAG, "Ignoring showInputMethodDialogFromClient of: " + client);
1175 }
1176
1177 mHandler.sendEmptyMessage(MSG_SHOW_IM_PICKER);
1178 }
1179 }
1180
1181 public void setInputMethod(IBinder token, String id) {
1182 synchronized (mMethodMap) {
1183 if (token == null) {
1184 if (mContext.checkCallingOrSelfPermission(
1185 android.Manifest.permission.WRITE_SECURE_SETTINGS)
1186 != PackageManager.PERMISSION_GRANTED) {
1187 throw new SecurityException(
1188 "Using null token requires permission "
1189 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
1190 }
1191 } else if (mCurToken != token) {
1192 Log.w(TAG, "Ignoring setInputMethod of token: " + token);
1193 return;
1194 }
1195
1196 long ident = Binder.clearCallingIdentity();
1197 try {
1198 setInputMethodLocked(id);
1199 } finally {
1200 Binder.restoreCallingIdentity(ident);
1201 }
1202 }
1203 }
1204
1205 public void hideMySoftInput(IBinder token, int flags) {
1206 synchronized (mMethodMap) {
1207 if (token == null || mCurToken != token) {
1208 Log.w(TAG, "Ignoring hideInputMethod of token: " + token);
1209 return;
1210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 long ident = Binder.clearCallingIdentity();
1212 try {
The Android Open Source Project4df24232009-03-05 14:34:35 -08001213 hideCurrentInputLocked(flags, null);
1214 } finally {
1215 Binder.restoreCallingIdentity(ident);
1216 }
1217 }
1218 }
1219
1220 public void showMySoftInput(IBinder token, int flags) {
1221 synchronized (mMethodMap) {
1222 if (token == null || mCurToken != token) {
1223 Log.w(TAG, "Ignoring hideInputMethod of token: " + token);
1224 return;
1225 }
1226 long ident = Binder.clearCallingIdentity();
1227 try {
1228 showCurrentInputLocked(flags, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 } finally {
1230 Binder.restoreCallingIdentity(ident);
1231 }
1232 }
1233 }
1234
1235 void setEnabledSessionInMainThread(SessionState session) {
1236 if (mEnabledSession != session) {
1237 if (mEnabledSession != null) {
1238 try {
1239 if (DEBUG) Log.v(TAG, "Disabling: " + mEnabledSession);
1240 mEnabledSession.method.setSessionEnabled(
1241 mEnabledSession.session, false);
1242 } catch (RemoteException e) {
1243 }
1244 }
1245 mEnabledSession = session;
1246 try {
1247 if (DEBUG) Log.v(TAG, "Enabling: " + mEnabledSession);
1248 session.method.setSessionEnabled(
1249 session.session, true);
1250 } catch (RemoteException e) {
1251 }
1252 }
1253 }
1254
1255 public boolean handleMessage(Message msg) {
1256 HandlerCaller.SomeArgs args;
1257 switch (msg.what) {
1258 case MSG_SHOW_IM_PICKER:
1259 showInputMethodMenu();
1260 return true;
1261
1262 // ---------------------------------------------------------
1263
1264 case MSG_UNBIND_INPUT:
1265 try {
1266 ((IInputMethod)msg.obj).unbindInput();
1267 } catch (RemoteException e) {
1268 // There is nothing interesting about the method dying.
1269 }
1270 return true;
1271 case MSG_BIND_INPUT:
1272 args = (HandlerCaller.SomeArgs)msg.obj;
1273 try {
1274 ((IInputMethod)args.arg1).bindInput((InputBinding)args.arg2);
1275 } catch (RemoteException e) {
1276 }
1277 return true;
1278 case MSG_SHOW_SOFT_INPUT:
The Android Open Source Project4df24232009-03-05 14:34:35 -08001279 args = (HandlerCaller.SomeArgs)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 try {
The Android Open Source Project4df24232009-03-05 14:34:35 -08001281 ((IInputMethod)args.arg1).showSoftInput(msg.arg1,
1282 (ResultReceiver)args.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 } catch (RemoteException e) {
1284 }
1285 return true;
1286 case MSG_HIDE_SOFT_INPUT:
The Android Open Source Project4df24232009-03-05 14:34:35 -08001287 args = (HandlerCaller.SomeArgs)msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 try {
The Android Open Source Project4df24232009-03-05 14:34:35 -08001289 ((IInputMethod)args.arg1).hideSoftInput(0,
1290 (ResultReceiver)args.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 } catch (RemoteException e) {
1292 }
1293 return true;
1294 case MSG_ATTACH_TOKEN:
1295 args = (HandlerCaller.SomeArgs)msg.obj;
1296 try {
1297 if (DEBUG) Log.v(TAG, "Sending attach of token: " + args.arg2);
1298 ((IInputMethod)args.arg1).attachToken((IBinder)args.arg2);
1299 } catch (RemoteException e) {
1300 }
1301 return true;
1302 case MSG_CREATE_SESSION:
1303 args = (HandlerCaller.SomeArgs)msg.obj;
1304 try {
1305 ((IInputMethod)args.arg1).createSession(
1306 (IInputMethodCallback)args.arg2);
1307 } catch (RemoteException e) {
1308 }
1309 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 // ---------------------------------------------------------
1311
1312 case MSG_START_INPUT:
1313 args = (HandlerCaller.SomeArgs)msg.obj;
1314 try {
1315 SessionState session = (SessionState)args.arg1;
1316 setEnabledSessionInMainThread(session);
1317 session.method.startInput((IInputContext)args.arg2,
1318 (EditorInfo)args.arg3);
1319 } catch (RemoteException e) {
1320 }
1321 return true;
1322 case MSG_RESTART_INPUT:
1323 args = (HandlerCaller.SomeArgs)msg.obj;
1324 try {
1325 SessionState session = (SessionState)args.arg1;
1326 setEnabledSessionInMainThread(session);
1327 session.method.restartInput((IInputContext)args.arg2,
1328 (EditorInfo)args.arg3);
1329 } catch (RemoteException e) {
1330 }
1331 return true;
1332
1333 // ---------------------------------------------------------
1334
1335 case MSG_UNBIND_METHOD:
1336 try {
1337 ((IInputMethodClient)msg.obj).onUnbindMethod(msg.arg1);
1338 } catch (RemoteException e) {
1339 // There is nothing interesting about the last client dying.
1340 }
1341 return true;
1342 case MSG_BIND_METHOD:
1343 args = (HandlerCaller.SomeArgs)msg.obj;
1344 try {
1345 ((IInputMethodClient)args.arg1).onBindMethod(
1346 (InputBindResult)args.arg2);
1347 } catch (RemoteException e) {
1348 Log.w(TAG, "Client died receiving input method " + args.arg2);
1349 }
1350 return true;
1351 }
1352 return false;
1353 }
1354
1355 void buildInputMethodListLocked(ArrayList<InputMethodInfo> list,
1356 HashMap<String, InputMethodInfo> map) {
1357 list.clear();
1358 map.clear();
1359
1360 PackageManager pm = mContext.getPackageManager();
1361
1362 List<ResolveInfo> services = pm.queryIntentServices(
1363 new Intent(InputMethod.SERVICE_INTERFACE),
1364 PackageManager.GET_META_DATA);
1365
1366 for (int i = 0; i < services.size(); ++i) {
1367 ResolveInfo ri = services.get(i);
1368 ServiceInfo si = ri.serviceInfo;
1369 ComponentName compName = new ComponentName(si.packageName, si.name);
1370 if (!android.Manifest.permission.BIND_INPUT_METHOD.equals(
1371 si.permission)) {
1372 Log.w(TAG, "Skipping input method " + compName
1373 + ": it does not require the permission "
1374 + android.Manifest.permission.BIND_INPUT_METHOD);
1375 continue;
1376 }
1377
1378 if (DEBUG) Log.d(TAG, "Checking " + compName);
1379
1380 try {
1381 InputMethodInfo p = new InputMethodInfo(mContext, ri);
1382 list.add(p);
1383 map.put(p.getId(), p);
1384
1385 if (DEBUG) {
1386 Log.d(TAG, "Found a third-party input method " + p);
1387 }
1388
1389 } catch (XmlPullParserException e) {
1390 Log.w(TAG, "Unable to load input method " + compName, e);
1391 } catch (IOException e) {
1392 Log.w(TAG, "Unable to load input method " + compName, e);
1393 }
1394 }
1395 }
1396
1397 // ----------------------------------------------------------------------
1398
1399 void showInputMethodMenu() {
1400 if (DEBUG) Log.v(TAG, "Show switching menu");
1401
1402 hideInputMethodMenu();
1403
1404 final Context context = mContext;
1405
1406 final PackageManager pm = context.getPackageManager();
1407
1408 String lastInputMethodId = Settings.Secure.getString(context
1409 .getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);
1410 if (DEBUG) Log.v(TAG, "Current IME: " + lastInputMethodId);
1411
1412 final List<InputMethodInfo> immis = getEnabledInputMethodList();
1413
1414 int N = (immis == null ? 0 : immis.size());
1415
1416 mItems = new CharSequence[N];
1417 mIms = new InputMethodInfo[N];
1418
1419 for (int i = 0; i < N; ++i) {
1420 InputMethodInfo property = immis.get(i);
1421 mItems[i] = property.loadLabel(pm);
1422 mIms[i] = property;
1423 }
1424
1425 int checkedItem = 0;
1426 for (int i = 0; i < N; ++i) {
1427 if (mIms[i].getId().equals(lastInputMethodId)) {
1428 checkedItem = i;
1429 break;
1430 }
1431 }
1432
1433 AlertDialog.OnClickListener adocl = new AlertDialog.OnClickListener() {
1434 public void onClick(DialogInterface dialog, int which) {
1435 hideInputMethodMenu();
1436 }
1437 };
1438
1439 TypedArray a = context.obtainStyledAttributes(null,
1440 com.android.internal.R.styleable.DialogPreference,
1441 com.android.internal.R.attr.alertDialogStyle, 0);
1442 mDialogBuilder = new AlertDialog.Builder(context)
1443 .setTitle(com.android.internal.R.string.select_input_method)
1444 .setOnCancelListener(new OnCancelListener() {
1445 public void onCancel(DialogInterface dialog) {
1446 hideInputMethodMenu();
1447 }
1448 })
1449 .setIcon(a.getDrawable(
1450 com.android.internal.R.styleable.DialogPreference_dialogTitle));
1451 a.recycle();
1452
1453 mDialogBuilder.setSingleChoiceItems(mItems, checkedItem,
1454 new AlertDialog.OnClickListener() {
1455 public void onClick(DialogInterface dialog, int which) {
1456 synchronized (mMethodMap) {
1457 InputMethodInfo im = mIms[which];
1458 hideInputMethodMenu();
1459 setInputMethodLocked(im.getId());
1460 }
1461 }
1462 });
1463
1464 synchronized (mMethodMap) {
1465 mSwitchingDialog = mDialogBuilder.create();
1466 mSwitchingDialog.getWindow().setType(
1467 WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG);
1468 mSwitchingDialog.show();
1469 }
1470 }
1471
1472 void hideInputMethodMenu() {
The Android Open Source Project10592532009-03-18 17:39:46 -07001473 synchronized (mMethodMap) {
1474 hideInputMethodMenuLocked();
1475 }
1476 }
1477
1478 void hideInputMethodMenuLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 if (DEBUG) Log.v(TAG, "Hide switching menu");
1480
The Android Open Source Project10592532009-03-18 17:39:46 -07001481 if (mSwitchingDialog != null) {
1482 mSwitchingDialog.dismiss();
1483 mSwitchingDialog = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001485
1486 mDialogBuilder = null;
1487 mItems = null;
1488 mIms = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 }
1490
1491 // ----------------------------------------------------------------------
1492
1493 public boolean setInputMethodEnabled(String id, boolean enabled) {
1494 synchronized (mMethodMap) {
1495 if (mContext.checkCallingOrSelfPermission(
1496 android.Manifest.permission.WRITE_SECURE_SETTINGS)
1497 != PackageManager.PERMISSION_GRANTED) {
1498 throw new SecurityException(
1499 "Requires permission "
1500 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
1501 }
1502
1503 long ident = Binder.clearCallingIdentity();
1504 try {
1505 // Make sure this is a valid input method.
1506 InputMethodInfo imm = mMethodMap.get(id);
1507 if (imm == null) {
1508 if (imm == null) {
1509 throw new IllegalArgumentException("Unknown id: " + mCurMethodId);
1510 }
1511 }
1512
1513 StringBuilder builder = new StringBuilder(256);
1514
1515 boolean removed = false;
1516 String firstId = null;
1517
1518 // Look through the currently enabled input methods.
1519 String enabledStr = Settings.Secure.getString(mContext.getContentResolver(),
1520 Settings.Secure.ENABLED_INPUT_METHODS);
1521 if (enabledStr != null) {
1522 final TextUtils.SimpleStringSplitter splitter = mStringColonSplitter;
1523 splitter.setString(enabledStr);
1524 while (splitter.hasNext()) {
1525 String curId = splitter.next();
1526 if (curId.equals(id)) {
1527 if (enabled) {
1528 // We are enabling this input method, but it is
1529 // already enabled. Nothing to do. The previous
1530 // state was enabled.
1531 return true;
1532 }
1533 // We are disabling this input method, and it is
1534 // currently enabled. Skip it to remove from the
1535 // new list.
1536 removed = true;
1537 } else if (!enabled) {
1538 // We are building a new list of input methods that
1539 // doesn't contain the given one.
1540 if (firstId == null) firstId = curId;
1541 if (builder.length() > 0) builder.append(':');
1542 builder.append(curId);
1543 }
1544 }
1545 }
1546
1547 if (!enabled) {
1548 if (!removed) {
1549 // We are disabling the input method but it is already
1550 // disabled. Nothing to do. The previous state was
1551 // disabled.
1552 return false;
1553 }
1554 // Update the setting with the new list of input methods.
1555 Settings.Secure.putString(mContext.getContentResolver(),
1556 Settings.Secure.ENABLED_INPUT_METHODS, builder.toString());
1557 // We the disabled input method is currently selected, switch
1558 // to another one.
1559 String selId = Settings.Secure.getString(mContext.getContentResolver(),
1560 Settings.Secure.DEFAULT_INPUT_METHOD);
1561 if (id.equals(selId)) {
1562 Settings.Secure.putString(mContext.getContentResolver(),
1563 Settings.Secure.DEFAULT_INPUT_METHOD,
1564 firstId != null ? firstId : "");
1565 }
1566 // Previous state was enabled.
1567 return true;
1568 }
1569
1570 // Add in the newly enabled input method.
1571 if (enabledStr == null || enabledStr.length() == 0) {
1572 enabledStr = id;
1573 } else {
1574 enabledStr = enabledStr + ':' + id;
1575 }
1576
1577 Settings.Secure.putString(mContext.getContentResolver(),
1578 Settings.Secure.ENABLED_INPUT_METHODS, enabledStr);
1579
1580 // Previous state was disabled.
1581 return false;
1582 } finally {
1583 Binder.restoreCallingIdentity(ident);
1584 }
1585 }
1586 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08001587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 // ----------------------------------------------------------------------
1589
1590 @Override
1591 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1592 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1593 != PackageManager.PERMISSION_GRANTED) {
1594
1595 pw.println("Permission Denial: can't dump InputMethodManager from from pid="
1596 + Binder.getCallingPid()
1597 + ", uid=" + Binder.getCallingUid());
1598 return;
1599 }
1600
1601 IInputMethod method;
1602 ClientState client;
1603
1604 final Printer p = new PrintWriterPrinter(pw);
1605
1606 synchronized (mMethodMap) {
1607 p.println("Current Input Method Manager state:");
1608 int N = mMethodList.size();
1609 p.println(" Input Methods:");
1610 for (int i=0; i<N; i++) {
1611 InputMethodInfo info = mMethodList.get(i);
1612 p.println(" InputMethod #" + i + ":");
1613 info.dump(p, " ");
1614 }
1615 p.println(" Clients:");
1616 for (ClientState ci : mClients.values()) {
1617 p.println(" Client " + ci + ":");
1618 p.println(" client=" + ci.client);
1619 p.println(" inputContext=" + ci.inputContext);
1620 p.println(" sessionRequested=" + ci.sessionRequested);
1621 p.println(" curSession=" + ci.curSession);
1622 }
1623 p.println(" mInputMethodIcon=" + mInputMethodIcon);
1624 p.println(" mInputMethodData=" + mInputMethodData);
The Android Open Source Project10592532009-03-18 17:39:46 -07001625 p.println(" mCurMethodId=" + mCurMethodId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 client = mCurClient;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001627 p.println(" mCurClient=" + client + " mCurSeq=" + mCurSeq);
1628 p.println(" mCurFocusedWindow=" + mCurFocusedWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 p.println(" mCurId=" + mCurId + " mHaveConnect=" + mHaveConnection
1630 + " mBoundToMethod=" + mBoundToMethod);
1631 p.println(" mCurToken=" + mCurToken);
1632 p.println(" mCurIntent=" + mCurIntent);
1633 method = mCurMethod;
1634 p.println(" mCurMethod=" + mCurMethod);
1635 p.println(" mEnabledSession=" + mEnabledSession);
1636 p.println(" mShowRequested=" + mShowRequested
1637 + " mShowExplicitlyRequested=" + mShowExplicitlyRequested
1638 + " mShowForced=" + mShowForced
1639 + " mInputShown=" + mInputShown);
1640 p.println(" mScreenOn=" + mScreenOn);
1641 }
1642
1643 if (client != null) {
1644 p.println(" ");
1645 pw.flush();
1646 try {
1647 client.client.asBinder().dump(fd, args);
1648 } catch (RemoteException e) {
1649 p.println("Input method client dead: " + e);
1650 }
1651 }
1652
1653 if (method != null) {
1654 p.println(" ");
1655 pw.flush();
1656 try {
1657 method.asBinder().dump(fd, args);
1658 } catch (RemoteException e) {
1659 p.println("Input method service dead: " + e);
1660 }
1661 }
1662 }
1663}