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.content.PackageMonitor; 20 import com.android.internal.textservice.ISpellCheckerService; 21 import com.android.internal.textservice.ISpellCheckerSession; 22 import com.android.internal.textservice.ISpellCheckerSessionListener; 23 import com.android.internal.textservice.ITextServicesManager; 24 import com.android.internal.textservice.ITextServicesSessionListener; 25 26 import org.xmlpull.v1.XmlPullParserException; 27 28 import android.app.ActivityManagerNative; 29 import android.app.AppGlobals; 30 import android.app.IUserSwitchObserver; 31 import android.content.ComponentName; 32 import android.content.ContentResolver; 33 import android.content.Context; 34 import android.content.Intent; 35 import android.content.ServiceConnection; 36 import android.content.pm.IPackageManager; 37 import android.content.pm.PackageManager; 38 import android.content.pm.ResolveInfo; 39 import android.content.pm.ServiceInfo; 40 import android.os.Binder; 41 import android.os.Bundle; 42 import android.os.IBinder; 43 import android.os.IRemoteCallback; 44 import android.os.Process; 45 import android.os.RemoteException; 46 import android.os.UserHandle; 47 import android.provider.Settings; 48 import android.service.textservice.SpellCheckerService; 49 import android.text.TextUtils; 50 import android.util.Slog; 51 import android.view.inputmethod.InputMethodManager; 52 import android.view.inputmethod.InputMethodSubtype; 53 import android.view.textservice.SpellCheckerInfo; 54 import android.view.textservice.SpellCheckerSubtype; 55 56 import java.io.FileDescriptor; 57 import java.io.IOException; 58 import java.io.PrintWriter; 59 import java.util.ArrayList; 60 import java.util.HashMap; 61 import java.util.List; 62 import java.util.Map; 63 import java.util.concurrent.CopyOnWriteArrayList; 64 65 public class TextServicesManagerService extends ITextServicesManager.Stub { 66 private static final String TAG = TextServicesManagerService.class.getSimpleName(); 67 private static final boolean DBG = false; 68 69 private final Context mContext; 70 private boolean mSystemReady; 71 private final TextServicesMonitor mMonitor; 72 private final HashMap<String, SpellCheckerInfo> mSpellCheckerMap = 73 new HashMap<String, SpellCheckerInfo>(); 74 private final ArrayList<SpellCheckerInfo> mSpellCheckerList = new ArrayList<SpellCheckerInfo>(); 75 private final HashMap<String, SpellCheckerBindGroup> mSpellCheckerBindGroups = 76 new HashMap<String, SpellCheckerBindGroup>(); 77 private final TextServicesSettings mSettings; 78 79 public void systemReady() { 80 if (!mSystemReady) { 81 mSystemReady = true; 82 } 83 } 84 85 public TextServicesManagerService(Context context) { 86 mSystemReady = false; 87 mContext = context; 88 int userId = UserHandle.USER_OWNER; 89 try { 90 ActivityManagerNative.getDefault().registerUserSwitchObserver( 91 new IUserSwitchObserver.Stub() { 92 @Override 93 public void onUserSwitching(int newUserId, IRemoteCallback reply) { 94 synchronized(mSpellCheckerMap) { 95 switchUserLocked(newUserId); 96 } 97 if (reply != null) { 98 try { 99 reply.sendResult(null); 100 } catch (RemoteException e) { 101 } 102 } 103 } 104 105 @Override 106 public void onUserSwitchComplete(int newUserId) throws RemoteException { 107 } 108 }); 109 userId = ActivityManagerNative.getDefault().getCurrentUser().id; 110 } catch (RemoteException e) { 111 Slog.w(TAG, "Couldn't get current user ID; guessing it's 0", e); 112 } 113 mMonitor = new TextServicesMonitor(); 114 mMonitor.register(context, null, true); 115 mSettings = new TextServicesSettings(context.getContentResolver(), userId); 116 117 // "switchUserLocked" initializes the states for the foreground user 118 switchUserLocked(userId); 119 } 120 121 private void switchUserLocked(int userId) { 122 mSettings.setCurrentUserId(userId); 123 unbindServiceLocked(); 124 buildSpellCheckerMapLocked(mContext, mSpellCheckerList, mSpellCheckerMap, mSettings); 125 SpellCheckerInfo sci = getCurrentSpellChecker(null); 126 if (sci == null) { 127 sci = findAvailSpellCheckerLocked(null, null); 128 if (sci != null) { 129 // Set the current spell checker if there is one or more spell checkers 130 // available. In this case, "sci" is the first one in the available spell 131 // checkers. 132 setCurrentSpellCheckerLocked(sci.getId()); 133 } 134 } 135 } 136 137 private class TextServicesMonitor extends PackageMonitor { 138 private boolean isChangingPackagesOfCurrentUser() { 139 final int userId = getChangingUserId(); 140 final boolean retval = userId == mSettings.getCurrentUserId(); 141 if (DBG) { 142 Slog.d(TAG, "--- ignore this call back from a background user: " + userId); 143 } 144 return retval; 145 } 146 147 @Override 148 public void onSomePackagesChanged() { 149 if (!isChangingPackagesOfCurrentUser()) { 150 return; 151 } 152 synchronized (mSpellCheckerMap) { 153 buildSpellCheckerMapLocked( 154 mContext, mSpellCheckerList, mSpellCheckerMap, mSettings); 155 // TODO: Update for each locale 156 SpellCheckerInfo sci = getCurrentSpellChecker(null); 157 if (sci == null) return; 158 final String packageName = sci.getPackageName(); 159 final int change = isPackageDisappearing(packageName); 160 if (// Package disappearing 161 change == PACKAGE_PERMANENT_CHANGE || change == PACKAGE_TEMPORARY_CHANGE 162 // Package modified 163 || isPackageModified(packageName)) { 164 sci = findAvailSpellCheckerLocked(null, packageName); 165 if (sci != null) { 166 setCurrentSpellCheckerLocked(sci.getId()); 167 } 168 } 169 } 170 } 171 } 172 173 private static void buildSpellCheckerMapLocked(Context context, 174 ArrayList<SpellCheckerInfo> list, HashMap<String, SpellCheckerInfo> map, 175 TextServicesSettings settings) { 176 list.clear(); 177 map.clear(); 178 final PackageManager pm = context.getPackageManager(); 179 final List<ResolveInfo> services = pm.queryIntentServicesAsUser( 180 new Intent(SpellCheckerService.SERVICE_INTERFACE), PackageManager.GET_META_DATA, 181 settings.getCurrentUserId()); 182 final int N = services.size(); 183 for (int i = 0; i < N; ++i) { 184 final ResolveInfo ri = services.get(i); 185 final ServiceInfo si = ri.serviceInfo; 186 final ComponentName compName = new ComponentName(si.packageName, si.name); 187 if (!android.Manifest.permission.BIND_TEXT_SERVICE.equals(si.permission)) { 188 Slog.w(TAG, "Skipping text service " + compName 189 + ": it does not require the permission " 190 + android.Manifest.permission.BIND_TEXT_SERVICE); 191 continue; 192 } 193 if (DBG) Slog.d(TAG, "Add: " + compName); 194 try { 195 final SpellCheckerInfo sci = new SpellCheckerInfo(context, ri); 196 if (sci.getSubtypeCount() <= 0) { 197 Slog.w(TAG, "Skipping text service " + compName 198 + ": it does not contain subtypes."); 199 continue; 200 } 201 list.add(sci); 202 map.put(sci.getId(), sci); 203 } catch (XmlPullParserException e) { 204 Slog.w(TAG, "Unable to load the spell checker " + compName, e); 205 } catch (IOException e) { 206 Slog.w(TAG, "Unable to load the spell checker " + compName, e); 207 } 208 } 209 if (DBG) { 210 Slog.d(TAG, "buildSpellCheckerMapLocked: " + list.size() + "," + map.size()); 211 } 212 } 213 214 // --------------------------------------------------------------------------------------- 215 // Check whether or not this is a valid IPC. Assumes an IPC is valid when either 216 // 1) it comes from the system process 217 // 2) the calling process' user id is identical to the current user id TSMS thinks. 218 private boolean calledFromValidUser() { 219 final int uid = Binder.getCallingUid(); 220 final int userId = UserHandle.getUserId(uid); 221 if (DBG) { 222 Slog.d(TAG, "--- calledFromForegroundUserOrSystemProcess ? " 223 + "calling uid = " + uid + " system uid = " + Process.SYSTEM_UID 224 + " calling userId = " + userId + ", foreground user id = " 225 + mSettings.getCurrentUserId()); 226 try { 227 final String[] packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid); 228 for (int i = 0; i < packageNames.length; ++i) { 229 if (DBG) { 230 Slog.d(TAG, "--- process name for "+ uid + " = " + packageNames[i]); 231 } 232 } 233 } catch (RemoteException e) { 234 } 235 } 236 237 if (uid == Process.SYSTEM_UID || userId == mSettings.getCurrentUserId()) { 238 return true; 239 } else { 240 Slog.w(TAG, "--- IPC called from background users. Ignore. \n" + getStackTrace()); 241 return false; 242 } 243 } 244 245 private boolean bindCurrentSpellCheckerService( 246 Intent service, ServiceConnection conn, int flags) { 247 if (service == null || conn == null) { 248 Slog.e(TAG, "--- bind failed: service = " + service + ", conn = " + conn); 249 return false; 250 } 251 return mContext.bindServiceAsUser(service, conn, flags, 252 new UserHandle(mSettings.getCurrentUserId())); 253 } 254 255 private void unbindServiceLocked() { 256 for (SpellCheckerBindGroup scbg : mSpellCheckerBindGroups.values()) { 257 scbg.removeAll(); 258 } 259 mSpellCheckerBindGroups.clear(); 260 } 261 262 // TODO: find an appropriate spell checker for specified locale 263 private SpellCheckerInfo findAvailSpellCheckerLocked(String locale, String prefPackage) { 264 final int spellCheckersCount = mSpellCheckerList.size(); 265 if (spellCheckersCount == 0) { 266 Slog.w(TAG, "no available spell checker services found"); 267 return null; 268 } 269 if (prefPackage != null) { 270 for (int i = 0; i < spellCheckersCount; ++i) { 271 final SpellCheckerInfo sci = mSpellCheckerList.get(i); 272 if (prefPackage.equals(sci.getPackageName())) { 273 if (DBG) { 274 Slog.d(TAG, "findAvailSpellCheckerLocked: " + sci.getPackageName()); 275 } 276 return sci; 277 } 278 } 279 } 280 if (spellCheckersCount > 1) { 281 Slog.w(TAG, "more than one spell checker service found, picking first"); 282 } 283 return mSpellCheckerList.get(0); 284 } 285 286 // TODO: Save SpellCheckerService by supported languages. Currently only one spell 287 // checker is saved. 288 @Override 289 public SpellCheckerInfo getCurrentSpellChecker(String locale) { 290 // TODO: Make this work even for non-current users? 291 if (!calledFromValidUser()) { 292 return null; 293 } 294 synchronized (mSpellCheckerMap) { 295 final String curSpellCheckerId = mSettings.getSelectedSpellChecker(); 296 if (DBG) { 297 Slog.w(TAG, "getCurrentSpellChecker: " + curSpellCheckerId); 298 } 299 if (TextUtils.isEmpty(curSpellCheckerId)) { 300 return null; 301 } 302 return mSpellCheckerMap.get(curSpellCheckerId); 303 } 304 } 305 306 // TODO: Respect allowImplicitlySelectedSubtype 307 // TODO: Save SpellCheckerSubtype by supported languages by looking at "locale". 308 @Override 309 public SpellCheckerSubtype getCurrentSpellCheckerSubtype( 310 String locale, boolean allowImplicitlySelectedSubtype) { 311 // TODO: Make this work even for non-current users? 312 if (!calledFromValidUser()) { 313 return null; 314 } 315 synchronized (mSpellCheckerMap) { 316 final String subtypeHashCodeStr = mSettings.getSelectedSpellCheckerSubtype(); 317 if (DBG) { 318 Slog.w(TAG, "getCurrentSpellCheckerSubtype: " + subtypeHashCodeStr); 319 } 320 final SpellCheckerInfo sci = getCurrentSpellChecker(null); 321 if (sci == null || sci.getSubtypeCount() == 0) { 322 if (DBG) { 323 Slog.w(TAG, "Subtype not found."); 324 } 325 return null; 326 } 327 final int hashCode; 328 if (!TextUtils.isEmpty(subtypeHashCodeStr)) { 329 hashCode = Integer.valueOf(subtypeHashCodeStr); 330 } else { 331 hashCode = 0; 332 } 333 if (hashCode == 0 && !allowImplicitlySelectedSubtype) { 334 return null; 335 } 336 String candidateLocale = null; 337 if (hashCode == 0) { 338 // Spell checker language settings == "auto" 339 final InputMethodManager imm = 340 (InputMethodManager)mContext.getSystemService(Context.INPUT_METHOD_SERVICE); 341 if (imm != null) { 342 final InputMethodSubtype currentInputMethodSubtype = 343 imm.getCurrentInputMethodSubtype(); 344 if (currentInputMethodSubtype != null) { 345 final String localeString = currentInputMethodSubtype.getLocale(); 346 if (!TextUtils.isEmpty(localeString)) { 347 // 1. Use keyboard locale if available in the spell checker 348 candidateLocale = localeString; 349 } 350 } 351 } 352 if (candidateLocale == null) { 353 // 2. Use System locale if available in the spell checker 354 candidateLocale = mContext.getResources().getConfiguration().locale.toString(); 355 } 356 } 357 SpellCheckerSubtype candidate = null; 358 for (int i = 0; i < sci.getSubtypeCount(); ++i) { 359 final SpellCheckerSubtype scs = sci.getSubtypeAt(i); 360 if (hashCode == 0) { 361 final String scsLocale = scs.getLocale(); 362 if (candidateLocale.equals(scsLocale)) { 363 return scs; 364 } else if (candidate == null) { 365 if (candidateLocale.length() >= 2 && scsLocale.length() >= 2 366 && candidateLocale.startsWith(scsLocale)) { 367 // Fall back to the applicable language 368 candidate = scs; 369 } 370 } 371 } else if (scs.hashCode() == hashCode) { 372 if (DBG) { 373 Slog.w(TAG, "Return subtype " + scs.hashCode() + ", input= " + locale 374 + ", " + scs.getLocale()); 375 } 376 // 3. Use the user specified spell check language 377 return scs; 378 } 379 } 380 // 4. Fall back to the applicable language and return it if not null 381 // 5. Simply just return it even if it's null which means we could find no suitable 382 // spell check languages 383 return candidate; 384 } 385 } 386 387 @Override 388 public void getSpellCheckerService(String sciId, String locale, 389 ITextServicesSessionListener tsListener, ISpellCheckerSessionListener scListener, 390 Bundle bundle) { 391 if (!calledFromValidUser()) { 392 return; 393 } 394 if (!mSystemReady) { 395 return; 396 } 397 if (TextUtils.isEmpty(sciId) || tsListener == null || scListener == null) { 398 Slog.e(TAG, "getSpellCheckerService: Invalid input."); 399 return; 400 } 401 synchronized(mSpellCheckerMap) { 402 if (!mSpellCheckerMap.containsKey(sciId)) { 403 return; 404 } 405 final SpellCheckerInfo sci = mSpellCheckerMap.get(sciId); 406 final int uid = Binder.getCallingUid(); 407 if (mSpellCheckerBindGroups.containsKey(sciId)) { 408 final SpellCheckerBindGroup bindGroup = mSpellCheckerBindGroups.get(sciId); 409 if (bindGroup != null) { 410 final InternalDeathRecipient recipient = 411 mSpellCheckerBindGroups.get(sciId).addListener( 412 tsListener, locale, scListener, uid, bundle); 413 if (recipient == null) { 414 if (DBG) { 415 Slog.w(TAG, "Didn't create a death recipient."); 416 } 417 return; 418 } 419 if (bindGroup.mSpellChecker == null & bindGroup.mConnected) { 420 Slog.e(TAG, "The state of the spell checker bind group is illegal."); 421 bindGroup.removeAll(); 422 } else if (bindGroup.mSpellChecker != null) { 423 if (DBG) { 424 Slog.w(TAG, "Existing bind found. Return a spell checker session now. " 425 + "Listeners count = " + bindGroup.mListeners.size()); 426 } 427 try { 428 final ISpellCheckerSession session = 429 bindGroup.mSpellChecker.getISpellCheckerSession( 430 recipient.mScLocale, recipient.mScListener, bundle); 431 if (session != null) { 432 tsListener.onServiceConnected(session); 433 return; 434 } else { 435 if (DBG) { 436 Slog.w(TAG, "Existing bind already expired. "); 437 } 438 bindGroup.removeAll(); 439 } 440 } catch (RemoteException e) { 441 Slog.e(TAG, "Exception in getting spell checker session: " + e); 442 bindGroup.removeAll(); 443 } 444 } 445 } 446 } 447 final long ident = Binder.clearCallingIdentity(); 448 try { 449 startSpellCheckerServiceInnerLocked( 450 sci, locale, tsListener, scListener, uid, bundle); 451 } finally { 452 Binder.restoreCallingIdentity(ident); 453 } 454 } 455 return; 456 } 457 458 @Override 459 public boolean isSpellCheckerEnabled() { 460 if (!calledFromValidUser()) { 461 return false; 462 } 463 synchronized(mSpellCheckerMap) { 464 return isSpellCheckerEnabledLocked(); 465 } 466 } 467 468 private void startSpellCheckerServiceInnerLocked(SpellCheckerInfo info, String locale, 469 ITextServicesSessionListener tsListener, ISpellCheckerSessionListener scListener, 470 int uid, Bundle bundle) { 471 if (DBG) { 472 Slog.w(TAG, "Start spell checker session inner locked."); 473 } 474 final String sciId = info.getId(); 475 final InternalServiceConnection connection = new InternalServiceConnection( 476 sciId, locale, bundle); 477 final Intent serviceIntent = new Intent(SpellCheckerService.SERVICE_INTERFACE); 478 serviceIntent.setComponent(info.getComponent()); 479 if (DBG) { 480 Slog.w(TAG, "bind service: " + info.getId()); 481 } 482 if (!bindCurrentSpellCheckerService(serviceIntent, connection, Context.BIND_AUTO_CREATE)) { 483 Slog.e(TAG, "Failed to get a spell checker service."); 484 return; 485 } 486 final SpellCheckerBindGroup group = new SpellCheckerBindGroup( 487 connection, tsListener, locale, scListener, uid, bundle); 488 mSpellCheckerBindGroups.put(sciId, group); 489 } 490 491 @Override 492 public SpellCheckerInfo[] getEnabledSpellCheckers() { 493 // TODO: Make this work even for non-current users? 494 if (!calledFromValidUser()) { 495 return null; 496 } 497 if (DBG) { 498 Slog.d(TAG, "getEnabledSpellCheckers: " + mSpellCheckerList.size()); 499 for (int i = 0; i < mSpellCheckerList.size(); ++i) { 500 Slog.d(TAG, "EnabledSpellCheckers: " + mSpellCheckerList.get(i).getPackageName()); 501 } 502 } 503 return mSpellCheckerList.toArray(new SpellCheckerInfo[mSpellCheckerList.size()]); 504 } 505 506 @Override 507 public void finishSpellCheckerService(ISpellCheckerSessionListener listener) { 508 if (!calledFromValidUser()) { 509 return; 510 } 511 if (DBG) { 512 Slog.d(TAG, "FinishSpellCheckerService"); 513 } 514 synchronized(mSpellCheckerMap) { 515 final ArrayList<SpellCheckerBindGroup> removeList = 516 new ArrayList<SpellCheckerBindGroup>(); 517 for (SpellCheckerBindGroup group : mSpellCheckerBindGroups.values()) { 518 if (group == null) continue; 519 // Use removeList to avoid modifying mSpellCheckerBindGroups in this loop. 520 removeList.add(group); 521 } 522 final int removeSize = removeList.size(); 523 for (int i = 0; i < removeSize; ++i) { 524 removeList.get(i).removeListener(listener); 525 } 526 } 527 } 528 529 @Override 530 public void setCurrentSpellChecker(String locale, String sciId) { 531 if (!calledFromValidUser()) { 532 return; 533 } 534 synchronized(mSpellCheckerMap) { 535 if (mContext.checkCallingOrSelfPermission( 536 android.Manifest.permission.WRITE_SECURE_SETTINGS) 537 != PackageManager.PERMISSION_GRANTED) { 538 throw new SecurityException( 539 "Requires permission " 540 + android.Manifest.permission.WRITE_SECURE_SETTINGS); 541 } 542 setCurrentSpellCheckerLocked(sciId); 543 } 544 } 545 546 @Override 547 public void setCurrentSpellCheckerSubtype(String locale, int hashCode) { 548 if (!calledFromValidUser()) { 549 return; 550 } 551 synchronized(mSpellCheckerMap) { 552 if (mContext.checkCallingOrSelfPermission( 553 android.Manifest.permission.WRITE_SECURE_SETTINGS) 554 != PackageManager.PERMISSION_GRANTED) { 555 throw new SecurityException( 556 "Requires permission " 557 + android.Manifest.permission.WRITE_SECURE_SETTINGS); 558 } 559 setCurrentSpellCheckerSubtypeLocked(hashCode); 560 } 561 } 562 563 @Override 564 public void setSpellCheckerEnabled(boolean enabled) { 565 if (!calledFromValidUser()) { 566 return; 567 } 568 synchronized(mSpellCheckerMap) { 569 if (mContext.checkCallingOrSelfPermission( 570 android.Manifest.permission.WRITE_SECURE_SETTINGS) 571 != PackageManager.PERMISSION_GRANTED) { 572 throw new SecurityException( 573 "Requires permission " 574 + android.Manifest.permission.WRITE_SECURE_SETTINGS); 575 } 576 setSpellCheckerEnabledLocked(enabled); 577 } 578 } 579 580 private void setCurrentSpellCheckerLocked(String sciId) { 581 if (DBG) { 582 Slog.w(TAG, "setCurrentSpellChecker: " + sciId); 583 } 584 if (TextUtils.isEmpty(sciId) || !mSpellCheckerMap.containsKey(sciId)) return; 585 final SpellCheckerInfo currentSci = getCurrentSpellChecker(null); 586 if (currentSci != null && currentSci.getId().equals(sciId)) { 587 // Do nothing if the current spell checker is same as new spell checker. 588 return; 589 } 590 final long ident = Binder.clearCallingIdentity(); 591 try { 592 mSettings.putSelectedSpellChecker(sciId); 593 setCurrentSpellCheckerSubtypeLocked(0); 594 } finally { 595 Binder.restoreCallingIdentity(ident); 596 } 597 } 598 599 private void setCurrentSpellCheckerSubtypeLocked(int hashCode) { 600 if (DBG) { 601 Slog.w(TAG, "setCurrentSpellCheckerSubtype: " + hashCode); 602 } 603 final SpellCheckerInfo sci = getCurrentSpellChecker(null); 604 int tempHashCode = 0; 605 for (int i = 0; sci != null && i < sci.getSubtypeCount(); ++i) { 606 if(sci.getSubtypeAt(i).hashCode() == hashCode) { 607 tempHashCode = hashCode; 608 break; 609 } 610 } 611 final long ident = Binder.clearCallingIdentity(); 612 try { 613 mSettings.putSelectedSpellCheckerSubtype(tempHashCode); 614 } finally { 615 Binder.restoreCallingIdentity(ident); 616 } 617 } 618 619 private void setSpellCheckerEnabledLocked(boolean enabled) { 620 if (DBG) { 621 Slog.w(TAG, "setSpellCheckerEnabled: " + enabled); 622 } 623 final long ident = Binder.clearCallingIdentity(); 624 try { 625 mSettings.setSpellCheckerEnabled(enabled); 626 } finally { 627 Binder.restoreCallingIdentity(ident); 628 } 629 } 630 631 private boolean isSpellCheckerEnabledLocked() { 632 final long ident = Binder.clearCallingIdentity(); 633 try { 634 final boolean retval = mSettings.isSpellCheckerEnabled(); 635 if (DBG) { 636 Slog.w(TAG, "getSpellCheckerEnabled: " + retval); 637 } 638 return retval; 639 } finally { 640 Binder.restoreCallingIdentity(ident); 641 } 642 } 643 644 @Override 645 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 646 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 647 != PackageManager.PERMISSION_GRANTED) { 648 649 pw.println("Permission Denial: can't dump TextServicesManagerService from from pid=" 650 + Binder.getCallingPid() 651 + ", uid=" + Binder.getCallingUid()); 652 return; 653 } 654 655 synchronized(mSpellCheckerMap) { 656 pw.println("Current Text Services Manager state:"); 657 pw.println(" Spell Checker Map:"); 658 for (Map.Entry<String, SpellCheckerInfo> ent : mSpellCheckerMap.entrySet()) { 659 pw.print(" "); pw.print(ent.getKey()); pw.println(":"); 660 SpellCheckerInfo info = ent.getValue(); 661 pw.print(" "); pw.print("id="); pw.println(info.getId()); 662 pw.print(" "); pw.print("comp="); 663 pw.println(info.getComponent().toShortString()); 664 int NS = info.getSubtypeCount(); 665 for (int i=0; i<NS; i++) { 666 SpellCheckerSubtype st = info.getSubtypeAt(i); 667 pw.print(" "); pw.print("Subtype #"); pw.print(i); pw.println(":"); 668 pw.print(" "); pw.print("locale="); pw.println(st.getLocale()); 669 pw.print(" "); pw.print("extraValue="); 670 pw.println(st.getExtraValue()); 671 } 672 } 673 pw.println(""); 674 pw.println(" Spell Checker Bind Groups:"); 675 for (Map.Entry<String, SpellCheckerBindGroup> ent 676 : mSpellCheckerBindGroups.entrySet()) { 677 SpellCheckerBindGroup grp = ent.getValue(); 678 pw.print(" "); pw.print(ent.getKey()); pw.print(" "); 679 pw.print(grp); pw.println(":"); 680 pw.print(" "); pw.print("mInternalConnection="); 681 pw.println(grp.mInternalConnection); 682 pw.print(" "); pw.print("mSpellChecker="); 683 pw.println(grp.mSpellChecker); 684 pw.print(" "); pw.print("mBound="); pw.print(grp.mBound); 685 pw.print(" mConnected="); pw.println(grp.mConnected); 686 int NL = grp.mListeners.size(); 687 for (int i=0; i<NL; i++) { 688 InternalDeathRecipient listener = grp.mListeners.get(i); 689 pw.print(" "); pw.print("Listener #"); pw.print(i); pw.println(":"); 690 pw.print(" "); pw.print("mTsListener="); 691 pw.println(listener.mTsListener); 692 pw.print(" "); pw.print("mScListener="); 693 pw.println(listener.mScListener); 694 pw.print(" "); pw.print("mGroup="); 695 pw.println(listener.mGroup); 696 pw.print(" "); pw.print("mScLocale="); 697 pw.print(listener.mScLocale); 698 pw.print(" mUid="); pw.println(listener.mUid); 699 } 700 } 701 } 702 } 703 704 // SpellCheckerBindGroup contains active text service session listeners. 705 // If there are no listeners anymore, the SpellCheckerBindGroup instance will be removed from 706 // mSpellCheckerBindGroups 707 private class SpellCheckerBindGroup { 708 private final String TAG = SpellCheckerBindGroup.class.getSimpleName(); 709 private final InternalServiceConnection mInternalConnection; 710 private final CopyOnWriteArrayList<InternalDeathRecipient> mListeners = 711 new CopyOnWriteArrayList<InternalDeathRecipient>(); 712 public boolean mBound; 713 public ISpellCheckerService mSpellChecker; 714 public boolean mConnected; 715 716 public SpellCheckerBindGroup(InternalServiceConnection connection, 717 ITextServicesSessionListener listener, String locale, 718 ISpellCheckerSessionListener scListener, int uid, Bundle bundle) { 719 mInternalConnection = connection; 720 mBound = true; 721 mConnected = false; 722 addListener(listener, locale, scListener, uid, bundle); 723 } 724 725 public void onServiceConnected(ISpellCheckerService spellChecker) { 726 if (DBG) { 727 Slog.d(TAG, "onServiceConnected"); 728 } 729 730 for (InternalDeathRecipient listener : mListeners) { 731 try { 732 final ISpellCheckerSession session = spellChecker.getISpellCheckerSession( 733 listener.mScLocale, listener.mScListener, listener.mBundle); 734 synchronized(mSpellCheckerMap) { 735 if (mListeners.contains(listener)) { 736 listener.mTsListener.onServiceConnected(session); 737 } 738 } 739 } catch (RemoteException e) { 740 Slog.e(TAG, "Exception in getting the spell checker session." 741 + "Reconnect to the spellchecker. ", e); 742 removeAll(); 743 return; 744 } 745 } 746 synchronized(mSpellCheckerMap) { 747 mSpellChecker = spellChecker; 748 mConnected = true; 749 } 750 } 751 752 public InternalDeathRecipient addListener(ITextServicesSessionListener tsListener, 753 String locale, ISpellCheckerSessionListener scListener, int uid, Bundle bundle) { 754 if (DBG) { 755 Slog.d(TAG, "addListener: " + locale); 756 } 757 InternalDeathRecipient recipient = null; 758 synchronized(mSpellCheckerMap) { 759 try { 760 final int size = mListeners.size(); 761 for (int i = 0; i < size; ++i) { 762 if (mListeners.get(i).hasSpellCheckerListener(scListener)) { 763 // do not add the lister if the group already contains this. 764 return null; 765 } 766 } 767 recipient = new InternalDeathRecipient( 768 this, tsListener, locale, scListener, uid, bundle); 769 scListener.asBinder().linkToDeath(recipient, 0); 770 mListeners.add(recipient); 771 } catch(RemoteException e) { 772 // do nothing 773 } 774 cleanLocked(); 775 } 776 return recipient; 777 } 778 779 public void removeListener(ISpellCheckerSessionListener listener) { 780 if (DBG) { 781 Slog.w(TAG, "remove listener: " + listener.hashCode()); 782 } 783 synchronized(mSpellCheckerMap) { 784 final int size = mListeners.size(); 785 final ArrayList<InternalDeathRecipient> removeList = 786 new ArrayList<InternalDeathRecipient>(); 787 for (int i = 0; i < size; ++i) { 788 final InternalDeathRecipient tempRecipient = mListeners.get(i); 789 if(tempRecipient.hasSpellCheckerListener(listener)) { 790 if (DBG) { 791 Slog.w(TAG, "found existing listener."); 792 } 793 removeList.add(tempRecipient); 794 } 795 } 796 final int removeSize = removeList.size(); 797 for (int i = 0; i < removeSize; ++i) { 798 if (DBG) { 799 Slog.w(TAG, "Remove " + removeList.get(i)); 800 } 801 final InternalDeathRecipient idr = removeList.get(i); 802 idr.mScListener.asBinder().unlinkToDeath(idr, 0); 803 mListeners.remove(idr); 804 } 805 cleanLocked(); 806 } 807 } 808 809 // cleanLocked may remove elements from mSpellCheckerBindGroups 810 private void cleanLocked() { 811 if (DBG) { 812 Slog.d(TAG, "cleanLocked"); 813 } 814 // If there are no more active listeners, clean up. Only do this 815 // once. 816 if (mBound && mListeners.isEmpty()) { 817 mBound = false; 818 final String sciId = mInternalConnection.mSciId; 819 SpellCheckerBindGroup cur = mSpellCheckerBindGroups.get(sciId); 820 if (cur == this) { 821 if (DBG) { 822 Slog.d(TAG, "Remove bind group."); 823 } 824 mSpellCheckerBindGroups.remove(sciId); 825 } 826 mContext.unbindService(mInternalConnection); 827 } 828 } 829 830 public void removeAll() { 831 Slog.e(TAG, "Remove the spell checker bind unexpectedly."); 832 synchronized(mSpellCheckerMap) { 833 final int size = mListeners.size(); 834 for (int i = 0; i < size; ++i) { 835 final InternalDeathRecipient idr = mListeners.get(i); 836 idr.mScListener.asBinder().unlinkToDeath(idr, 0); 837 } 838 mListeners.clear(); 839 cleanLocked(); 840 } 841 } 842 } 843 844 private class InternalServiceConnection implements ServiceConnection { 845 private final String mSciId; 846 private final String mLocale; 847 private final Bundle mBundle; 848 public InternalServiceConnection( 849 String id, String locale, Bundle bundle) { 850 mSciId = id; 851 mLocale = locale; 852 mBundle = bundle; 853 } 854 855 @Override 856 public void onServiceConnected(ComponentName name, IBinder service) { 857 synchronized(mSpellCheckerMap) { 858 onServiceConnectedInnerLocked(name, service); 859 } 860 } 861 862 private void onServiceConnectedInnerLocked(ComponentName name, IBinder service) { 863 if (DBG) { 864 Slog.w(TAG, "onServiceConnected: " + name); 865 } 866 final ISpellCheckerService spellChecker = 867 ISpellCheckerService.Stub.asInterface(service); 868 final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId); 869 if (group != null && this == group.mInternalConnection) { 870 group.onServiceConnected(spellChecker); 871 } 872 } 873 874 @Override 875 public void onServiceDisconnected(ComponentName name) { 876 synchronized(mSpellCheckerMap) { 877 final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId); 878 if (group != null && this == group.mInternalConnection) { 879 mSpellCheckerBindGroups.remove(mSciId); 880 } 881 } 882 } 883 } 884 885 private class InternalDeathRecipient implements IBinder.DeathRecipient { 886 public final ITextServicesSessionListener mTsListener; 887 public final ISpellCheckerSessionListener mScListener; 888 public final String mScLocale; 889 private final SpellCheckerBindGroup mGroup; 890 public final int mUid; 891 public final Bundle mBundle; 892 public InternalDeathRecipient(SpellCheckerBindGroup group, 893 ITextServicesSessionListener tsListener, String scLocale, 894 ISpellCheckerSessionListener scListener, int uid, Bundle bundle) { 895 mTsListener = tsListener; 896 mScListener = scListener; 897 mScLocale = scLocale; 898 mGroup = group; 899 mUid = uid; 900 mBundle = bundle; 901 } 902 903 public boolean hasSpellCheckerListener(ISpellCheckerSessionListener listener) { 904 return listener.asBinder().equals(mScListener.asBinder()); 905 } 906 907 @Override 908 public void binderDied() { 909 mGroup.removeListener(mScListener); 910 } 911 } 912 913 private static class TextServicesSettings { 914 private final ContentResolver mResolver; 915 private int mCurrentUserId; 916 public TextServicesSettings(ContentResolver resolver, int userId) { 917 mResolver = resolver; 918 mCurrentUserId = userId; 919 } 920 921 public void setCurrentUserId(int userId) { 922 if (DBG) { 923 Slog.d(TAG, "--- Swtich the current user from " + mCurrentUserId + " to " 924 + userId + ", new ime = " + getSelectedSpellChecker()); 925 } 926 // TSMS settings are kept per user, so keep track of current user 927 mCurrentUserId = userId; 928 } 929 930 public int getCurrentUserId() { 931 return mCurrentUserId; 932 } 933 934 public void putSelectedSpellChecker(String sciId) { 935 Settings.Secure.putStringForUser(mResolver, 936 Settings.Secure.SELECTED_SPELL_CHECKER, sciId, mCurrentUserId); 937 } 938 939 public void putSelectedSpellCheckerSubtype(int hashCode) { 940 Settings.Secure.putStringForUser(mResolver, 941 Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE, String.valueOf(hashCode), 942 mCurrentUserId); 943 } 944 945 public void setSpellCheckerEnabled(boolean enabled) { 946 Settings.Secure.putIntForUser(mResolver, 947 Settings.Secure.SPELL_CHECKER_ENABLED, enabled ? 1 : 0, mCurrentUserId); 948 } 949 950 public String getSelectedSpellChecker() { 951 return Settings.Secure.getStringForUser(mResolver, 952 Settings.Secure.SELECTED_SPELL_CHECKER, mCurrentUserId); 953 } 954 955 public String getSelectedSpellCheckerSubtype() { 956 return Settings.Secure.getStringForUser(mResolver, 957 Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE, mCurrentUserId); 958 } 959 960 public boolean isSpellCheckerEnabled() { 961 return Settings.Secure.getIntForUser(mResolver, 962 Settings.Secure.SPELL_CHECKER_ENABLED, 1, mCurrentUserId) == 1; 963 } 964 } 965 966 // ---------------------------------------------------------------------- 967 // Utilities for debug 968 private static String getStackTrace() { 969 final StringBuilder sb = new StringBuilder(); 970 try { 971 throw new RuntimeException(); 972 } catch (RuntimeException e) { 973 final StackTraceElement[] frames = e.getStackTrace(); 974 // Start at 1 because the first frame is here and we don't care about it 975 for (int j = 1; j < frames.length; ++j) { 976 sb.append(frames[j].toString() + "\n"); 977 } 978 } 979 return sb.toString(); 980 } 981 } 982