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