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