2 * Copyright (C) 2011 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.server;
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;
28 import org.xmlpull.v1.XmlPullParserException;
30 import android.app.ActivityManagerNative;
31 import android.app.AppGlobals;
32 import android.app.SynchronousUserSwitchObserver;
33 import android.content.BroadcastReceiver;
34 import android.content.ComponentName;
35 import android.content.ContentResolver;
36 import android.content.Context;
37 import android.content.Intent;
38 import android.content.IntentFilter;
39 import android.content.ServiceConnection;
40 import android.content.pm.ApplicationInfo;
41 import android.content.pm.PackageManager;
42 import android.content.pm.ResolveInfo;
43 import android.content.pm.ServiceInfo;
44 import android.content.pm.UserInfo;
45 import android.os.Binder;
46 import android.os.Bundle;
47 import android.os.IBinder;
48 import android.os.Process;
49 import android.os.RemoteException;
50 import android.os.UserHandle;
51 import android.os.UserManager;
52 import android.provider.Settings;
53 import android.service.textservice.SpellCheckerService;
54 import android.text.TextUtils;
55 import android.util.Slog;
56 import android.view.inputmethod.InputMethodManager;
57 import android.view.inputmethod.InputMethodSubtype;
58 import android.view.textservice.SpellCheckerInfo;
59 import android.view.textservice.SpellCheckerSubtype;
61 import java.io.FileDescriptor;
62 import java.io.IOException;
63 import java.io.PrintWriter;
64 import java.util.Arrays;
65 import java.util.ArrayList;
66 import java.util.HashMap;
67 import java.util.List;
68 import java.util.Locale;
70 import java.util.concurrent.CopyOnWriteArrayList;
72 public class TextServicesManagerService extends ITextServicesManager.Stub {
73 private static final String TAG = TextServicesManagerService.class.getSimpleName();
74 private static final boolean DBG = false;
76 private final Context mContext;
77 private boolean mSystemReady;
78 private final TextServicesMonitor mMonitor;
79 private final HashMap<String, SpellCheckerInfo> mSpellCheckerMap = new HashMap<>();
80 private final ArrayList<SpellCheckerInfo> mSpellCheckerList = new ArrayList<>();
81 private final HashMap<String, SpellCheckerBindGroup> mSpellCheckerBindGroups = new HashMap<>();
82 private final TextServicesSettings mSettings;
84 public void systemRunning() {
90 public TextServicesManagerService(Context context) {
94 final IntentFilter broadcastFilter = new IntentFilter();
95 broadcastFilter.addAction(Intent.ACTION_USER_ADDED);
96 broadcastFilter.addAction(Intent.ACTION_USER_REMOVED);
97 mContext.registerReceiver(new TextServicesBroadcastReceiver(), broadcastFilter);
99 int userId = UserHandle.USER_SYSTEM;
101 ActivityManagerNative.getDefault().registerUserSwitchObserver(
102 new SynchronousUserSwitchObserver() {
104 public void onUserSwitching(int newUserId) throws RemoteException {
105 synchronized(mSpellCheckerMap) {
106 switchUserLocked(newUserId);
111 public void onUserSwitchComplete(int newUserId) throws RemoteException {
115 public void onForegroundProfileSwitch(int newProfileId) {
119 userId = ActivityManagerNative.getDefault().getCurrentUser().id;
120 } catch (RemoteException e) {
121 Slog.w(TAG, "Couldn't get current user ID; guessing it's 0", e);
123 mMonitor = new TextServicesMonitor();
124 mMonitor.register(context, null, true);
125 mSettings = new TextServicesSettings(context.getContentResolver(), userId);
127 // "switchUserLocked" initializes the states for the foreground user
128 switchUserLocked(userId);
131 private void switchUserLocked(int userId) {
132 mSettings.setCurrentUserId(userId);
133 updateCurrentProfileIds();
134 unbindServiceLocked();
135 buildSpellCheckerMapLocked(mContext, mSpellCheckerList, mSpellCheckerMap, mSettings);
136 SpellCheckerInfo sci = getCurrentSpellChecker(null);
138 sci = findAvailSpellCheckerLocked(null);
140 // Set the current spell checker if there is one or more spell checkers
141 // available. In this case, "sci" is the first one in the available spell
143 setCurrentSpellCheckerLocked(sci.getId());
148 void updateCurrentProfileIds() {
149 List<UserInfo> profiles =
150 UserManager.get(mContext).getProfiles(mSettings.getCurrentUserId());
151 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
152 for (int i = 0; i < currentProfileIds.length; i++) {
153 currentProfileIds[i] = profiles.get(i).id;
155 mSettings.setCurrentProfileIds(currentProfileIds);
158 private class TextServicesMonitor extends PackageMonitor {
159 private boolean isChangingPackagesOfCurrentUser() {
160 final int userId = getChangingUserId();
161 final boolean retval = userId == mSettings.getCurrentUserId();
163 Slog.d(TAG, "--- ignore this call back from a background user: " + userId);
169 public void onSomePackagesChanged() {
170 if (!isChangingPackagesOfCurrentUser()) {
173 synchronized (mSpellCheckerMap) {
174 buildSpellCheckerMapLocked(
175 mContext, mSpellCheckerList, mSpellCheckerMap, mSettings);
176 // TODO: Update for each locale
177 SpellCheckerInfo sci = getCurrentSpellChecker(null);
178 // If no spell checker is enabled, just return. The user should explicitly
179 // enable the spell checker.
180 if (sci == null) return;
181 final String packageName = sci.getPackageName();
182 final int change = isPackageDisappearing(packageName);
183 if (// Package disappearing
184 change == PACKAGE_PERMANENT_CHANGE || change == PACKAGE_TEMPORARY_CHANGE
186 || isPackageModified(packageName)) {
187 sci = findAvailSpellCheckerLocked(packageName);
189 setCurrentSpellCheckerLocked(sci.getId());
196 class TextServicesBroadcastReceiver extends BroadcastReceiver {
198 public void onReceive(Context context, Intent intent) {
199 final String action = intent.getAction();
200 if (Intent.ACTION_USER_ADDED.equals(action)
201 || Intent.ACTION_USER_REMOVED.equals(action)) {
202 updateCurrentProfileIds();
205 Slog.w(TAG, "Unexpected intent " + intent);
209 private static void buildSpellCheckerMapLocked(Context context,
210 ArrayList<SpellCheckerInfo> list, HashMap<String, SpellCheckerInfo> map,
211 TextServicesSettings settings) {
214 final PackageManager pm = context.getPackageManager();
215 final List<ResolveInfo> services = pm.queryIntentServicesAsUser(
216 new Intent(SpellCheckerService.SERVICE_INTERFACE), PackageManager.GET_META_DATA,
217 settings.getCurrentUserId());
218 final int N = services.size();
219 for (int i = 0; i < N; ++i) {
220 final ResolveInfo ri = services.get(i);
221 final ServiceInfo si = ri.serviceInfo;
222 final ComponentName compName = new ComponentName(si.packageName, si.name);
223 if (!android.Manifest.permission.BIND_TEXT_SERVICE.equals(si.permission)) {
224 Slog.w(TAG, "Skipping text service " + compName
225 + ": it does not require the permission "
226 + android.Manifest.permission.BIND_TEXT_SERVICE);
229 if (DBG) Slog.d(TAG, "Add: " + compName);
231 final SpellCheckerInfo sci = new SpellCheckerInfo(context, ri);
232 if (sci.getSubtypeCount() <= 0) {
233 Slog.w(TAG, "Skipping text service " + compName
234 + ": it does not contain subtypes.");
238 map.put(sci.getId(), sci);
239 } catch (XmlPullParserException e) {
240 Slog.w(TAG, "Unable to load the spell checker " + compName, e);
241 } catch (IOException e) {
242 Slog.w(TAG, "Unable to load the spell checker " + compName, e);
246 Slog.d(TAG, "buildSpellCheckerMapLocked: " + list.size() + "," + map.size());
250 // ---------------------------------------------------------------------------------------
251 // Check whether or not this is a valid IPC. Assumes an IPC is valid when either
252 // 1) it comes from the system process
253 // 2) the calling process' user id is identical to the current user id TSMS thinks.
254 private boolean calledFromValidUser() {
255 final int uid = Binder.getCallingUid();
256 final int userId = UserHandle.getUserId(uid);
258 Slog.d(TAG, "--- calledFromForegroundUserOrSystemProcess ? "
259 + "calling uid = " + uid + " system uid = " + Process.SYSTEM_UID
260 + " calling userId = " + userId + ", foreground user id = "
261 + mSettings.getCurrentUserId() + ", calling pid = " + Binder.getCallingPid());
263 final String[] packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
264 for (int i = 0; i < packageNames.length; ++i) {
266 Slog.d(TAG, "--- process name for "+ uid + " = " + packageNames[i]);
269 } catch (RemoteException e) {
273 if (uid == Process.SYSTEM_UID || userId == mSettings.getCurrentUserId()) {
277 // Permits current profile to use TSFM as long as the current text service is the system's
278 // one. This is a tentative solution and should be replaced with fully functional multiuser
280 // TODO: Implement multiuser support in TSMS.
281 final boolean isCurrentProfile = mSettings.isCurrentProfile(userId);
283 Slog.d(TAG, "--- userId = "+ userId + " isCurrentProfile = " + isCurrentProfile);
285 if (mSettings.isCurrentProfile(userId)) {
286 final SpellCheckerInfo spellCheckerInfo = getCurrentSpellCheckerWithoutVerification();
287 if (spellCheckerInfo != null) {
288 final ServiceInfo serviceInfo = spellCheckerInfo.getServiceInfo();
289 final boolean isSystemSpellChecker =
290 (serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
292 Slog.d(TAG, "--- current spell checker = "+ spellCheckerInfo.getPackageName()
293 + " isSystem = " + isSystemSpellChecker);
295 if (isSystemSpellChecker) {
301 // Unlike InputMethodManagerService#calledFromValidUser, INTERACT_ACROSS_USERS_FULL isn't
302 // taken into account here. Anyway this method is supposed to be removed once multiuser
303 // support is implemented.
305 Slog.d(TAG, "--- IPC from userId:" + userId + " is being ignored. \n"
311 private boolean bindCurrentSpellCheckerService(
312 Intent service, ServiceConnection conn, int flags) {
313 if (service == null || conn == null) {
314 Slog.e(TAG, "--- bind failed: service = " + service + ", conn = " + conn);
317 return mContext.bindServiceAsUser(service, conn, flags,
318 new UserHandle(mSettings.getCurrentUserId()));
321 private void unbindServiceLocked() {
322 for (SpellCheckerBindGroup scbg : mSpellCheckerBindGroups.values()) {
325 mSpellCheckerBindGroups.clear();
328 private SpellCheckerInfo findAvailSpellCheckerLocked(String prefPackage) {
329 final int spellCheckersCount = mSpellCheckerList.size();
330 if (spellCheckersCount == 0) {
331 Slog.w(TAG, "no available spell checker services found");
334 if (prefPackage != null) {
335 for (int i = 0; i < spellCheckersCount; ++i) {
336 final SpellCheckerInfo sci = mSpellCheckerList.get(i);
337 if (prefPackage.equals(sci.getPackageName())) {
339 Slog.d(TAG, "findAvailSpellCheckerLocked: " + sci.getPackageName());
346 // Look up a spell checker based on the system locale.
347 // TODO: Still there is a room to improve in the following logic: e.g., check if the package
348 // is pre-installed or not.
349 final Locale systemLocal = mContext.getResources().getConfiguration().locale;
350 final ArrayList<Locale> suitableLocales =
351 InputMethodUtils.getSuitableLocalesForSpellChecker(systemLocal);
353 Slog.w(TAG, "findAvailSpellCheckerLocked suitableLocales="
354 + Arrays.toString(suitableLocales.toArray(new Locale[suitableLocales.size()])));
356 final int localeCount = suitableLocales.size();
357 for (int localeIndex = 0; localeIndex < localeCount; ++localeIndex) {
358 final Locale locale = suitableLocales.get(localeIndex);
359 for (int spellCheckersIndex = 0; spellCheckersIndex < spellCheckersCount;
360 ++spellCheckersIndex) {
361 final SpellCheckerInfo info = mSpellCheckerList.get(spellCheckersIndex);
362 final int subtypeCount = info.getSubtypeCount();
363 for (int subtypeIndex = 0; subtypeIndex < subtypeCount; ++subtypeIndex) {
364 final SpellCheckerSubtype subtype = info.getSubtypeAt(subtypeIndex);
365 final Locale subtypeLocale = InputMethodUtils.constructLocaleFromString(
366 subtype.getLocale());
367 if (locale.equals(subtypeLocale)) {
368 // TODO: We may have more spell checkers that fall into this category.
369 // Ideally we should pick up the most suitable one instead of simply
370 // returning the first found one.
377 if (spellCheckersCount > 1) {
378 Slog.w(TAG, "more than one spell checker service found, picking first");
380 return mSpellCheckerList.get(0);
383 // TODO: Save SpellCheckerService by supported languages. Currently only one spell
386 public SpellCheckerInfo getCurrentSpellChecker(String locale) {
387 // TODO: Make this work even for non-current users?
388 if (!calledFromValidUser()) {
391 return getCurrentSpellCheckerWithoutVerification();
394 private SpellCheckerInfo getCurrentSpellCheckerWithoutVerification() {
395 synchronized (mSpellCheckerMap) {
396 final String curSpellCheckerId = mSettings.getSelectedSpellChecker();
398 Slog.w(TAG, "getCurrentSpellChecker: " + curSpellCheckerId);
400 if (TextUtils.isEmpty(curSpellCheckerId)) {
403 return mSpellCheckerMap.get(curSpellCheckerId);
407 // TODO: Respect allowImplicitlySelectedSubtype
408 // TODO: Save SpellCheckerSubtype by supported languages by looking at "locale".
410 public SpellCheckerSubtype getCurrentSpellCheckerSubtype(
411 String locale, boolean allowImplicitlySelectedSubtype) {
412 // TODO: Make this work even for non-current users?
413 if (!calledFromValidUser()) {
416 synchronized (mSpellCheckerMap) {
417 final String subtypeHashCodeStr = mSettings.getSelectedSpellCheckerSubtype();
419 Slog.w(TAG, "getCurrentSpellCheckerSubtype: " + subtypeHashCodeStr);
421 final SpellCheckerInfo sci = getCurrentSpellChecker(null);
422 if (sci == null || sci.getSubtypeCount() == 0) {
424 Slog.w(TAG, "Subtype not found.");
429 if (!TextUtils.isEmpty(subtypeHashCodeStr)) {
430 hashCode = Integer.valueOf(subtypeHashCodeStr);
434 if (hashCode == 0 && !allowImplicitlySelectedSubtype) {
437 String candidateLocale = null;
439 // Spell checker language settings == "auto"
440 final InputMethodManager imm = mContext.getSystemService(InputMethodManager.class);
442 final InputMethodSubtype currentInputMethodSubtype =
443 imm.getCurrentInputMethodSubtype();
444 if (currentInputMethodSubtype != null) {
445 final String localeString = currentInputMethodSubtype.getLocale();
446 if (!TextUtils.isEmpty(localeString)) {
447 // 1. Use keyboard locale if available in the spell checker
448 candidateLocale = localeString;
452 if (candidateLocale == null) {
453 // 2. Use System locale if available in the spell checker
454 candidateLocale = mContext.getResources().getConfiguration().locale.toString();
457 SpellCheckerSubtype candidate = null;
458 for (int i = 0; i < sci.getSubtypeCount(); ++i) {
459 final SpellCheckerSubtype scs = sci.getSubtypeAt(i);
461 final String scsLocale = scs.getLocale();
462 if (candidateLocale.equals(scsLocale)) {
464 } else if (candidate == null) {
465 if (candidateLocale.length() >= 2 && scsLocale.length() >= 2
466 && candidateLocale.startsWith(scsLocale)) {
467 // Fall back to the applicable language
471 } else if (scs.hashCode() == hashCode) {
473 Slog.w(TAG, "Return subtype " + scs.hashCode() + ", input= " + locale
474 + ", " + scs.getLocale());
476 // 3. Use the user specified spell check language
480 // 4. Fall back to the applicable language and return it if not null
481 // 5. Simply just return it even if it's null which means we could find no suitable
482 // spell check languages
488 public void getSpellCheckerService(String sciId, String locale,
489 ITextServicesSessionListener tsListener, ISpellCheckerSessionListener scListener,
491 if (!calledFromValidUser()) {
497 if (TextUtils.isEmpty(sciId) || tsListener == null || scListener == null) {
498 Slog.e(TAG, "getSpellCheckerService: Invalid input.");
501 synchronized(mSpellCheckerMap) {
502 if (!mSpellCheckerMap.containsKey(sciId)) {
505 final SpellCheckerInfo sci = mSpellCheckerMap.get(sciId);
506 final int uid = Binder.getCallingUid();
507 if (mSpellCheckerBindGroups.containsKey(sciId)) {
508 final SpellCheckerBindGroup bindGroup = mSpellCheckerBindGroups.get(sciId);
509 if (bindGroup != null) {
510 final InternalDeathRecipient recipient =
511 mSpellCheckerBindGroups.get(sciId).addListener(
512 tsListener, locale, scListener, uid, bundle);
513 if (recipient == null) {
515 Slog.w(TAG, "Didn't create a death recipient.");
519 if (bindGroup.mSpellChecker == null & bindGroup.mConnected) {
520 Slog.e(TAG, "The state of the spell checker bind group is illegal.");
521 bindGroup.removeAll();
522 } else if (bindGroup.mSpellChecker != null) {
524 Slog.w(TAG, "Existing bind found. Return a spell checker session now. "
525 + "Listeners count = " + bindGroup.mListeners.size());
528 final ISpellCheckerSession session =
529 bindGroup.mSpellChecker.getISpellCheckerSession(
530 recipient.mScLocale, recipient.mScListener, bundle);
531 if (session != null) {
532 tsListener.onServiceConnected(session);
536 Slog.w(TAG, "Existing bind already expired. ");
538 bindGroup.removeAll();
540 } catch (RemoteException e) {
541 Slog.e(TAG, "Exception in getting spell checker session: " + e);
542 bindGroup.removeAll();
547 final long ident = Binder.clearCallingIdentity();
549 startSpellCheckerServiceInnerLocked(
550 sci, locale, tsListener, scListener, uid, bundle);
552 Binder.restoreCallingIdentity(ident);
559 public boolean isSpellCheckerEnabled() {
560 if (!calledFromValidUser()) {
563 synchronized(mSpellCheckerMap) {
564 return isSpellCheckerEnabledLocked();
568 private void startSpellCheckerServiceInnerLocked(SpellCheckerInfo info, String locale,
569 ITextServicesSessionListener tsListener, ISpellCheckerSessionListener scListener,
570 int uid, Bundle bundle) {
572 Slog.w(TAG, "Start spell checker session inner locked.");
574 final String sciId = info.getId();
575 final InternalServiceConnection connection = new InternalServiceConnection(
576 sciId, locale, bundle);
577 final Intent serviceIntent = new Intent(SpellCheckerService.SERVICE_INTERFACE);
578 serviceIntent.setComponent(info.getComponent());
580 Slog.w(TAG, "bind service: " + info.getId());
582 if (!bindCurrentSpellCheckerService(serviceIntent, connection,
583 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE_WHILE_AWAKE)) {
584 Slog.e(TAG, "Failed to get a spell checker service.");
587 final SpellCheckerBindGroup group = new SpellCheckerBindGroup(
588 connection, tsListener, locale, scListener, uid, bundle);
589 mSpellCheckerBindGroups.put(sciId, group);
593 public SpellCheckerInfo[] getEnabledSpellCheckers() {
594 // TODO: Make this work even for non-current users?
595 if (!calledFromValidUser()) {
599 Slog.d(TAG, "getEnabledSpellCheckers: " + mSpellCheckerList.size());
600 for (int i = 0; i < mSpellCheckerList.size(); ++i) {
601 Slog.d(TAG, "EnabledSpellCheckers: " + mSpellCheckerList.get(i).getPackageName());
604 return mSpellCheckerList.toArray(new SpellCheckerInfo[mSpellCheckerList.size()]);
608 public void finishSpellCheckerService(ISpellCheckerSessionListener listener) {
609 if (!calledFromValidUser()) {
613 Slog.d(TAG, "FinishSpellCheckerService");
615 synchronized(mSpellCheckerMap) {
616 final ArrayList<SpellCheckerBindGroup> removeList = new ArrayList<>();
617 for (SpellCheckerBindGroup group : mSpellCheckerBindGroups.values()) {
618 if (group == null) continue;
619 // Use removeList to avoid modifying mSpellCheckerBindGroups in this loop.
620 removeList.add(group);
622 final int removeSize = removeList.size();
623 for (int i = 0; i < removeSize; ++i) {
624 removeList.get(i).removeListener(listener);
630 public void setCurrentSpellChecker(String locale, String sciId) {
631 if (!calledFromValidUser()) {
634 synchronized(mSpellCheckerMap) {
635 if (mContext.checkCallingOrSelfPermission(
636 android.Manifest.permission.WRITE_SECURE_SETTINGS)
637 != PackageManager.PERMISSION_GRANTED) {
638 throw new SecurityException(
639 "Requires permission "
640 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
642 setCurrentSpellCheckerLocked(sciId);
647 public void setCurrentSpellCheckerSubtype(String locale, int hashCode) {
648 if (!calledFromValidUser()) {
651 synchronized(mSpellCheckerMap) {
652 if (mContext.checkCallingOrSelfPermission(
653 android.Manifest.permission.WRITE_SECURE_SETTINGS)
654 != PackageManager.PERMISSION_GRANTED) {
655 throw new SecurityException(
656 "Requires permission "
657 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
659 setCurrentSpellCheckerSubtypeLocked(hashCode);
664 public void setSpellCheckerEnabled(boolean enabled) {
665 if (!calledFromValidUser()) {
668 synchronized(mSpellCheckerMap) {
669 if (mContext.checkCallingOrSelfPermission(
670 android.Manifest.permission.WRITE_SECURE_SETTINGS)
671 != PackageManager.PERMISSION_GRANTED) {
672 throw new SecurityException(
673 "Requires permission "
674 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
676 setSpellCheckerEnabledLocked(enabled);
680 private void setCurrentSpellCheckerLocked(String sciId) {
682 Slog.w(TAG, "setCurrentSpellChecker: " + sciId);
684 if (TextUtils.isEmpty(sciId) || !mSpellCheckerMap.containsKey(sciId)) return;
685 final SpellCheckerInfo currentSci = getCurrentSpellChecker(null);
686 if (currentSci != null && currentSci.getId().equals(sciId)) {
687 // Do nothing if the current spell checker is same as new spell checker.
690 final long ident = Binder.clearCallingIdentity();
692 mSettings.putSelectedSpellChecker(sciId);
693 setCurrentSpellCheckerSubtypeLocked(0);
695 Binder.restoreCallingIdentity(ident);
699 private void setCurrentSpellCheckerSubtypeLocked(int hashCode) {
701 Slog.w(TAG, "setCurrentSpellCheckerSubtype: " + hashCode);
703 final SpellCheckerInfo sci = getCurrentSpellChecker(null);
704 int tempHashCode = 0;
705 for (int i = 0; sci != null && i < sci.getSubtypeCount(); ++i) {
706 if(sci.getSubtypeAt(i).hashCode() == hashCode) {
707 tempHashCode = hashCode;
711 final long ident = Binder.clearCallingIdentity();
713 mSettings.putSelectedSpellCheckerSubtype(tempHashCode);
715 Binder.restoreCallingIdentity(ident);
719 private void setSpellCheckerEnabledLocked(boolean enabled) {
721 Slog.w(TAG, "setSpellCheckerEnabled: " + enabled);
723 final long ident = Binder.clearCallingIdentity();
725 mSettings.setSpellCheckerEnabled(enabled);
727 Binder.restoreCallingIdentity(ident);
731 private boolean isSpellCheckerEnabledLocked() {
732 final long ident = Binder.clearCallingIdentity();
734 final boolean retval = mSettings.isSpellCheckerEnabled();
736 Slog.w(TAG, "getSpellCheckerEnabled: " + retval);
740 Binder.restoreCallingIdentity(ident);
745 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
746 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
747 != PackageManager.PERMISSION_GRANTED) {
749 pw.println("Permission Denial: can't dump TextServicesManagerService from from pid="
750 + Binder.getCallingPid()
751 + ", uid=" + Binder.getCallingUid());
755 synchronized(mSpellCheckerMap) {
756 pw.println("Current Text Services Manager state:");
757 pw.println(" Spell Checker Map:");
758 for (Map.Entry<String, SpellCheckerInfo> ent : mSpellCheckerMap.entrySet()) {
759 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
760 SpellCheckerInfo info = ent.getValue();
761 pw.print(" "); pw.print("id="); pw.println(info.getId());
762 pw.print(" "); pw.print("comp=");
763 pw.println(info.getComponent().toShortString());
764 int NS = info.getSubtypeCount();
765 for (int i=0; i<NS; i++) {
766 SpellCheckerSubtype st = info.getSubtypeAt(i);
767 pw.print(" "); pw.print("Subtype #"); pw.print(i); pw.println(":");
768 pw.print(" "); pw.print("locale="); pw.println(st.getLocale());
769 pw.print(" "); pw.print("extraValue=");
770 pw.println(st.getExtraValue());
774 pw.println(" Spell Checker Bind Groups:");
775 for (Map.Entry<String, SpellCheckerBindGroup> ent
776 : mSpellCheckerBindGroups.entrySet()) {
777 SpellCheckerBindGroup grp = ent.getValue();
778 pw.print(" "); pw.print(ent.getKey()); pw.print(" ");
779 pw.print(grp); pw.println(":");
780 pw.print(" "); pw.print("mInternalConnection=");
781 pw.println(grp.mInternalConnection);
782 pw.print(" "); pw.print("mSpellChecker=");
783 pw.println(grp.mSpellChecker);
784 pw.print(" "); pw.print("mBound="); pw.print(grp.mBound);
785 pw.print(" mConnected="); pw.println(grp.mConnected);
786 int NL = grp.mListeners.size();
787 for (int i=0; i<NL; i++) {
788 InternalDeathRecipient listener = grp.mListeners.get(i);
789 pw.print(" "); pw.print("Listener #"); pw.print(i); pw.println(":");
790 pw.print(" "); pw.print("mTsListener=");
791 pw.println(listener.mTsListener);
792 pw.print(" "); pw.print("mScListener=");
793 pw.println(listener.mScListener);
794 pw.print(" "); pw.print("mGroup=");
795 pw.println(listener.mGroup);
796 pw.print(" "); pw.print("mScLocale=");
797 pw.print(listener.mScLocale);
798 pw.print(" mUid="); pw.println(listener.mUid);
804 // SpellCheckerBindGroup contains active text service session listeners.
805 // If there are no listeners anymore, the SpellCheckerBindGroup instance will be removed from
806 // mSpellCheckerBindGroups
807 private class SpellCheckerBindGroup {
808 private final String TAG = SpellCheckerBindGroup.class.getSimpleName();
809 private final InternalServiceConnection mInternalConnection;
810 private final CopyOnWriteArrayList<InternalDeathRecipient> mListeners =
811 new CopyOnWriteArrayList<>();
812 public boolean mBound;
813 public ISpellCheckerService mSpellChecker;
814 public boolean mConnected;
816 public SpellCheckerBindGroup(InternalServiceConnection connection,
817 ITextServicesSessionListener listener, String locale,
818 ISpellCheckerSessionListener scListener, int uid, Bundle bundle) {
819 mInternalConnection = connection;
822 addListener(listener, locale, scListener, uid, bundle);
825 public void onServiceConnected(ISpellCheckerService spellChecker) {
827 Slog.d(TAG, "onServiceConnected");
830 for (InternalDeathRecipient listener : mListeners) {
832 final ISpellCheckerSession session = spellChecker.getISpellCheckerSession(
833 listener.mScLocale, listener.mScListener, listener.mBundle);
834 synchronized(mSpellCheckerMap) {
835 if (mListeners.contains(listener)) {
836 listener.mTsListener.onServiceConnected(session);
839 } catch (RemoteException e) {
840 Slog.e(TAG, "Exception in getting the spell checker session."
841 + "Reconnect to the spellchecker. ", e);
846 synchronized(mSpellCheckerMap) {
847 mSpellChecker = spellChecker;
852 public InternalDeathRecipient addListener(ITextServicesSessionListener tsListener,
853 String locale, ISpellCheckerSessionListener scListener, int uid, Bundle bundle) {
855 Slog.d(TAG, "addListener: " + locale);
857 InternalDeathRecipient recipient = null;
858 synchronized(mSpellCheckerMap) {
860 final int size = mListeners.size();
861 for (int i = 0; i < size; ++i) {
862 if (mListeners.get(i).hasSpellCheckerListener(scListener)) {
863 // do not add the lister if the group already contains this.
867 recipient = new InternalDeathRecipient(
868 this, tsListener, locale, scListener, uid, bundle);
869 scListener.asBinder().linkToDeath(recipient, 0);
870 mListeners.add(recipient);
871 } catch(RemoteException e) {
879 public void removeListener(ISpellCheckerSessionListener listener) {
881 Slog.w(TAG, "remove listener: " + listener.hashCode());
883 synchronized(mSpellCheckerMap) {
884 final int size = mListeners.size();
885 final ArrayList<InternalDeathRecipient> removeList = new ArrayList<>();
886 for (int i = 0; i < size; ++i) {
887 final InternalDeathRecipient tempRecipient = mListeners.get(i);
888 if(tempRecipient.hasSpellCheckerListener(listener)) {
890 Slog.w(TAG, "found existing listener.");
892 removeList.add(tempRecipient);
895 final int removeSize = removeList.size();
896 for (int i = 0; i < removeSize; ++i) {
898 Slog.w(TAG, "Remove " + removeList.get(i));
900 final InternalDeathRecipient idr = removeList.get(i);
901 idr.mScListener.asBinder().unlinkToDeath(idr, 0);
902 mListeners.remove(idr);
908 // cleanLocked may remove elements from mSpellCheckerBindGroups
909 private void cleanLocked() {
911 Slog.d(TAG, "cleanLocked");
913 // If there are no more active listeners, clean up. Only do this
915 if (mBound && mListeners.isEmpty()) {
917 final String sciId = mInternalConnection.mSciId;
918 SpellCheckerBindGroup cur = mSpellCheckerBindGroups.get(sciId);
921 Slog.d(TAG, "Remove bind group.");
923 mSpellCheckerBindGroups.remove(sciId);
925 mContext.unbindService(mInternalConnection);
929 public void removeAll() {
930 Slog.e(TAG, "Remove the spell checker bind unexpectedly.");
931 synchronized(mSpellCheckerMap) {
932 final int size = mListeners.size();
933 for (int i = 0; i < size; ++i) {
934 final InternalDeathRecipient idr = mListeners.get(i);
935 idr.mScListener.asBinder().unlinkToDeath(idr, 0);
943 private class InternalServiceConnection implements ServiceConnection {
944 private final String mSciId;
945 private final String mLocale;
946 private final Bundle mBundle;
947 public InternalServiceConnection(
948 String id, String locale, Bundle bundle) {
955 public void onServiceConnected(ComponentName name, IBinder service) {
956 synchronized(mSpellCheckerMap) {
957 onServiceConnectedInnerLocked(name, service);
961 private void onServiceConnectedInnerLocked(ComponentName name, IBinder service) {
963 Slog.w(TAG, "onServiceConnected: " + name);
965 final ISpellCheckerService spellChecker =
966 ISpellCheckerService.Stub.asInterface(service);
967 final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId);
968 if (group != null && this == group.mInternalConnection) {
969 group.onServiceConnected(spellChecker);
974 public void onServiceDisconnected(ComponentName name) {
975 synchronized(mSpellCheckerMap) {
976 final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId);
977 if (group != null && this == group.mInternalConnection) {
978 mSpellCheckerBindGroups.remove(mSciId);
984 private class InternalDeathRecipient implements IBinder.DeathRecipient {
985 public final ITextServicesSessionListener mTsListener;
986 public final ISpellCheckerSessionListener mScListener;
987 public final String mScLocale;
988 private final SpellCheckerBindGroup mGroup;
989 public final int mUid;
990 public final Bundle mBundle;
991 public InternalDeathRecipient(SpellCheckerBindGroup group,
992 ITextServicesSessionListener tsListener, String scLocale,
993 ISpellCheckerSessionListener scListener, int uid, Bundle bundle) {
994 mTsListener = tsListener;
995 mScListener = scListener;
996 mScLocale = scLocale;
1002 public boolean hasSpellCheckerListener(ISpellCheckerSessionListener listener) {
1003 return listener.asBinder().equals(mScListener.asBinder());
1007 public void binderDied() {
1008 mGroup.removeListener(mScListener);
1012 private static class TextServicesSettings {
1013 private final ContentResolver mResolver;
1014 private int mCurrentUserId;
1016 private int[] mCurrentProfileIds = new int[0];
1017 private Object mLock = new Object();
1019 public TextServicesSettings(ContentResolver resolver, int userId) {
1020 mResolver = resolver;
1021 mCurrentUserId = userId;
1024 public void setCurrentUserId(int userId) {
1026 Slog.d(TAG, "--- Swtich the current user from " + mCurrentUserId + " to "
1027 + userId + ", new ime = " + getSelectedSpellChecker());
1029 // TSMS settings are kept per user, so keep track of current user
1030 mCurrentUserId = userId;
1033 public void setCurrentProfileIds(int[] currentProfileIds) {
1034 synchronized (mLock) {
1035 mCurrentProfileIds = currentProfileIds;
1039 public boolean isCurrentProfile(int userId) {
1040 synchronized (mLock) {
1041 if (userId == mCurrentUserId) return true;
1042 for (int i = 0; i < mCurrentProfileIds.length; i++) {
1043 if (userId == mCurrentProfileIds[i]) return true;
1049 public int getCurrentUserId() {
1050 return mCurrentUserId;
1053 public void putSelectedSpellChecker(String sciId) {
1054 Settings.Secure.putStringForUser(mResolver,
1055 Settings.Secure.SELECTED_SPELL_CHECKER, sciId, mCurrentUserId);
1058 public void putSelectedSpellCheckerSubtype(int hashCode) {
1059 Settings.Secure.putStringForUser(mResolver,
1060 Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE, String.valueOf(hashCode),
1064 public void setSpellCheckerEnabled(boolean enabled) {
1065 Settings.Secure.putIntForUser(mResolver,
1066 Settings.Secure.SPELL_CHECKER_ENABLED, enabled ? 1 : 0, mCurrentUserId);
1069 public String getSelectedSpellChecker() {
1070 return Settings.Secure.getStringForUser(mResolver,
1071 Settings.Secure.SELECTED_SPELL_CHECKER, mCurrentUserId);
1074 public String getSelectedSpellCheckerSubtype() {
1075 return Settings.Secure.getStringForUser(mResolver,
1076 Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE, mCurrentUserId);
1079 public boolean isSpellCheckerEnabled() {
1080 return Settings.Secure.getIntForUser(mResolver,
1081 Settings.Secure.SPELL_CHECKER_ENABLED, 1, mCurrentUserId) == 1;
1085 // ----------------------------------------------------------------------
1086 // Utilities for debug
1087 private static String getStackTrace() {
1088 final StringBuilder sb = new StringBuilder();
1090 throw new RuntimeException();
1091 } catch (RuntimeException e) {
1092 final StackTraceElement[] frames = e.getStackTrace();
1093 // Start at 1 because the first frame is here and we don't care about it
1094 for (int j = 1; j < frames.length; ++j) {
1095 sb.append(frames[j].toString() + "\n");
1098 return sb.toString();