1 /* 2 * Copyright (C) 2011 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.server; 18 19 import com.android.internal.annotations.GuardedBy; 20 import com.android.internal.content.PackageMonitor; 21 import com.android.internal.inputmethod.InputMethodUtils; 22 import com.android.internal.textservice.ISpellCheckerService; 23 import com.android.internal.textservice.ISpellCheckerSession; 24 import com.android.internal.textservice.ISpellCheckerSessionListener; 25 import com.android.internal.textservice.ITextServicesManager; 26 import com.android.internal.textservice.ITextServicesSessionListener; 27 28 import org.xmlpull.v1.XmlPullParserException; 29 30 import android.annotation.NonNull; 31 import android.annotation.Nullable; 32 import android.annotation.UserIdInt; 33 import android.app.ActivityManagerNative; 34 import android.app.AppGlobals; 35 import android.content.BroadcastReceiver; 36 import android.content.ComponentName; 37 import android.content.ContentResolver; 38 import android.content.Context; 39 import android.content.Intent; 40 import android.content.IntentFilter; 41 import android.content.ServiceConnection; 42 import android.content.pm.ApplicationInfo; 43 import android.content.pm.PackageManager; 44 import android.content.pm.ResolveInfo; 45 import android.content.pm.ServiceInfo; 46 import android.os.Binder; 47 import android.os.Bundle; 48 import android.os.IBinder; 49 import android.os.Process; 50 import android.os.RemoteException; 51 import android.os.UserHandle; 52 import android.os.UserManager; 53 import android.provider.Settings; 54 import android.service.textservice.SpellCheckerService; 55 import android.text.TextUtils; 56 import android.util.Slog; 57 import android.view.inputmethod.InputMethodManager; 58 import android.view.inputmethod.InputMethodSubtype; 59 import android.view.textservice.SpellCheckerInfo; 60 import android.view.textservice.SpellCheckerSubtype; 61 62 import java.io.FileDescriptor; 63 import java.io.IOException; 64 import java.io.PrintWriter; 65 import java.util.Arrays; 66 import java.util.ArrayList; 67 import java.util.HashMap; 68 import java.util.List; 69 import java.util.Locale; 70 import java.util.Map; 71 import java.util.concurrent.CopyOnWriteArrayList; 72 73 public class TextServicesManagerService extends ITextServicesManager.Stub { 74 private static final String TAG = TextServicesManagerService.class.getSimpleName(); 75 private static final boolean DBG = false; 76 77 private final Context mContext; 78 private boolean mSystemReady; 79 private final TextServicesMonitor mMonitor; 80 private final HashMap<String, SpellCheckerInfo> mSpellCheckerMap = new HashMap<>(); 81 private final ArrayList<SpellCheckerInfo> mSpellCheckerList = new ArrayList<>(); 82 private final HashMap<String, SpellCheckerBindGroup> mSpellCheckerBindGroups = new HashMap<>(); 83 private final TextServicesSettings mSettings; 84 @NonNull 85 private final UserManager mUserManager; 86 87 public static final class Lifecycle extends SystemService { 88 private TextServicesManagerService mService; 89 90 public Lifecycle(Context context) { 91 super(context); 92 mService = new TextServicesManagerService(context); 93 } 94 95 @Override 96 public void onStart() { 97 publishBinderService(Context.TEXT_SERVICES_MANAGER_SERVICE, mService); 98 } 99 100 @Override 101 public void onSwitchUser(@UserIdInt int userHandle) { 102 // Called on the system server's main looper thread. 103 // TODO: Dispatch this to a worker thread as needed. 104 mService.onSwitchUser(userHandle); 105 } 106 107 @Override 108 public void onBootPhase(int phase) { 109 // Called on the system server's main looper thread. 110 // TODO: Dispatch this to a worker thread as needed. 111 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) { 112 mService.systemRunning(); 113 } 114 } 115 116 @Override 117 public void onUnlockUser(@UserIdInt int userHandle) { 118 // Called on the system server's main looper thread. 119 // TODO: Dispatch this to a worker thread as needed. 120 mService.onUnlockUser(userHandle); 121 } 122 } 123 124 void systemRunning() { 125 synchronized (mSpellCheckerMap) { 126 if (!mSystemReady) { 127 mSystemReady = true; 128 resetInternalState(mSettings.getCurrentUserId()); 129 } 130 } 131 } 132 133 void onSwitchUser(@UserIdInt int userId) { 134 synchronized (mSpellCheckerMap) { 135 resetInternalState(userId); 136 } 137 } 138 139 void onUnlockUser(@UserIdInt int userId) { 140 synchronized(mSpellCheckerMap) { 141 final int currentUserId = mSettings.getCurrentUserId(); 142 if (userId != currentUserId) { 143 return; 144 } 145 resetInternalState(currentUserId); 146 } 147 } 148 149 public TextServicesManagerService(Context context) { 150 mSystemReady = false; 151 mContext = context; 152 153 mUserManager = mContext.getSystemService(UserManager.class); 154 155 final IntentFilter broadcastFilter = new IntentFilter(); 156 broadcastFilter.addAction(Intent.ACTION_USER_ADDED); 157 broadcastFilter.addAction(Intent.ACTION_USER_REMOVED); 158 mContext.registerReceiver(new TextServicesBroadcastReceiver(), broadcastFilter); 159 160 int userId = UserHandle.USER_SYSTEM; 161 try { 162 userId = ActivityManagerNative.getDefault().getCurrentUser().id; 163 } catch (RemoteException e) { 164 Slog.w(TAG, "Couldn't get current user ID; guessing it's 0", e); 165 } 166 mMonitor = new TextServicesMonitor(); 167 mMonitor.register(context, null, true); 168 final boolean useCopyOnWriteSettings = 169 !mSystemReady || !mUserManager.isUserUnlockingOrUnlocked(userId); 170 mSettings = new TextServicesSettings(context.getContentResolver(), userId, 171 useCopyOnWriteSettings); 172 173 // "resetInternalState" initializes the states for the foreground user 174 resetInternalState(userId); 175 } 176 177 private void resetInternalState(@UserIdInt int userId) { 178 final boolean useCopyOnWriteSettings = 179 !mSystemReady || !mUserManager.isUserUnlockingOrUnlocked(userId); 180 mSettings.switchCurrentUser(userId, useCopyOnWriteSettings); 181 updateCurrentProfileIds(); 182 unbindServiceLocked(); 183 buildSpellCheckerMapLocked(mContext, mSpellCheckerList, mSpellCheckerMap, mSettings); 184 SpellCheckerInfo sci = getCurrentSpellChecker(null); 185 if (sci == null) { 186 sci = findAvailSpellCheckerLocked(null); 187 if (sci != null) { 188 // Set the current spell checker if there is one or more spell checkers 189 // available. In this case, "sci" is the first one in the available spell 190 // checkers. 191 setCurrentSpellCheckerLocked(sci.getId()); 192 } 193 } 194 } 195 196 void updateCurrentProfileIds() { 197 mSettings.setCurrentProfileIds( 198 mUserManager.getProfileIdsWithDisabled(mSettings.getCurrentUserId())); 199 } 200 201 private class TextServicesMonitor extends PackageMonitor { 202 private boolean isChangingPackagesOfCurrentUser() { 203 final int userId = getChangingUserId(); 204 final boolean retval = userId == mSettings.getCurrentUserId(); 205 if (DBG) { 206 Slog.d(TAG, "--- ignore this call back from a background user: " + userId); 207 } 208 return retval; 209 } 210 211 @Override 212 public void onSomePackagesChanged() { 213 if (!isChangingPackagesOfCurrentUser()) { 214 return; 215 } 216 synchronized (mSpellCheckerMap) { 217 buildSpellCheckerMapLocked( 218 mContext, mSpellCheckerList, mSpellCheckerMap, mSettings); 219 // TODO: Update for each locale 220 SpellCheckerInfo sci = getCurrentSpellChecker(null); 221 // If no spell checker is enabled, just return. The user should explicitly 222 // enable the spell checker. 223 if (sci == null) return; 224 final String packageName = sci.getPackageName(); 225 final int change = isPackageDisappearing(packageName); 226 if (// Package disappearing 227 change == PACKAGE_PERMANENT_CHANGE || change == PACKAGE_TEMPORARY_CHANGE 228 // Package modified 229 || isPackageModified(packageName)) { 230 sci = findAvailSpellCheckerLocked(packageName); 231 if (sci != null) { 232 setCurrentSpellCheckerLocked(sci.getId()); 233 } 234 } 235 } 236 } 237 } 238 239 class TextServicesBroadcastReceiver extends BroadcastReceiver { 240 @Override 241 public void onReceive(Context context, Intent intent) { 242 final String action = intent.getAction(); 243 if (Intent.ACTION_USER_ADDED.equals(action) 244 || Intent.ACTION_USER_REMOVED.equals(action)) { 245 updateCurrentProfileIds(); 246 return; 247 } 248 Slog.w(TAG, "Unexpected intent " + intent); 249 } 250 } 251 252 private static void buildSpellCheckerMapLocked(Context context, 253 ArrayList<SpellCheckerInfo> list, HashMap<String, SpellCheckerInfo> map, 254 TextServicesSettings settings) { 255 list.clear(); 256 map.clear(); 257 final PackageManager pm = context.getPackageManager(); 258 // Note: We do not specify PackageManager.MATCH_ENCRYPTION_* flags here because the default 259 // behavior of PackageManager is exactly what we want. It by default picks up appropriate 260 // services depending on the unlock state for the specified user. 261 final List<ResolveInfo> services = pm.queryIntentServicesAsUser( 262 new Intent(SpellCheckerService.SERVICE_INTERFACE), PackageManager.GET_META_DATA, 263 settings.getCurrentUserId()); 264 final int N = services.size(); 265 for (int i = 0; i < N; ++i) { 266 final ResolveInfo ri = services.get(i); 267 final ServiceInfo si = ri.serviceInfo; 268 final ComponentName compName = new ComponentName(si.packageName, si.name); 269 if (!android.Manifest.permission.BIND_TEXT_SERVICE.equals(si.permission)) { 270 Slog.w(TAG, "Skipping text service " + compName 271 + ": it does not require the permission " 272 + android.Manifest.permission.BIND_TEXT_SERVICE); 273 continue; 274 } 275 if (DBG) Slog.d(TAG, "Add: " + compName); 276 try { 277 final SpellCheckerInfo sci = new SpellCheckerInfo(context, ri); 278 if (sci.getSubtypeCount() <= 0) { 279 Slog.w(TAG, "Skipping text service " + compName 280 + ": it does not contain subtypes."); 281 continue; 282 } 283 list.add(sci); 284 map.put(sci.getId(), sci); 285 } catch (XmlPullParserException e) { 286 Slog.w(TAG, "Unable to load the spell checker " + compName, e); 287 } catch (IOException e) { 288 Slog.w(TAG, "Unable to load the spell checker " + compName, e); 289 } 290 } 291 if (DBG) { 292 Slog.d(TAG, "buildSpellCheckerMapLocked: " + list.size() + "," + map.size()); 293 } 294 } 295 296 // --------------------------------------------------------------------------------------- 297 // Check whether or not this is a valid IPC. Assumes an IPC is valid when either 298 // 1) it comes from the system process 299 // 2) the calling process' user id is identical to the current user id TSMS thinks. 300 private boolean calledFromValidUser() { 301 final int uid = Binder.getCallingUid(); 302 final int userId = UserHandle.getUserId(uid); 303 if (DBG) { 304 Slog.d(TAG, "--- calledFromForegroundUserOrSystemProcess ? " 305 + "calling uid = " + uid + " system uid = " + Process.SYSTEM_UID 306 + " calling userId = " + userId + ", foreground user id = " 307 + mSettings.getCurrentUserId() + ", calling pid = " + Binder.getCallingPid()); 308 try { 309 final String[] packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid); 310 for (int i = 0; i < packageNames.length; ++i) { 311 if (DBG) { 312 Slog.d(TAG, "--- process name for "+ uid + " = " + packageNames[i]); 313 } 314 } 315 } catch (RemoteException e) { 316 } 317 } 318 319 if (uid == Process.SYSTEM_UID || userId == mSettings.getCurrentUserId()) { 320 return true; 321 } 322 323 // Permits current profile to use TSFM as long as the current text service is the system's 324 // one. This is a tentative solution and should be replaced with fully functional multiuser 325 // support. 326 // TODO: Implement multiuser support in TSMS. 327 final boolean isCurrentProfile = mSettings.isCurrentProfile(userId); 328 if (DBG) { 329 Slog.d(TAG, "--- userId = "+ userId + " isCurrentProfile = " + isCurrentProfile); 330 } 331 if (mSettings.isCurrentProfile(userId)) { 332 final SpellCheckerInfo spellCheckerInfo = getCurrentSpellCheckerWithoutVerification(); 333 if (spellCheckerInfo != null) { 334 final ServiceInfo serviceInfo = spellCheckerInfo.getServiceInfo(); 335 final boolean isSystemSpellChecker = 336 (serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 337 if (DBG) { 338 Slog.d(TAG, "--- current spell checker = "+ spellCheckerInfo.getPackageName() 339 + " isSystem = " + isSystemSpellChecker); 340 } 341 if (isSystemSpellChecker) { 342 return true; 343 } 344 } 345 } 346 347 // Unlike InputMethodManagerService#calledFromValidUser, INTERACT_ACROSS_USERS_FULL isn't 348 // taken into account here. Anyway this method is supposed to be removed once multiuser 349 // support is implemented. 350 if (DBG) { 351 Slog.d(TAG, "--- IPC from userId:" + userId + " is being ignored. \n" 352 + getStackTrace()); 353 } 354 return false; 355 } 356 357 private boolean bindCurrentSpellCheckerService( 358 Intent service, ServiceConnection conn, int flags) { 359 if (service == null || conn == null) { 360 Slog.e(TAG, "--- bind failed: service = " + service + ", conn = " + conn); 361 return false; 362 } 363 return mContext.bindServiceAsUser(service, conn, flags, 364 new UserHandle(mSettings.getCurrentUserId())); 365 } 366 367 private void unbindServiceLocked() { 368 for (SpellCheckerBindGroup scbg : mSpellCheckerBindGroups.values()) { 369 scbg.removeAll(); 370 } 371 mSpellCheckerBindGroups.clear(); 372 } 373 374 private SpellCheckerInfo findAvailSpellCheckerLocked(String prefPackage) { 375 final int spellCheckersCount = mSpellCheckerList.size(); 376 if (spellCheckersCount == 0) { 377 Slog.w(TAG, "no available spell checker services found"); 378 return null; 379 } 380 if (prefPackage != null) { 381 for (int i = 0; i < spellCheckersCount; ++i) { 382 final SpellCheckerInfo sci = mSpellCheckerList.get(i); 383 if (prefPackage.equals(sci.getPackageName())) { 384 if (DBG) { 385 Slog.d(TAG, "findAvailSpellCheckerLocked: " + sci.getPackageName()); 386 } 387 return sci; 388 } 389 } 390 } 391 392 // Look up a spell checker based on the system locale. 393 // TODO: Still there is a room to improve in the following logic: e.g., check if the package 394 // is pre-installed or not. 395 final Locale systemLocal = mContext.getResources().getConfiguration().locale; 396 final ArrayList<Locale> suitableLocales = 397 InputMethodUtils.getSuitableLocalesForSpellChecker(systemLocal); 398 if (DBG) { 399 Slog.w(TAG, "findAvailSpellCheckerLocked suitableLocales=" 400 + Arrays.toString(suitableLocales.toArray(new Locale[suitableLocales.size()]))); 401 } 402 final int localeCount = suitableLocales.size(); 403 for (int localeIndex = 0; localeIndex < localeCount; ++localeIndex) { 404 final Locale locale = suitableLocales.get(localeIndex); 405 for (int spellCheckersIndex = 0; spellCheckersIndex < spellCheckersCount; 406 ++spellCheckersIndex) { 407 final SpellCheckerInfo info = mSpellCheckerList.get(spellCheckersIndex); 408 final int subtypeCount = info.getSubtypeCount(); 409 for (int subtypeIndex = 0; subtypeIndex < subtypeCount; ++subtypeIndex) { 410 final SpellCheckerSubtype subtype = info.getSubtypeAt(subtypeIndex); 411 final Locale subtypeLocale = InputMethodUtils.constructLocaleFromString( 412 subtype.getLocale()); 413 if (locale.equals(subtypeLocale)) { 414 // TODO: We may have more spell checkers that fall into this category. 415 // Ideally we should pick up the most suitable one instead of simply 416 // returning the first found one. 417 return info; 418 } 419 } 420 } 421 } 422 423 if (spellCheckersCount > 1) { 424 Slog.w(TAG, "more than one spell checker service found, picking first"); 425 } 426 return mSpellCheckerList.get(0); 427 } 428 429 // TODO: Save SpellCheckerService by supported languages. Currently only one spell 430 // checker is saved. 431 @Override 432 public SpellCheckerInfo getCurrentSpellChecker(String locale) { 433 // TODO: Make this work even for non-current users? 434 if (!calledFromValidUser()) { 435 return null; 436 } 437 return getCurrentSpellCheckerWithoutVerification(); 438 } 439 440 private SpellCheckerInfo getCurrentSpellCheckerWithoutVerification() { 441 synchronized (mSpellCheckerMap) { 442 final String curSpellCheckerId = mSettings.getSelectedSpellChecker(); 443 if (DBG) { 444 Slog.w(TAG, "getCurrentSpellChecker: " + curSpellCheckerId); 445 } 446 if (TextUtils.isEmpty(curSpellCheckerId)) { 447 return null; 448 } 449 return mSpellCheckerMap.get(curSpellCheckerId); 450 } 451 } 452 453 // TODO: Respect allowImplicitlySelectedSubtype 454 // TODO: Save SpellCheckerSubtype by supported languages by looking at "locale". 455 @Override 456 public SpellCheckerSubtype getCurrentSpellCheckerSubtype( 457 String locale, boolean allowImplicitlySelectedSubtype) { 458 // TODO: Make this work even for non-current users? 459 if (!calledFromValidUser()) { 460 return null; 461 } 462 final int subtypeHashCode; 463 final SpellCheckerInfo sci; 464 final Locale systemLocale; 465 synchronized (mSpellCheckerMap) { 466 subtypeHashCode = 467 mSettings.getSelectedSpellCheckerSubtype(SpellCheckerSubtype.SUBTYPE_ID_NONE); 468 if (DBG) { 469 Slog.w(TAG, "getCurrentSpellCheckerSubtype: " + subtypeHashCode); 470 } 471 sci = getCurrentSpellChecker(null); 472 systemLocale = mContext.getResources().getConfiguration().locale; 473 } 474 if (sci == null || sci.getSubtypeCount() == 0) { 475 if (DBG) { 476 Slog.w(TAG, "Subtype not found."); 477 } 478 return null; 479 } 480 if (subtypeHashCode == SpellCheckerSubtype.SUBTYPE_ID_NONE 481 && !allowImplicitlySelectedSubtype) { 482 return null; 483 } 484 String candidateLocale = null; 485 if (subtypeHashCode == 0) { 486 // Spell checker language settings == "auto" 487 final InputMethodManager imm = mContext.getSystemService(InputMethodManager.class); 488 if (imm != null) { 489 final InputMethodSubtype currentInputMethodSubtype = 490 imm.getCurrentInputMethodSubtype(); 491 if (currentInputMethodSubtype != null) { 492 final String localeString = currentInputMethodSubtype.getLocale(); 493 if (!TextUtils.isEmpty(localeString)) { 494 // 1. Use keyboard locale if available in the spell checker 495 candidateLocale = localeString; 496 } 497 } 498 } 499 if (candidateLocale == null) { 500 // 2. Use System locale if available in the spell checker 501 candidateLocale = systemLocale.toString(); 502 } 503 } 504 SpellCheckerSubtype candidate = null; 505 for (int i = 0; i < sci.getSubtypeCount(); ++i) { 506 final SpellCheckerSubtype scs = sci.getSubtypeAt(i); 507 if (subtypeHashCode == 0) { 508 final String scsLocale = scs.getLocale(); 509 if (candidateLocale.equals(scsLocale)) { 510 return scs; 511 } else if (candidate == null) { 512 if (candidateLocale.length() >= 2 && scsLocale.length() >= 2 513 && candidateLocale.startsWith(scsLocale)) { 514 // Fall back to the applicable language 515 candidate = scs; 516 } 517 } 518 } else if (scs.hashCode() == subtypeHashCode) { 519 if (DBG) { 520 Slog.w(TAG, "Return subtype " + scs.hashCode() + ", input= " + locale 521 + ", " + scs.getLocale()); 522 } 523 // 3. Use the user specified spell check language 524 return scs; 525 } 526 } 527 // 4. Fall back to the applicable language and return it if not null 528 // 5. Simply just return it even if it's null which means we could find no suitable 529 // spell check languages 530 return candidate; 531 } 532 533 @Override 534 public void getSpellCheckerService(String sciId, String locale, 535 ITextServicesSessionListener tsListener, ISpellCheckerSessionListener scListener, 536 Bundle bundle) { 537 if (!calledFromValidUser()) { 538 return; 539 } 540 if (!mSystemReady) { 541 return; 542 } 543 if (TextUtils.isEmpty(sciId) || tsListener == null || scListener == null) { 544 Slog.e(TAG, "getSpellCheckerService: Invalid input."); 545 return; 546 } 547 synchronized(mSpellCheckerMap) { 548 if (!mSpellCheckerMap.containsKey(sciId)) { 549 return; 550 } 551 final SpellCheckerInfo sci = mSpellCheckerMap.get(sciId); 552 final int uid = Binder.getCallingUid(); 553 if (mSpellCheckerBindGroups.containsKey(sciId)) { 554 final SpellCheckerBindGroup bindGroup = mSpellCheckerBindGroups.get(sciId); 555 if (bindGroup != null) { 556 final InternalDeathRecipient recipient = 557 mSpellCheckerBindGroups.get(sciId).addListener( 558 tsListener, locale, scListener, uid, bundle); 559 if (recipient == null) { 560 if (DBG) { 561 Slog.w(TAG, "Didn't create a death recipient."); 562 } 563 return; 564 } 565 if (bindGroup.mSpellChecker == null & bindGroup.mConnected) { 566 Slog.e(TAG, "The state of the spell checker bind group is illegal."); 567 bindGroup.removeAll(); 568 } else if (bindGroup.mSpellChecker != null) { 569 if (DBG) { 570 Slog.w(TAG, "Existing bind found. Return a spell checker session now. " 571 + "Listeners count = " + bindGroup.mListeners.size()); 572 } 573 try { 574 final ISpellCheckerSession session = 575 bindGroup.mSpellChecker.getISpellCheckerSession( 576 recipient.mScLocale, recipient.mScListener, bundle); 577 if (session != null) { 578 tsListener.onServiceConnected(session); 579 return; 580 } else { 581 if (DBG) { 582 Slog.w(TAG, "Existing bind already expired. "); 583 } 584 bindGroup.removeAll(); 585 } 586 } catch (RemoteException e) { 587 Slog.e(TAG, "Exception in getting spell checker session: " + e); 588 bindGroup.removeAll(); 589 } 590 } 591 } 592 } 593 final long ident = Binder.clearCallingIdentity(); 594 try { 595 startSpellCheckerServiceInnerLocked( 596 sci, locale, tsListener, scListener, uid, bundle); 597 } finally { 598 Binder.restoreCallingIdentity(ident); 599 } 600 } 601 return; 602 } 603 604 @Override 605 public boolean isSpellCheckerEnabled() { 606 if (!calledFromValidUser()) { 607 return false; 608 } 609 synchronized(mSpellCheckerMap) { 610 return isSpellCheckerEnabledLocked(); 611 } 612 } 613 614 private void startSpellCheckerServiceInnerLocked(SpellCheckerInfo info, String locale, 615 ITextServicesSessionListener tsListener, ISpellCheckerSessionListener scListener, 616 int uid, Bundle bundle) { 617 if (DBG) { 618 Slog.w(TAG, "Start spell checker session inner locked."); 619 } 620 final String sciId = info.getId(); 621 final InternalServiceConnection connection = new InternalServiceConnection( 622 sciId, locale, bundle); 623 final Intent serviceIntent = new Intent(SpellCheckerService.SERVICE_INTERFACE); 624 serviceIntent.setComponent(info.getComponent()); 625 if (DBG) { 626 Slog.w(TAG, "bind service: " + info.getId()); 627 } 628 if (!bindCurrentSpellCheckerService(serviceIntent, connection, 629 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE_WHILE_AWAKE)) { 630 Slog.e(TAG, "Failed to get a spell checker service."); 631 return; 632 } 633 final SpellCheckerBindGroup group = new SpellCheckerBindGroup( 634 connection, tsListener, locale, scListener, uid, bundle); 635 mSpellCheckerBindGroups.put(sciId, group); 636 } 637 638 @Override 639 public SpellCheckerInfo[] getEnabledSpellCheckers() { 640 // TODO: Make this work even for non-current users? 641 if (!calledFromValidUser()) { 642 return null; 643 } 644 if (DBG) { 645 Slog.d(TAG, "getEnabledSpellCheckers: " + mSpellCheckerList.size()); 646 for (int i = 0; i < mSpellCheckerList.size(); ++i) { 647 Slog.d(TAG, "EnabledSpellCheckers: " + mSpellCheckerList.get(i).getPackageName()); 648 } 649 } 650 return mSpellCheckerList.toArray(new SpellCheckerInfo[mSpellCheckerList.size()]); 651 } 652 653 @Override 654 public void finishSpellCheckerService(ISpellCheckerSessionListener listener) { 655 if (!calledFromValidUser()) { 656 return; 657 } 658 if (DBG) { 659 Slog.d(TAG, "FinishSpellCheckerService"); 660 } 661 synchronized(mSpellCheckerMap) { 662 final ArrayList<SpellCheckerBindGroup> removeList = new ArrayList<>(); 663 for (SpellCheckerBindGroup group : mSpellCheckerBindGroups.values()) { 664 if (group == null) continue; 665 // Use removeList to avoid modifying mSpellCheckerBindGroups in this loop. 666 removeList.add(group); 667 } 668 final int removeSize = removeList.size(); 669 for (int i = 0; i < removeSize; ++i) { 670 removeList.get(i).removeListener(listener); 671 } 672 } 673 } 674 675 @Override 676 public void setCurrentSpellChecker(String locale, String sciId) { 677 if (!calledFromValidUser()) { 678 return; 679 } 680 synchronized(mSpellCheckerMap) { 681 if (mContext.checkCallingOrSelfPermission( 682 android.Manifest.permission.WRITE_SECURE_SETTINGS) 683 != PackageManager.PERMISSION_GRANTED) { 684 throw new SecurityException( 685 "Requires permission " 686 + android.Manifest.permission.WRITE_SECURE_SETTINGS); 687 } 688 setCurrentSpellCheckerLocked(sciId); 689 } 690 } 691 692 @Override 693 public void setCurrentSpellCheckerSubtype(String locale, int hashCode) { 694 if (!calledFromValidUser()) { 695 return; 696 } 697 synchronized(mSpellCheckerMap) { 698 if (mContext.checkCallingOrSelfPermission( 699 android.Manifest.permission.WRITE_SECURE_SETTINGS) 700 != PackageManager.PERMISSION_GRANTED) { 701 throw new SecurityException( 702 "Requires permission " 703 + android.Manifest.permission.WRITE_SECURE_SETTINGS); 704 } 705 setCurrentSpellCheckerSubtypeLocked(hashCode); 706 } 707 } 708 709 @Override 710 public void setSpellCheckerEnabled(boolean enabled) { 711 if (!calledFromValidUser()) { 712 return; 713 } 714 synchronized(mSpellCheckerMap) { 715 if (mContext.checkCallingOrSelfPermission( 716 android.Manifest.permission.WRITE_SECURE_SETTINGS) 717 != PackageManager.PERMISSION_GRANTED) { 718 throw new SecurityException( 719 "Requires permission " 720 + android.Manifest.permission.WRITE_SECURE_SETTINGS); 721 } 722 setSpellCheckerEnabledLocked(enabled); 723 } 724 } 725 726 private void setCurrentSpellCheckerLocked(String sciId) { 727 if (DBG) { 728 Slog.w(TAG, "setCurrentSpellChecker: " + sciId); 729 } 730 if (TextUtils.isEmpty(sciId) || !mSpellCheckerMap.containsKey(sciId)) return; 731 final SpellCheckerInfo currentSci = getCurrentSpellChecker(null); 732 if (currentSci != null && currentSci.getId().equals(sciId)) { 733 // Do nothing if the current spell checker is same as new spell checker. 734 return; 735 } 736 final long ident = Binder.clearCallingIdentity(); 737 try { 738 mSettings.putSelectedSpellChecker(sciId); 739 setCurrentSpellCheckerSubtypeLocked(0); 740 } finally { 741 Binder.restoreCallingIdentity(ident); 742 } 743 } 744 745 private void setCurrentSpellCheckerSubtypeLocked(int hashCode) { 746 if (DBG) { 747 Slog.w(TAG, "setCurrentSpellCheckerSubtype: " + hashCode); 748 } 749 final SpellCheckerInfo sci = getCurrentSpellChecker(null); 750 int tempHashCode = 0; 751 for (int i = 0; sci != null && i < sci.getSubtypeCount(); ++i) { 752 if(sci.getSubtypeAt(i).hashCode() == hashCode) { 753 tempHashCode = hashCode; 754 break; 755 } 756 } 757 final long ident = Binder.clearCallingIdentity(); 758 try { 759 mSettings.putSelectedSpellCheckerSubtype(tempHashCode); 760 } finally { 761 Binder.restoreCallingIdentity(ident); 762 } 763 } 764 765 private void setSpellCheckerEnabledLocked(boolean enabled) { 766 if (DBG) { 767 Slog.w(TAG, "setSpellCheckerEnabled: " + enabled); 768 } 769 final long ident = Binder.clearCallingIdentity(); 770 try { 771 mSettings.setSpellCheckerEnabled(enabled); 772 } finally { 773 Binder.restoreCallingIdentity(ident); 774 } 775 } 776 777 private boolean isSpellCheckerEnabledLocked() { 778 final long ident = Binder.clearCallingIdentity(); 779 try { 780 final boolean retval = mSettings.isSpellCheckerEnabled(); 781 if (DBG) { 782 Slog.w(TAG, "getSpellCheckerEnabled: " + retval); 783 } 784 return retval; 785 } finally { 786 Binder.restoreCallingIdentity(ident); 787 } 788 } 789 790 @Override 791 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 792 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 793 != PackageManager.PERMISSION_GRANTED) { 794 795 pw.println("Permission Denial: can't dump TextServicesManagerService from from pid=" 796 + Binder.getCallingPid() 797 + ", uid=" + Binder.getCallingUid()); 798 return; 799 } 800 801 synchronized(mSpellCheckerMap) { 802 pw.println("Current Text Services Manager state:"); 803 pw.println(" Spell Checkers:"); 804 int spellCheckerIndex = 0; 805 for (final SpellCheckerInfo info : mSpellCheckerMap.values()) { 806 pw.println(" Spell Checker #" + spellCheckerIndex); 807 info.dump(pw, " "); 808 ++spellCheckerIndex; 809 } 810 pw.println(""); 811 pw.println(" Spell Checker Bind Groups:"); 812 for (final Map.Entry<String, SpellCheckerBindGroup> ent 813 : mSpellCheckerBindGroups.entrySet()) { 814 final SpellCheckerBindGroup grp = ent.getValue(); 815 pw.println(" " + ent.getKey() + " " + grp + ":"); 816 pw.println(" " + "mInternalConnection=" + grp.mInternalConnection); 817 pw.println(" " + "mSpellChecker=" + grp.mSpellChecker); 818 pw.println(" " + "mBound=" + grp.mBound + " mConnected=" + grp.mConnected); 819 final int N = grp.mListeners.size(); 820 for (int i = 0; i < N; i++) { 821 final InternalDeathRecipient listener = grp.mListeners.get(i); 822 pw.println(" " + "Listener #" + i + ":"); 823 pw.println(" " + "mTsListener=" + listener.mTsListener); 824 pw.println(" " + "mScListener=" + listener.mScListener); 825 pw.println(" " + "mGroup=" + listener.mGroup); 826 pw.println(" " + "mScLocale=" + listener.mScLocale 827 + " mUid=" + listener.mUid); 828 } 829 } 830 pw.println(""); 831 pw.println(" mSettings:"); 832 mSettings.dumpLocked(pw, " "); 833 } 834 } 835 836 // SpellCheckerBindGroup contains active text service session listeners. 837 // If there are no listeners anymore, the SpellCheckerBindGroup instance will be removed from 838 // mSpellCheckerBindGroups 839 private class SpellCheckerBindGroup { 840 private final String TAG = SpellCheckerBindGroup.class.getSimpleName(); 841 private final InternalServiceConnection mInternalConnection; 842 private final CopyOnWriteArrayList<InternalDeathRecipient> mListeners = 843 new CopyOnWriteArrayList<>(); 844 public boolean mBound; 845 public ISpellCheckerService mSpellChecker; 846 public boolean mConnected; 847 848 public SpellCheckerBindGroup(InternalServiceConnection connection, 849 ITextServicesSessionListener listener, String locale, 850 ISpellCheckerSessionListener scListener, int uid, Bundle bundle) { 851 mInternalConnection = connection; 852 mBound = true; 853 mConnected = false; 854 addListener(listener, locale, scListener, uid, bundle); 855 } 856 857 public void onServiceConnected(ISpellCheckerService spellChecker) { 858 if (DBG) { 859 Slog.d(TAG, "onServiceConnected"); 860 } 861 862 for (InternalDeathRecipient listener : mListeners) { 863 try { 864 final ISpellCheckerSession session = spellChecker.getISpellCheckerSession( 865 listener.mScLocale, listener.mScListener, listener.mBundle); 866 synchronized(mSpellCheckerMap) { 867 if (mListeners.contains(listener)) { 868 listener.mTsListener.onServiceConnected(session); 869 } 870 } 871 } catch (RemoteException e) { 872 Slog.e(TAG, "Exception in getting the spell checker session." 873 + "Reconnect to the spellchecker. ", e); 874 removeAll(); 875 return; 876 } 877 } 878 synchronized(mSpellCheckerMap) { 879 mSpellChecker = spellChecker; 880 mConnected = true; 881 } 882 } 883 884 public InternalDeathRecipient addListener(ITextServicesSessionListener tsListener, 885 String locale, ISpellCheckerSessionListener scListener, int uid, Bundle bundle) { 886 if (DBG) { 887 Slog.d(TAG, "addListener: " + locale); 888 } 889 InternalDeathRecipient recipient = null; 890 synchronized(mSpellCheckerMap) { 891 try { 892 final int size = mListeners.size(); 893 for (int i = 0; i < size; ++i) { 894 if (mListeners.get(i).hasSpellCheckerListener(scListener)) { 895 // do not add the lister if the group already contains this. 896 return null; 897 } 898 } 899 recipient = new InternalDeathRecipient( 900 this, tsListener, locale, scListener, uid, bundle); 901 scListener.asBinder().linkToDeath(recipient, 0); 902 mListeners.add(recipient); 903 } catch(RemoteException e) { 904 // do nothing 905 } 906 cleanLocked(); 907 } 908 return recipient; 909 } 910 911 public void removeListener(ISpellCheckerSessionListener listener) { 912 if (DBG) { 913 Slog.w(TAG, "remove listener: " + listener.hashCode()); 914 } 915 synchronized(mSpellCheckerMap) { 916 final int size = mListeners.size(); 917 final ArrayList<InternalDeathRecipient> removeList = new ArrayList<>(); 918 for (int i = 0; i < size; ++i) { 919 final InternalDeathRecipient tempRecipient = mListeners.get(i); 920 if(tempRecipient.hasSpellCheckerListener(listener)) { 921 if (DBG) { 922 Slog.w(TAG, "found existing listener."); 923 } 924 removeList.add(tempRecipient); 925 } 926 } 927 final int removeSize = removeList.size(); 928 for (int i = 0; i < removeSize; ++i) { 929 if (DBG) { 930 Slog.w(TAG, "Remove " + removeList.get(i)); 931 } 932 final InternalDeathRecipient idr = removeList.get(i); 933 idr.mScListener.asBinder().unlinkToDeath(idr, 0); 934 mListeners.remove(idr); 935 } 936 cleanLocked(); 937 } 938 } 939 940 // cleanLocked may remove elements from mSpellCheckerBindGroups 941 private void cleanLocked() { 942 if (DBG) { 943 Slog.d(TAG, "cleanLocked"); 944 } 945 // If there are no more active listeners, clean up. Only do this 946 // once. 947 if (mBound && mListeners.isEmpty()) { 948 mBound = false; 949 final String sciId = mInternalConnection.mSciId; 950 SpellCheckerBindGroup cur = mSpellCheckerBindGroups.get(sciId); 951 if (cur == this) { 952 if (DBG) { 953 Slog.d(TAG, "Remove bind group."); 954 } 955 mSpellCheckerBindGroups.remove(sciId); 956 } 957 mContext.unbindService(mInternalConnection); 958 } 959 } 960 961 public void removeAll() { 962 Slog.e(TAG, "Remove the spell checker bind unexpectedly."); 963 synchronized(mSpellCheckerMap) { 964 final int size = mListeners.size(); 965 for (int i = 0; i < size; ++i) { 966 final InternalDeathRecipient idr = mListeners.get(i); 967 idr.mScListener.asBinder().unlinkToDeath(idr, 0); 968 } 969 mListeners.clear(); 970 cleanLocked(); 971 } 972 } 973 } 974 975 private class InternalServiceConnection implements ServiceConnection { 976 private final String mSciId; 977 private final String mLocale; 978 private final Bundle mBundle; 979 public InternalServiceConnection( 980 String id, String locale, Bundle bundle) { 981 mSciId = id; 982 mLocale = locale; 983 mBundle = bundle; 984 } 985 986 @Override 987 public void onServiceConnected(ComponentName name, IBinder service) { 988 synchronized(mSpellCheckerMap) { 989 onServiceConnectedInnerLocked(name, service); 990 } 991 } 992 993 private void onServiceConnectedInnerLocked(ComponentName name, IBinder service) { 994 if (DBG) { 995 Slog.w(TAG, "onServiceConnected: " + name); 996 } 997 final ISpellCheckerService spellChecker = 998 ISpellCheckerService.Stub.asInterface(service); 999 final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId); 1000 if (group != null && this == group.mInternalConnection) { 1001 group.onServiceConnected(spellChecker); 1002 } 1003 } 1004 1005 @Override 1006 public void onServiceDisconnected(ComponentName name) { 1007 synchronized(mSpellCheckerMap) { 1008 final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId); 1009 if (group != null && this == group.mInternalConnection) { 1010 mSpellCheckerBindGroups.remove(mSciId); 1011 } 1012 } 1013 } 1014 } 1015 1016 private class InternalDeathRecipient implements IBinder.DeathRecipient { 1017 public final ITextServicesSessionListener mTsListener; 1018 public final ISpellCheckerSessionListener mScListener; 1019 public final String mScLocale; 1020 private final SpellCheckerBindGroup mGroup; 1021 public final int mUid; 1022 public final Bundle mBundle; 1023 public InternalDeathRecipient(SpellCheckerBindGroup group, 1024 ITextServicesSessionListener tsListener, String scLocale, 1025 ISpellCheckerSessionListener scListener, int uid, Bundle bundle) { 1026 mTsListener = tsListener; 1027 mScListener = scListener; 1028 mScLocale = scLocale; 1029 mGroup = group; 1030 mUid = uid; 1031 mBundle = bundle; 1032 } 1033 1034 public boolean hasSpellCheckerListener(ISpellCheckerSessionListener listener) { 1035 return listener.asBinder().equals(mScListener.asBinder()); 1036 } 1037 1038 @Override 1039 public void binderDied() { 1040 mGroup.removeListener(mScListener); 1041 } 1042 } 1043 1044 private static class TextServicesSettings { 1045 private final ContentResolver mResolver; 1046 @UserIdInt 1047 private int mCurrentUserId; 1048 @GuardedBy("mLock") 1049 private int[] mCurrentProfileIds = new int[0]; 1050 private Object mLock = new Object(); 1051 1052 /** 1053 * On-memory data store to emulate when {@link #mCopyOnWrite} is {@code true}. 1054 */ 1055 private final HashMap<String, String> mCopyOnWriteDataStore = new HashMap<>(); 1056 private boolean mCopyOnWrite = false; 1057 1058 public TextServicesSettings(ContentResolver resolver, @UserIdInt int userId, 1059 boolean copyOnWrite) { 1060 mResolver = resolver; 1061 switchCurrentUser(userId, copyOnWrite); 1062 } 1063 1064 /** 1065 * Must be called when the current user is changed. 1066 * 1067 * @param userId The user ID. 1068 * @param copyOnWrite If {@code true}, for each settings key 1069 * (e.g. {@link Settings.Secure#SELECTED_SPELL_CHECKER}) we use the actual settings on the 1070 * {@link Settings.Secure} until we do the first write operation. 1071 */ 1072 public void switchCurrentUser(@UserIdInt int userId, boolean copyOnWrite) { 1073 if (DBG) { 1074 Slog.d(TAG, "--- Swtich the current user from " + mCurrentUserId + " to " 1075 + userId + ", new ime = " + getSelectedSpellChecker()); 1076 } 1077 if (mCurrentUserId != userId || mCopyOnWrite != copyOnWrite) { 1078 mCopyOnWriteDataStore.clear(); 1079 // TODO: mCurrentProfileIds should be cleared here. 1080 } 1081 // TSMS settings are kept per user, so keep track of current user 1082 mCurrentUserId = userId; 1083 mCopyOnWrite = copyOnWrite; 1084 // TODO: mCurrentProfileIds should be updated here. 1085 } 1086 1087 private void putString(final String key, final String str) { 1088 if (mCopyOnWrite) { 1089 mCopyOnWriteDataStore.put(key, str); 1090 } else { 1091 Settings.Secure.putStringForUser(mResolver, key, str, mCurrentUserId); 1092 } 1093 } 1094 1095 @Nullable 1096 private String getString(@NonNull final String key, @Nullable final String defaultValue) { 1097 final String result; 1098 if (mCopyOnWrite && mCopyOnWriteDataStore.containsKey(key)) { 1099 result = mCopyOnWriteDataStore.get(key); 1100 } else { 1101 result = Settings.Secure.getStringForUser(mResolver, key, mCurrentUserId); 1102 } 1103 return result != null ? result : defaultValue; 1104 } 1105 1106 private void putInt(final String key, final int value) { 1107 if (mCopyOnWrite) { 1108 mCopyOnWriteDataStore.put(key, String.valueOf(value)); 1109 } else { 1110 Settings.Secure.putIntForUser(mResolver, key, value, mCurrentUserId); 1111 } 1112 } 1113 1114 private int getInt(final String key, final int defaultValue) { 1115 if (mCopyOnWrite && mCopyOnWriteDataStore.containsKey(key)) { 1116 final String result = mCopyOnWriteDataStore.get(key); 1117 return result != null ? Integer.parseInt(result) : 0; 1118 } 1119 return Settings.Secure.getIntForUser(mResolver, key, defaultValue, mCurrentUserId); 1120 } 1121 1122 private void putBoolean(final String key, final boolean value) { 1123 putInt(key, value ? 1 : 0); 1124 } 1125 1126 private boolean getBoolean(final String key, final boolean defaultValue) { 1127 return getInt(key, defaultValue ? 1 : 0) == 1; 1128 } 1129 1130 public void setCurrentProfileIds(int[] currentProfileIds) { 1131 synchronized (mLock) { 1132 mCurrentProfileIds = currentProfileIds; 1133 } 1134 } 1135 1136 public boolean isCurrentProfile(@UserIdInt int userId) { 1137 synchronized (mLock) { 1138 if (userId == mCurrentUserId) return true; 1139 for (int i = 0; i < mCurrentProfileIds.length; i++) { 1140 if (userId == mCurrentProfileIds[i]) return true; 1141 } 1142 return false; 1143 } 1144 } 1145 1146 @UserIdInt 1147 public int getCurrentUserId() { 1148 return mCurrentUserId; 1149 } 1150 1151 public void putSelectedSpellChecker(@Nullable String sciId) { 1152 if (TextUtils.isEmpty(sciId)) { 1153 // OK to coalesce to null, since getSelectedSpellChecker() can take care of the 1154 // empty data scenario. 1155 putString(Settings.Secure.SELECTED_SPELL_CHECKER, null); 1156 } else { 1157 putString(Settings.Secure.SELECTED_SPELL_CHECKER, sciId); 1158 } 1159 } 1160 1161 public void putSelectedSpellCheckerSubtype(int hashCode) { 1162 putInt(Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE, hashCode); 1163 } 1164 1165 public void setSpellCheckerEnabled(boolean enabled) { 1166 putBoolean(Settings.Secure.SPELL_CHECKER_ENABLED, enabled); 1167 } 1168 1169 @NonNull 1170 public String getSelectedSpellChecker() { 1171 return getString(Settings.Secure.SELECTED_SPELL_CHECKER, ""); 1172 } 1173 1174 public int getSelectedSpellCheckerSubtype(final int defaultValue) { 1175 return getInt(Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE, defaultValue); 1176 } 1177 1178 public boolean isSpellCheckerEnabled() { 1179 return getBoolean(Settings.Secure.SPELL_CHECKER_ENABLED, true); 1180 } 1181 1182 public void dumpLocked(final PrintWriter pw, final String prefix) { 1183 pw.println(prefix + "mCurrentUserId=" + mCurrentUserId); 1184 pw.println(prefix + "mCurrentProfileIds=" + Arrays.toString(mCurrentProfileIds)); 1185 pw.println(prefix + "mCopyOnWrite=" + mCopyOnWrite); 1186 } 1187 } 1188 1189 // ---------------------------------------------------------------------- 1190 // Utilities for debug 1191 private static String getStackTrace() { 1192 final StringBuilder sb = new StringBuilder(); 1193 try { 1194 throw new RuntimeException(); 1195 } catch (RuntimeException e) { 1196 final StackTraceElement[] frames = e.getStackTrace(); 1197 // Start at 1 because the first frame is here and we don't care about it 1198 for (int j = 1; j < frames.length; ++j) { 1199 sb.append(frames[j].toString() + "\n"); 1200 } 1201 } 1202 return sb.toString(); 1203 } 1204 } 1205