InputMethodManagerService.java revision cf44a124ab4eca431b3c57776183cd3857113e6f
1/* 2 * 3 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 4 * use this file except in compliance with the License. You may obtain a copy of 5 * the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 * License for the specific language governing permissions and limitations under 13 * the License. 14 */ 15 16package com.android.server; 17 18import com.android.internal.content.PackageMonitor; 19import com.android.internal.inputmethod.InputMethodUtils; 20import com.android.internal.inputmethod.InputMethodUtils.InputMethodSettings; 21import com.android.internal.os.HandlerCaller; 22import com.android.internal.os.SomeArgs; 23import com.android.internal.util.FastXmlSerializer; 24import com.android.internal.view.IInputContext; 25import com.android.internal.view.IInputMethod; 26import com.android.internal.view.IInputSessionCallback; 27import com.android.internal.view.IInputMethodClient; 28import com.android.internal.view.IInputMethodManager; 29import com.android.internal.view.IInputMethodSession; 30import com.android.internal.view.InputBindResult; 31import com.android.server.statusbar.StatusBarManagerService; 32import com.android.server.wm.WindowManagerService; 33 34import org.xmlpull.v1.XmlPullParser; 35import org.xmlpull.v1.XmlPullParserException; 36import org.xmlpull.v1.XmlSerializer; 37 38import android.app.ActivityManagerNative; 39import android.app.AppGlobals; 40import android.app.AlertDialog; 41import android.app.IUserSwitchObserver; 42import android.app.KeyguardManager; 43import android.app.Notification; 44import android.app.NotificationManager; 45import android.app.PendingIntent; 46import android.content.BroadcastReceiver; 47import android.content.ComponentName; 48import android.content.ContentResolver; 49import android.content.Context; 50import android.content.DialogInterface; 51import android.content.DialogInterface.OnCancelListener; 52import android.content.Intent; 53import android.content.IntentFilter; 54import android.content.ServiceConnection; 55import android.content.pm.ApplicationInfo; 56import android.content.pm.IPackageManager; 57import android.content.pm.PackageManager; 58import android.content.pm.ResolveInfo; 59import android.content.pm.ServiceInfo; 60import android.content.res.Configuration; 61import android.content.res.Resources; 62import android.content.res.TypedArray; 63import android.database.ContentObserver; 64import android.inputmethodservice.InputMethodService; 65import android.os.Binder; 66import android.os.Environment; 67import android.os.Handler; 68import android.os.IBinder; 69import android.os.IInterface; 70import android.os.IRemoteCallback; 71import android.os.Message; 72import android.os.Process; 73import android.os.Parcel; 74import android.os.RemoteException; 75import android.os.ResultReceiver; 76import android.os.ServiceManager; 77import android.os.SystemClock; 78import android.os.UserHandle; 79import android.provider.Settings; 80import android.text.TextUtils; 81import android.text.style.SuggestionSpan; 82import android.util.AtomicFile; 83import android.util.EventLog; 84import android.util.LruCache; 85import android.util.Pair; 86import android.util.PrintWriterPrinter; 87import android.util.Printer; 88import android.util.Slog; 89import android.util.Xml; 90import android.view.IWindowManager; 91import android.view.InputChannel; 92import android.view.LayoutInflater; 93import android.view.View; 94import android.view.ViewGroup; 95import android.view.WindowManager; 96import android.view.inputmethod.EditorInfo; 97import android.view.inputmethod.InputBinding; 98import android.view.inputmethod.InputMethod; 99import android.view.inputmethod.InputMethodInfo; 100import android.view.inputmethod.InputMethodManager; 101import android.view.inputmethod.InputMethodSubtype; 102import android.widget.ArrayAdapter; 103import android.widget.CompoundButton; 104import android.widget.CompoundButton.OnCheckedChangeListener; 105import android.widget.RadioButton; 106import android.widget.Switch; 107import android.widget.TextView; 108 109import java.io.File; 110import java.io.FileDescriptor; 111import java.io.FileInputStream; 112import java.io.FileOutputStream; 113import java.io.IOException; 114import java.io.PrintWriter; 115import java.util.ArrayList; 116import java.util.Collections; 117import java.util.Comparator; 118import java.util.HashMap; 119import java.util.HashSet; 120import java.util.List; 121import java.util.Locale; 122import java.util.TreeMap; 123 124/** 125 * This class provides a system service that manages input methods. 126 */ 127public class InputMethodManagerService extends IInputMethodManager.Stub 128 implements ServiceConnection, Handler.Callback { 129 static final boolean DEBUG = false; 130 static final String TAG = "InputMethodManagerService"; 131 132 static final int MSG_SHOW_IM_PICKER = 1; 133 static final int MSG_SHOW_IM_SUBTYPE_PICKER = 2; 134 static final int MSG_SHOW_IM_SUBTYPE_ENABLER = 3; 135 static final int MSG_SHOW_IM_CONFIG = 4; 136 137 static final int MSG_UNBIND_INPUT = 1000; 138 static final int MSG_BIND_INPUT = 1010; 139 static final int MSG_SHOW_SOFT_INPUT = 1020; 140 static final int MSG_HIDE_SOFT_INPUT = 1030; 141 static final int MSG_ATTACH_TOKEN = 1040; 142 static final int MSG_CREATE_SESSION = 1050; 143 144 static final int MSG_START_INPUT = 2000; 145 static final int MSG_RESTART_INPUT = 2010; 146 147 static final int MSG_UNBIND_METHOD = 3000; 148 static final int MSG_BIND_METHOD = 3010; 149 static final int MSG_SET_ACTIVE = 3020; 150 151 static final int MSG_HARD_KEYBOARD_SWITCH_CHANGED = 4000; 152 153 static final long TIME_TO_RECONNECT = 10*1000; 154 155 static final int SECURE_SUGGESTION_SPANS_MAX_SIZE = 20; 156 157 private static final int NOT_A_SUBTYPE_ID = InputMethodUtils.NOT_A_SUBTYPE_ID; 158 private static final String TAG_TRY_SUPPRESSING_IME_SWITCHER = "TrySuppressingImeSwitcher"; 159 160 161 final Context mContext; 162 final Resources mRes; 163 final Handler mHandler; 164 final InputMethodSettings mSettings; 165 final SettingsObserver mSettingsObserver; 166 final IWindowManager mIWindowManager; 167 final HandlerCaller mCaller; 168 final boolean mHasFeature; 169 private InputMethodFileManager mFileManager; 170 private InputMethodAndSubtypeListManager mImListManager; 171 private final HardKeyboardListener mHardKeyboardListener; 172 private final WindowManagerService mWindowManagerService; 173 174 final InputBindResult mNoBinding = new InputBindResult(null, null, null, -1); 175 176 // All known input methods. mMethodMap also serves as the global 177 // lock for this class. 178 final ArrayList<InputMethodInfo> mMethodList = new ArrayList<InputMethodInfo>(); 179 final HashMap<String, InputMethodInfo> mMethodMap = new HashMap<String, InputMethodInfo>(); 180 private final LruCache<SuggestionSpan, InputMethodInfo> mSecureSuggestionSpans = 181 new LruCache<SuggestionSpan, InputMethodInfo>(SECURE_SUGGESTION_SPANS_MAX_SIZE); 182 183 // Used to bring IME service up to visible adjustment while it is being shown. 184 final ServiceConnection mVisibleConnection = new ServiceConnection() { 185 @Override public void onServiceConnected(ComponentName name, IBinder service) { 186 } 187 188 @Override public void onServiceDisconnected(ComponentName name) { 189 } 190 }; 191 boolean mVisibleBound = false; 192 193 // Ongoing notification 194 private NotificationManager mNotificationManager; 195 private KeyguardManager mKeyguardManager; 196 private StatusBarManagerService mStatusBar; 197 private Notification mImeSwitcherNotification; 198 private PendingIntent mImeSwitchPendingIntent; 199 private boolean mShowOngoingImeSwitcherForPhones; 200 private boolean mNotificationShown; 201 private final boolean mImeSelectedOnBoot; 202 203 class SessionState { 204 final ClientState client; 205 final IInputMethod method; 206 207 IInputMethodSession session; 208 InputChannel channel; 209 210 @Override 211 public String toString() { 212 return "SessionState{uid " + client.uid + " pid " + client.pid 213 + " method " + Integer.toHexString( 214 System.identityHashCode(method)) 215 + " session " + Integer.toHexString( 216 System.identityHashCode(session)) 217 + " channel " + channel 218 + "}"; 219 } 220 221 SessionState(ClientState _client, IInputMethod _method, 222 IInputMethodSession _session, InputChannel _channel) { 223 client = _client; 224 method = _method; 225 session = _session; 226 channel = _channel; 227 } 228 } 229 230 static final class ClientState { 231 final IInputMethodClient client; 232 final IInputContext inputContext; 233 final int uid; 234 final int pid; 235 final InputBinding binding; 236 237 boolean sessionRequested; 238 SessionState curSession; 239 240 @Override 241 public String toString() { 242 return "ClientState{" + Integer.toHexString( 243 System.identityHashCode(this)) + " uid " + uid 244 + " pid " + pid + "}"; 245 } 246 247 ClientState(IInputMethodClient _client, IInputContext _inputContext, 248 int _uid, int _pid) { 249 client = _client; 250 inputContext = _inputContext; 251 uid = _uid; 252 pid = _pid; 253 binding = new InputBinding(null, inputContext.asBinder(), uid, pid); 254 } 255 } 256 257 final HashMap<IBinder, ClientState> mClients 258 = new HashMap<IBinder, ClientState>(); 259 260 /** 261 * Set once the system is ready to run third party code. 262 */ 263 boolean mSystemReady; 264 265 /** 266 * Id of the currently selected input method. 267 */ 268 String mCurMethodId; 269 270 /** 271 * The current binding sequence number, incremented every time there is 272 * a new bind performed. 273 */ 274 int mCurSeq; 275 276 /** 277 * The client that is currently bound to an input method. 278 */ 279 ClientState mCurClient; 280 281 /** 282 * The last window token that gained focus. 283 */ 284 IBinder mCurFocusedWindow; 285 286 /** 287 * The input context last provided by the current client. 288 */ 289 IInputContext mCurInputContext; 290 291 /** 292 * The attributes last provided by the current client. 293 */ 294 EditorInfo mCurAttribute; 295 296 /** 297 * The input method ID of the input method service that we are currently 298 * connected to or in the process of connecting to. 299 */ 300 String mCurId; 301 302 /** 303 * The current subtype of the current input method. 304 */ 305 private InputMethodSubtype mCurrentSubtype; 306 307 // This list contains the pairs of InputMethodInfo and InputMethodSubtype. 308 private final HashMap<InputMethodInfo, ArrayList<InputMethodSubtype>> 309 mShortcutInputMethodsAndSubtypes = 310 new HashMap<InputMethodInfo, ArrayList<InputMethodSubtype>>(); 311 312 // Was the keyguard locked when this client became current? 313 private boolean mCurClientInKeyguard; 314 315 /** 316 * Set to true if our ServiceConnection is currently actively bound to 317 * a service (whether or not we have gotten its IBinder back yet). 318 */ 319 boolean mHaveConnection; 320 321 /** 322 * Set if the client has asked for the input method to be shown. 323 */ 324 boolean mShowRequested; 325 326 /** 327 * Set if we were explicitly told to show the input method. 328 */ 329 boolean mShowExplicitlyRequested; 330 331 /** 332 * Set if we were forced to be shown. 333 */ 334 boolean mShowForced; 335 336 /** 337 * Set if we last told the input method to show itself. 338 */ 339 boolean mInputShown; 340 341 /** 342 * The Intent used to connect to the current input method. 343 */ 344 Intent mCurIntent; 345 346 /** 347 * The token we have made for the currently active input method, to 348 * identify it in the future. 349 */ 350 IBinder mCurToken; 351 352 /** 353 * If non-null, this is the input method service we are currently connected 354 * to. 355 */ 356 IInputMethod mCurMethod; 357 358 /** 359 * Time that we last initiated a bind to the input method, to determine 360 * if we should try to disconnect and reconnect to it. 361 */ 362 long mLastBindTime; 363 364 /** 365 * Have we called mCurMethod.bindInput()? 366 */ 367 boolean mBoundToMethod; 368 369 /** 370 * Currently enabled session. Only touched by service thread, not 371 * protected by a lock. 372 */ 373 SessionState mEnabledSession; 374 375 /** 376 * True if the screen is on. The value is true initially. 377 */ 378 boolean mScreenOn = true; 379 380 int mBackDisposition = InputMethodService.BACK_DISPOSITION_DEFAULT; 381 int mImeWindowVis; 382 383 private AlertDialog.Builder mDialogBuilder; 384 private AlertDialog mSwitchingDialog; 385 private View mSwitchingDialogTitleView; 386 private InputMethodInfo[] mIms; 387 private int[] mSubtypeIds; 388 private Locale mLastSystemLocale; 389 private final MyPackageMonitor mMyPackageMonitor = new MyPackageMonitor(); 390 private final IPackageManager mIPackageManager; 391 392 class SettingsObserver extends ContentObserver { 393 String mLastEnabled = ""; 394 395 SettingsObserver(Handler handler) { 396 super(handler); 397 ContentResolver resolver = mContext.getContentResolver(); 398 resolver.registerContentObserver(Settings.Secure.getUriFor( 399 Settings.Secure.DEFAULT_INPUT_METHOD), false, this); 400 resolver.registerContentObserver(Settings.Secure.getUriFor( 401 Settings.Secure.ENABLED_INPUT_METHODS), false, this); 402 resolver.registerContentObserver(Settings.Secure.getUriFor( 403 Settings.Secure.SELECTED_INPUT_METHOD_SUBTYPE), false, this); 404 } 405 406 @Override public void onChange(boolean selfChange) { 407 synchronized (mMethodMap) { 408 boolean enabledChanged = false; 409 String newEnabled = mSettings.getEnabledInputMethodsStr(); 410 if (!mLastEnabled.equals(newEnabled)) { 411 mLastEnabled = newEnabled; 412 enabledChanged = true; 413 } 414 updateFromSettingsLocked(enabledChanged); 415 } 416 } 417 } 418 419 class ImmsBroadcastReceiver extends android.content.BroadcastReceiver { 420 private void updateActive() { 421 // Inform the current client of the change in active status 422 if (mCurClient != null && mCurClient.client != null) { 423 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO( 424 MSG_SET_ACTIVE, mScreenOn ? 1 : 0, mCurClient)); 425 } 426 } 427 428 @Override 429 public void onReceive(Context context, Intent intent) { 430 final String action = intent.getAction(); 431 if (Intent.ACTION_SCREEN_ON.equals(action)) { 432 mScreenOn = true; 433 refreshImeWindowVisibilityLocked(); 434 updateActive(); 435 return; 436 } else if (Intent.ACTION_SCREEN_OFF.equals(action)) { 437 mScreenOn = false; 438 setImeWindowVisibilityStatusHiddenLocked(); 439 updateActive(); 440 return; 441 } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) { 442 hideInputMethodMenu(); 443 // No need to updateActive 444 return; 445 } else { 446 Slog.w(TAG, "Unexpected intent " + intent); 447 } 448 } 449 } 450 451 class MyPackageMonitor extends PackageMonitor { 452 private boolean isChangingPackagesOfCurrentUser() { 453 final int userId = getChangingUserId(); 454 final boolean retval = userId == mSettings.getCurrentUserId(); 455 if (DEBUG) { 456 if (!retval) { 457 Slog.d(TAG, "--- ignore this call back from a background user: " + userId); 458 } 459 } 460 return retval; 461 } 462 463 @Override 464 public boolean onHandleForceStop(Intent intent, String[] packages, int uid, boolean doit) { 465 if (!isChangingPackagesOfCurrentUser()) { 466 return false; 467 } 468 synchronized (mMethodMap) { 469 String curInputMethodId = mSettings.getSelectedInputMethod(); 470 final int N = mMethodList.size(); 471 if (curInputMethodId != null) { 472 for (int i=0; i<N; i++) { 473 InputMethodInfo imi = mMethodList.get(i); 474 if (imi.getId().equals(curInputMethodId)) { 475 for (String pkg : packages) { 476 if (imi.getPackageName().equals(pkg)) { 477 if (!doit) { 478 return true; 479 } 480 resetSelectedInputMethodAndSubtypeLocked(""); 481 chooseNewDefaultIMELocked(); 482 return true; 483 } 484 } 485 } 486 } 487 } 488 } 489 return false; 490 } 491 492 @Override 493 public void onSomePackagesChanged() { 494 if (!isChangingPackagesOfCurrentUser()) { 495 return; 496 } 497 synchronized (mMethodMap) { 498 InputMethodInfo curIm = null; 499 String curInputMethodId = mSettings.getSelectedInputMethod(); 500 final int N = mMethodList.size(); 501 if (curInputMethodId != null) { 502 for (int i=0; i<N; i++) { 503 InputMethodInfo imi = mMethodList.get(i); 504 final String imiId = imi.getId(); 505 if (imiId.equals(curInputMethodId)) { 506 curIm = imi; 507 } 508 509 int change = isPackageDisappearing(imi.getPackageName()); 510 if (isPackageModified(imi.getPackageName())) { 511 mFileManager.deleteAllInputMethodSubtypes(imiId); 512 } 513 if (change == PACKAGE_TEMPORARY_CHANGE 514 || change == PACKAGE_PERMANENT_CHANGE) { 515 Slog.i(TAG, "Input method uninstalled, disabling: " 516 + imi.getComponent()); 517 setInputMethodEnabledLocked(imi.getId(), false); 518 } 519 } 520 } 521 522 buildInputMethodListLocked( 523 mMethodList, mMethodMap, false /* resetDefaultEnabledIme */); 524 525 boolean changed = false; 526 527 if (curIm != null) { 528 int change = isPackageDisappearing(curIm.getPackageName()); 529 if (change == PACKAGE_TEMPORARY_CHANGE 530 || change == PACKAGE_PERMANENT_CHANGE) { 531 ServiceInfo si = null; 532 try { 533 si = mIPackageManager.getServiceInfo( 534 curIm.getComponent(), 0, mSettings.getCurrentUserId()); 535 } catch (RemoteException ex) { 536 } 537 if (si == null) { 538 // Uh oh, current input method is no longer around! 539 // Pick another one... 540 Slog.i(TAG, "Current input method removed: " + curInputMethodId); 541 setImeWindowVisibilityStatusHiddenLocked(); 542 if (!chooseNewDefaultIMELocked()) { 543 changed = true; 544 curIm = null; 545 Slog.i(TAG, "Unsetting current input method"); 546 resetSelectedInputMethodAndSubtypeLocked(""); 547 } 548 } 549 } 550 } 551 552 if (curIm == null) { 553 // We currently don't have a default input method... is 554 // one now available? 555 changed = chooseNewDefaultIMELocked(); 556 } 557 558 if (changed) { 559 updateFromSettingsLocked(false); 560 } 561 } 562 } 563 } 564 565 private static final class MethodCallback extends IInputSessionCallback.Stub { 566 private final InputMethodManagerService mParentIMMS; 567 private final IInputMethod mMethod; 568 private final InputChannel mChannel; 569 570 MethodCallback(InputMethodManagerService imms, IInputMethod method, 571 InputChannel channel) { 572 mParentIMMS = imms; 573 mMethod = method; 574 mChannel = channel; 575 } 576 577 @Override 578 public void sessionCreated(IInputMethodSession session) { 579 mParentIMMS.onSessionCreated(mMethod, session, mChannel); 580 } 581 } 582 583 private class HardKeyboardListener 584 implements WindowManagerService.OnHardKeyboardStatusChangeListener { 585 @Override 586 public void onHardKeyboardStatusChange(boolean available, boolean enabled) { 587 mHandler.sendMessage(mHandler.obtainMessage( 588 MSG_HARD_KEYBOARD_SWITCH_CHANGED, available ? 1 : 0, enabled ? 1 : 0)); 589 } 590 591 public void handleHardKeyboardStatusChange(boolean available, boolean enabled) { 592 if (DEBUG) { 593 Slog.w(TAG, "HardKeyboardStatusChanged: available = " + available + ", enabled = " 594 + enabled); 595 } 596 synchronized(mMethodMap) { 597 if (mSwitchingDialog != null && mSwitchingDialogTitleView != null 598 && mSwitchingDialog.isShowing()) { 599 mSwitchingDialogTitleView.findViewById( 600 com.android.internal.R.id.hard_keyboard_section).setVisibility( 601 available ? View.VISIBLE : View.GONE); 602 } 603 } 604 } 605 } 606 607 public InputMethodManagerService(Context context, WindowManagerService windowManager) { 608 mIPackageManager = AppGlobals.getPackageManager(); 609 mContext = context; 610 mRes = context.getResources(); 611 mHandler = new Handler(this); 612 mIWindowManager = IWindowManager.Stub.asInterface( 613 ServiceManager.getService(Context.WINDOW_SERVICE)); 614 mCaller = new HandlerCaller(context, null, new HandlerCaller.Callback() { 615 @Override 616 public void executeMessage(Message msg) { 617 handleMessage(msg); 618 } 619 }, true /*asyncHandler*/); 620 mWindowManagerService = windowManager; 621 mHardKeyboardListener = new HardKeyboardListener(); 622 mHasFeature = context.getPackageManager().hasSystemFeature( 623 PackageManager.FEATURE_INPUT_METHODS); 624 625 mImeSwitcherNotification = new Notification(); 626 mImeSwitcherNotification.icon = com.android.internal.R.drawable.ic_notification_ime_default; 627 mImeSwitcherNotification.when = 0; 628 mImeSwitcherNotification.flags = Notification.FLAG_ONGOING_EVENT; 629 mImeSwitcherNotification.tickerText = null; 630 mImeSwitcherNotification.defaults = 0; // please be quiet 631 mImeSwitcherNotification.sound = null; 632 mImeSwitcherNotification.vibrate = null; 633 634 // Tag this notification specially so SystemUI knows it's important 635 mImeSwitcherNotification.extras.putBoolean(Notification.EXTRA_ALLOW_DURING_SETUP, true); 636 mImeSwitcherNotification.category = Notification.CATEGORY_SYSTEM; 637 638 Intent intent = new Intent(Settings.ACTION_SHOW_INPUT_METHOD_PICKER); 639 mImeSwitchPendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0); 640 641 mShowOngoingImeSwitcherForPhones = false; 642 643 final IntentFilter broadcastFilter = new IntentFilter(); 644 broadcastFilter.addAction(Intent.ACTION_SCREEN_ON); 645 broadcastFilter.addAction(Intent.ACTION_SCREEN_OFF); 646 broadcastFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); 647 mContext.registerReceiver(new ImmsBroadcastReceiver(), broadcastFilter); 648 649 mNotificationShown = false; 650 int userId = 0; 651 try { 652 ActivityManagerNative.getDefault().registerUserSwitchObserver( 653 new IUserSwitchObserver.Stub() { 654 @Override 655 public void onUserSwitching(int newUserId, IRemoteCallback reply) { 656 synchronized(mMethodMap) { 657 switchUserLocked(newUserId); 658 } 659 if (reply != null) { 660 try { 661 reply.sendResult(null); 662 } catch (RemoteException e) { 663 } 664 } 665 } 666 667 @Override 668 public void onUserSwitchComplete(int newUserId) throws RemoteException { 669 } 670 }); 671 userId = ActivityManagerNative.getDefault().getCurrentUser().id; 672 } catch (RemoteException e) { 673 Slog.w(TAG, "Couldn't get current user ID; guessing it's 0", e); 674 } 675 mMyPackageMonitor.register(mContext, null, UserHandle.ALL, true); 676 677 // mSettings should be created before buildInputMethodListLocked 678 mSettings = new InputMethodSettings( 679 mRes, context.getContentResolver(), mMethodMap, mMethodList, userId); 680 mFileManager = new InputMethodFileManager(mMethodMap, userId); 681 mImListManager = new InputMethodAndSubtypeListManager(context, this); 682 683 // Just checking if defaultImiId is empty or not 684 final String defaultImiId = mSettings.getSelectedInputMethod(); 685 if (DEBUG) { 686 Slog.d(TAG, "Initial default ime = " + defaultImiId); 687 } 688 mImeSelectedOnBoot = !TextUtils.isEmpty(defaultImiId); 689 690 buildInputMethodListLocked(mMethodList, mMethodMap, 691 !mImeSelectedOnBoot /* resetDefaultEnabledIme */); 692 mSettings.enableAllIMEsIfThereIsNoEnabledIME(); 693 694 if (!mImeSelectedOnBoot) { 695 Slog.w(TAG, "No IME selected. Choose the most applicable IME."); 696 resetDefaultImeLocked(context); 697 } 698 699 mSettingsObserver = new SettingsObserver(mHandler); 700 updateFromSettingsLocked(true); 701 702 // IMMS wants to receive Intent.ACTION_LOCALE_CHANGED in order to update the current IME 703 // according to the new system locale. 704 final IntentFilter filter = new IntentFilter(); 705 filter.addAction(Intent.ACTION_LOCALE_CHANGED); 706 mContext.registerReceiver( 707 new BroadcastReceiver() { 708 @Override 709 public void onReceive(Context context, Intent intent) { 710 synchronized(mMethodMap) { 711 resetStateIfCurrentLocaleChangedLocked(); 712 } 713 } 714 }, filter); 715 } 716 717 private void resetDefaultImeLocked(Context context) { 718 // Do not reset the default (current) IME when it is a 3rd-party IME 719 if (mCurMethodId != null 720 && !InputMethodUtils.isSystemIme(mMethodMap.get(mCurMethodId))) { 721 return; 722 } 723 724 InputMethodInfo defIm = null; 725 for (InputMethodInfo imi : mMethodList) { 726 if (defIm == null) { 727 if (InputMethodUtils.isValidSystemDefaultIme( 728 mSystemReady, imi, context)) { 729 defIm = imi; 730 Slog.i(TAG, "Selected default: " + imi.getId()); 731 } 732 } 733 } 734 if (defIm == null && mMethodList.size() > 0) { 735 defIm = InputMethodUtils.getMostApplicableDefaultIME( 736 mSettings.getEnabledInputMethodListLocked()); 737 Slog.i(TAG, "No default found, using " + defIm.getId()); 738 } 739 if (defIm != null) { 740 setSelectedInputMethodAndSubtypeLocked(defIm, NOT_A_SUBTYPE_ID, false); 741 } 742 } 743 744 private void resetAllInternalStateLocked(final boolean updateOnlyWhenLocaleChanged, 745 final boolean resetDefaultEnabledIme) { 746 if (!mSystemReady) { 747 // not system ready 748 return; 749 } 750 final Locale newLocale = mRes.getConfiguration().locale; 751 if (!updateOnlyWhenLocaleChanged 752 || (newLocale != null && !newLocale.equals(mLastSystemLocale))) { 753 if (!updateOnlyWhenLocaleChanged) { 754 hideCurrentInputLocked(0, null); 755 mCurMethodId = null; 756 unbindCurrentMethodLocked(true, false); 757 } 758 if (DEBUG) { 759 Slog.i(TAG, "Locale has been changed to " + newLocale); 760 } 761 // InputMethodAndSubtypeListManager should be reset when the locale is changed. 762 mImListManager = new InputMethodAndSubtypeListManager(mContext, this); 763 buildInputMethodListLocked(mMethodList, mMethodMap, resetDefaultEnabledIme); 764 if (!updateOnlyWhenLocaleChanged) { 765 final String selectedImiId = mSettings.getSelectedInputMethod(); 766 if (TextUtils.isEmpty(selectedImiId)) { 767 // This is the first time of the user switch and 768 // set the current ime to the proper one. 769 resetDefaultImeLocked(mContext); 770 } 771 } else { 772 // If the locale is changed, needs to reset the default ime 773 resetDefaultImeLocked(mContext); 774 } 775 updateFromSettingsLocked(true); 776 mLastSystemLocale = newLocale; 777 if (!updateOnlyWhenLocaleChanged) { 778 try { 779 startInputInnerLocked(); 780 } catch (RuntimeException e) { 781 Slog.w(TAG, "Unexpected exception", e); 782 } 783 } 784 } 785 } 786 787 private void resetStateIfCurrentLocaleChangedLocked() { 788 resetAllInternalStateLocked(true /* updateOnlyWhenLocaleChanged */, 789 true /* resetDefaultImeLocked */); 790 } 791 792 private void switchUserLocked(int newUserId) { 793 mSettings.setCurrentUserId(newUserId); 794 // InputMethodFileManager should be reset when the user is changed 795 mFileManager = new InputMethodFileManager(mMethodMap, newUserId); 796 final String defaultImiId = mSettings.getSelectedInputMethod(); 797 // For secondary users, the list of enabled IMEs may not have been updated since the 798 // callbacks to PackageMonitor are ignored for the secondary user. Here, defaultImiId may 799 // not be empty even if the IME has been uninstalled by the primary user. 800 // Even in such cases, IMMS works fine because it will find the most applicable 801 // IME for that user. 802 final boolean initialUserSwitch = TextUtils.isEmpty(defaultImiId); 803 if (DEBUG) { 804 Slog.d(TAG, "Switch user: " + newUserId + " current ime = " + defaultImiId); 805 } 806 resetAllInternalStateLocked(false /* updateOnlyWhenLocaleChanged */, 807 initialUserSwitch /* needsToResetDefaultIme */); 808 if (initialUserSwitch) { 809 InputMethodUtils.setNonSelectedSystemImesDisabledUntilUsed(mContext.getPackageManager(), 810 mSettings.getEnabledInputMethodListLocked()); 811 } 812 } 813 814 @Override 815 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 816 throws RemoteException { 817 try { 818 return super.onTransact(code, data, reply, flags); 819 } catch (RuntimeException e) { 820 // The input method manager only throws security exceptions, so let's 821 // log all others. 822 if (!(e instanceof SecurityException)) { 823 Slog.wtf(TAG, "Input Method Manager Crash", e); 824 } 825 throw e; 826 } 827 } 828 829 public void systemRunning(StatusBarManagerService statusBar) { 830 synchronized (mMethodMap) { 831 if (DEBUG) { 832 Slog.d(TAG, "--- systemReady"); 833 } 834 if (!mSystemReady) { 835 mSystemReady = true; 836 mKeyguardManager = 837 (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE); 838 mNotificationManager = (NotificationManager) 839 mContext.getSystemService(Context.NOTIFICATION_SERVICE); 840 mStatusBar = statusBar; 841 statusBar.setIconVisibility("ime", false); 842 updateImeWindowStatusLocked(); 843 mShowOngoingImeSwitcherForPhones = mRes.getBoolean( 844 com.android.internal.R.bool.show_ongoing_ime_switcher); 845 if (mShowOngoingImeSwitcherForPhones) { 846 mWindowManagerService.setOnHardKeyboardStatusChangeListener( 847 mHardKeyboardListener); 848 } 849 buildInputMethodListLocked(mMethodList, mMethodMap, 850 !mImeSelectedOnBoot /* resetDefaultEnabledIme */); 851 if (!mImeSelectedOnBoot) { 852 Slog.w(TAG, "Reset the default IME as \"Resource\" is ready here."); 853 resetStateIfCurrentLocaleChangedLocked(); 854 InputMethodUtils.setNonSelectedSystemImesDisabledUntilUsed( 855 mContext.getPackageManager(), 856 mSettings.getEnabledInputMethodListLocked()); 857 } 858 mLastSystemLocale = mRes.getConfiguration().locale; 859 try { 860 startInputInnerLocked(); 861 } catch (RuntimeException e) { 862 Slog.w(TAG, "Unexpected exception", e); 863 } 864 } 865 } 866 } 867 868 private void setImeWindowVisibilityStatusHiddenLocked() { 869 mImeWindowVis = 0; 870 updateImeWindowStatusLocked(); 871 } 872 873 private void refreshImeWindowVisibilityLocked() { 874 final Configuration conf = mRes.getConfiguration(); 875 final boolean haveHardKeyboard = conf.keyboard 876 != Configuration.KEYBOARD_NOKEYS; 877 final boolean hardKeyShown = haveHardKeyboard 878 && conf.hardKeyboardHidden 879 != Configuration.HARDKEYBOARDHIDDEN_YES; 880 881 final boolean isScreenLocked = isKeyguardLocked(); 882 final boolean inputActive = !isScreenLocked && (mInputShown || hardKeyShown); 883 // We assume the softkeyboard is shown when the input is active as long as the 884 // hard keyboard is not shown. 885 final boolean inputVisible = inputActive && !hardKeyShown; 886 mImeWindowVis = (inputActive ? InputMethodService.IME_ACTIVE : 0) 887 | (inputVisible ? InputMethodService.IME_VISIBLE : 0); 888 updateImeWindowStatusLocked(); 889 } 890 891 private void updateImeWindowStatusLocked() { 892 setImeWindowStatus(mCurToken, mImeWindowVis, mBackDisposition); 893 } 894 895 // --------------------------------------------------------------------------------------- 896 // Check whether or not this is a valid IPC. Assumes an IPC is valid when either 897 // 1) it comes from the system process 898 // 2) the calling process' user id is identical to the current user id IMMS thinks. 899 private boolean calledFromValidUser() { 900 final int uid = Binder.getCallingUid(); 901 final int userId = UserHandle.getUserId(uid); 902 if (DEBUG) { 903 Slog.d(TAG, "--- calledFromForegroundUserOrSystemProcess ? " 904 + "calling uid = " + uid + " system uid = " + Process.SYSTEM_UID 905 + " calling userId = " + userId + ", foreground user id = " 906 + mSettings.getCurrentUserId() + ", calling pid = " + Binder.getCallingPid() 907 + InputMethodUtils.getApiCallStack()); 908 } 909 if (uid == Process.SYSTEM_UID || userId == mSettings.getCurrentUserId()) { 910 return true; 911 } 912 913 // Caveat: A process which has INTERACT_ACROSS_USERS_FULL gets results for the 914 // foreground user, not for the user of that process. Accordingly InputMethodManagerService 915 // must not manage background users' states in any functions. 916 // Note that privacy-sensitive IPCs, such as setInputMethod, are still securely guarded 917 // by a token. 918 if (mContext.checkCallingOrSelfPermission( 919 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL) 920 == PackageManager.PERMISSION_GRANTED) { 921 if (DEBUG) { 922 Slog.d(TAG, "--- Access granted because the calling process has " 923 + "the INTERACT_ACROSS_USERS_FULL permission"); 924 } 925 return true; 926 } 927 Slog.w(TAG, "--- IPC called from background users. Ignore. \n" 928 + InputMethodUtils.getStackTrace()); 929 return false; 930 } 931 932 private boolean bindCurrentInputMethodService( 933 Intent service, ServiceConnection conn, int flags) { 934 if (service == null || conn == null) { 935 Slog.e(TAG, "--- bind failed: service = " + service + ", conn = " + conn); 936 return false; 937 } 938 return mContext.bindServiceAsUser(service, conn, flags, 939 new UserHandle(mSettings.getCurrentUserId())); 940 } 941 942 @Override 943 public List<InputMethodInfo> getInputMethodList() { 944 // TODO: Make this work even for non-current users? 945 if (!calledFromValidUser()) { 946 return Collections.emptyList(); 947 } 948 synchronized (mMethodMap) { 949 return new ArrayList<InputMethodInfo>(mMethodList); 950 } 951 } 952 953 @Override 954 public List<InputMethodInfo> getEnabledInputMethodList() { 955 // TODO: Make this work even for non-current users? 956 if (!calledFromValidUser()) { 957 return Collections.emptyList(); 958 } 959 synchronized (mMethodMap) { 960 return mSettings.getEnabledInputMethodListLocked(); 961 } 962 } 963 964 private HashMap<InputMethodInfo, List<InputMethodSubtype>> 965 getExplicitlyOrImplicitlyEnabledInputMethodsAndSubtypeListLocked() { 966 HashMap<InputMethodInfo, List<InputMethodSubtype>> enabledInputMethodAndSubtypes = 967 new HashMap<InputMethodInfo, List<InputMethodSubtype>>(); 968 for (InputMethodInfo imi: mSettings.getEnabledInputMethodListLocked()) { 969 enabledInputMethodAndSubtypes.put( 970 imi, mSettings.getEnabledInputMethodSubtypeListLocked(mContext, imi, true)); 971 } 972 return enabledInputMethodAndSubtypes; 973 } 974 975 /** 976 * @param imiId if null, returns enabled subtypes for the current imi 977 * @return enabled subtypes of the specified imi 978 */ 979 @Override 980 public List<InputMethodSubtype> getEnabledInputMethodSubtypeList(String imiId, 981 boolean allowsImplicitlySelectedSubtypes) { 982 // TODO: Make this work even for non-current users? 983 if (!calledFromValidUser()) { 984 return Collections.<InputMethodSubtype>emptyList(); 985 } 986 synchronized (mMethodMap) { 987 final InputMethodInfo imi; 988 if (imiId == null && mCurMethodId != null) { 989 imi = mMethodMap.get(mCurMethodId); 990 } else { 991 imi = mMethodMap.get(imiId); 992 } 993 if (imi == null) { 994 return Collections.<InputMethodSubtype>emptyList(); 995 } 996 return mSettings.getEnabledInputMethodSubtypeListLocked( 997 mContext, imi, allowsImplicitlySelectedSubtypes); 998 } 999 } 1000 1001 @Override 1002 public void addClient(IInputMethodClient client, 1003 IInputContext inputContext, int uid, int pid) { 1004 if (!calledFromValidUser()) { 1005 return; 1006 } 1007 synchronized (mMethodMap) { 1008 mClients.put(client.asBinder(), new ClientState(client, 1009 inputContext, uid, pid)); 1010 } 1011 } 1012 1013 @Override 1014 public void removeClient(IInputMethodClient client) { 1015 if (!calledFromValidUser()) { 1016 return; 1017 } 1018 synchronized (mMethodMap) { 1019 ClientState cs = mClients.remove(client.asBinder()); 1020 if (cs != null) { 1021 clearClientSessionLocked(cs); 1022 } 1023 } 1024 } 1025 1026 void executeOrSendMessage(IInterface target, Message msg) { 1027 if (target.asBinder() instanceof Binder) { 1028 mCaller.sendMessage(msg); 1029 } else { 1030 handleMessage(msg); 1031 msg.recycle(); 1032 } 1033 } 1034 1035 void unbindCurrentClientLocked() { 1036 if (mCurClient != null) { 1037 if (DEBUG) Slog.v(TAG, "unbindCurrentInputLocked: client = " 1038 + mCurClient.client.asBinder()); 1039 if (mBoundToMethod) { 1040 mBoundToMethod = false; 1041 if (mCurMethod != null) { 1042 executeOrSendMessage(mCurMethod, mCaller.obtainMessageO( 1043 MSG_UNBIND_INPUT, mCurMethod)); 1044 } 1045 } 1046 1047 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO( 1048 MSG_SET_ACTIVE, 0, mCurClient)); 1049 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO( 1050 MSG_UNBIND_METHOD, mCurSeq, mCurClient.client)); 1051 mCurClient.sessionRequested = false; 1052 mCurClient = null; 1053 1054 hideInputMethodMenuLocked(); 1055 } 1056 } 1057 1058 private int getImeShowFlags() { 1059 int flags = 0; 1060 if (mShowForced) { 1061 flags |= InputMethod.SHOW_FORCED 1062 | InputMethod.SHOW_EXPLICIT; 1063 } else if (mShowExplicitlyRequested) { 1064 flags |= InputMethod.SHOW_EXPLICIT; 1065 } 1066 return flags; 1067 } 1068 1069 private int getAppShowFlags() { 1070 int flags = 0; 1071 if (mShowForced) { 1072 flags |= InputMethodManager.SHOW_FORCED; 1073 } else if (!mShowExplicitlyRequested) { 1074 flags |= InputMethodManager.SHOW_IMPLICIT; 1075 } 1076 return flags; 1077 } 1078 1079 InputBindResult attachNewInputLocked(boolean initial) { 1080 if (!mBoundToMethod) { 1081 executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO( 1082 MSG_BIND_INPUT, mCurMethod, mCurClient.binding)); 1083 mBoundToMethod = true; 1084 } 1085 final SessionState session = mCurClient.curSession; 1086 if (initial) { 1087 executeOrSendMessage(session.method, mCaller.obtainMessageOOO( 1088 MSG_START_INPUT, session, mCurInputContext, mCurAttribute)); 1089 } else { 1090 executeOrSendMessage(session.method, mCaller.obtainMessageOOO( 1091 MSG_RESTART_INPUT, session, mCurInputContext, mCurAttribute)); 1092 } 1093 if (mShowRequested) { 1094 if (DEBUG) Slog.v(TAG, "Attach new input asks to show input"); 1095 showCurrentInputLocked(getAppShowFlags(), null); 1096 } 1097 return new InputBindResult(session.session, 1098 session.channel != null ? session.channel.dup() : null, mCurId, mCurSeq); 1099 } 1100 1101 InputBindResult startInputLocked(IInputMethodClient client, 1102 IInputContext inputContext, EditorInfo attribute, int controlFlags) { 1103 // If no method is currently selected, do nothing. 1104 if (mCurMethodId == null) { 1105 return mNoBinding; 1106 } 1107 1108 ClientState cs = mClients.get(client.asBinder()); 1109 if (cs == null) { 1110 throw new IllegalArgumentException("unknown client " 1111 + client.asBinder()); 1112 } 1113 1114 try { 1115 if (!mIWindowManager.inputMethodClientHasFocus(cs.client)) { 1116 // Check with the window manager to make sure this client actually 1117 // has a window with focus. If not, reject. This is thread safe 1118 // because if the focus changes some time before or after, the 1119 // next client receiving focus that has any interest in input will 1120 // be calling through here after that change happens. 1121 Slog.w(TAG, "Starting input on non-focused client " + cs.client 1122 + " (uid=" + cs.uid + " pid=" + cs.pid + ")"); 1123 return null; 1124 } 1125 } catch (RemoteException e) { 1126 } 1127 1128 return startInputUncheckedLocked(cs, inputContext, attribute, controlFlags); 1129 } 1130 1131 InputBindResult startInputUncheckedLocked(ClientState cs, 1132 IInputContext inputContext, EditorInfo attribute, int controlFlags) { 1133 // If no method is currently selected, do nothing. 1134 if (mCurMethodId == null) { 1135 return mNoBinding; 1136 } 1137 1138 if (mCurClient != cs) { 1139 // Was the keyguard locked when switching over to the new client? 1140 mCurClientInKeyguard = isKeyguardLocked(); 1141 // If the client is changing, we need to switch over to the new 1142 // one. 1143 unbindCurrentClientLocked(); 1144 if (DEBUG) Slog.v(TAG, "switching to client: client = " 1145 + cs.client.asBinder() + " keyguard=" + mCurClientInKeyguard); 1146 1147 // If the screen is on, inform the new client it is active 1148 if (mScreenOn) { 1149 executeOrSendMessage(cs.client, mCaller.obtainMessageIO( 1150 MSG_SET_ACTIVE, mScreenOn ? 1 : 0, cs)); 1151 } 1152 } 1153 1154 // Bump up the sequence for this client and attach it. 1155 mCurSeq++; 1156 if (mCurSeq <= 0) mCurSeq = 1; 1157 mCurClient = cs; 1158 mCurInputContext = inputContext; 1159 mCurAttribute = attribute; 1160 1161 // Check if the input method is changing. 1162 if (mCurId != null && mCurId.equals(mCurMethodId)) { 1163 if (cs.curSession != null) { 1164 // Fast case: if we are already connected to the input method, 1165 // then just return it. 1166 return attachNewInputLocked( 1167 (controlFlags&InputMethodManager.CONTROL_START_INITIAL) != 0); 1168 } 1169 if (mHaveConnection) { 1170 if (mCurMethod != null) { 1171 // Return to client, and we will get back with it when 1172 // we have had a session made for it. 1173 requestClientSessionLocked(cs); 1174 return new InputBindResult(null, null, mCurId, mCurSeq); 1175 } else if (SystemClock.uptimeMillis() 1176 < (mLastBindTime+TIME_TO_RECONNECT)) { 1177 // In this case we have connected to the service, but 1178 // don't yet have its interface. If it hasn't been too 1179 // long since we did the connection, we'll return to 1180 // the client and wait to get the service interface so 1181 // we can report back. If it has been too long, we want 1182 // to fall through so we can try a disconnect/reconnect 1183 // to see if we can get back in touch with the service. 1184 return new InputBindResult(null, null, mCurId, mCurSeq); 1185 } else { 1186 EventLog.writeEvent(EventLogTags.IMF_FORCE_RECONNECT_IME, 1187 mCurMethodId, SystemClock.uptimeMillis()-mLastBindTime, 0); 1188 } 1189 } 1190 } 1191 1192 return startInputInnerLocked(); 1193 } 1194 1195 InputBindResult startInputInnerLocked() { 1196 if (mCurMethodId == null) { 1197 return mNoBinding; 1198 } 1199 1200 if (!mSystemReady) { 1201 // If the system is not yet ready, we shouldn't be running third 1202 // party code. 1203 return new InputBindResult(null, null, mCurMethodId, mCurSeq); 1204 } 1205 1206 InputMethodInfo info = mMethodMap.get(mCurMethodId); 1207 if (info == null) { 1208 throw new IllegalArgumentException("Unknown id: " + mCurMethodId); 1209 } 1210 1211 unbindCurrentMethodLocked(false, true); 1212 1213 mCurIntent = new Intent(InputMethod.SERVICE_INTERFACE); 1214 mCurIntent.setComponent(info.getComponent()); 1215 mCurIntent.putExtra(Intent.EXTRA_CLIENT_LABEL, 1216 com.android.internal.R.string.input_method_binding_label); 1217 mCurIntent.putExtra(Intent.EXTRA_CLIENT_INTENT, PendingIntent.getActivity( 1218 mContext, 0, new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS), 0)); 1219 if (bindCurrentInputMethodService(mCurIntent, this, Context.BIND_AUTO_CREATE 1220 | Context.BIND_NOT_VISIBLE | Context.BIND_SHOWING_UI)) { 1221 mLastBindTime = SystemClock.uptimeMillis(); 1222 mHaveConnection = true; 1223 mCurId = info.getId(); 1224 mCurToken = new Binder(); 1225 try { 1226 if (true || DEBUG) Slog.v(TAG, "Adding window token: " + mCurToken); 1227 mIWindowManager.addWindowToken(mCurToken, 1228 WindowManager.LayoutParams.TYPE_INPUT_METHOD); 1229 } catch (RemoteException e) { 1230 } 1231 return new InputBindResult(null, null, mCurId, mCurSeq); 1232 } else { 1233 mCurIntent = null; 1234 Slog.w(TAG, "Failure connecting to input method service: " 1235 + mCurIntent); 1236 } 1237 return null; 1238 } 1239 1240 @Override 1241 public InputBindResult startInput(IInputMethodClient client, 1242 IInputContext inputContext, EditorInfo attribute, int controlFlags) { 1243 if (!calledFromValidUser()) { 1244 return null; 1245 } 1246 synchronized (mMethodMap) { 1247 final long ident = Binder.clearCallingIdentity(); 1248 try { 1249 return startInputLocked(client, inputContext, attribute, controlFlags); 1250 } finally { 1251 Binder.restoreCallingIdentity(ident); 1252 } 1253 } 1254 } 1255 1256 @Override 1257 public void finishInput(IInputMethodClient client) { 1258 } 1259 1260 @Override 1261 public void onServiceConnected(ComponentName name, IBinder service) { 1262 synchronized (mMethodMap) { 1263 if (mCurIntent != null && name.equals(mCurIntent.getComponent())) { 1264 mCurMethod = IInputMethod.Stub.asInterface(service); 1265 if (mCurToken == null) { 1266 Slog.w(TAG, "Service connected without a token!"); 1267 unbindCurrentMethodLocked(false, false); 1268 return; 1269 } 1270 if (DEBUG) Slog.v(TAG, "Initiating attach with token: " + mCurToken); 1271 executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO( 1272 MSG_ATTACH_TOKEN, mCurMethod, mCurToken)); 1273 if (mCurClient != null) { 1274 clearClientSessionLocked(mCurClient); 1275 requestClientSessionLocked(mCurClient); 1276 } 1277 } 1278 } 1279 } 1280 1281 void onSessionCreated(IInputMethod method, IInputMethodSession session, 1282 InputChannel channel) { 1283 synchronized (mMethodMap) { 1284 if (mCurMethod != null && method != null 1285 && mCurMethod.asBinder() == method.asBinder()) { 1286 if (mCurClient != null) { 1287 clearClientSessionLocked(mCurClient); 1288 mCurClient.curSession = new SessionState(mCurClient, 1289 method, session, channel); 1290 InputBindResult res = attachNewInputLocked(true); 1291 if (res.method != null) { 1292 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageOO( 1293 MSG_BIND_METHOD, mCurClient.client, res)); 1294 } 1295 return; 1296 } 1297 } 1298 } 1299 1300 // Session abandoned. Close its associated input channel. 1301 channel.dispose(); 1302 } 1303 1304 void unbindCurrentMethodLocked(boolean reportToClient, boolean savePosition) { 1305 if (mVisibleBound) { 1306 mContext.unbindService(mVisibleConnection); 1307 mVisibleBound = false; 1308 } 1309 1310 if (mHaveConnection) { 1311 mContext.unbindService(this); 1312 mHaveConnection = false; 1313 } 1314 1315 if (mCurToken != null) { 1316 try { 1317 if (DEBUG) Slog.v(TAG, "Removing window token: " + mCurToken); 1318 if ((mImeWindowVis & InputMethodService.IME_ACTIVE) != 0 && savePosition) { 1319 // The current IME is shown. Hence an IME switch (transition) is happening. 1320 mWindowManagerService.saveLastInputMethodWindowForTransition(); 1321 } 1322 mIWindowManager.removeWindowToken(mCurToken); 1323 } catch (RemoteException e) { 1324 } 1325 mCurToken = null; 1326 } 1327 1328 mCurId = null; 1329 clearCurMethodLocked(); 1330 1331 if (reportToClient && mCurClient != null) { 1332 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO( 1333 MSG_UNBIND_METHOD, mCurSeq, mCurClient.client)); 1334 } 1335 } 1336 1337 void requestClientSessionLocked(ClientState cs) { 1338 if (!cs.sessionRequested) { 1339 if (DEBUG) Slog.v(TAG, "Creating new session for client " + cs); 1340 InputChannel[] channels = InputChannel.openInputChannelPair(cs.toString()); 1341 cs.sessionRequested = true; 1342 executeOrSendMessage(mCurMethod, mCaller.obtainMessageOOO( 1343 MSG_CREATE_SESSION, mCurMethod, channels[1], 1344 new MethodCallback(this, mCurMethod, channels[0]))); 1345 } 1346 } 1347 1348 void clearClientSessionLocked(ClientState cs) { 1349 finishSessionLocked(cs.curSession); 1350 cs.curSession = null; 1351 cs.sessionRequested = false; 1352 } 1353 1354 private void finishSessionLocked(SessionState sessionState) { 1355 if (sessionState != null) { 1356 if (sessionState.session != null) { 1357 try { 1358 sessionState.session.finishSession(); 1359 } catch (RemoteException e) { 1360 Slog.w(TAG, "Session failed to close due to remote exception", e); 1361 setImeWindowVisibilityStatusHiddenLocked(); 1362 } 1363 sessionState.session = null; 1364 } 1365 if (sessionState.channel != null) { 1366 sessionState.channel.dispose(); 1367 sessionState.channel = null; 1368 } 1369 } 1370 } 1371 1372 void clearCurMethodLocked() { 1373 if (mCurMethod != null) { 1374 for (ClientState cs : mClients.values()) { 1375 clearClientSessionLocked(cs); 1376 } 1377 1378 finishSessionLocked(mEnabledSession); 1379 mEnabledSession = null; 1380 mCurMethod = null; 1381 } 1382 if (mStatusBar != null) { 1383 mStatusBar.setIconVisibility("ime", false); 1384 } 1385 } 1386 1387 @Override 1388 public void onServiceDisconnected(ComponentName name) { 1389 synchronized (mMethodMap) { 1390 if (DEBUG) Slog.v(TAG, "Service disconnected: " + name 1391 + " mCurIntent=" + mCurIntent); 1392 if (mCurMethod != null && mCurIntent != null 1393 && name.equals(mCurIntent.getComponent())) { 1394 clearCurMethodLocked(); 1395 // We consider this to be a new bind attempt, since the system 1396 // should now try to restart the service for us. 1397 mLastBindTime = SystemClock.uptimeMillis(); 1398 mShowRequested = mInputShown; 1399 mInputShown = false; 1400 if (mCurClient != null) { 1401 executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO( 1402 MSG_UNBIND_METHOD, mCurSeq, mCurClient.client)); 1403 } 1404 } 1405 } 1406 } 1407 1408 @Override 1409 public void updateStatusIcon(IBinder token, String packageName, int iconId) { 1410 int uid = Binder.getCallingUid(); 1411 long ident = Binder.clearCallingIdentity(); 1412 try { 1413 if (token == null || mCurToken != token) { 1414 Slog.w(TAG, "Ignoring setInputMethod of uid " + uid + " token: " + token); 1415 return; 1416 } 1417 1418 synchronized (mMethodMap) { 1419 if (iconId == 0) { 1420 if (DEBUG) Slog.d(TAG, "hide the small icon for the input method"); 1421 if (mStatusBar != null) { 1422 mStatusBar.setIconVisibility("ime", false); 1423 } 1424 } else if (packageName != null) { 1425 if (DEBUG) Slog.d(TAG, "show a small icon for the input method"); 1426 CharSequence contentDescription = null; 1427 try { 1428 // Use PackageManager to load label 1429 final PackageManager packageManager = mContext.getPackageManager(); 1430 contentDescription = packageManager.getApplicationLabel( 1431 mIPackageManager.getApplicationInfo(packageName, 0, 1432 mSettings.getCurrentUserId())); 1433 } catch (RemoteException e) { 1434 /* ignore */ 1435 } 1436 if (mStatusBar != null) { 1437 mStatusBar.setIcon("ime", packageName, iconId, 0, 1438 contentDescription != null 1439 ? contentDescription.toString() : null); 1440 mStatusBar.setIconVisibility("ime", true); 1441 } 1442 } 1443 } 1444 } finally { 1445 Binder.restoreCallingIdentity(ident); 1446 } 1447 } 1448 1449 private boolean needsToShowImeSwitchOngoingNotification() { 1450 if (!mShowOngoingImeSwitcherForPhones) return false; 1451 if (isScreenLocked()) return false; 1452 synchronized (mMethodMap) { 1453 List<InputMethodInfo> imis = mSettings.getEnabledInputMethodListLocked(); 1454 final int N = imis.size(); 1455 if (N > 2) return true; 1456 if (N < 1) return false; 1457 int nonAuxCount = 0; 1458 int auxCount = 0; 1459 InputMethodSubtype nonAuxSubtype = null; 1460 InputMethodSubtype auxSubtype = null; 1461 for(int i = 0; i < N; ++i) { 1462 final InputMethodInfo imi = imis.get(i); 1463 final List<InputMethodSubtype> subtypes = 1464 mSettings.getEnabledInputMethodSubtypeListLocked(mContext, imi, true); 1465 final int subtypeCount = subtypes.size(); 1466 if (subtypeCount == 0) { 1467 ++nonAuxCount; 1468 } else { 1469 for (int j = 0; j < subtypeCount; ++j) { 1470 final InputMethodSubtype subtype = subtypes.get(j); 1471 if (!subtype.isAuxiliary()) { 1472 ++nonAuxCount; 1473 nonAuxSubtype = subtype; 1474 } else { 1475 ++auxCount; 1476 auxSubtype = subtype; 1477 } 1478 } 1479 } 1480 } 1481 if (nonAuxCount > 1 || auxCount > 1) { 1482 return true; 1483 } else if (nonAuxCount == 1 && auxCount == 1) { 1484 if (nonAuxSubtype != null && auxSubtype != null 1485 && (nonAuxSubtype.getLocale().equals(auxSubtype.getLocale()) 1486 || auxSubtype.overridesImplicitlyEnabledSubtype() 1487 || nonAuxSubtype.overridesImplicitlyEnabledSubtype()) 1488 && nonAuxSubtype.containsExtraValueKey(TAG_TRY_SUPPRESSING_IME_SWITCHER)) { 1489 return false; 1490 } 1491 return true; 1492 } 1493 return false; 1494 } 1495 } 1496 1497 private boolean isKeyguardLocked() { 1498 return mKeyguardManager != null && mKeyguardManager.isKeyguardLocked(); 1499 } 1500 1501 // Caution! This method is called in this class. Handle multi-user carefully 1502 @SuppressWarnings("deprecation") 1503 @Override 1504 public void setImeWindowStatus(IBinder token, int vis, int backDisposition) { 1505 final long ident = Binder.clearCallingIdentity(); 1506 try { 1507 if (token == null || mCurToken != token) { 1508 int uid = Binder.getCallingUid(); 1509 Slog.w(TAG, "Ignoring setImeWindowStatus of uid " + uid + " token: " + token); 1510 return; 1511 } 1512 synchronized (mMethodMap) { 1513 // apply policy for binder calls 1514 if (vis != 0 && isKeyguardLocked() && !mCurClientInKeyguard) { 1515 vis = 0; 1516 } 1517 mImeWindowVis = vis; 1518 mBackDisposition = backDisposition; 1519 if (mStatusBar != null) { 1520 mStatusBar.setImeWindowStatus(token, vis, backDisposition); 1521 } 1522 final boolean iconVisibility = ((vis & (InputMethodService.IME_ACTIVE)) != 0) 1523 && (mWindowManagerService.isHardKeyboardAvailable() 1524 || (vis & (InputMethodService.IME_VISIBLE)) != 0); 1525 final InputMethodInfo imi = mMethodMap.get(mCurMethodId); 1526 if (imi != null && iconVisibility && needsToShowImeSwitchOngoingNotification()) { 1527 // Used to load label 1528 final CharSequence title = mRes.getText( 1529 com.android.internal.R.string.select_input_method); 1530 final CharSequence summary = InputMethodUtils.getImeAndSubtypeDisplayName( 1531 mContext, imi, mCurrentSubtype); 1532 1533 mImeSwitcherNotification.setLatestEventInfo( 1534 mContext, title, summary, mImeSwitchPendingIntent); 1535 if (mNotificationManager != null) { 1536 if (DEBUG) { 1537 Slog.d(TAG, "--- show notification: label = " + summary); 1538 } 1539 mNotificationManager.notifyAsUser(null, 1540 com.android.internal.R.string.select_input_method, 1541 mImeSwitcherNotification, UserHandle.ALL); 1542 mNotificationShown = true; 1543 } 1544 } else { 1545 if (mNotificationShown && mNotificationManager != null) { 1546 if (DEBUG) { 1547 Slog.d(TAG, "--- hide notification"); 1548 } 1549 mNotificationManager.cancelAsUser(null, 1550 com.android.internal.R.string.select_input_method, UserHandle.ALL); 1551 mNotificationShown = false; 1552 } 1553 } 1554 } 1555 } finally { 1556 Binder.restoreCallingIdentity(ident); 1557 } 1558 } 1559 1560 @Override 1561 public void registerSuggestionSpansForNotification(SuggestionSpan[] spans) { 1562 if (!calledFromValidUser()) { 1563 return; 1564 } 1565 synchronized (mMethodMap) { 1566 final InputMethodInfo currentImi = mMethodMap.get(mCurMethodId); 1567 for (int i = 0; i < spans.length; ++i) { 1568 SuggestionSpan ss = spans[i]; 1569 if (!TextUtils.isEmpty(ss.getNotificationTargetClassName())) { 1570 mSecureSuggestionSpans.put(ss, currentImi); 1571 } 1572 } 1573 } 1574 } 1575 1576 @Override 1577 public boolean notifySuggestionPicked(SuggestionSpan span, String originalString, int index) { 1578 if (!calledFromValidUser()) { 1579 return false; 1580 } 1581 synchronized (mMethodMap) { 1582 final InputMethodInfo targetImi = mSecureSuggestionSpans.get(span); 1583 // TODO: Do not send the intent if the process of the targetImi is already dead. 1584 if (targetImi != null) { 1585 final String[] suggestions = span.getSuggestions(); 1586 if (index < 0 || index >= suggestions.length) return false; 1587 final String className = span.getNotificationTargetClassName(); 1588 final Intent intent = new Intent(); 1589 // Ensures that only a class in the original IME package will receive the 1590 // notification. 1591 intent.setClassName(targetImi.getPackageName(), className); 1592 intent.setAction(SuggestionSpan.ACTION_SUGGESTION_PICKED); 1593 intent.putExtra(SuggestionSpan.SUGGESTION_SPAN_PICKED_BEFORE, originalString); 1594 intent.putExtra(SuggestionSpan.SUGGESTION_SPAN_PICKED_AFTER, suggestions[index]); 1595 intent.putExtra(SuggestionSpan.SUGGESTION_SPAN_PICKED_HASHCODE, span.hashCode()); 1596 final long ident = Binder.clearCallingIdentity(); 1597 try { 1598 mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT); 1599 } finally { 1600 Binder.restoreCallingIdentity(ident); 1601 } 1602 return true; 1603 } 1604 } 1605 return false; 1606 } 1607 1608 void updateFromSettingsLocked(boolean enabledMayChange) { 1609 if (enabledMayChange) { 1610 List<InputMethodInfo> enabled = mSettings.getEnabledInputMethodListLocked(); 1611 for (int i=0; i<enabled.size(); i++) { 1612 // We allow the user to select "disabled until used" apps, so if they 1613 // are enabling one of those here we now need to make it enabled. 1614 InputMethodInfo imm = enabled.get(i); 1615 try { 1616 ApplicationInfo ai = mIPackageManager.getApplicationInfo(imm.getPackageName(), 1617 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS, 1618 mSettings.getCurrentUserId()); 1619 if (ai != null && ai.enabledSetting 1620 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) { 1621 if (DEBUG) { 1622 Slog.d(TAG, "Update state(" + imm.getId() 1623 + "): DISABLED_UNTIL_USED -> DEFAULT"); 1624 } 1625 mIPackageManager.setApplicationEnabledSetting(imm.getPackageName(), 1626 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 1627 PackageManager.DONT_KILL_APP, mSettings.getCurrentUserId(), 1628 mContext.getBasePackageName()); 1629 } 1630 } catch (RemoteException e) { 1631 } 1632 } 1633 } 1634 // We are assuming that whoever is changing DEFAULT_INPUT_METHOD and 1635 // ENABLED_INPUT_METHODS is taking care of keeping them correctly in 1636 // sync, so we will never have a DEFAULT_INPUT_METHOD that is not 1637 // enabled. 1638 String id = mSettings.getSelectedInputMethod(); 1639 // There is no input method selected, try to choose new applicable input method. 1640 if (TextUtils.isEmpty(id) && chooseNewDefaultIMELocked()) { 1641 id = mSettings.getSelectedInputMethod(); 1642 } 1643 if (!TextUtils.isEmpty(id)) { 1644 try { 1645 setInputMethodLocked(id, mSettings.getSelectedInputMethodSubtypeId(id)); 1646 } catch (IllegalArgumentException e) { 1647 Slog.w(TAG, "Unknown input method from prefs: " + id, e); 1648 mCurMethodId = null; 1649 unbindCurrentMethodLocked(true, false); 1650 } 1651 mShortcutInputMethodsAndSubtypes.clear(); 1652 } else { 1653 // There is no longer an input method set, so stop any current one. 1654 mCurMethodId = null; 1655 unbindCurrentMethodLocked(true, false); 1656 } 1657 } 1658 1659 /* package */ void setInputMethodLocked(String id, int subtypeId) { 1660 InputMethodInfo info = mMethodMap.get(id); 1661 if (info == null) { 1662 throw new IllegalArgumentException("Unknown id: " + id); 1663 } 1664 1665 // See if we need to notify a subtype change within the same IME. 1666 if (id.equals(mCurMethodId)) { 1667 final int subtypeCount = info.getSubtypeCount(); 1668 if (subtypeCount <= 0) { 1669 return; 1670 } 1671 final InputMethodSubtype oldSubtype = mCurrentSubtype; 1672 final InputMethodSubtype newSubtype; 1673 if (subtypeId >= 0 && subtypeId < subtypeCount) { 1674 newSubtype = info.getSubtypeAt(subtypeId); 1675 } else { 1676 // If subtype is null, try to find the most applicable one from 1677 // getCurrentInputMethodSubtype. 1678 newSubtype = getCurrentInputMethodSubtypeLocked(); 1679 } 1680 if (newSubtype == null || oldSubtype == null) { 1681 Slog.w(TAG, "Illegal subtype state: old subtype = " + oldSubtype 1682 + ", new subtype = " + newSubtype); 1683 return; 1684 } 1685 if (newSubtype != oldSubtype) { 1686 setSelectedInputMethodAndSubtypeLocked(info, subtypeId, true); 1687 if (mCurMethod != null) { 1688 try { 1689 refreshImeWindowVisibilityLocked(); 1690 mCurMethod.changeInputMethodSubtype(newSubtype); 1691 } catch (RemoteException e) { 1692 Slog.w(TAG, "Failed to call changeInputMethodSubtype"); 1693 } 1694 } 1695 } 1696 return; 1697 } 1698 1699 // Changing to a different IME. 1700 final long ident = Binder.clearCallingIdentity(); 1701 try { 1702 // Set a subtype to this input method. 1703 // subtypeId the name of a subtype which will be set. 1704 setSelectedInputMethodAndSubtypeLocked(info, subtypeId, false); 1705 // mCurMethodId should be updated after setSelectedInputMethodAndSubtypeLocked() 1706 // because mCurMethodId is stored as a history in 1707 // setSelectedInputMethodAndSubtypeLocked(). 1708 mCurMethodId = id; 1709 1710 if (ActivityManagerNative.isSystemReady()) { 1711 Intent intent = new Intent(Intent.ACTION_INPUT_METHOD_CHANGED); 1712 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING); 1713 intent.putExtra("input_method_id", id); 1714 mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT); 1715 } 1716 unbindCurrentClientLocked(); 1717 } finally { 1718 Binder.restoreCallingIdentity(ident); 1719 } 1720 } 1721 1722 @Override 1723 public boolean showSoftInput(IInputMethodClient client, int flags, 1724 ResultReceiver resultReceiver) { 1725 if (!calledFromValidUser()) { 1726 return false; 1727 } 1728 int uid = Binder.getCallingUid(); 1729 long ident = Binder.clearCallingIdentity(); 1730 try { 1731 synchronized (mMethodMap) { 1732 if (mCurClient == null || client == null 1733 || mCurClient.client.asBinder() != client.asBinder()) { 1734 try { 1735 // We need to check if this is the current client with 1736 // focus in the window manager, to allow this call to 1737 // be made before input is started in it. 1738 if (!mIWindowManager.inputMethodClientHasFocus(client)) { 1739 Slog.w(TAG, "Ignoring showSoftInput of uid " + uid + ": " + client); 1740 return false; 1741 } 1742 } catch (RemoteException e) { 1743 return false; 1744 } 1745 } 1746 1747 if (DEBUG) Slog.v(TAG, "Client requesting input be shown"); 1748 return showCurrentInputLocked(flags, resultReceiver); 1749 } 1750 } finally { 1751 Binder.restoreCallingIdentity(ident); 1752 } 1753 } 1754 1755 boolean showCurrentInputLocked(int flags, ResultReceiver resultReceiver) { 1756 mShowRequested = true; 1757 if ((flags&InputMethodManager.SHOW_IMPLICIT) == 0) { 1758 mShowExplicitlyRequested = true; 1759 } 1760 if ((flags&InputMethodManager.SHOW_FORCED) != 0) { 1761 mShowExplicitlyRequested = true; 1762 mShowForced = true; 1763 } 1764 1765 if (!mSystemReady) { 1766 return false; 1767 } 1768 1769 boolean res = false; 1770 if (mCurMethod != null) { 1771 if (DEBUG) Slog.d(TAG, "showCurrentInputLocked: mCurToken=" + mCurToken); 1772 executeOrSendMessage(mCurMethod, mCaller.obtainMessageIOO( 1773 MSG_SHOW_SOFT_INPUT, getImeShowFlags(), mCurMethod, 1774 resultReceiver)); 1775 mInputShown = true; 1776 if (mHaveConnection && !mVisibleBound) { 1777 bindCurrentInputMethodService( 1778 mCurIntent, mVisibleConnection, Context.BIND_AUTO_CREATE); 1779 mVisibleBound = true; 1780 } 1781 res = true; 1782 } else if (mHaveConnection && SystemClock.uptimeMillis() 1783 >= (mLastBindTime+TIME_TO_RECONNECT)) { 1784 // The client has asked to have the input method shown, but 1785 // we have been sitting here too long with a connection to the 1786 // service and no interface received, so let's disconnect/connect 1787 // to try to prod things along. 1788 EventLog.writeEvent(EventLogTags.IMF_FORCE_RECONNECT_IME, mCurMethodId, 1789 SystemClock.uptimeMillis()-mLastBindTime,1); 1790 Slog.w(TAG, "Force disconnect/connect to the IME in showCurrentInputLocked()"); 1791 mContext.unbindService(this); 1792 bindCurrentInputMethodService(mCurIntent, this, Context.BIND_AUTO_CREATE 1793 | Context.BIND_NOT_VISIBLE); 1794 } else { 1795 if (DEBUG) { 1796 Slog.d(TAG, "Can't show input: connection = " + mHaveConnection + ", time = " 1797 + ((mLastBindTime+TIME_TO_RECONNECT) - SystemClock.uptimeMillis())); 1798 } 1799 } 1800 1801 return res; 1802 } 1803 1804 @Override 1805 public boolean hideSoftInput(IInputMethodClient client, int flags, 1806 ResultReceiver resultReceiver) { 1807 if (!calledFromValidUser()) { 1808 return false; 1809 } 1810 int uid = Binder.getCallingUid(); 1811 long ident = Binder.clearCallingIdentity(); 1812 try { 1813 synchronized (mMethodMap) { 1814 if (mCurClient == null || client == null 1815 || mCurClient.client.asBinder() != client.asBinder()) { 1816 try { 1817 // We need to check if this is the current client with 1818 // focus in the window manager, to allow this call to 1819 // be made before input is started in it. 1820 if (!mIWindowManager.inputMethodClientHasFocus(client)) { 1821 if (DEBUG) Slog.w(TAG, "Ignoring hideSoftInput of uid " 1822 + uid + ": " + client); 1823 setImeWindowVisibilityStatusHiddenLocked(); 1824 return false; 1825 } 1826 } catch (RemoteException e) { 1827 setImeWindowVisibilityStatusHiddenLocked(); 1828 return false; 1829 } 1830 } 1831 1832 if (DEBUG) Slog.v(TAG, "Client requesting input be hidden"); 1833 return hideCurrentInputLocked(flags, resultReceiver); 1834 } 1835 } finally { 1836 Binder.restoreCallingIdentity(ident); 1837 } 1838 } 1839 1840 boolean hideCurrentInputLocked(int flags, ResultReceiver resultReceiver) { 1841 if ((flags&InputMethodManager.HIDE_IMPLICIT_ONLY) != 0 1842 && (mShowExplicitlyRequested || mShowForced)) { 1843 if (DEBUG) Slog.v(TAG, "Not hiding: explicit show not cancelled by non-explicit hide"); 1844 return false; 1845 } 1846 if (mShowForced && (flags&InputMethodManager.HIDE_NOT_ALWAYS) != 0) { 1847 if (DEBUG) Slog.v(TAG, "Not hiding: forced show not cancelled by not-always hide"); 1848 return false; 1849 } 1850 boolean res; 1851 if (mInputShown && mCurMethod != null) { 1852 executeOrSendMessage(mCurMethod, mCaller.obtainMessageOO( 1853 MSG_HIDE_SOFT_INPUT, mCurMethod, resultReceiver)); 1854 res = true; 1855 } else { 1856 res = false; 1857 } 1858 if (mHaveConnection && mVisibleBound) { 1859 mContext.unbindService(mVisibleConnection); 1860 mVisibleBound = false; 1861 } 1862 mInputShown = false; 1863 mShowRequested = false; 1864 mShowExplicitlyRequested = false; 1865 mShowForced = false; 1866 return res; 1867 } 1868 1869 @Override 1870 public InputBindResult windowGainedFocus(IInputMethodClient client, IBinder windowToken, 1871 int controlFlags, int softInputMode, int windowFlags, 1872 EditorInfo attribute, IInputContext inputContext) { 1873 // Needs to check the validity before clearing calling identity 1874 final boolean calledFromValidUser = calledFromValidUser(); 1875 1876 InputBindResult res = null; 1877 long ident = Binder.clearCallingIdentity(); 1878 try { 1879 synchronized (mMethodMap) { 1880 if (DEBUG) Slog.v(TAG, "windowGainedFocus: " + client.asBinder() 1881 + " controlFlags=#" + Integer.toHexString(controlFlags) 1882 + " softInputMode=#" + Integer.toHexString(softInputMode) 1883 + " windowFlags=#" + Integer.toHexString(windowFlags)); 1884 1885 ClientState cs = mClients.get(client.asBinder()); 1886 if (cs == null) { 1887 throw new IllegalArgumentException("unknown client " 1888 + client.asBinder()); 1889 } 1890 1891 try { 1892 if (!mIWindowManager.inputMethodClientHasFocus(cs.client)) { 1893 // Check with the window manager to make sure this client actually 1894 // has a window with focus. If not, reject. This is thread safe 1895 // because if the focus changes some time before or after, the 1896 // next client receiving focus that has any interest in input will 1897 // be calling through here after that change happens. 1898 Slog.w(TAG, "Focus gain on non-focused client " + cs.client 1899 + " (uid=" + cs.uid + " pid=" + cs.pid + ")"); 1900 return null; 1901 } 1902 } catch (RemoteException e) { 1903 } 1904 1905 if (!calledFromValidUser) { 1906 Slog.w(TAG, "A background user is requesting window. Hiding IME."); 1907 Slog.w(TAG, "If you want to interect with IME, you need " 1908 + "android.permission.INTERACT_ACROSS_USERS_FULL"); 1909 hideCurrentInputLocked(0, null); 1910 return null; 1911 } 1912 1913 if (mCurFocusedWindow == windowToken) { 1914 Slog.w(TAG, "Window already focused, ignoring focus gain of: " + client 1915 + " attribute=" + attribute + ", token = " + windowToken); 1916 if (attribute != null) { 1917 return startInputUncheckedLocked(cs, inputContext, attribute, 1918 controlFlags); 1919 } 1920 return null; 1921 } 1922 mCurFocusedWindow = windowToken; 1923 1924 // Should we auto-show the IME even if the caller has not 1925 // specified what should be done with it? 1926 // We only do this automatically if the window can resize 1927 // to accommodate the IME (so what the user sees will give 1928 // them good context without input information being obscured 1929 // by the IME) or if running on a large screen where there 1930 // is more room for the target window + IME. 1931 final boolean doAutoShow = 1932 (softInputMode & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) 1933 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE 1934 || mRes.getConfiguration().isLayoutSizeAtLeast( 1935 Configuration.SCREENLAYOUT_SIZE_LARGE); 1936 final boolean isTextEditor = 1937 (controlFlags&InputMethodManager.CONTROL_WINDOW_IS_TEXT_EDITOR) != 0; 1938 1939 // We want to start input before showing the IME, but after closing 1940 // it. We want to do this after closing it to help the IME disappear 1941 // more quickly (not get stuck behind it initializing itself for the 1942 // new focused input, even if its window wants to hide the IME). 1943 boolean didStart = false; 1944 1945 switch (softInputMode&WindowManager.LayoutParams.SOFT_INPUT_MASK_STATE) { 1946 case WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED: 1947 if (!isTextEditor || !doAutoShow) { 1948 if (WindowManager.LayoutParams.mayUseInputMethod(windowFlags)) { 1949 // There is no focus view, and this window will 1950 // be behind any soft input window, so hide the 1951 // soft input window if it is shown. 1952 if (DEBUG) Slog.v(TAG, "Unspecified window will hide input"); 1953 hideCurrentInputLocked(InputMethodManager.HIDE_NOT_ALWAYS, null); 1954 } 1955 } else if (isTextEditor && doAutoShow && (softInputMode & 1956 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) { 1957 // There is a focus view, and we are navigating forward 1958 // into the window, so show the input window for the user. 1959 // We only do this automatically if the window can resize 1960 // to accommodate the IME (so what the user sees will give 1961 // them good context without input information being obscured 1962 // by the IME) or if running on a large screen where there 1963 // is more room for the target window + IME. 1964 if (DEBUG) Slog.v(TAG, "Unspecified window will show input"); 1965 if (attribute != null) { 1966 res = startInputUncheckedLocked(cs, inputContext, attribute, 1967 controlFlags); 1968 didStart = true; 1969 } 1970 showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null); 1971 } 1972 break; 1973 case WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED: 1974 // Do nothing. 1975 break; 1976 case WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN: 1977 if ((softInputMode & 1978 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) { 1979 if (DEBUG) Slog.v(TAG, "Window asks to hide input going forward"); 1980 hideCurrentInputLocked(0, null); 1981 } 1982 break; 1983 case WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN: 1984 if (DEBUG) Slog.v(TAG, "Window asks to hide input"); 1985 hideCurrentInputLocked(0, null); 1986 break; 1987 case WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE: 1988 if ((softInputMode & 1989 WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) != 0) { 1990 if (DEBUG) Slog.v(TAG, "Window asks to show input going forward"); 1991 if (attribute != null) { 1992 res = startInputUncheckedLocked(cs, inputContext, attribute, 1993 controlFlags); 1994 didStart = true; 1995 } 1996 showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null); 1997 } 1998 break; 1999 case WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE: 2000 if (DEBUG) Slog.v(TAG, "Window asks to always show input"); 2001 if (attribute != null) { 2002 res = startInputUncheckedLocked(cs, inputContext, attribute, 2003 controlFlags); 2004 didStart = true; 2005 } 2006 showCurrentInputLocked(InputMethodManager.SHOW_IMPLICIT, null); 2007 break; 2008 } 2009 2010 if (!didStart && attribute != null) { 2011 res = startInputUncheckedLocked(cs, inputContext, attribute, 2012 controlFlags); 2013 } 2014 } 2015 } finally { 2016 Binder.restoreCallingIdentity(ident); 2017 } 2018 2019 return res; 2020 } 2021 2022 @Override 2023 public void showInputMethodPickerFromClient(IInputMethodClient client) { 2024 if (!calledFromValidUser()) { 2025 return; 2026 } 2027 synchronized (mMethodMap) { 2028 if (mCurClient == null || client == null 2029 || mCurClient.client.asBinder() != client.asBinder()) { 2030 Slog.w(TAG, "Ignoring showInputMethodPickerFromClient of uid " 2031 + Binder.getCallingUid() + ": " + client); 2032 } 2033 2034 // Always call subtype picker, because subtype picker is a superset of input method 2035 // picker. 2036 mHandler.sendEmptyMessage(MSG_SHOW_IM_SUBTYPE_PICKER); 2037 } 2038 } 2039 2040 @Override 2041 public void setInputMethod(IBinder token, String id) { 2042 if (!calledFromValidUser()) { 2043 return; 2044 } 2045 setInputMethodWithSubtypeId(token, id, NOT_A_SUBTYPE_ID); 2046 } 2047 2048 @Override 2049 public void setInputMethodAndSubtype(IBinder token, String id, InputMethodSubtype subtype) { 2050 if (!calledFromValidUser()) { 2051 return; 2052 } 2053 synchronized (mMethodMap) { 2054 if (subtype != null) { 2055 setInputMethodWithSubtypeId(token, id, InputMethodUtils.getSubtypeIdFromHashCode( 2056 mMethodMap.get(id), subtype.hashCode())); 2057 } else { 2058 setInputMethod(token, id); 2059 } 2060 } 2061 } 2062 2063 @Override 2064 public void showInputMethodAndSubtypeEnablerFromClient( 2065 IInputMethodClient client, String inputMethodId) { 2066 if (!calledFromValidUser()) { 2067 return; 2068 } 2069 synchronized (mMethodMap) { 2070 if (mCurClient == null || client == null 2071 || mCurClient.client.asBinder() != client.asBinder()) { 2072 Slog.w(TAG, "Ignoring showInputMethodAndSubtypeEnablerFromClient of: " + client); 2073 } 2074 executeOrSendMessage(mCurMethod, mCaller.obtainMessageO( 2075 MSG_SHOW_IM_SUBTYPE_ENABLER, inputMethodId)); 2076 } 2077 } 2078 2079 @Override 2080 public boolean switchToLastInputMethod(IBinder token) { 2081 if (!calledFromValidUser()) { 2082 return false; 2083 } 2084 synchronized (mMethodMap) { 2085 final Pair<String, String> lastIme = mSettings.getLastInputMethodAndSubtypeLocked(); 2086 final InputMethodInfo lastImi; 2087 if (lastIme != null) { 2088 lastImi = mMethodMap.get(lastIme.first); 2089 } else { 2090 lastImi = null; 2091 } 2092 String targetLastImiId = null; 2093 int subtypeId = NOT_A_SUBTYPE_ID; 2094 if (lastIme != null && lastImi != null) { 2095 final boolean imiIdIsSame = lastImi.getId().equals(mCurMethodId); 2096 final int lastSubtypeHash = Integer.valueOf(lastIme.second); 2097 final int currentSubtypeHash = mCurrentSubtype == null ? NOT_A_SUBTYPE_ID 2098 : mCurrentSubtype.hashCode(); 2099 // If the last IME is the same as the current IME and the last subtype is not 2100 // defined, there is no need to switch to the last IME. 2101 if (!imiIdIsSame || lastSubtypeHash != currentSubtypeHash) { 2102 targetLastImiId = lastIme.first; 2103 subtypeId = InputMethodUtils.getSubtypeIdFromHashCode(lastImi, lastSubtypeHash); 2104 } 2105 } 2106 2107 if (TextUtils.isEmpty(targetLastImiId) 2108 && !InputMethodUtils.canAddToLastInputMethod(mCurrentSubtype)) { 2109 // This is a safety net. If the currentSubtype can't be added to the history 2110 // and the framework couldn't find the last ime, we will make the last ime be 2111 // the most applicable enabled keyboard subtype of the system imes. 2112 final List<InputMethodInfo> enabled = mSettings.getEnabledInputMethodListLocked(); 2113 if (enabled != null) { 2114 final int N = enabled.size(); 2115 final String locale = mCurrentSubtype == null 2116 ? mRes.getConfiguration().locale.toString() 2117 : mCurrentSubtype.getLocale(); 2118 for (int i = 0; i < N; ++i) { 2119 final InputMethodInfo imi = enabled.get(i); 2120 if (imi.getSubtypeCount() > 0 && InputMethodUtils.isSystemIme(imi)) { 2121 InputMethodSubtype keyboardSubtype = 2122 InputMethodUtils.findLastResortApplicableSubtypeLocked(mRes, 2123 InputMethodUtils.getSubtypes(imi), 2124 InputMethodUtils.SUBTYPE_MODE_KEYBOARD, locale, true); 2125 if (keyboardSubtype != null) { 2126 targetLastImiId = imi.getId(); 2127 subtypeId = InputMethodUtils.getSubtypeIdFromHashCode( 2128 imi, keyboardSubtype.hashCode()); 2129 if(keyboardSubtype.getLocale().equals(locale)) { 2130 break; 2131 } 2132 } 2133 } 2134 } 2135 } 2136 } 2137 2138 if (!TextUtils.isEmpty(targetLastImiId)) { 2139 if (DEBUG) { 2140 Slog.d(TAG, "Switch to: " + lastImi.getId() + ", " + lastIme.second 2141 + ", from: " + mCurMethodId + ", " + subtypeId); 2142 } 2143 setInputMethodWithSubtypeId(token, targetLastImiId, subtypeId); 2144 return true; 2145 } else { 2146 return false; 2147 } 2148 } 2149 } 2150 2151 @Override 2152 public boolean switchToNextInputMethod(IBinder token, boolean onlyCurrentIme) { 2153 if (!calledFromValidUser()) { 2154 return false; 2155 } 2156 synchronized (mMethodMap) { 2157 final ImeSubtypeListItem nextSubtype = mImListManager.getNextInputMethod( 2158 onlyCurrentIme, mMethodMap.get(mCurMethodId), mCurrentSubtype); 2159 if (nextSubtype == null) { 2160 return false; 2161 } 2162 setInputMethodWithSubtypeId(token, nextSubtype.mImi.getId(), nextSubtype.mSubtypeId); 2163 return true; 2164 } 2165 } 2166 2167 @Override 2168 public boolean shouldOfferSwitchingToNextInputMethod(IBinder token) { 2169 if (!calledFromValidUser()) { 2170 return false; 2171 } 2172 synchronized (mMethodMap) { 2173 final ImeSubtypeListItem nextSubtype = mImListManager.getNextInputMethod( 2174 false /* onlyCurrentIme */, mMethodMap.get(mCurMethodId), mCurrentSubtype); 2175 if (nextSubtype == null) { 2176 return false; 2177 } 2178 return true; 2179 } 2180 } 2181 2182 @Override 2183 public InputMethodSubtype getLastInputMethodSubtype() { 2184 if (!calledFromValidUser()) { 2185 return null; 2186 } 2187 synchronized (mMethodMap) { 2188 final Pair<String, String> lastIme = mSettings.getLastInputMethodAndSubtypeLocked(); 2189 // TODO: Handle the case of the last IME with no subtypes 2190 if (lastIme == null || TextUtils.isEmpty(lastIme.first) 2191 || TextUtils.isEmpty(lastIme.second)) return null; 2192 final InputMethodInfo lastImi = mMethodMap.get(lastIme.first); 2193 if (lastImi == null) return null; 2194 try { 2195 final int lastSubtypeHash = Integer.valueOf(lastIme.second); 2196 final int lastSubtypeId = 2197 InputMethodUtils.getSubtypeIdFromHashCode(lastImi, lastSubtypeHash); 2198 if (lastSubtypeId < 0 || lastSubtypeId >= lastImi.getSubtypeCount()) { 2199 return null; 2200 } 2201 return lastImi.getSubtypeAt(lastSubtypeId); 2202 } catch (NumberFormatException e) { 2203 return null; 2204 } 2205 } 2206 } 2207 2208 @Override 2209 public void setAdditionalInputMethodSubtypes(String imiId, InputMethodSubtype[] subtypes) { 2210 if (!calledFromValidUser()) { 2211 return; 2212 } 2213 // By this IPC call, only a process which shares the same uid with the IME can add 2214 // additional input method subtypes to the IME. 2215 if (TextUtils.isEmpty(imiId) || subtypes == null || subtypes.length == 0) return; 2216 synchronized (mMethodMap) { 2217 final InputMethodInfo imi = mMethodMap.get(imiId); 2218 if (imi == null) return; 2219 final String[] packageInfos; 2220 try { 2221 packageInfos = mIPackageManager.getPackagesForUid(Binder.getCallingUid()); 2222 } catch (RemoteException e) { 2223 Slog.e(TAG, "Failed to get package infos"); 2224 return; 2225 } 2226 if (packageInfos != null) { 2227 final int packageNum = packageInfos.length; 2228 for (int i = 0; i < packageNum; ++i) { 2229 if (packageInfos[i].equals(imi.getPackageName())) { 2230 mFileManager.addInputMethodSubtypes(imi, subtypes); 2231 final long ident = Binder.clearCallingIdentity(); 2232 try { 2233 buildInputMethodListLocked(mMethodList, mMethodMap, 2234 false /* resetDefaultEnabledIme */); 2235 } finally { 2236 Binder.restoreCallingIdentity(ident); 2237 } 2238 return; 2239 } 2240 } 2241 } 2242 } 2243 return; 2244 } 2245 2246 private void setInputMethodWithSubtypeId(IBinder token, String id, int subtypeId) { 2247 synchronized (mMethodMap) { 2248 if (token == null) { 2249 if (mContext.checkCallingOrSelfPermission( 2250 android.Manifest.permission.WRITE_SECURE_SETTINGS) 2251 != PackageManager.PERMISSION_GRANTED) { 2252 throw new SecurityException( 2253 "Using null token requires permission " 2254 + android.Manifest.permission.WRITE_SECURE_SETTINGS); 2255 } 2256 } else if (mCurToken != token) { 2257 Slog.w(TAG, "Ignoring setInputMethod of uid " + Binder.getCallingUid() 2258 + " token: " + token); 2259 return; 2260 } 2261 2262 final long ident = Binder.clearCallingIdentity(); 2263 try { 2264 setInputMethodLocked(id, subtypeId); 2265 } finally { 2266 Binder.restoreCallingIdentity(ident); 2267 } 2268 } 2269 } 2270 2271 @Override 2272 public void hideMySoftInput(IBinder token, int flags) { 2273 if (!calledFromValidUser()) { 2274 return; 2275 } 2276 synchronized (mMethodMap) { 2277 if (token == null || mCurToken != token) { 2278 if (DEBUG) Slog.w(TAG, "Ignoring hideInputMethod of uid " 2279 + Binder.getCallingUid() + " token: " + token); 2280 return; 2281 } 2282 long ident = Binder.clearCallingIdentity(); 2283 try { 2284 hideCurrentInputLocked(flags, null); 2285 } finally { 2286 Binder.restoreCallingIdentity(ident); 2287 } 2288 } 2289 } 2290 2291 @Override 2292 public void showMySoftInput(IBinder token, int flags) { 2293 if (!calledFromValidUser()) { 2294 return; 2295 } 2296 synchronized (mMethodMap) { 2297 if (token == null || mCurToken != token) { 2298 Slog.w(TAG, "Ignoring showMySoftInput of uid " 2299 + Binder.getCallingUid() + " token: " + token); 2300 return; 2301 } 2302 long ident = Binder.clearCallingIdentity(); 2303 try { 2304 showCurrentInputLocked(flags, null); 2305 } finally { 2306 Binder.restoreCallingIdentity(ident); 2307 } 2308 } 2309 } 2310 2311 void setEnabledSessionInMainThread(SessionState session) { 2312 if (mEnabledSession != session) { 2313 if (mEnabledSession != null) { 2314 try { 2315 if (DEBUG) Slog.v(TAG, "Disabling: " + mEnabledSession); 2316 mEnabledSession.method.setSessionEnabled( 2317 mEnabledSession.session, false); 2318 } catch (RemoteException e) { 2319 } 2320 } 2321 mEnabledSession = session; 2322 try { 2323 if (DEBUG) Slog.v(TAG, "Enabling: " + mEnabledSession); 2324 session.method.setSessionEnabled( 2325 session.session, true); 2326 } catch (RemoteException e) { 2327 } 2328 } 2329 } 2330 2331 @Override 2332 public boolean handleMessage(Message msg) { 2333 SomeArgs args; 2334 switch (msg.what) { 2335 case MSG_SHOW_IM_PICKER: 2336 showInputMethodMenu(); 2337 return true; 2338 2339 case MSG_SHOW_IM_SUBTYPE_PICKER: 2340 showInputMethodSubtypeMenu(); 2341 return true; 2342 2343 case MSG_SHOW_IM_SUBTYPE_ENABLER: 2344 args = (SomeArgs)msg.obj; 2345 showInputMethodAndSubtypeEnabler((String)args.arg1); 2346 args.recycle(); 2347 return true; 2348 2349 case MSG_SHOW_IM_CONFIG: 2350 showConfigureInputMethods(); 2351 return true; 2352 2353 // --------------------------------------------------------- 2354 2355 case MSG_UNBIND_INPUT: 2356 try { 2357 ((IInputMethod)msg.obj).unbindInput(); 2358 } catch (RemoteException e) { 2359 // There is nothing interesting about the method dying. 2360 } 2361 return true; 2362 case MSG_BIND_INPUT: 2363 args = (SomeArgs)msg.obj; 2364 try { 2365 ((IInputMethod)args.arg1).bindInput((InputBinding)args.arg2); 2366 } catch (RemoteException e) { 2367 } 2368 args.recycle(); 2369 return true; 2370 case MSG_SHOW_SOFT_INPUT: 2371 args = (SomeArgs)msg.obj; 2372 try { 2373 if (DEBUG) Slog.v(TAG, "Calling " + args.arg1 + ".showSoftInput(" 2374 + msg.arg1 + ", " + args.arg2 + ")"); 2375 ((IInputMethod)args.arg1).showSoftInput(msg.arg1, (ResultReceiver)args.arg2); 2376 } catch (RemoteException e) { 2377 } 2378 args.recycle(); 2379 return true; 2380 case MSG_HIDE_SOFT_INPUT: 2381 args = (SomeArgs)msg.obj; 2382 try { 2383 if (DEBUG) Slog.v(TAG, "Calling " + args.arg1 + ".hideSoftInput(0, " 2384 + args.arg2 + ")"); 2385 ((IInputMethod)args.arg1).hideSoftInput(0, (ResultReceiver)args.arg2); 2386 } catch (RemoteException e) { 2387 } 2388 args.recycle(); 2389 return true; 2390 case MSG_ATTACH_TOKEN: 2391 args = (SomeArgs)msg.obj; 2392 try { 2393 if (DEBUG) Slog.v(TAG, "Sending attach of token: " + args.arg2); 2394 ((IInputMethod)args.arg1).attachToken((IBinder)args.arg2); 2395 } catch (RemoteException e) { 2396 } 2397 args.recycle(); 2398 return true; 2399 case MSG_CREATE_SESSION: { 2400 args = (SomeArgs)msg.obj; 2401 IInputMethod method = (IInputMethod)args.arg1; 2402 InputChannel channel = (InputChannel)args.arg2; 2403 try { 2404 method.createSession(channel, (IInputSessionCallback)args.arg3); 2405 } catch (RemoteException e) { 2406 } finally { 2407 // Dispose the channel if the input method is not local to this process 2408 // because the remote proxy will get its own copy when unparceled. 2409 if (channel != null && Binder.isProxy(method)) { 2410 channel.dispose(); 2411 } 2412 } 2413 args.recycle(); 2414 return true; 2415 } 2416 // --------------------------------------------------------- 2417 2418 case MSG_START_INPUT: 2419 args = (SomeArgs)msg.obj; 2420 try { 2421 SessionState session = (SessionState)args.arg1; 2422 setEnabledSessionInMainThread(session); 2423 session.method.startInput((IInputContext)args.arg2, 2424 (EditorInfo)args.arg3); 2425 } catch (RemoteException e) { 2426 } 2427 args.recycle(); 2428 return true; 2429 case MSG_RESTART_INPUT: 2430 args = (SomeArgs)msg.obj; 2431 try { 2432 SessionState session = (SessionState)args.arg1; 2433 setEnabledSessionInMainThread(session); 2434 session.method.restartInput((IInputContext)args.arg2, 2435 (EditorInfo)args.arg3); 2436 } catch (RemoteException e) { 2437 } 2438 args.recycle(); 2439 return true; 2440 2441 // --------------------------------------------------------- 2442 2443 case MSG_UNBIND_METHOD: 2444 try { 2445 ((IInputMethodClient)msg.obj).onUnbindMethod(msg.arg1); 2446 } catch (RemoteException e) { 2447 // There is nothing interesting about the last client dying. 2448 } 2449 return true; 2450 case MSG_BIND_METHOD: { 2451 args = (SomeArgs)msg.obj; 2452 IInputMethodClient client = (IInputMethodClient)args.arg1; 2453 InputBindResult res = (InputBindResult)args.arg2; 2454 try { 2455 client.onBindMethod(res); 2456 } catch (RemoteException e) { 2457 Slog.w(TAG, "Client died receiving input method " + args.arg2); 2458 } finally { 2459 // Dispose the channel if the input method is not local to this process 2460 // because the remote proxy will get its own copy when unparceled. 2461 if (res.channel != null && Binder.isProxy(client)) { 2462 res.channel.dispose(); 2463 } 2464 } 2465 args.recycle(); 2466 return true; 2467 } 2468 case MSG_SET_ACTIVE: 2469 try { 2470 ((ClientState)msg.obj).client.setActive(msg.arg1 != 0); 2471 } catch (RemoteException e) { 2472 Slog.w(TAG, "Got RemoteException sending setActive(false) notification to pid " 2473 + ((ClientState)msg.obj).pid + " uid " 2474 + ((ClientState)msg.obj).uid); 2475 } 2476 return true; 2477 2478 // -------------------------------------------------------------- 2479 case MSG_HARD_KEYBOARD_SWITCH_CHANGED: 2480 mHardKeyboardListener.handleHardKeyboardStatusChange( 2481 msg.arg1 == 1, msg.arg2 == 1); 2482 return true; 2483 } 2484 return false; 2485 } 2486 2487 private boolean chooseNewDefaultIMELocked() { 2488 final InputMethodInfo imi = InputMethodUtils.getMostApplicableDefaultIME( 2489 mSettings.getEnabledInputMethodListLocked()); 2490 if (imi != null) { 2491 if (DEBUG) { 2492 Slog.d(TAG, "New default IME was selected: " + imi.getId()); 2493 } 2494 resetSelectedInputMethodAndSubtypeLocked(imi.getId()); 2495 return true; 2496 } 2497 2498 return false; 2499 } 2500 2501 void buildInputMethodListLocked(ArrayList<InputMethodInfo> list, 2502 HashMap<String, InputMethodInfo> map, boolean resetDefaultEnabledIme) { 2503 if (DEBUG) { 2504 Slog.d(TAG, "--- re-buildInputMethodList reset = " + resetDefaultEnabledIme 2505 + " \n ------ \n" + InputMethodUtils.getStackTrace()); 2506 } 2507 list.clear(); 2508 map.clear(); 2509 2510 // Use for queryIntentServicesAsUser 2511 final PackageManager pm = mContext.getPackageManager(); 2512 String disabledSysImes = mSettings.getDisabledSystemInputMethods(); 2513 if (disabledSysImes == null) disabledSysImes = ""; 2514 2515 final List<ResolveInfo> services = pm.queryIntentServicesAsUser( 2516 new Intent(InputMethod.SERVICE_INTERFACE), 2517 PackageManager.GET_META_DATA | PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS, 2518 mSettings.getCurrentUserId()); 2519 2520 final HashMap<String, List<InputMethodSubtype>> additionalSubtypes = 2521 mFileManager.getAllAdditionalInputMethodSubtypes(); 2522 for (int i = 0; i < services.size(); ++i) { 2523 ResolveInfo ri = services.get(i); 2524 ServiceInfo si = ri.serviceInfo; 2525 ComponentName compName = new ComponentName(si.packageName, si.name); 2526 if (!android.Manifest.permission.BIND_INPUT_METHOD.equals( 2527 si.permission)) { 2528 Slog.w(TAG, "Skipping input method " + compName 2529 + ": it does not require the permission " 2530 + android.Manifest.permission.BIND_INPUT_METHOD); 2531 continue; 2532 } 2533 2534 if (DEBUG) Slog.d(TAG, "Checking " + compName); 2535 2536 try { 2537 InputMethodInfo p = new InputMethodInfo(mContext, ri, additionalSubtypes); 2538 list.add(p); 2539 final String id = p.getId(); 2540 map.put(id, p); 2541 2542 if (DEBUG) { 2543 Slog.d(TAG, "Found an input method " + p); 2544 } 2545 2546 } catch (XmlPullParserException e) { 2547 Slog.w(TAG, "Unable to load input method " + compName, e); 2548 } catch (IOException e) { 2549 Slog.w(TAG, "Unable to load input method " + compName, e); 2550 } 2551 } 2552 2553 if (resetDefaultEnabledIme) { 2554 final ArrayList<InputMethodInfo> defaultEnabledIme = 2555 InputMethodUtils.getDefaultEnabledImes(mContext, mSystemReady, list); 2556 for (int i = 0; i < defaultEnabledIme.size(); ++i) { 2557 final InputMethodInfo imi = defaultEnabledIme.get(i); 2558 if (DEBUG) { 2559 Slog.d(TAG, "--- enable ime = " + imi); 2560 } 2561 setInputMethodEnabledLocked(imi.getId(), true); 2562 } 2563 } 2564 2565 final String defaultImiId = mSettings.getSelectedInputMethod(); 2566 if (!TextUtils.isEmpty(defaultImiId)) { 2567 if (!map.containsKey(defaultImiId)) { 2568 Slog.w(TAG, "Default IME is uninstalled. Choose new default IME."); 2569 if (chooseNewDefaultIMELocked()) { 2570 updateFromSettingsLocked(true); 2571 } 2572 } else { 2573 // Double check that the default IME is certainly enabled. 2574 setInputMethodEnabledLocked(defaultImiId, true); 2575 } 2576 } 2577 } 2578 2579 // ---------------------------------------------------------------------- 2580 2581 private void showInputMethodMenu() { 2582 showInputMethodMenuInternal(false); 2583 } 2584 2585 private void showInputMethodSubtypeMenu() { 2586 showInputMethodMenuInternal(true); 2587 } 2588 2589 private void showInputMethodAndSubtypeEnabler(String inputMethodId) { 2590 Intent intent = new Intent(Settings.ACTION_INPUT_METHOD_SUBTYPE_SETTINGS); 2591 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK 2592 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED 2593 | Intent.FLAG_ACTIVITY_CLEAR_TOP); 2594 if (!TextUtils.isEmpty(inputMethodId)) { 2595 intent.putExtra(Settings.EXTRA_INPUT_METHOD_ID, inputMethodId); 2596 } 2597 mContext.startActivityAsUser(intent, null, UserHandle.CURRENT); 2598 } 2599 2600 private void showConfigureInputMethods() { 2601 Intent intent = new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS); 2602 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK 2603 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED 2604 | Intent.FLAG_ACTIVITY_CLEAR_TOP); 2605 mContext.startActivityAsUser(intent, null, UserHandle.CURRENT); 2606 } 2607 2608 private boolean isScreenLocked() { 2609 return mKeyguardManager != null 2610 && mKeyguardManager.isKeyguardLocked() && mKeyguardManager.isKeyguardSecure(); 2611 } 2612 private void showInputMethodMenuInternal(boolean showSubtypes) { 2613 if (DEBUG) Slog.v(TAG, "Show switching menu"); 2614 2615 final Context context = mContext; 2616 final boolean isScreenLocked = isScreenLocked(); 2617 2618 final String lastInputMethodId = mSettings.getSelectedInputMethod(); 2619 int lastInputMethodSubtypeId = mSettings.getSelectedInputMethodSubtypeId(lastInputMethodId); 2620 if (DEBUG) Slog.v(TAG, "Current IME: " + lastInputMethodId); 2621 2622 synchronized (mMethodMap) { 2623 final HashMap<InputMethodInfo, List<InputMethodSubtype>> immis = 2624 getExplicitlyOrImplicitlyEnabledInputMethodsAndSubtypeListLocked(); 2625 if (immis == null || immis.size() == 0) { 2626 return; 2627 } 2628 2629 hideInputMethodMenuLocked(); 2630 2631 final List<ImeSubtypeListItem> imList = 2632 mImListManager.getSortedInputMethodAndSubtypeList( 2633 showSubtypes, mInputShown, isScreenLocked); 2634 2635 if (lastInputMethodSubtypeId == NOT_A_SUBTYPE_ID) { 2636 final InputMethodSubtype currentSubtype = getCurrentInputMethodSubtypeLocked(); 2637 if (currentSubtype != null) { 2638 final InputMethodInfo currentImi = mMethodMap.get(mCurMethodId); 2639 lastInputMethodSubtypeId = InputMethodUtils.getSubtypeIdFromHashCode( 2640 currentImi, currentSubtype.hashCode()); 2641 } 2642 } 2643 2644 final int N = imList.size(); 2645 mIms = new InputMethodInfo[N]; 2646 mSubtypeIds = new int[N]; 2647 int checkedItem = 0; 2648 for (int i = 0; i < N; ++i) { 2649 final ImeSubtypeListItem item = imList.get(i); 2650 mIms[i] = item.mImi; 2651 mSubtypeIds[i] = item.mSubtypeId; 2652 if (mIms[i].getId().equals(lastInputMethodId)) { 2653 int subtypeId = mSubtypeIds[i]; 2654 if ((subtypeId == NOT_A_SUBTYPE_ID) 2655 || (lastInputMethodSubtypeId == NOT_A_SUBTYPE_ID && subtypeId == 0) 2656 || (subtypeId == lastInputMethodSubtypeId)) { 2657 checkedItem = i; 2658 } 2659 } 2660 } 2661 final TypedArray a = context.obtainStyledAttributes(null, 2662 com.android.internal.R.styleable.DialogPreference, 2663 com.android.internal.R.attr.alertDialogStyle, 0); 2664 mDialogBuilder = new AlertDialog.Builder(context) 2665 .setOnCancelListener(new OnCancelListener() { 2666 @Override 2667 public void onCancel(DialogInterface dialog) { 2668 hideInputMethodMenu(); 2669 } 2670 }) 2671 .setIcon(a.getDrawable( 2672 com.android.internal.R.styleable.DialogPreference_dialogTitle)); 2673 a.recycle(); 2674 final LayoutInflater inflater = 2675 (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 2676 final View tv = inflater.inflate( 2677 com.android.internal.R.layout.input_method_switch_dialog_title, null); 2678 mDialogBuilder.setCustomTitle(tv); 2679 2680 // Setup layout for a toggle switch of the hardware keyboard 2681 mSwitchingDialogTitleView = tv; 2682 mSwitchingDialogTitleView.findViewById( 2683 com.android.internal.R.id.hard_keyboard_section).setVisibility( 2684 mWindowManagerService.isHardKeyboardAvailable() ? 2685 View.VISIBLE : View.GONE); 2686 final Switch hardKeySwitch = ((Switch)mSwitchingDialogTitleView.findViewById( 2687 com.android.internal.R.id.hard_keyboard_switch)); 2688 hardKeySwitch.setChecked(mWindowManagerService.isHardKeyboardEnabled()); 2689 hardKeySwitch.setOnCheckedChangeListener( 2690 new OnCheckedChangeListener() { 2691 @Override 2692 public void onCheckedChanged( 2693 CompoundButton buttonView, boolean isChecked) { 2694 mWindowManagerService.setHardKeyboardEnabled(isChecked); 2695 // Ensure that the input method dialog is dismissed when changing 2696 // the hardware keyboard state. 2697 hideInputMethodMenu(); 2698 } 2699 }); 2700 2701 final ImeSubtypeListAdapter adapter = new ImeSubtypeListAdapter(context, 2702 com.android.internal.R.layout.simple_list_item_2_single_choice, imList, 2703 checkedItem); 2704 2705 mDialogBuilder.setSingleChoiceItems(adapter, checkedItem, 2706 new AlertDialog.OnClickListener() { 2707 @Override 2708 public void onClick(DialogInterface dialog, int which) { 2709 synchronized (mMethodMap) { 2710 if (mIms == null || mIms.length <= which 2711 || mSubtypeIds == null || mSubtypeIds.length <= which) { 2712 return; 2713 } 2714 InputMethodInfo im = mIms[which]; 2715 int subtypeId = mSubtypeIds[which]; 2716 adapter.mCheckedItem = which; 2717 adapter.notifyDataSetChanged(); 2718 hideInputMethodMenu(); 2719 if (im != null) { 2720 if ((subtypeId < 0) 2721 || (subtypeId >= im.getSubtypeCount())) { 2722 subtypeId = NOT_A_SUBTYPE_ID; 2723 } 2724 setInputMethodLocked(im.getId(), subtypeId); 2725 } 2726 } 2727 } 2728 }); 2729 2730 if (showSubtypes && !isScreenLocked) { 2731 mDialogBuilder.setPositiveButton( 2732 com.android.internal.R.string.configure_input_methods, 2733 new DialogInterface.OnClickListener() { 2734 @Override 2735 public void onClick(DialogInterface dialog, int whichButton) { 2736 showConfigureInputMethods(); 2737 } 2738 }); 2739 } 2740 mSwitchingDialog = mDialogBuilder.create(); 2741 mSwitchingDialog.setCanceledOnTouchOutside(true); 2742 mSwitchingDialog.getWindow().setType( 2743 WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG); 2744 mSwitchingDialog.getWindow().getAttributes().privateFlags |= 2745 WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS; 2746 mSwitchingDialog.getWindow().getAttributes().setTitle("Select input method"); 2747 mSwitchingDialog.show(); 2748 } 2749 } 2750 2751 private static class ImeSubtypeListItem implements Comparable<ImeSubtypeListItem> { 2752 public final CharSequence mImeName; 2753 public final CharSequence mSubtypeName; 2754 public final InputMethodInfo mImi; 2755 public final int mSubtypeId; 2756 private final boolean mIsSystemLocale; 2757 private final boolean mIsSystemLanguage; 2758 2759 public ImeSubtypeListItem(CharSequence imeName, CharSequence subtypeName, 2760 InputMethodInfo imi, int subtypeId, String subtypeLocale, String systemLocale) { 2761 mImeName = imeName; 2762 mSubtypeName = subtypeName; 2763 mImi = imi; 2764 mSubtypeId = subtypeId; 2765 if (TextUtils.isEmpty(subtypeLocale)) { 2766 mIsSystemLocale = false; 2767 mIsSystemLanguage = false; 2768 } else { 2769 mIsSystemLocale = subtypeLocale.equals(systemLocale); 2770 mIsSystemLanguage = mIsSystemLocale 2771 || subtypeLocale.startsWith(systemLocale.substring(0, 2)); 2772 } 2773 } 2774 2775 @Override 2776 public int compareTo(ImeSubtypeListItem other) { 2777 if (TextUtils.isEmpty(mImeName)) { 2778 return 1; 2779 } 2780 if (TextUtils.isEmpty(other.mImeName)) { 2781 return -1; 2782 } 2783 if (!TextUtils.equals(mImeName, other.mImeName)) { 2784 return mImeName.toString().compareTo(other.mImeName.toString()); 2785 } 2786 if (TextUtils.equals(mSubtypeName, other.mSubtypeName)) { 2787 return 0; 2788 } 2789 if (mIsSystemLocale) { 2790 return -1; 2791 } 2792 if (other.mIsSystemLocale) { 2793 return 1; 2794 } 2795 if (mIsSystemLanguage) { 2796 return -1; 2797 } 2798 if (other.mIsSystemLanguage) { 2799 return 1; 2800 } 2801 if (TextUtils.isEmpty(mSubtypeName)) { 2802 return 1; 2803 } 2804 if (TextUtils.isEmpty(other.mSubtypeName)) { 2805 return -1; 2806 } 2807 return mSubtypeName.toString().compareTo(other.mSubtypeName.toString()); 2808 } 2809 } 2810 2811 private static class ImeSubtypeListAdapter extends ArrayAdapter<ImeSubtypeListItem> { 2812 private final LayoutInflater mInflater; 2813 private final int mTextViewResourceId; 2814 private final List<ImeSubtypeListItem> mItemsList; 2815 public int mCheckedItem; 2816 public ImeSubtypeListAdapter(Context context, int textViewResourceId, 2817 List<ImeSubtypeListItem> itemsList, int checkedItem) { 2818 super(context, textViewResourceId, itemsList); 2819 mTextViewResourceId = textViewResourceId; 2820 mItemsList = itemsList; 2821 mCheckedItem = checkedItem; 2822 mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 2823 } 2824 2825 @Override 2826 public View getView(int position, View convertView, ViewGroup parent) { 2827 final View view = convertView != null ? convertView 2828 : mInflater.inflate(mTextViewResourceId, null); 2829 if (position < 0 || position >= mItemsList.size()) return view; 2830 final ImeSubtypeListItem item = mItemsList.get(position); 2831 final CharSequence imeName = item.mImeName; 2832 final CharSequence subtypeName = item.mSubtypeName; 2833 final TextView firstTextView = (TextView)view.findViewById(android.R.id.text1); 2834 final TextView secondTextView = (TextView)view.findViewById(android.R.id.text2); 2835 if (TextUtils.isEmpty(subtypeName)) { 2836 firstTextView.setText(imeName); 2837 secondTextView.setVisibility(View.GONE); 2838 } else { 2839 firstTextView.setText(subtypeName); 2840 secondTextView.setText(imeName); 2841 secondTextView.setVisibility(View.VISIBLE); 2842 } 2843 final RadioButton radioButton = 2844 (RadioButton)view.findViewById(com.android.internal.R.id.radio); 2845 radioButton.setChecked(position == mCheckedItem); 2846 return view; 2847 } 2848 } 2849 2850 void hideInputMethodMenu() { 2851 synchronized (mMethodMap) { 2852 hideInputMethodMenuLocked(); 2853 } 2854 } 2855 2856 void hideInputMethodMenuLocked() { 2857 if (DEBUG) Slog.v(TAG, "Hide switching menu"); 2858 2859 if (mSwitchingDialog != null) { 2860 mSwitchingDialog.dismiss(); 2861 mSwitchingDialog = null; 2862 } 2863 2864 mDialogBuilder = null; 2865 mIms = null; 2866 } 2867 2868 // ---------------------------------------------------------------------- 2869 2870 @Override 2871 public boolean setInputMethodEnabled(String id, boolean enabled) { 2872 // TODO: Make this work even for non-current users? 2873 if (!calledFromValidUser()) { 2874 return false; 2875 } 2876 synchronized (mMethodMap) { 2877 if (mContext.checkCallingOrSelfPermission( 2878 android.Manifest.permission.WRITE_SECURE_SETTINGS) 2879 != PackageManager.PERMISSION_GRANTED) { 2880 throw new SecurityException( 2881 "Requires permission " 2882 + android.Manifest.permission.WRITE_SECURE_SETTINGS); 2883 } 2884 2885 long ident = Binder.clearCallingIdentity(); 2886 try { 2887 return setInputMethodEnabledLocked(id, enabled); 2888 } finally { 2889 Binder.restoreCallingIdentity(ident); 2890 } 2891 } 2892 } 2893 2894 boolean setInputMethodEnabledLocked(String id, boolean enabled) { 2895 // Make sure this is a valid input method. 2896 InputMethodInfo imm = mMethodMap.get(id); 2897 if (imm == null) { 2898 throw new IllegalArgumentException("Unknown id: " + mCurMethodId); 2899 } 2900 2901 List<Pair<String, ArrayList<String>>> enabledInputMethodsList = mSettings 2902 .getEnabledInputMethodsAndSubtypeListLocked(); 2903 2904 if (enabled) { 2905 for (Pair<String, ArrayList<String>> pair: enabledInputMethodsList) { 2906 if (pair.first.equals(id)) { 2907 // We are enabling this input method, but it is already enabled. 2908 // Nothing to do. The previous state was enabled. 2909 return true; 2910 } 2911 } 2912 mSettings.appendAndPutEnabledInputMethodLocked(id, false); 2913 // Previous state was disabled. 2914 return false; 2915 } else { 2916 StringBuilder builder = new StringBuilder(); 2917 if (mSettings.buildAndPutEnabledInputMethodsStrRemovingIdLocked( 2918 builder, enabledInputMethodsList, id)) { 2919 // Disabled input method is currently selected, switch to another one. 2920 final String selId = mSettings.getSelectedInputMethod(); 2921 if (id.equals(selId) && !chooseNewDefaultIMELocked()) { 2922 Slog.i(TAG, "Can't find new IME, unsetting the current input method."); 2923 resetSelectedInputMethodAndSubtypeLocked(""); 2924 } 2925 // Previous state was enabled. 2926 return true; 2927 } else { 2928 // We are disabling the input method but it is already disabled. 2929 // Nothing to do. The previous state was disabled. 2930 return false; 2931 } 2932 } 2933 } 2934 2935 private void setSelectedInputMethodAndSubtypeLocked(InputMethodInfo imi, int subtypeId, 2936 boolean setSubtypeOnly) { 2937 // Update the history of InputMethod and Subtype 2938 mSettings.saveCurrentInputMethodAndSubtypeToHistory(mCurMethodId, mCurrentSubtype); 2939 2940 // Set Subtype here 2941 if (imi == null || subtypeId < 0) { 2942 mSettings.putSelectedSubtype(NOT_A_SUBTYPE_ID); 2943 mCurrentSubtype = null; 2944 } else { 2945 if (subtypeId < imi.getSubtypeCount()) { 2946 InputMethodSubtype subtype = imi.getSubtypeAt(subtypeId); 2947 mSettings.putSelectedSubtype(subtype.hashCode()); 2948 mCurrentSubtype = subtype; 2949 } else { 2950 mSettings.putSelectedSubtype(NOT_A_SUBTYPE_ID); 2951 // If the subtype is not specified, choose the most applicable one 2952 mCurrentSubtype = getCurrentInputMethodSubtypeLocked(); 2953 } 2954 } 2955 2956 // Workaround. 2957 // ASEC is not ready in the IMMS constructor. Accordingly, forward-locked 2958 // IMEs are not recognized and considered uninstalled. 2959 // Actually, we can't move everything after SystemReady because 2960 // IMMS needs to run in the encryption lock screen. So, we just skip changing 2961 // the default IME here and try cheking the default IME again in systemReady(). 2962 // TODO: Do nothing before system ready and implement a separated logic for 2963 // the encryption lock screen. 2964 // TODO: ASEC should be ready before IMMS is instantiated. 2965 if (mSystemReady && !setSubtypeOnly) { 2966 // Set InputMethod here 2967 mSettings.putSelectedInputMethod(imi != null ? imi.getId() : ""); 2968 } 2969 } 2970 2971 private void resetSelectedInputMethodAndSubtypeLocked(String newDefaultIme) { 2972 InputMethodInfo imi = mMethodMap.get(newDefaultIme); 2973 int lastSubtypeId = NOT_A_SUBTYPE_ID; 2974 // newDefaultIme is empty when there is no candidate for the selected IME. 2975 if (imi != null && !TextUtils.isEmpty(newDefaultIme)) { 2976 String subtypeHashCode = mSettings.getLastSubtypeForInputMethodLocked(newDefaultIme); 2977 if (subtypeHashCode != null) { 2978 try { 2979 lastSubtypeId = InputMethodUtils.getSubtypeIdFromHashCode( 2980 imi, Integer.valueOf(subtypeHashCode)); 2981 } catch (NumberFormatException e) { 2982 Slog.w(TAG, "HashCode for subtype looks broken: " + subtypeHashCode, e); 2983 } 2984 } 2985 } 2986 setSelectedInputMethodAndSubtypeLocked(imi, lastSubtypeId, false); 2987 } 2988 2989 // If there are no selected shortcuts, tries finding the most applicable ones. 2990 private Pair<InputMethodInfo, InputMethodSubtype> 2991 findLastResortApplicableShortcutInputMethodAndSubtypeLocked(String mode) { 2992 List<InputMethodInfo> imis = mSettings.getEnabledInputMethodListLocked(); 2993 InputMethodInfo mostApplicableIMI = null; 2994 InputMethodSubtype mostApplicableSubtype = null; 2995 boolean foundInSystemIME = false; 2996 2997 // Search applicable subtype for each InputMethodInfo 2998 for (InputMethodInfo imi: imis) { 2999 final String imiId = imi.getId(); 3000 if (foundInSystemIME && !imiId.equals(mCurMethodId)) { 3001 continue; 3002 } 3003 InputMethodSubtype subtype = null; 3004 final List<InputMethodSubtype> enabledSubtypes = 3005 mSettings.getEnabledInputMethodSubtypeListLocked(mContext, imi, true); 3006 // 1. Search by the current subtype's locale from enabledSubtypes. 3007 if (mCurrentSubtype != null) { 3008 subtype = InputMethodUtils.findLastResortApplicableSubtypeLocked( 3009 mRes, enabledSubtypes, mode, mCurrentSubtype.getLocale(), false); 3010 } 3011 // 2. Search by the system locale from enabledSubtypes. 3012 // 3. Search the first enabled subtype matched with mode from enabledSubtypes. 3013 if (subtype == null) { 3014 subtype = InputMethodUtils.findLastResortApplicableSubtypeLocked( 3015 mRes, enabledSubtypes, mode, null, true); 3016 } 3017 final ArrayList<InputMethodSubtype> overridingImplicitlyEnabledSubtypes = 3018 InputMethodUtils.getOverridingImplicitlyEnabledSubtypes(imi, mode); 3019 final ArrayList<InputMethodSubtype> subtypesForSearch = 3020 overridingImplicitlyEnabledSubtypes.isEmpty() 3021 ? InputMethodUtils.getSubtypes(imi) 3022 : overridingImplicitlyEnabledSubtypes; 3023 // 4. Search by the current subtype's locale from all subtypes. 3024 if (subtype == null && mCurrentSubtype != null) { 3025 subtype = InputMethodUtils.findLastResortApplicableSubtypeLocked( 3026 mRes, subtypesForSearch, mode, mCurrentSubtype.getLocale(), false); 3027 } 3028 // 5. Search by the system locale from all subtypes. 3029 // 6. Search the first enabled subtype matched with mode from all subtypes. 3030 if (subtype == null) { 3031 subtype = InputMethodUtils.findLastResortApplicableSubtypeLocked( 3032 mRes, subtypesForSearch, mode, null, true); 3033 } 3034 if (subtype != null) { 3035 if (imiId.equals(mCurMethodId)) { 3036 // The current input method is the most applicable IME. 3037 mostApplicableIMI = imi; 3038 mostApplicableSubtype = subtype; 3039 break; 3040 } else if (!foundInSystemIME) { 3041 // The system input method is 2nd applicable IME. 3042 mostApplicableIMI = imi; 3043 mostApplicableSubtype = subtype; 3044 if ((imi.getServiceInfo().applicationInfo.flags 3045 & ApplicationInfo.FLAG_SYSTEM) != 0) { 3046 foundInSystemIME = true; 3047 } 3048 } 3049 } 3050 } 3051 if (DEBUG) { 3052 if (mostApplicableIMI != null) { 3053 Slog.w(TAG, "Most applicable shortcut input method was:" 3054 + mostApplicableIMI.getId()); 3055 if (mostApplicableSubtype != null) { 3056 Slog.w(TAG, "Most applicable shortcut input method subtype was:" 3057 + "," + mostApplicableSubtype.getMode() + "," 3058 + mostApplicableSubtype.getLocale()); 3059 } 3060 } 3061 } 3062 if (mostApplicableIMI != null) { 3063 return new Pair<InputMethodInfo, InputMethodSubtype> (mostApplicableIMI, 3064 mostApplicableSubtype); 3065 } else { 3066 return null; 3067 } 3068 } 3069 3070 /** 3071 * @return Return the current subtype of this input method. 3072 */ 3073 @Override 3074 public InputMethodSubtype getCurrentInputMethodSubtype() { 3075 // TODO: Make this work even for non-current users? 3076 if (!calledFromValidUser()) { 3077 return null; 3078 } 3079 synchronized (mMethodMap) { 3080 return getCurrentInputMethodSubtypeLocked(); 3081 } 3082 } 3083 3084 private InputMethodSubtype getCurrentInputMethodSubtypeLocked() { 3085 if (mCurMethodId == null) { 3086 return null; 3087 } 3088 final boolean subtypeIsSelected = mSettings.isSubtypeSelected(); 3089 final InputMethodInfo imi = mMethodMap.get(mCurMethodId); 3090 if (imi == null || imi.getSubtypeCount() == 0) { 3091 return null; 3092 } 3093 if (!subtypeIsSelected || mCurrentSubtype == null 3094 || !InputMethodUtils.isValidSubtypeId(imi, mCurrentSubtype.hashCode())) { 3095 int subtypeId = mSettings.getSelectedInputMethodSubtypeId(mCurMethodId); 3096 if (subtypeId == NOT_A_SUBTYPE_ID) { 3097 // If there are no selected subtypes, the framework will try to find 3098 // the most applicable subtype from explicitly or implicitly enabled 3099 // subtypes. 3100 List<InputMethodSubtype> explicitlyOrImplicitlyEnabledSubtypes = 3101 mSettings.getEnabledInputMethodSubtypeListLocked(mContext, imi, true); 3102 // If there is only one explicitly or implicitly enabled subtype, 3103 // just returns it. 3104 if (explicitlyOrImplicitlyEnabledSubtypes.size() == 1) { 3105 mCurrentSubtype = explicitlyOrImplicitlyEnabledSubtypes.get(0); 3106 } else if (explicitlyOrImplicitlyEnabledSubtypes.size() > 1) { 3107 mCurrentSubtype = InputMethodUtils.findLastResortApplicableSubtypeLocked( 3108 mRes, explicitlyOrImplicitlyEnabledSubtypes, 3109 InputMethodUtils.SUBTYPE_MODE_KEYBOARD, null, true); 3110 if (mCurrentSubtype == null) { 3111 mCurrentSubtype = InputMethodUtils.findLastResortApplicableSubtypeLocked( 3112 mRes, explicitlyOrImplicitlyEnabledSubtypes, null, null, 3113 true); 3114 } 3115 } 3116 } else { 3117 mCurrentSubtype = InputMethodUtils.getSubtypes(imi).get(subtypeId); 3118 } 3119 } 3120 return mCurrentSubtype; 3121 } 3122 3123 private void addShortcutInputMethodAndSubtypes(InputMethodInfo imi, 3124 InputMethodSubtype subtype) { 3125 if (mShortcutInputMethodsAndSubtypes.containsKey(imi)) { 3126 mShortcutInputMethodsAndSubtypes.get(imi).add(subtype); 3127 } else { 3128 ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>(); 3129 subtypes.add(subtype); 3130 mShortcutInputMethodsAndSubtypes.put(imi, subtypes); 3131 } 3132 } 3133 3134 // TODO: We should change the return type from List to List<Parcelable> 3135 @SuppressWarnings("rawtypes") 3136 @Override 3137 public List getShortcutInputMethodsAndSubtypes() { 3138 synchronized (mMethodMap) { 3139 ArrayList<Object> ret = new ArrayList<Object>(); 3140 if (mShortcutInputMethodsAndSubtypes.size() == 0) { 3141 // If there are no selected shortcut subtypes, the framework will try to find 3142 // the most applicable subtype from all subtypes whose mode is 3143 // SUBTYPE_MODE_VOICE. This is an exceptional case, so we will hardcode the mode. 3144 Pair<InputMethodInfo, InputMethodSubtype> info = 3145 findLastResortApplicableShortcutInputMethodAndSubtypeLocked( 3146 InputMethodUtils.SUBTYPE_MODE_VOICE); 3147 if (info != null) { 3148 ret.add(info.first); 3149 ret.add(info.second); 3150 } 3151 return ret; 3152 } 3153 for (InputMethodInfo imi: mShortcutInputMethodsAndSubtypes.keySet()) { 3154 ret.add(imi); 3155 for (InputMethodSubtype subtype: mShortcutInputMethodsAndSubtypes.get(imi)) { 3156 ret.add(subtype); 3157 } 3158 } 3159 return ret; 3160 } 3161 } 3162 3163 @Override 3164 public boolean setCurrentInputMethodSubtype(InputMethodSubtype subtype) { 3165 // TODO: Make this work even for non-current users? 3166 if (!calledFromValidUser()) { 3167 return false; 3168 } 3169 synchronized (mMethodMap) { 3170 if (subtype != null && mCurMethodId != null) { 3171 InputMethodInfo imi = mMethodMap.get(mCurMethodId); 3172 int subtypeId = InputMethodUtils.getSubtypeIdFromHashCode(imi, subtype.hashCode()); 3173 if (subtypeId != NOT_A_SUBTYPE_ID) { 3174 setInputMethodLocked(mCurMethodId, subtypeId); 3175 return true; 3176 } 3177 } 3178 return false; 3179 } 3180 } 3181 3182 private static class InputMethodAndSubtypeListManager { 3183 private final Context mContext; 3184 // Used to load label 3185 private final PackageManager mPm; 3186 private final InputMethodManagerService mImms; 3187 private final String mSystemLocaleStr; 3188 public InputMethodAndSubtypeListManager(Context context, InputMethodManagerService imms) { 3189 mContext = context; 3190 mPm = context.getPackageManager(); 3191 mImms = imms; 3192 final Locale locale = context.getResources().getConfiguration().locale; 3193 mSystemLocaleStr = locale != null ? locale.toString() : ""; 3194 } 3195 3196 private final TreeMap<InputMethodInfo, List<InputMethodSubtype>> mSortedImmis = 3197 new TreeMap<InputMethodInfo, List<InputMethodSubtype>>( 3198 new Comparator<InputMethodInfo>() { 3199 @Override 3200 public int compare(InputMethodInfo imi1, InputMethodInfo imi2) { 3201 if (imi2 == null) return 0; 3202 if (imi1 == null) return 1; 3203 if (mPm == null) { 3204 return imi1.getId().compareTo(imi2.getId()); 3205 } 3206 CharSequence imiId1 = imi1.loadLabel(mPm) + "/" + imi1.getId(); 3207 CharSequence imiId2 = imi2.loadLabel(mPm) + "/" + imi2.getId(); 3208 return imiId1.toString().compareTo(imiId2.toString()); 3209 } 3210 }); 3211 3212 public ImeSubtypeListItem getNextInputMethod( 3213 boolean onlyCurrentIme, InputMethodInfo imi, InputMethodSubtype subtype) { 3214 if (imi == null) { 3215 return null; 3216 } 3217 final List<ImeSubtypeListItem> imList = getSortedInputMethodAndSubtypeList(); 3218 if (imList.size() <= 1) { 3219 return null; 3220 } 3221 final int N = imList.size(); 3222 final int currentSubtypeId = subtype != null 3223 ? InputMethodUtils.getSubtypeIdFromHashCode(imi, subtype.hashCode()) 3224 : NOT_A_SUBTYPE_ID; 3225 for (int i = 0; i < N; ++i) { 3226 final ImeSubtypeListItem isli = imList.get(i); 3227 if (isli.mImi.equals(imi) && isli.mSubtypeId == currentSubtypeId) { 3228 if (!onlyCurrentIme) { 3229 return imList.get((i + 1) % N); 3230 } 3231 for (int j = 0; j < N - 1; ++j) { 3232 final ImeSubtypeListItem candidate = imList.get((i + j + 1) % N); 3233 if (candidate.mImi.equals(imi)) { 3234 return candidate; 3235 } 3236 } 3237 return null; 3238 } 3239 } 3240 return null; 3241 } 3242 3243 public List<ImeSubtypeListItem> getSortedInputMethodAndSubtypeList() { 3244 return getSortedInputMethodAndSubtypeList(true, false, false); 3245 } 3246 3247 public List<ImeSubtypeListItem> getSortedInputMethodAndSubtypeList(boolean showSubtypes, 3248 boolean inputShown, boolean isScreenLocked) { 3249 final ArrayList<ImeSubtypeListItem> imList = new ArrayList<ImeSubtypeListItem>(); 3250 final HashMap<InputMethodInfo, List<InputMethodSubtype>> immis = 3251 mImms.getExplicitlyOrImplicitlyEnabledInputMethodsAndSubtypeListLocked(); 3252 if (immis == null || immis.size() == 0) { 3253 return Collections.emptyList(); 3254 } 3255 mSortedImmis.clear(); 3256 mSortedImmis.putAll(immis); 3257 for (InputMethodInfo imi : mSortedImmis.keySet()) { 3258 if (imi == null) continue; 3259 List<InputMethodSubtype> explicitlyOrImplicitlyEnabledSubtypeList = immis.get(imi); 3260 HashSet<String> enabledSubtypeSet = new HashSet<String>(); 3261 for (InputMethodSubtype subtype: explicitlyOrImplicitlyEnabledSubtypeList) { 3262 enabledSubtypeSet.add(String.valueOf(subtype.hashCode())); 3263 } 3264 final CharSequence imeLabel = imi.loadLabel(mPm); 3265 if (showSubtypes && enabledSubtypeSet.size() > 0) { 3266 final int subtypeCount = imi.getSubtypeCount(); 3267 if (DEBUG) { 3268 Slog.v(TAG, "Add subtypes: " + subtypeCount + ", " + imi.getId()); 3269 } 3270 for (int j = 0; j < subtypeCount; ++j) { 3271 final InputMethodSubtype subtype = imi.getSubtypeAt(j); 3272 final String subtypeHashCode = String.valueOf(subtype.hashCode()); 3273 // We show all enabled IMEs and subtypes when an IME is shown. 3274 if (enabledSubtypeSet.contains(subtypeHashCode) 3275 && ((inputShown && !isScreenLocked) || !subtype.isAuxiliary())) { 3276 final CharSequence subtypeLabel = 3277 subtype.overridesImplicitlyEnabledSubtype() ? null 3278 : subtype.getDisplayName(mContext, imi.getPackageName(), 3279 imi.getServiceInfo().applicationInfo); 3280 imList.add(new ImeSubtypeListItem(imeLabel, subtypeLabel, imi, j, 3281 subtype.getLocale(), mSystemLocaleStr)); 3282 3283 // Removing this subtype from enabledSubtypeSet because we no longer 3284 // need to add an entry of this subtype to imList to avoid duplicated 3285 // entries. 3286 enabledSubtypeSet.remove(subtypeHashCode); 3287 } 3288 } 3289 } else { 3290 imList.add(new ImeSubtypeListItem(imeLabel, null, imi, NOT_A_SUBTYPE_ID, 3291 null, mSystemLocaleStr)); 3292 } 3293 } 3294 Collections.sort(imList); 3295 return imList; 3296 } 3297 } 3298 3299 // TODO: Cache the state for each user and reset when the cached user is removed. 3300 private static class InputMethodFileManager { 3301 private static final String SYSTEM_PATH = "system"; 3302 private static final String INPUT_METHOD_PATH = "inputmethod"; 3303 private static final String ADDITIONAL_SUBTYPES_FILE_NAME = "subtypes.xml"; 3304 private static final String NODE_SUBTYPES = "subtypes"; 3305 private static final String NODE_SUBTYPE = "subtype"; 3306 private static final String NODE_IMI = "imi"; 3307 private static final String ATTR_ID = "id"; 3308 private static final String ATTR_LABEL = "label"; 3309 private static final String ATTR_ICON = "icon"; 3310 private static final String ATTR_IME_SUBTYPE_LOCALE = "imeSubtypeLocale"; 3311 private static final String ATTR_IME_SUBTYPE_MODE = "imeSubtypeMode"; 3312 private static final String ATTR_IME_SUBTYPE_EXTRA_VALUE = "imeSubtypeExtraValue"; 3313 private static final String ATTR_IS_AUXILIARY = "isAuxiliary"; 3314 private final AtomicFile mAdditionalInputMethodSubtypeFile; 3315 private final HashMap<String, InputMethodInfo> mMethodMap; 3316 private final HashMap<String, List<InputMethodSubtype>> mAdditionalSubtypesMap = 3317 new HashMap<String, List<InputMethodSubtype>>(); 3318 public InputMethodFileManager(HashMap<String, InputMethodInfo> methodMap, int userId) { 3319 if (methodMap == null) { 3320 throw new NullPointerException("methodMap is null"); 3321 } 3322 mMethodMap = methodMap; 3323 final File systemDir = userId == UserHandle.USER_OWNER 3324 ? new File(Environment.getDataDirectory(), SYSTEM_PATH) 3325 : Environment.getUserSystemDirectory(userId); 3326 final File inputMethodDir = new File(systemDir, INPUT_METHOD_PATH); 3327 if (!inputMethodDir.mkdirs()) { 3328 Slog.w(TAG, "Couldn't create dir.: " + inputMethodDir.getAbsolutePath()); 3329 } 3330 final File subtypeFile = new File(inputMethodDir, ADDITIONAL_SUBTYPES_FILE_NAME); 3331 mAdditionalInputMethodSubtypeFile = new AtomicFile(subtypeFile); 3332 if (!subtypeFile.exists()) { 3333 // If "subtypes.xml" doesn't exist, create a blank file. 3334 writeAdditionalInputMethodSubtypes( 3335 mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile, methodMap); 3336 } else { 3337 readAdditionalInputMethodSubtypes( 3338 mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile); 3339 } 3340 } 3341 3342 private void deleteAllInputMethodSubtypes(String imiId) { 3343 synchronized (mMethodMap) { 3344 mAdditionalSubtypesMap.remove(imiId); 3345 writeAdditionalInputMethodSubtypes( 3346 mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile, mMethodMap); 3347 } 3348 } 3349 3350 public void addInputMethodSubtypes( 3351 InputMethodInfo imi, InputMethodSubtype[] additionalSubtypes) { 3352 synchronized (mMethodMap) { 3353 final ArrayList<InputMethodSubtype> subtypes = new ArrayList<InputMethodSubtype>(); 3354 final int N = additionalSubtypes.length; 3355 for (int i = 0; i < N; ++i) { 3356 final InputMethodSubtype subtype = additionalSubtypes[i]; 3357 if (!subtypes.contains(subtype)) { 3358 subtypes.add(subtype); 3359 } else { 3360 Slog.w(TAG, "Duplicated subtype definition found: " 3361 + subtype.getLocale() + ", " + subtype.getMode()); 3362 } 3363 } 3364 mAdditionalSubtypesMap.put(imi.getId(), subtypes); 3365 writeAdditionalInputMethodSubtypes( 3366 mAdditionalSubtypesMap, mAdditionalInputMethodSubtypeFile, mMethodMap); 3367 } 3368 } 3369 3370 public HashMap<String, List<InputMethodSubtype>> getAllAdditionalInputMethodSubtypes() { 3371 synchronized (mMethodMap) { 3372 return mAdditionalSubtypesMap; 3373 } 3374 } 3375 3376 private static void writeAdditionalInputMethodSubtypes( 3377 HashMap<String, List<InputMethodSubtype>> allSubtypes, AtomicFile subtypesFile, 3378 HashMap<String, InputMethodInfo> methodMap) { 3379 // Safety net for the case that this function is called before methodMap is set. 3380 final boolean isSetMethodMap = methodMap != null && methodMap.size() > 0; 3381 FileOutputStream fos = null; 3382 try { 3383 fos = subtypesFile.startWrite(); 3384 final XmlSerializer out = new FastXmlSerializer(); 3385 out.setOutput(fos, "utf-8"); 3386 out.startDocument(null, true); 3387 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); 3388 out.startTag(null, NODE_SUBTYPES); 3389 for (String imiId : allSubtypes.keySet()) { 3390 if (isSetMethodMap && !methodMap.containsKey(imiId)) { 3391 Slog.w(TAG, "IME uninstalled or not valid.: " + imiId); 3392 continue; 3393 } 3394 out.startTag(null, NODE_IMI); 3395 out.attribute(null, ATTR_ID, imiId); 3396 final List<InputMethodSubtype> subtypesList = allSubtypes.get(imiId); 3397 final int N = subtypesList.size(); 3398 for (int i = 0; i < N; ++i) { 3399 final InputMethodSubtype subtype = subtypesList.get(i); 3400 out.startTag(null, NODE_SUBTYPE); 3401 out.attribute(null, ATTR_ICON, String.valueOf(subtype.getIconResId())); 3402 out.attribute(null, ATTR_LABEL, String.valueOf(subtype.getNameResId())); 3403 out.attribute(null, ATTR_IME_SUBTYPE_LOCALE, subtype.getLocale()); 3404 out.attribute(null, ATTR_IME_SUBTYPE_MODE, subtype.getMode()); 3405 out.attribute(null, ATTR_IME_SUBTYPE_EXTRA_VALUE, subtype.getExtraValue()); 3406 out.attribute(null, ATTR_IS_AUXILIARY, 3407 String.valueOf(subtype.isAuxiliary() ? 1 : 0)); 3408 out.endTag(null, NODE_SUBTYPE); 3409 } 3410 out.endTag(null, NODE_IMI); 3411 } 3412 out.endTag(null, NODE_SUBTYPES); 3413 out.endDocument(); 3414 subtypesFile.finishWrite(fos); 3415 } catch (java.io.IOException e) { 3416 Slog.w(TAG, "Error writing subtypes", e); 3417 if (fos != null) { 3418 subtypesFile.failWrite(fos); 3419 } 3420 } 3421 } 3422 3423 private static void readAdditionalInputMethodSubtypes( 3424 HashMap<String, List<InputMethodSubtype>> allSubtypes, AtomicFile subtypesFile) { 3425 if (allSubtypes == null || subtypesFile == null) return; 3426 allSubtypes.clear(); 3427 FileInputStream fis = null; 3428 try { 3429 fis = subtypesFile.openRead(); 3430 final XmlPullParser parser = Xml.newPullParser(); 3431 parser.setInput(fis, null); 3432 int type = parser.getEventType(); 3433 // Skip parsing until START_TAG 3434 while ((type = parser.next()) != XmlPullParser.START_TAG 3435 && type != XmlPullParser.END_DOCUMENT) {} 3436 String firstNodeName = parser.getName(); 3437 if (!NODE_SUBTYPES.equals(firstNodeName)) { 3438 throw new XmlPullParserException("Xml doesn't start with subtypes"); 3439 } 3440 final int depth =parser.getDepth(); 3441 String currentImiId = null; 3442 ArrayList<InputMethodSubtype> tempSubtypesArray = null; 3443 while (((type = parser.next()) != XmlPullParser.END_TAG 3444 || parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) { 3445 if (type != XmlPullParser.START_TAG) 3446 continue; 3447 final String nodeName = parser.getName(); 3448 if (NODE_IMI.equals(nodeName)) { 3449 currentImiId = parser.getAttributeValue(null, ATTR_ID); 3450 if (TextUtils.isEmpty(currentImiId)) { 3451 Slog.w(TAG, "Invalid imi id found in subtypes.xml"); 3452 continue; 3453 } 3454 tempSubtypesArray = new ArrayList<InputMethodSubtype>(); 3455 allSubtypes.put(currentImiId, tempSubtypesArray); 3456 } else if (NODE_SUBTYPE.equals(nodeName)) { 3457 if (TextUtils.isEmpty(currentImiId) || tempSubtypesArray == null) { 3458 Slog.w(TAG, "IME uninstalled or not valid.: " + currentImiId); 3459 continue; 3460 } 3461 final int icon = Integer.valueOf( 3462 parser.getAttributeValue(null, ATTR_ICON)); 3463 final int label = Integer.valueOf( 3464 parser.getAttributeValue(null, ATTR_LABEL)); 3465 final String imeSubtypeLocale = 3466 parser.getAttributeValue(null, ATTR_IME_SUBTYPE_LOCALE); 3467 final String imeSubtypeMode = 3468 parser.getAttributeValue(null, ATTR_IME_SUBTYPE_MODE); 3469 final String imeSubtypeExtraValue = 3470 parser.getAttributeValue(null, ATTR_IME_SUBTYPE_EXTRA_VALUE); 3471 final boolean isAuxiliary = "1".equals(String.valueOf( 3472 parser.getAttributeValue(null, ATTR_IS_AUXILIARY))); 3473 final InputMethodSubtype subtype = 3474 new InputMethodSubtype(label, icon, imeSubtypeLocale, 3475 imeSubtypeMode, imeSubtypeExtraValue, isAuxiliary); 3476 tempSubtypesArray.add(subtype); 3477 } 3478 } 3479 } catch (XmlPullParserException e) { 3480 Slog.w(TAG, "Error reading subtypes: " + e); 3481 return; 3482 } catch (java.io.IOException e) { 3483 Slog.w(TAG, "Error reading subtypes: " + e); 3484 return; 3485 } catch (NumberFormatException e) { 3486 Slog.w(TAG, "Error reading subtypes: " + e); 3487 return; 3488 } finally { 3489 if (fis != null) { 3490 try { 3491 fis.close(); 3492 } catch (java.io.IOException e1) { 3493 Slog.w(TAG, "Failed to close."); 3494 } 3495 } 3496 } 3497 } 3498 } 3499 3500 @Override 3501 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 3502 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 3503 != PackageManager.PERMISSION_GRANTED) { 3504 3505 pw.println("Permission Denial: can't dump InputMethodManager from from pid=" 3506 + Binder.getCallingPid() 3507 + ", uid=" + Binder.getCallingUid()); 3508 return; 3509 } 3510 3511 IInputMethod method; 3512 ClientState client; 3513 3514 final Printer p = new PrintWriterPrinter(pw); 3515 3516 synchronized (mMethodMap) { 3517 p.println("Current Input Method Manager state:"); 3518 int N = mMethodList.size(); 3519 p.println(" Input Methods:"); 3520 for (int i=0; i<N; i++) { 3521 InputMethodInfo info = mMethodList.get(i); 3522 p.println(" InputMethod #" + i + ":"); 3523 info.dump(p, " "); 3524 } 3525 p.println(" Clients:"); 3526 for (ClientState ci : mClients.values()) { 3527 p.println(" Client " + ci + ":"); 3528 p.println(" client=" + ci.client); 3529 p.println(" inputContext=" + ci.inputContext); 3530 p.println(" sessionRequested=" + ci.sessionRequested); 3531 p.println(" curSession=" + ci.curSession); 3532 } 3533 p.println(" mCurMethodId=" + mCurMethodId); 3534 client = mCurClient; 3535 p.println(" mCurClient=" + client + " mCurSeq=" + mCurSeq); 3536 p.println(" mCurFocusedWindow=" + mCurFocusedWindow); 3537 p.println(" mCurId=" + mCurId + " mHaveConnect=" + mHaveConnection 3538 + " mBoundToMethod=" + mBoundToMethod); 3539 p.println(" mCurToken=" + mCurToken); 3540 p.println(" mCurIntent=" + mCurIntent); 3541 method = mCurMethod; 3542 p.println(" mCurMethod=" + mCurMethod); 3543 p.println(" mEnabledSession=" + mEnabledSession); 3544 p.println(" mShowRequested=" + mShowRequested 3545 + " mShowExplicitlyRequested=" + mShowExplicitlyRequested 3546 + " mShowForced=" + mShowForced 3547 + " mInputShown=" + mInputShown); 3548 p.println(" mSystemReady=" + mSystemReady + " mScreenOn=" + mScreenOn); 3549 } 3550 3551 p.println(" "); 3552 if (client != null) { 3553 pw.flush(); 3554 try { 3555 client.client.asBinder().dump(fd, args); 3556 } catch (RemoteException e) { 3557 p.println("Input method client dead: " + e); 3558 } 3559 } else { 3560 p.println("No input method client."); 3561 } 3562 3563 p.println(" "); 3564 if (method != null) { 3565 pw.flush(); 3566 try { 3567 method.asBinder().dump(fd, args); 3568 } catch (RemoteException e) { 3569 p.println("Input method service dead: " + e); 3570 } 3571 } else { 3572 p.println("No input method service."); 3573 } 3574 } 3575} 3576