blob: e2e0ba9cc0b9454fa9ccde620906a1d0a75514d9 [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;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070035import 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;
Brandon Ballinger6da35a02009-10-21 00:38:13 -070044import 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 /**
Dianne Hackborna34f1ad2009-09-02 13:26:28 -0700185 * 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);
Brandon Ballinger6da35a02009-10-21 00:38:13 -0700370 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?
Brandon Ballinger6da35a02009-10-21 00:38:13 -0700384 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() {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -0700500 synchronized (mMethodMap) {
501 if (!mSystemReady) {
502 mSystemReady = true;
Dianne Hackborncc278702009-09-02 23:07:23 -0700503 try {
504 startInputInnerLocked();
505 } catch (RuntimeException e) {
506 Log.w(TAG, "Unexpected exception", e);
507 }
Dianne Hackborna34f1ad2009-09-02 13:26:28 -0700508 }
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
Dianne Hackborna34f1ad2009-09-02 13:26:28 -0700729 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.
Dianne Hackborncc278702009-09-02 23:07:23 -0700740 return new InputBindResult(null, mCurMethodId, mCurSeq);
Dianne Hackborna34f1ad2009-09-02 13:26:28 -0700741 }
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());
Dianne Hackborndd9b82c2009-09-03 00:18:47 -0700752 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);
Dianne Hackborncc278702009-09-02 23:07:23 -0700797 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) {
Dianne Hackborncc278702009-09-02 23:07:23 -0700806 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(
Dianne Hackborncc278702009-09-02 23:07:23 -0700809 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
858 void clearCurMethodLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 if (mCurMethod != null) {
860 for (ClientState cs : mClients.values()) {
861 cs.sessionRequested = false;
862 cs.curSession = null;
863 }
864 mCurMethod = null;
865 }
866 mStatusBar.setIconVisibility(mInputMethodIcon, false);
867 }
868
869 public void onServiceDisconnected(ComponentName name) {
870 synchronized (mMethodMap) {
871 if (DEBUG) Log.v(TAG, "Service disconnected: " + name
872 + " mCurIntent=" + mCurIntent);
873 if (mCurMethod != null && mCurIntent != null
874 && name.equals(mCurIntent.getComponent())) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700875 clearCurMethodLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 // We consider this to be a new bind attempt, since the system
877 // should now try to restart the service for us.
878 mLastBindTime = SystemClock.uptimeMillis();
879 mShowRequested = mInputShown;
880 mInputShown = false;
881 if (mCurClient != null) {
882 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
883 MSG_UNBIND_METHOD, mCurSeq, mCurClient.client));
884 }
885 }
886 }
887 }
888
889 public void updateStatusIcon(IBinder token, String packageName, int iconId) {
890 long ident = Binder.clearCallingIdentity();
891 try {
892 if (token == null || mCurToken != token) {
893 Log.w(TAG, "Ignoring setInputMethod of token: " + token);
894 return;
895 }
896
897 synchronized (mMethodMap) {
898 if (iconId == 0) {
899 if (DEBUG) Log.d(TAG, "hide the small icon for the input method");
900 mStatusBar.setIconVisibility(mInputMethodIcon, false);
901 } else if (packageName != null) {
902 if (DEBUG) Log.d(TAG, "show a small icon for the input method");
903 mInputMethodData.iconId = iconId;
904 mInputMethodData.iconPackage = packageName;
905 mStatusBar.updateIcon(mInputMethodIcon, mInputMethodData, null);
906 mStatusBar.setIconVisibility(mInputMethodIcon, true);
907 }
908 }
909 } finally {
910 Binder.restoreCallingIdentity(ident);
911 }
912 }
913
914 void updateFromSettingsLocked() {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700915 // We are assuming that whoever is changing DEFAULT_INPUT_METHOD and
916 // ENABLED_INPUT_METHODS is taking care of keeping them correctly in
917 // sync, so we will never have a DEFAULT_INPUT_METHOD that is not
918 // enabled.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 String id = Settings.Secure.getString(mContext.getContentResolver(),
920 Settings.Secure.DEFAULT_INPUT_METHOD);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700921 if (id != null && id.length() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 try {
923 setInputMethodLocked(id);
924 } catch (IllegalArgumentException e) {
925 Log.w(TAG, "Unknown input method from prefs: " + id, e);
The Android Open Source Project10592532009-03-18 17:39:46 -0700926 mCurMethodId = null;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700927 unbindCurrentMethodLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700929 } else {
930 // There is no longer an input method set, so stop any current one.
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 }
934 }
935
936 void setInputMethodLocked(String id) {
937 InputMethodInfo info = mMethodMap.get(id);
938 if (info == null) {
939 throw new IllegalArgumentException("Unknown id: " + mCurMethodId);
940 }
941
942 if (id.equals(mCurMethodId)) {
943 return;
944 }
945
946 final long ident = Binder.clearCallingIdentity();
947 try {
948 mCurMethodId = id;
949 Settings.Secure.putString(mContext.getContentResolver(),
950 Settings.Secure.DEFAULT_INPUT_METHOD, id);
951
952 if (ActivityManagerNative.isSystemReady()) {
953 Intent intent = new Intent(Intent.ACTION_INPUT_METHOD_CHANGED);
954 intent.putExtra("input_method_id", id);
955 mContext.sendBroadcast(intent);
956 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700957 unbindCurrentClientLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 } finally {
959 Binder.restoreCallingIdentity(ident);
960 }
961 }
962
The Android Open Source Project4df24232009-03-05 14:34:35 -0800963 public boolean showSoftInput(IInputMethodClient client, int flags,
964 ResultReceiver resultReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 long ident = Binder.clearCallingIdentity();
966 try {
967 synchronized (mMethodMap) {
968 if (mCurClient == null || client == null
969 || mCurClient.client.asBinder() != client.asBinder()) {
970 try {
971 // We need to check if this is the current client with
972 // focus in the window manager, to allow this call to
973 // be made before input is started in it.
974 if (!mIWindowManager.inputMethodClientHasFocus(client)) {
975 Log.w(TAG, "Ignoring showSoftInput of: " + client);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800976 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 }
978 } catch (RemoteException e) {
The Android Open Source Project4df24232009-03-05 14:34:35 -0800979 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 }
981 }
982
983 if (DEBUG) Log.v(TAG, "Client requesting input be shown");
The Android Open Source Project4df24232009-03-05 14:34:35 -0800984 return showCurrentInputLocked(flags, resultReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 }
986 } finally {
987 Binder.restoreCallingIdentity(ident);
988 }
989 }
990
The Android Open Source Project4df24232009-03-05 14:34:35 -0800991 boolean showCurrentInputLocked(int flags, ResultReceiver resultReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 mShowRequested = true;
993 if ((flags&InputMethodManager.SHOW_IMPLICIT) == 0) {
994 mShowExplicitlyRequested = true;
995 }
996 if ((flags&InputMethodManager.SHOW_FORCED) != 0) {
997 mShowExplicitlyRequested = true;
998 mShowForced = true;
999 }
Dianne Hackborncc278702009-09-02 23:07:23 -07001000
1001 if (!mSystemReady) {
1002 return false;
1003 }
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
Brandon Ballinger6da35a02009-10-21 00:38:13 -07001355 private boolean isSystemIme(InputMethodInfo inputMethod) {
1356 return (inputMethod.getServiceInfo().applicationInfo.flags
1357 & ApplicationInfo.FLAG_SYSTEM) != 0;
1358 }
1359
1360 private boolean chooseNewDefaultIME() {
1361 List<InputMethodInfo> enabled = getEnabledInputMethodListLocked();
1362 if (enabled != null && enabled.size() > 0) {
1363 Settings.Secure.putString(mContext.getContentResolver(),
1364 Settings.Secure.DEFAULT_INPUT_METHOD,
1365 enabled.get(0).getId());
1366 return true;
1367 }
1368
1369 return false;
1370 }
1371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 void buildInputMethodListLocked(ArrayList<InputMethodInfo> list,
1373 HashMap<String, InputMethodInfo> map) {
1374 list.clear();
1375 map.clear();
1376
1377 PackageManager pm = mContext.getPackageManager();
1378
1379 List<ResolveInfo> services = pm.queryIntentServices(
1380 new Intent(InputMethod.SERVICE_INTERFACE),
1381 PackageManager.GET_META_DATA);
1382
1383 for (int i = 0; i < services.size(); ++i) {
1384 ResolveInfo ri = services.get(i);
1385 ServiceInfo si = ri.serviceInfo;
1386 ComponentName compName = new ComponentName(si.packageName, si.name);
1387 if (!android.Manifest.permission.BIND_INPUT_METHOD.equals(
1388 si.permission)) {
1389 Log.w(TAG, "Skipping input method " + compName
1390 + ": it does not require the permission "
1391 + android.Manifest.permission.BIND_INPUT_METHOD);
1392 continue;
1393 }
1394
1395 if (DEBUG) Log.d(TAG, "Checking " + compName);
1396
1397 try {
1398 InputMethodInfo p = new InputMethodInfo(mContext, ri);
1399 list.add(p);
1400 map.put(p.getId(), p);
1401
Brandon Ballinger6da35a02009-10-21 00:38:13 -07001402 // System IMEs are enabled by default
1403 if (isSystemIme(p)) {
1404 setInputMethodEnabled(p.getId(), true);
1405 }
1406
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 if (DEBUG) {
1408 Log.d(TAG, "Found a third-party input method " + p);
1409 }
1410
1411 } catch (XmlPullParserException e) {
1412 Log.w(TAG, "Unable to load input method " + compName, e);
1413 } catch (IOException e) {
1414 Log.w(TAG, "Unable to load input method " + compName, e);
1415 }
1416 }
Brandon Ballinger6da35a02009-10-21 00:38:13 -07001417
1418 String defaultIme = Settings.Secure.getString(mContext
1419 .getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);
1420 if (!map.containsKey(defaultIme)) {
1421 if (chooseNewDefaultIME()) {
1422 updateFromSettingsLocked();
1423 }
1424 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 }
1426
1427 // ----------------------------------------------------------------------
1428
1429 void showInputMethodMenu() {
1430 if (DEBUG) Log.v(TAG, "Show switching menu");
1431
1432 hideInputMethodMenu();
1433
1434 final Context context = mContext;
1435
1436 final PackageManager pm = context.getPackageManager();
1437
1438 String lastInputMethodId = Settings.Secure.getString(context
1439 .getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);
1440 if (DEBUG) Log.v(TAG, "Current IME: " + lastInputMethodId);
1441
1442 final List<InputMethodInfo> immis = getEnabledInputMethodList();
1443
1444 int N = (immis == null ? 0 : immis.size());
1445
1446 mItems = new CharSequence[N];
1447 mIms = new InputMethodInfo[N];
1448
1449 for (int i = 0; i < N; ++i) {
1450 InputMethodInfo property = immis.get(i);
1451 mItems[i] = property.loadLabel(pm);
1452 mIms[i] = property;
1453 }
1454
1455 int checkedItem = 0;
1456 for (int i = 0; i < N; ++i) {
1457 if (mIms[i].getId().equals(lastInputMethodId)) {
1458 checkedItem = i;
1459 break;
1460 }
1461 }
1462
1463 AlertDialog.OnClickListener adocl = new AlertDialog.OnClickListener() {
1464 public void onClick(DialogInterface dialog, int which) {
1465 hideInputMethodMenu();
1466 }
1467 };
1468
1469 TypedArray a = context.obtainStyledAttributes(null,
1470 com.android.internal.R.styleable.DialogPreference,
1471 com.android.internal.R.attr.alertDialogStyle, 0);
1472 mDialogBuilder = new AlertDialog.Builder(context)
1473 .setTitle(com.android.internal.R.string.select_input_method)
1474 .setOnCancelListener(new OnCancelListener() {
1475 public void onCancel(DialogInterface dialog) {
1476 hideInputMethodMenu();
1477 }
1478 })
1479 .setIcon(a.getDrawable(
1480 com.android.internal.R.styleable.DialogPreference_dialogTitle));
1481 a.recycle();
1482
1483 mDialogBuilder.setSingleChoiceItems(mItems, checkedItem,
1484 new AlertDialog.OnClickListener() {
1485 public void onClick(DialogInterface dialog, int which) {
1486 synchronized (mMethodMap) {
1487 InputMethodInfo im = mIms[which];
1488 hideInputMethodMenu();
1489 setInputMethodLocked(im.getId());
1490 }
1491 }
1492 });
1493
1494 synchronized (mMethodMap) {
1495 mSwitchingDialog = mDialogBuilder.create();
1496 mSwitchingDialog.getWindow().setType(
1497 WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG);
1498 mSwitchingDialog.show();
1499 }
1500 }
1501
1502 void hideInputMethodMenu() {
The Android Open Source Project10592532009-03-18 17:39:46 -07001503 synchronized (mMethodMap) {
1504 hideInputMethodMenuLocked();
1505 }
1506 }
1507
1508 void hideInputMethodMenuLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 if (DEBUG) Log.v(TAG, "Hide switching menu");
1510
The Android Open Source Project10592532009-03-18 17:39:46 -07001511 if (mSwitchingDialog != null) {
1512 mSwitchingDialog.dismiss();
1513 mSwitchingDialog = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001515
1516 mDialogBuilder = null;
1517 mItems = null;
1518 mIms = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 }
1520
1521 // ----------------------------------------------------------------------
1522
1523 public boolean setInputMethodEnabled(String id, boolean enabled) {
1524 synchronized (mMethodMap) {
1525 if (mContext.checkCallingOrSelfPermission(
1526 android.Manifest.permission.WRITE_SECURE_SETTINGS)
1527 != PackageManager.PERMISSION_GRANTED) {
1528 throw new SecurityException(
1529 "Requires permission "
1530 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
1531 }
1532
1533 long ident = Binder.clearCallingIdentity();
1534 try {
1535 // Make sure this is a valid input method.
1536 InputMethodInfo imm = mMethodMap.get(id);
1537 if (imm == null) {
1538 if (imm == null) {
1539 throw new IllegalArgumentException("Unknown id: " + mCurMethodId);
1540 }
1541 }
1542
1543 StringBuilder builder = new StringBuilder(256);
1544
1545 boolean removed = false;
1546 String firstId = null;
1547
1548 // Look through the currently enabled input methods.
1549 String enabledStr = Settings.Secure.getString(mContext.getContentResolver(),
1550 Settings.Secure.ENABLED_INPUT_METHODS);
1551 if (enabledStr != null) {
1552 final TextUtils.SimpleStringSplitter splitter = mStringColonSplitter;
1553 splitter.setString(enabledStr);
1554 while (splitter.hasNext()) {
1555 String curId = splitter.next();
1556 if (curId.equals(id)) {
1557 if (enabled) {
1558 // We are enabling this input method, but it is
1559 // already enabled. Nothing to do. The previous
1560 // state was enabled.
1561 return true;
1562 }
1563 // We are disabling this input method, and it is
1564 // currently enabled. Skip it to remove from the
1565 // new list.
1566 removed = true;
1567 } else if (!enabled) {
1568 // We are building a new list of input methods that
1569 // doesn't contain the given one.
1570 if (firstId == null) firstId = curId;
1571 if (builder.length() > 0) builder.append(':');
1572 builder.append(curId);
1573 }
1574 }
1575 }
1576
1577 if (!enabled) {
1578 if (!removed) {
1579 // We are disabling the input method but it is already
1580 // disabled. Nothing to do. The previous state was
1581 // disabled.
1582 return false;
1583 }
1584 // Update the setting with the new list of input methods.
1585 Settings.Secure.putString(mContext.getContentResolver(),
1586 Settings.Secure.ENABLED_INPUT_METHODS, builder.toString());
1587 // We the disabled input method is currently selected, switch
1588 // to another one.
1589 String selId = Settings.Secure.getString(mContext.getContentResolver(),
1590 Settings.Secure.DEFAULT_INPUT_METHOD);
1591 if (id.equals(selId)) {
1592 Settings.Secure.putString(mContext.getContentResolver(),
1593 Settings.Secure.DEFAULT_INPUT_METHOD,
1594 firstId != null ? firstId : "");
1595 }
1596 // Previous state was enabled.
1597 return true;
1598 }
1599
1600 // Add in the newly enabled input method.
1601 if (enabledStr == null || enabledStr.length() == 0) {
1602 enabledStr = id;
1603 } else {
1604 enabledStr = enabledStr + ':' + id;
1605 }
1606
1607 Settings.Secure.putString(mContext.getContentResolver(),
1608 Settings.Secure.ENABLED_INPUT_METHODS, enabledStr);
1609
1610 // Previous state was disabled.
1611 return false;
1612 } finally {
1613 Binder.restoreCallingIdentity(ident);
1614 }
1615 }
1616 }
The Android Open Source Project4df24232009-03-05 14:34:35 -08001617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 // ----------------------------------------------------------------------
1619
1620 @Override
1621 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1622 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1623 != PackageManager.PERMISSION_GRANTED) {
1624
1625 pw.println("Permission Denial: can't dump InputMethodManager from from pid="
1626 + Binder.getCallingPid()
1627 + ", uid=" + Binder.getCallingUid());
1628 return;
1629 }
1630
1631 IInputMethod method;
1632 ClientState client;
1633
1634 final Printer p = new PrintWriterPrinter(pw);
1635
1636 synchronized (mMethodMap) {
1637 p.println("Current Input Method Manager state:");
1638 int N = mMethodList.size();
1639 p.println(" Input Methods:");
1640 for (int i=0; i<N; i++) {
1641 InputMethodInfo info = mMethodList.get(i);
1642 p.println(" InputMethod #" + i + ":");
1643 info.dump(p, " ");
1644 }
1645 p.println(" Clients:");
1646 for (ClientState ci : mClients.values()) {
1647 p.println(" Client " + ci + ":");
1648 p.println(" client=" + ci.client);
1649 p.println(" inputContext=" + ci.inputContext);
1650 p.println(" sessionRequested=" + ci.sessionRequested);
1651 p.println(" curSession=" + ci.curSession);
1652 }
1653 p.println(" mInputMethodIcon=" + mInputMethodIcon);
1654 p.println(" mInputMethodData=" + mInputMethodData);
The Android Open Source Project10592532009-03-18 17:39:46 -07001655 p.println(" mCurMethodId=" + mCurMethodId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 client = mCurClient;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001657 p.println(" mCurClient=" + client + " mCurSeq=" + mCurSeq);
1658 p.println(" mCurFocusedWindow=" + mCurFocusedWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 p.println(" mCurId=" + mCurId + " mHaveConnect=" + mHaveConnection
1660 + " mBoundToMethod=" + mBoundToMethod);
1661 p.println(" mCurToken=" + mCurToken);
1662 p.println(" mCurIntent=" + mCurIntent);
1663 method = mCurMethod;
1664 p.println(" mCurMethod=" + mCurMethod);
1665 p.println(" mEnabledSession=" + mEnabledSession);
1666 p.println(" mShowRequested=" + mShowRequested
1667 + " mShowExplicitlyRequested=" + mShowExplicitlyRequested
1668 + " mShowForced=" + mShowForced
1669 + " mInputShown=" + mInputShown);
Dianne Hackborncc278702009-09-02 23:07:23 -07001670 p.println(" mSystemReady=" + mSystemReady + " mScreenOn=" + mScreenOn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 }
1672
1673 if (client != null) {
1674 p.println(" ");
1675 pw.flush();
1676 try {
1677 client.client.asBinder().dump(fd, args);
1678 } catch (RemoteException e) {
1679 p.println("Input method client dead: " + e);
1680 }
1681 }
1682
1683 if (method != null) {
1684 p.println(" ");
1685 pw.flush();
1686 try {
1687 method.asBinder().dump(fd, args);
1688 } catch (RemoteException e) {
1689 p.println("Input method service dead: " + e);
1690 }
1691 }
1692 }
1693}