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