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.ISpellCheckerServiceCallback;
24 import com.android.internal.textservice.ISpellCheckerSession;
25 import com.android.internal.textservice.ISpellCheckerSessionListener;
26 import com.android.internal.textservice.ITextServicesManager;
27 import com.android.internal.textservice.ITextServicesSessionListener;
28 import com.android.internal.util.DumpUtils;
30 import org.xmlpull.v1.XmlPullParserException;
32 import android.annotation.NonNull;
33 import android.annotation.Nullable;
34 import android.annotation.UserIdInt;
35 import android.app.ActivityManager;
36 import android.app.AppGlobals;
37 import android.content.BroadcastReceiver;
38 import android.content.ComponentName;
39 import android.content.ContentResolver;
40 import android.content.Context;
41 import android.content.Intent;
42 import android.content.IntentFilter;
43 import android.content.ServiceConnection;
44 import android.content.pm.ApplicationInfo;
45 import android.content.pm.PackageManager;
46 import android.content.pm.ResolveInfo;
47 import android.content.pm.ServiceInfo;
48 import android.os.Binder;
49 import android.os.Bundle;
50 import android.os.IBinder;
51 import android.os.Process;
52 import android.os.RemoteCallbackList;
53 import android.os.RemoteException;
54 import android.os.UserHandle;
55 import android.os.UserManager;
56 import android.provider.Settings;
57 import android.service.textservice.SpellCheckerService;
58 import android.text.TextUtils;
59 import android.util.Slog;
60 import android.view.inputmethod.InputMethodManager;
61 import android.view.inputmethod.InputMethodSubtype;
62 import android.view.textservice.SpellCheckerInfo;
63 import android.view.textservice.SpellCheckerSubtype;
65 import java.io.FileDescriptor;
66 import java.io.IOException;
67 import java.io.PrintWriter;
68 import java.util.Arrays;
69 import java.util.ArrayList;
70 import java.util.HashMap;
71 import java.util.List;
72 import java.util.Locale;
75 public class TextServicesManagerService extends ITextServicesManager.Stub {
76 private static final String TAG = TextServicesManagerService.class.getSimpleName();
77 private static final boolean DBG = false;
79 private final Context mContext;
80 private boolean mSystemReady;
81 private final TextServicesMonitor mMonitor;
82 private final HashMap<String, SpellCheckerInfo> mSpellCheckerMap = new HashMap<>();
83 private final ArrayList<SpellCheckerInfo> mSpellCheckerList = new ArrayList<>();
84 private final HashMap<String, SpellCheckerBindGroup> mSpellCheckerBindGroups = new HashMap<>();
85 private final TextServicesSettings mSettings;
87 private final UserManager mUserManager;
89 public static final class Lifecycle extends SystemService {
90 private TextServicesManagerService mService;
92 public Lifecycle(Context context) {
94 mService = new TextServicesManagerService(context);
98 public void onStart() {
99 publishBinderService(Context.TEXT_SERVICES_MANAGER_SERVICE, mService);
103 public void onSwitchUser(@UserIdInt int userHandle) {
104 // Called on the system server's main looper thread.
105 // TODO: Dispatch this to a worker thread as needed.
106 mService.onSwitchUser(userHandle);
110 public void onBootPhase(int phase) {
111 // Called on the system server's main looper thread.
112 // TODO: Dispatch this to a worker thread as needed.
113 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
114 mService.systemRunning();
119 public void onUnlockUser(@UserIdInt int userHandle) {
120 // Called on the system server's main looper thread.
121 // TODO: Dispatch this to a worker thread as needed.
122 mService.onUnlockUser(userHandle);
126 void systemRunning() {
127 synchronized (mSpellCheckerMap) {
130 resetInternalState(mSettings.getCurrentUserId());
135 void onSwitchUser(@UserIdInt int userId) {
136 synchronized (mSpellCheckerMap) {
137 resetInternalState(userId);
141 void onUnlockUser(@UserIdInt int userId) {
142 synchronized(mSpellCheckerMap) {
143 final int currentUserId = mSettings.getCurrentUserId();
144 if (userId != currentUserId) {
147 resetInternalState(currentUserId);
151 public TextServicesManagerService(Context context) {
152 mSystemReady = false;
155 mUserManager = mContext.getSystemService(UserManager.class);
157 final IntentFilter broadcastFilter = new IntentFilter();
158 broadcastFilter.addAction(Intent.ACTION_USER_ADDED);
159 broadcastFilter.addAction(Intent.ACTION_USER_REMOVED);
160 mContext.registerReceiver(new TextServicesBroadcastReceiver(), broadcastFilter);
162 int userId = UserHandle.USER_SYSTEM;
164 userId = ActivityManager.getService().getCurrentUser().id;
165 } catch (RemoteException e) {
166 Slog.w(TAG, "Couldn't get current user ID; guessing it's 0", e);
168 mMonitor = new TextServicesMonitor();
169 mMonitor.register(context, null, true);
170 final boolean useCopyOnWriteSettings =
171 !mSystemReady || !mUserManager.isUserUnlockingOrUnlocked(userId);
172 mSettings = new TextServicesSettings(context.getContentResolver(), userId,
173 useCopyOnWriteSettings);
175 // "resetInternalState" initializes the states for the foreground user
176 resetInternalState(userId);
179 private void resetInternalState(@UserIdInt int userId) {
180 final boolean useCopyOnWriteSettings =
181 !mSystemReady || !mUserManager.isUserUnlockingOrUnlocked(userId);
182 mSettings.switchCurrentUser(userId, useCopyOnWriteSettings);
183 updateCurrentProfileIds();
184 unbindServiceLocked();
185 buildSpellCheckerMapLocked(mContext, mSpellCheckerList, mSpellCheckerMap, mSettings);
186 SpellCheckerInfo sci = getCurrentSpellChecker(null);
188 sci = findAvailSpellCheckerLocked(null);
190 // Set the current spell checker if there is one or more spell checkers
191 // available. In this case, "sci" is the first one in the available spell
193 setCurrentSpellCheckerLocked(sci.getId());
198 void updateCurrentProfileIds() {
199 mSettings.setCurrentProfileIds(
200 mUserManager.getProfileIdsWithDisabled(mSettings.getCurrentUserId()));
203 private final class TextServicesMonitor extends PackageMonitor {
204 private boolean isChangingPackagesOfCurrentUser() {
205 final int userId = getChangingUserId();
206 final boolean retval = userId == mSettings.getCurrentUserId();
208 Slog.d(TAG, "--- ignore this call back from a background user: " + userId);
214 public void onSomePackagesChanged() {
215 if (!isChangingPackagesOfCurrentUser()) {
218 synchronized (mSpellCheckerMap) {
219 buildSpellCheckerMapLocked(
220 mContext, mSpellCheckerList, mSpellCheckerMap, mSettings);
221 // TODO: Update for each locale
222 SpellCheckerInfo sci = getCurrentSpellChecker(null);
223 // If no spell checker is enabled, just return. The user should explicitly
224 // enable the spell checker.
225 if (sci == null) return;
226 final String packageName = sci.getPackageName();
227 final int change = isPackageDisappearing(packageName);
228 if (// Package disappearing
229 change == PACKAGE_PERMANENT_CHANGE || change == PACKAGE_TEMPORARY_CHANGE
231 || isPackageModified(packageName)) {
232 sci = findAvailSpellCheckerLocked(packageName);
234 setCurrentSpellCheckerLocked(sci.getId());
241 private final class TextServicesBroadcastReceiver extends BroadcastReceiver {
243 public void onReceive(Context context, Intent intent) {
244 final String action = intent.getAction();
245 if (Intent.ACTION_USER_ADDED.equals(action)
246 || Intent.ACTION_USER_REMOVED.equals(action)) {
247 updateCurrentProfileIds();
250 Slog.w(TAG, "Unexpected intent " + intent);
254 private static void buildSpellCheckerMapLocked(Context context,
255 ArrayList<SpellCheckerInfo> list, HashMap<String, SpellCheckerInfo> map,
256 TextServicesSettings settings) {
259 final PackageManager pm = context.getPackageManager();
260 // Note: We do not specify PackageManager.MATCH_ENCRYPTION_* flags here because the default
261 // behavior of PackageManager is exactly what we want. It by default picks up appropriate
262 // services depending on the unlock state for the specified user.
263 final List<ResolveInfo> services = pm.queryIntentServicesAsUser(
264 new Intent(SpellCheckerService.SERVICE_INTERFACE), PackageManager.GET_META_DATA,
265 settings.getCurrentUserId());
266 final int N = services.size();
267 for (int i = 0; i < N; ++i) {
268 final ResolveInfo ri = services.get(i);
269 final ServiceInfo si = ri.serviceInfo;
270 final ComponentName compName = new ComponentName(si.packageName, si.name);
271 if (!android.Manifest.permission.BIND_TEXT_SERVICE.equals(si.permission)) {
272 Slog.w(TAG, "Skipping text service " + compName
273 + ": it does not require the permission "
274 + android.Manifest.permission.BIND_TEXT_SERVICE);
277 if (DBG) Slog.d(TAG, "Add: " + compName);
279 final SpellCheckerInfo sci = new SpellCheckerInfo(context, ri);
280 if (sci.getSubtypeCount() <= 0) {
281 Slog.w(TAG, "Skipping text service " + compName
282 + ": it does not contain subtypes.");
286 map.put(sci.getId(), sci);
287 } catch (XmlPullParserException e) {
288 Slog.w(TAG, "Unable to load the spell checker " + compName, e);
289 } catch (IOException e) {
290 Slog.w(TAG, "Unable to load the spell checker " + compName, e);
294 Slog.d(TAG, "buildSpellCheckerMapLocked: " + list.size() + "," + map.size());
298 // ---------------------------------------------------------------------------------------
299 // Check whether or not this is a valid IPC. Assumes an IPC is valid when either
300 // 1) it comes from the system process
301 // 2) the calling process' user id is identical to the current user id TSMS thinks.
302 private boolean calledFromValidUser() {
303 final int uid = Binder.getCallingUid();
304 final int userId = UserHandle.getUserId(uid);
306 Slog.d(TAG, "--- calledFromForegroundUserOrSystemProcess ? "
307 + "calling uid = " + uid + " system uid = " + Process.SYSTEM_UID
308 + " calling userId = " + userId + ", foreground user id = "
309 + mSettings.getCurrentUserId() + ", calling pid = " + Binder.getCallingPid());
311 final String[] packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
312 for (int i = 0; i < packageNames.length; ++i) {
314 Slog.d(TAG, "--- process name for "+ uid + " = " + packageNames[i]);
317 } catch (RemoteException e) {
321 if (uid == Process.SYSTEM_UID || userId == mSettings.getCurrentUserId()) {
325 // Permits current profile to use TSFM as long as the current text service is the system's
326 // one. This is a tentative solution and should be replaced with fully functional multiuser
328 // TODO: Implement multiuser support in TSMS.
329 final boolean isCurrentProfile = mSettings.isCurrentProfile(userId);
331 Slog.d(TAG, "--- userId = "+ userId + " isCurrentProfile = " + isCurrentProfile);
333 if (mSettings.isCurrentProfile(userId)) {
334 final SpellCheckerInfo spellCheckerInfo = getCurrentSpellCheckerWithoutVerification();
335 if (spellCheckerInfo != null) {
336 final ServiceInfo serviceInfo = spellCheckerInfo.getServiceInfo();
337 final boolean isSystemSpellChecker =
338 (serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
340 Slog.d(TAG, "--- current spell checker = "+ spellCheckerInfo.getPackageName()
341 + " isSystem = " + isSystemSpellChecker);
343 if (isSystemSpellChecker) {
349 // Unlike InputMethodManagerService#calledFromValidUser, INTERACT_ACROSS_USERS_FULL isn't
350 // taken into account here. Anyway this method is supposed to be removed once multiuser
351 // support is implemented.
353 Slog.d(TAG, "--- IPC from userId:" + userId + " is being ignored. \n"
359 private boolean bindCurrentSpellCheckerService(
360 Intent service, ServiceConnection conn, int flags) {
361 if (service == null || conn == null) {
362 Slog.e(TAG, "--- bind failed: service = " + service + ", conn = " + conn);
365 return mContext.bindServiceAsUser(service, conn, flags,
366 new UserHandle(mSettings.getCurrentUserId()));
369 private void unbindServiceLocked() {
370 for (SpellCheckerBindGroup scbg : mSpellCheckerBindGroups.values()) {
373 mSpellCheckerBindGroups.clear();
376 private SpellCheckerInfo findAvailSpellCheckerLocked(String prefPackage) {
377 final int spellCheckersCount = mSpellCheckerList.size();
378 if (spellCheckersCount == 0) {
379 Slog.w(TAG, "no available spell checker services found");
382 if (prefPackage != null) {
383 for (int i = 0; i < spellCheckersCount; ++i) {
384 final SpellCheckerInfo sci = mSpellCheckerList.get(i);
385 if (prefPackage.equals(sci.getPackageName())) {
387 Slog.d(TAG, "findAvailSpellCheckerLocked: " + sci.getPackageName());
394 // Look up a spell checker based on the system locale.
395 // TODO: Still there is a room to improve in the following logic: e.g., check if the package
396 // is pre-installed or not.
397 final Locale systemLocal = mContext.getResources().getConfiguration().locale;
398 final ArrayList<Locale> suitableLocales =
399 InputMethodUtils.getSuitableLocalesForSpellChecker(systemLocal);
401 Slog.w(TAG, "findAvailSpellCheckerLocked suitableLocales="
402 + Arrays.toString(suitableLocales.toArray(new Locale[suitableLocales.size()])));
404 final int localeCount = suitableLocales.size();
405 for (int localeIndex = 0; localeIndex < localeCount; ++localeIndex) {
406 final Locale locale = suitableLocales.get(localeIndex);
407 for (int spellCheckersIndex = 0; spellCheckersIndex < spellCheckersCount;
408 ++spellCheckersIndex) {
409 final SpellCheckerInfo info = mSpellCheckerList.get(spellCheckersIndex);
410 final int subtypeCount = info.getSubtypeCount();
411 for (int subtypeIndex = 0; subtypeIndex < subtypeCount; ++subtypeIndex) {
412 final SpellCheckerSubtype subtype = info.getSubtypeAt(subtypeIndex);
413 final Locale subtypeLocale = InputMethodUtils.constructLocaleFromString(
414 subtype.getLocale());
415 if (locale.equals(subtypeLocale)) {
416 // TODO: We may have more spell checkers that fall into this category.
417 // Ideally we should pick up the most suitable one instead of simply
418 // returning the first found one.
425 if (spellCheckersCount > 1) {
426 Slog.w(TAG, "more than one spell checker service found, picking first");
428 return mSpellCheckerList.get(0);
431 // TODO: Save SpellCheckerService by supported languages. Currently only one spell
434 public SpellCheckerInfo getCurrentSpellChecker(String locale) {
435 // TODO: Make this work even for non-current users?
436 if (!calledFromValidUser()) {
439 return getCurrentSpellCheckerWithoutVerification();
442 private SpellCheckerInfo getCurrentSpellCheckerWithoutVerification() {
443 synchronized (mSpellCheckerMap) {
444 final String curSpellCheckerId = mSettings.getSelectedSpellChecker();
446 Slog.w(TAG, "getCurrentSpellChecker: " + curSpellCheckerId);
448 if (TextUtils.isEmpty(curSpellCheckerId)) {
451 return mSpellCheckerMap.get(curSpellCheckerId);
455 // TODO: Respect allowImplicitlySelectedSubtype
456 // TODO: Save SpellCheckerSubtype by supported languages by looking at "locale".
458 public SpellCheckerSubtype getCurrentSpellCheckerSubtype(
459 String locale, boolean allowImplicitlySelectedSubtype) {
460 // TODO: Make this work even for non-current users?
461 if (!calledFromValidUser()) {
464 final int subtypeHashCode;
465 final SpellCheckerInfo sci;
466 final Locale systemLocale;
467 synchronized (mSpellCheckerMap) {
469 mSettings.getSelectedSpellCheckerSubtype(SpellCheckerSubtype.SUBTYPE_ID_NONE);
471 Slog.w(TAG, "getCurrentSpellCheckerSubtype: " + subtypeHashCode);
473 sci = getCurrentSpellChecker(null);
474 systemLocale = mContext.getResources().getConfiguration().locale;
476 if (sci == null || sci.getSubtypeCount() == 0) {
478 Slog.w(TAG, "Subtype not found.");
482 if (subtypeHashCode == SpellCheckerSubtype.SUBTYPE_ID_NONE
483 && !allowImplicitlySelectedSubtype) {
486 String candidateLocale = null;
487 if (subtypeHashCode == 0) {
488 // Spell checker language settings == "auto"
489 final InputMethodManager imm = mContext.getSystemService(InputMethodManager.class);
491 final InputMethodSubtype currentInputMethodSubtype =
492 imm.getCurrentInputMethodSubtype();
493 if (currentInputMethodSubtype != null) {
494 final String localeString = currentInputMethodSubtype.getLocale();
495 if (!TextUtils.isEmpty(localeString)) {
496 // 1. Use keyboard locale if available in the spell checker
497 candidateLocale = localeString;
501 if (candidateLocale == null) {
502 // 2. Use System locale if available in the spell checker
503 candidateLocale = systemLocale.toString();
506 SpellCheckerSubtype candidate = null;
507 for (int i = 0; i < sci.getSubtypeCount(); ++i) {
508 final SpellCheckerSubtype scs = sci.getSubtypeAt(i);
509 if (subtypeHashCode == 0) {
510 final String scsLocale = scs.getLocale();
511 if (candidateLocale.equals(scsLocale)) {
513 } else if (candidate == null) {
514 if (candidateLocale.length() >= 2 && scsLocale.length() >= 2
515 && candidateLocale.startsWith(scsLocale)) {
516 // Fall back to the applicable language
520 } else if (scs.hashCode() == subtypeHashCode) {
522 Slog.w(TAG, "Return subtype " + scs.hashCode() + ", input= " + locale
523 + ", " + scs.getLocale());
525 // 3. Use the user specified spell check language
529 // 4. Fall back to the applicable language and return it if not null
530 // 5. Simply just return it even if it's null which means we could find no suitable
531 // spell check languages
536 public void getSpellCheckerService(String sciId, String locale,
537 ITextServicesSessionListener tsListener, ISpellCheckerSessionListener scListener,
539 if (!calledFromValidUser()) {
545 if (TextUtils.isEmpty(sciId) || tsListener == null || scListener == null) {
546 Slog.e(TAG, "getSpellCheckerService: Invalid input.");
549 synchronized(mSpellCheckerMap) {
550 if (!mSpellCheckerMap.containsKey(sciId)) {
553 final SpellCheckerInfo sci = mSpellCheckerMap.get(sciId);
554 SpellCheckerBindGroup bindGroup = mSpellCheckerBindGroups.get(sciId);
555 final int uid = Binder.getCallingUid();
556 if (bindGroup == null) {
557 final long ident = Binder.clearCallingIdentity();
559 bindGroup = startSpellCheckerServiceInnerLocked(sci);
561 Binder.restoreCallingIdentity(ident);
563 if (bindGroup == null) {
564 // startSpellCheckerServiceInnerLocked failed.
569 // Start getISpellCheckerSession async IPC, or just queue the request until the spell
570 // checker service is bound.
571 bindGroup.getISpellCheckerSessionOrQueueLocked(
572 new SessionRequest(uid, locale, tsListener, scListener, bundle));
577 public boolean isSpellCheckerEnabled() {
578 if (!calledFromValidUser()) {
581 synchronized(mSpellCheckerMap) {
582 return isSpellCheckerEnabledLocked();
587 private SpellCheckerBindGroup startSpellCheckerServiceInnerLocked(SpellCheckerInfo info) {
589 Slog.w(TAG, "Start spell checker session inner locked.");
591 final String sciId = info.getId();
592 final InternalServiceConnection connection = new InternalServiceConnection(sciId);
593 final Intent serviceIntent = new Intent(SpellCheckerService.SERVICE_INTERFACE);
594 serviceIntent.setComponent(info.getComponent());
596 Slog.w(TAG, "bind service: " + info.getId());
598 if (!bindCurrentSpellCheckerService(serviceIntent, connection,
599 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE_WHILE_AWAKE)) {
600 Slog.e(TAG, "Failed to get a spell checker service.");
603 final SpellCheckerBindGroup group = new SpellCheckerBindGroup(connection);
604 mSpellCheckerBindGroups.put(sciId, group);
609 public SpellCheckerInfo[] getEnabledSpellCheckers() {
610 // TODO: Make this work even for non-current users?
611 if (!calledFromValidUser()) {
615 Slog.d(TAG, "getEnabledSpellCheckers: " + mSpellCheckerList.size());
616 for (int i = 0; i < mSpellCheckerList.size(); ++i) {
617 Slog.d(TAG, "EnabledSpellCheckers: " + mSpellCheckerList.get(i).getPackageName());
620 return mSpellCheckerList.toArray(new SpellCheckerInfo[mSpellCheckerList.size()]);
624 public void finishSpellCheckerService(ISpellCheckerSessionListener listener) {
625 if (!calledFromValidUser()) {
629 Slog.d(TAG, "FinishSpellCheckerService");
631 synchronized(mSpellCheckerMap) {
632 final ArrayList<SpellCheckerBindGroup> removeList = new ArrayList<>();
633 for (SpellCheckerBindGroup group : mSpellCheckerBindGroups.values()) {
634 if (group == null) continue;
635 // Use removeList to avoid modifying mSpellCheckerBindGroups in this loop.
636 removeList.add(group);
638 final int removeSize = removeList.size();
639 for (int i = 0; i < removeSize; ++i) {
640 removeList.get(i).removeListener(listener);
646 public void setCurrentSpellChecker(String locale, String sciId) {
647 if (!calledFromValidUser()) {
650 synchronized(mSpellCheckerMap) {
651 if (mContext.checkCallingOrSelfPermission(
652 android.Manifest.permission.WRITE_SECURE_SETTINGS)
653 != PackageManager.PERMISSION_GRANTED) {
654 throw new SecurityException(
655 "Requires permission "
656 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
658 setCurrentSpellCheckerLocked(sciId);
663 public void setCurrentSpellCheckerSubtype(String locale, int hashCode) {
664 if (!calledFromValidUser()) {
667 synchronized(mSpellCheckerMap) {
668 if (mContext.checkCallingOrSelfPermission(
669 android.Manifest.permission.WRITE_SECURE_SETTINGS)
670 != PackageManager.PERMISSION_GRANTED) {
671 throw new SecurityException(
672 "Requires permission "
673 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
675 setCurrentSpellCheckerSubtypeLocked(hashCode);
680 public void setSpellCheckerEnabled(boolean enabled) {
681 if (!calledFromValidUser()) {
684 synchronized(mSpellCheckerMap) {
685 if (mContext.checkCallingOrSelfPermission(
686 android.Manifest.permission.WRITE_SECURE_SETTINGS)
687 != PackageManager.PERMISSION_GRANTED) {
688 throw new SecurityException(
689 "Requires permission "
690 + android.Manifest.permission.WRITE_SECURE_SETTINGS);
692 setSpellCheckerEnabledLocked(enabled);
696 private void setCurrentSpellCheckerLocked(String sciId) {
698 Slog.w(TAG, "setCurrentSpellChecker: " + sciId);
700 if (TextUtils.isEmpty(sciId) || !mSpellCheckerMap.containsKey(sciId)) return;
701 final SpellCheckerInfo currentSci = getCurrentSpellChecker(null);
702 if (currentSci != null && currentSci.getId().equals(sciId)) {
703 // Do nothing if the current spell checker is same as new spell checker.
706 final long ident = Binder.clearCallingIdentity();
708 mSettings.putSelectedSpellChecker(sciId);
709 setCurrentSpellCheckerSubtypeLocked(0);
711 Binder.restoreCallingIdentity(ident);
715 private void setCurrentSpellCheckerSubtypeLocked(int hashCode) {
717 Slog.w(TAG, "setCurrentSpellCheckerSubtype: " + hashCode);
719 final SpellCheckerInfo sci = getCurrentSpellChecker(null);
720 int tempHashCode = 0;
721 for (int i = 0; sci != null && i < sci.getSubtypeCount(); ++i) {
722 if(sci.getSubtypeAt(i).hashCode() == hashCode) {
723 tempHashCode = hashCode;
727 final long ident = Binder.clearCallingIdentity();
729 mSettings.putSelectedSpellCheckerSubtype(tempHashCode);
731 Binder.restoreCallingIdentity(ident);
735 private void setSpellCheckerEnabledLocked(boolean enabled) {
737 Slog.w(TAG, "setSpellCheckerEnabled: " + enabled);
739 final long ident = Binder.clearCallingIdentity();
741 mSettings.setSpellCheckerEnabled(enabled);
743 Binder.restoreCallingIdentity(ident);
747 private boolean isSpellCheckerEnabledLocked() {
748 final long ident = Binder.clearCallingIdentity();
750 final boolean retval = mSettings.isSpellCheckerEnabled();
752 Slog.w(TAG, "getSpellCheckerEnabled: " + retval);
756 Binder.restoreCallingIdentity(ident);
761 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
762 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
764 synchronized(mSpellCheckerMap) {
765 pw.println("Current Text Services Manager state:");
766 pw.println(" Spell Checkers:");
767 int spellCheckerIndex = 0;
768 for (final SpellCheckerInfo info : mSpellCheckerMap.values()) {
769 pw.println(" Spell Checker #" + spellCheckerIndex);
774 pw.println(" Spell Checker Bind Groups:");
775 for (final Map.Entry<String, SpellCheckerBindGroup> ent
776 : mSpellCheckerBindGroups.entrySet()) {
777 final SpellCheckerBindGroup grp = ent.getValue();
778 pw.println(" " + ent.getKey() + " " + grp + ":");
779 pw.println(" " + "mInternalConnection=" + grp.mInternalConnection);
780 pw.println(" " + "mSpellChecker=" + grp.mSpellChecker);
781 pw.println(" " + "mUnbindCalled=" + grp.mUnbindCalled);
782 pw.println(" " + "mConnected=" + grp.mConnected);
783 final int numPendingSessionRequests = grp.mPendingSessionRequests.size();
784 for (int i = 0; i < numPendingSessionRequests; i++) {
785 final SessionRequest req = grp.mPendingSessionRequests.get(i);
786 pw.println(" " + "Pending Request #" + i + ":");
787 pw.println(" " + "mTsListener=" + req.mTsListener);
788 pw.println(" " + "mScListener=" + req.mScListener);
789 pw.println(" " + "mScLocale=" + req.mLocale + " mUid=" + req.mUserId);
791 final int numOnGoingSessionRequests = grp.mOnGoingSessionRequests.size();
792 for (int i = 0; i < numOnGoingSessionRequests; i++) {
793 final SessionRequest req = grp.mOnGoingSessionRequests.get(i);
794 pw.println(" " + "On going Request #" + i + ":");
796 pw.println(" " + "mTsListener=" + req.mTsListener);
797 pw.println(" " + "mScListener=" + req.mScListener);
799 " " + "mScLocale=" + req.mLocale + " mUid=" + req.mUserId);
801 final int N = grp.mListeners.getRegisteredCallbackCount();
802 for (int i = 0; i < N; i++) {
803 final ISpellCheckerSessionListener mScListener =
804 grp.mListeners.getRegisteredCallbackItem(i);
805 pw.println(" " + "Listener #" + i + ":");
806 pw.println(" " + "mScListener=" + mScListener);
807 pw.println(" " + "mGroup=" + grp);
811 pw.println(" mSettings:");
812 mSettings.dumpLocked(pw, " ");
816 private static final class SessionRequest {
818 public final int mUserId;
820 public final String mLocale;
822 public final ITextServicesSessionListener mTsListener;
824 public final ISpellCheckerSessionListener mScListener;
826 public final Bundle mBundle;
828 SessionRequest(@UserIdInt final int userId, @Nullable String locale,
829 @NonNull ITextServicesSessionListener tsListener,
830 @NonNull ISpellCheckerSessionListener scListener, @Nullable Bundle bundle) {
833 mTsListener = tsListener;
834 mScListener = scListener;
839 // SpellCheckerBindGroup contains active text service session listeners.
840 // If there are no listeners anymore, the SpellCheckerBindGroup instance will be removed from
841 // mSpellCheckerBindGroups
842 private final class SpellCheckerBindGroup {
843 private final String TAG = SpellCheckerBindGroup.class.getSimpleName();
844 private final InternalServiceConnection mInternalConnection;
845 private final InternalDeathRecipients mListeners;
846 private boolean mUnbindCalled;
847 private ISpellCheckerService mSpellChecker;
848 private boolean mConnected;
849 private final ArrayList<SessionRequest> mPendingSessionRequests = new ArrayList<>();
850 private final ArrayList<SessionRequest> mOnGoingSessionRequests = new ArrayList<>();
852 public SpellCheckerBindGroup(InternalServiceConnection connection) {
853 mInternalConnection = connection;
854 mListeners = new InternalDeathRecipients(this);
857 public void onServiceConnected(ISpellCheckerService spellChecker) {
859 Slog.d(TAG, "onServiceConnected");
862 synchronized(mSpellCheckerMap) {
863 mSpellChecker = spellChecker;
865 // Dispatch pending getISpellCheckerSession requests.
866 mPendingSessionRequests.forEach(this::getISpellCheckerSessionLocked);
867 mPendingSessionRequests.clear();
871 public void onServiceDisconnected() {
873 Slog.d(TAG, "onServiceDisconnected");
876 synchronized(mSpellCheckerMap) {
877 mSpellChecker = null;
882 public void removeListener(ISpellCheckerSessionListener listener) {
884 Slog.w(TAG, "remove listener: " + listener.hashCode());
886 synchronized(mSpellCheckerMap) {
887 mListeners.unregister(listener);
892 // cleanLocked may remove elements from mSpellCheckerBindGroups
893 private void cleanLocked() {
895 Slog.d(TAG, "cleanLocked");
900 // If there are no more active listeners, clean up. Only do this once.
901 if (mListeners.getRegisteredCallbackCount() > 0) {
904 if (!mPendingSessionRequests.isEmpty()) {
907 if (!mOnGoingSessionRequests.isEmpty()) {
910 final String sciId = mInternalConnection.mSciId;
911 final SpellCheckerBindGroup cur = mSpellCheckerBindGroups.get(sciId);
914 Slog.d(TAG, "Remove bind group.");
916 mSpellCheckerBindGroups.remove(sciId);
918 mContext.unbindService(mInternalConnection);
919 mUnbindCalled = true;
922 public void removeAll() {
923 Slog.e(TAG, "Remove the spell checker bind unexpectedly.");
924 synchronized(mSpellCheckerMap) {
925 final int size = mListeners.getRegisteredCallbackCount();
926 for (int i = 0; i < size; ++i) {
927 mListeners.unregister(mListeners.getRegisteredCallbackItem(i));
929 mPendingSessionRequests.clear();
930 mOnGoingSessionRequests.clear();
935 public void getISpellCheckerSessionOrQueueLocked(@NonNull SessionRequest request) {
940 mPendingSessionRequests.add(request);
943 getISpellCheckerSessionLocked(request);
946 private void getISpellCheckerSessionLocked(@NonNull SessionRequest request) {
951 mSpellChecker.getISpellCheckerSession(
952 request.mLocale, request.mScListener, request.mBundle,
953 new ISpellCheckerServiceCallbackBinder(this, request));
954 mOnGoingSessionRequests.add(request);
955 } catch(RemoteException e) {
956 // The target spell checker service is not available. Better to reset the state.
962 void onSessionCreated(@Nullable final ISpellCheckerSession newSession,
963 @NonNull final SessionRequest request) {
964 synchronized (mSpellCheckerMap) {
968 if (mOnGoingSessionRequests.remove(request)) {
970 request.mTsListener.onServiceConnected(newSession);
971 mListeners.register(request.mScListener);
972 } catch (RemoteException e) {
973 // Technically this can happen if the spell checker client app is already
974 // dead. We can just forget about this request; the request is already
975 // removed from mOnGoingSessionRequests and the death recipient listener is
976 // not yet added to mListeners. There is nothing to release further.
984 private final class InternalServiceConnection implements ServiceConnection {
985 private final String mSciId;
986 public InternalServiceConnection(String id) {
991 public void onServiceConnected(ComponentName name, IBinder service) {
992 synchronized(mSpellCheckerMap) {
993 onServiceConnectedInnerLocked(name, service);
997 private void onServiceConnectedInnerLocked(ComponentName name, IBinder service) {
999 Slog.w(TAG, "onServiceConnected: " + name);
1001 final ISpellCheckerService spellChecker =
1002 ISpellCheckerService.Stub.asInterface(service);
1003 final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId);
1004 if (group != null && this == group.mInternalConnection) {
1005 group.onServiceConnected(spellChecker);
1010 public void onServiceDisconnected(ComponentName name) {
1011 synchronized(mSpellCheckerMap) {
1012 onServiceDisconnectedInnerLocked(name);
1016 private void onServiceDisconnectedInnerLocked(ComponentName name) {
1018 Slog.w(TAG, "onServiceDisconnected: " + name);
1020 final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId);
1021 if (group != null && this == group.mInternalConnection) {
1022 group.onServiceDisconnected();
1027 private static final class InternalDeathRecipients extends
1028 RemoteCallbackList<ISpellCheckerSessionListener> {
1029 private final SpellCheckerBindGroup mGroup;
1031 public InternalDeathRecipients(SpellCheckerBindGroup group) {
1036 public void onCallbackDied(ISpellCheckerSessionListener listener) {
1037 mGroup.removeListener(listener);
1041 private static final class ISpellCheckerServiceCallbackBinder
1042 extends ISpellCheckerServiceCallback.Stub {
1044 private final SpellCheckerBindGroup mBindGroup;
1046 private final SessionRequest mRequest;
1048 ISpellCheckerServiceCallbackBinder(@NonNull final SpellCheckerBindGroup bindGroup,
1049 @NonNull final SessionRequest request) {
1050 mBindGroup = bindGroup;
1055 public void onSessionCreated(@Nullable ISpellCheckerSession newSession) {
1056 mBindGroup.onSessionCreated(newSession, mRequest);
1060 private static final class TextServicesSettings {
1061 private final ContentResolver mResolver;
1063 private int mCurrentUserId;
1065 private int[] mCurrentProfileIds = new int[0];
1066 private Object mLock = new Object();
1069 * On-memory data store to emulate when {@link #mCopyOnWrite} is {@code true}.
1071 private final HashMap<String, String> mCopyOnWriteDataStore = new HashMap<>();
1072 private boolean mCopyOnWrite = false;
1074 public TextServicesSettings(ContentResolver resolver, @UserIdInt int userId,
1075 boolean copyOnWrite) {
1076 mResolver = resolver;
1077 switchCurrentUser(userId, copyOnWrite);
1081 * Must be called when the current user is changed.
1083 * @param userId The user ID.
1084 * @param copyOnWrite If {@code true}, for each settings key
1085 * (e.g. {@link Settings.Secure#SELECTED_SPELL_CHECKER}) we use the actual settings on the
1086 * {@link Settings.Secure} until we do the first write operation.
1088 public void switchCurrentUser(@UserIdInt int userId, boolean copyOnWrite) {
1090 Slog.d(TAG, "--- Swtich the current user from " + mCurrentUserId + " to "
1091 + userId + ", new ime = " + getSelectedSpellChecker());
1093 if (mCurrentUserId != userId || mCopyOnWrite != copyOnWrite) {
1094 mCopyOnWriteDataStore.clear();
1095 // TODO: mCurrentProfileIds should be cleared here.
1097 // TSMS settings are kept per user, so keep track of current user
1098 mCurrentUserId = userId;
1099 mCopyOnWrite = copyOnWrite;
1100 // TODO: mCurrentProfileIds should be updated here.
1103 private void putString(final String key, final String str) {
1105 mCopyOnWriteDataStore.put(key, str);
1107 Settings.Secure.putStringForUser(mResolver, key, str, mCurrentUserId);
1112 private String getString(@NonNull final String key, @Nullable final String defaultValue) {
1113 final String result;
1114 if (mCopyOnWrite && mCopyOnWriteDataStore.containsKey(key)) {
1115 result = mCopyOnWriteDataStore.get(key);
1117 result = Settings.Secure.getStringForUser(mResolver, key, mCurrentUserId);
1119 return result != null ? result : defaultValue;
1122 private void putInt(final String key, final int value) {
1124 mCopyOnWriteDataStore.put(key, String.valueOf(value));
1126 Settings.Secure.putIntForUser(mResolver, key, value, mCurrentUserId);
1130 private int getInt(final String key, final int defaultValue) {
1131 if (mCopyOnWrite && mCopyOnWriteDataStore.containsKey(key)) {
1132 final String result = mCopyOnWriteDataStore.get(key);
1133 return result != null ? Integer.parseInt(result) : 0;
1135 return Settings.Secure.getIntForUser(mResolver, key, defaultValue, mCurrentUserId);
1138 private void putBoolean(final String key, final boolean value) {
1139 putInt(key, value ? 1 : 0);
1142 private boolean getBoolean(final String key, final boolean defaultValue) {
1143 return getInt(key, defaultValue ? 1 : 0) == 1;
1146 public void setCurrentProfileIds(int[] currentProfileIds) {
1147 synchronized (mLock) {
1148 mCurrentProfileIds = currentProfileIds;
1152 public boolean isCurrentProfile(@UserIdInt int userId) {
1153 synchronized (mLock) {
1154 if (userId == mCurrentUserId) return true;
1155 for (int i = 0; i < mCurrentProfileIds.length; i++) {
1156 if (userId == mCurrentProfileIds[i]) return true;
1163 public int getCurrentUserId() {
1164 return mCurrentUserId;
1167 public void putSelectedSpellChecker(@Nullable String sciId) {
1168 if (TextUtils.isEmpty(sciId)) {
1169 // OK to coalesce to null, since getSelectedSpellChecker() can take care of the
1170 // empty data scenario.
1171 putString(Settings.Secure.SELECTED_SPELL_CHECKER, null);
1173 putString(Settings.Secure.SELECTED_SPELL_CHECKER, sciId);
1177 public void putSelectedSpellCheckerSubtype(int hashCode) {
1178 putInt(Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE, hashCode);
1181 public void setSpellCheckerEnabled(boolean enabled) {
1182 putBoolean(Settings.Secure.SPELL_CHECKER_ENABLED, enabled);
1186 public String getSelectedSpellChecker() {
1187 return getString(Settings.Secure.SELECTED_SPELL_CHECKER, "");
1190 public int getSelectedSpellCheckerSubtype(final int defaultValue) {
1191 return getInt(Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE, defaultValue);
1194 public boolean isSpellCheckerEnabled() {
1195 return getBoolean(Settings.Secure.SPELL_CHECKER_ENABLED, true);
1198 public void dumpLocked(final PrintWriter pw, final String prefix) {
1199 pw.println(prefix + "mCurrentUserId=" + mCurrentUserId);
1200 pw.println(prefix + "mCurrentProfileIds=" + Arrays.toString(mCurrentProfileIds));
1201 pw.println(prefix + "mCopyOnWrite=" + mCopyOnWrite);
1205 // ----------------------------------------------------------------------
1206 // Utilities for debug
1207 private static String getStackTrace() {
1208 final StringBuilder sb = new StringBuilder();
1210 throw new RuntimeException();
1211 } catch (RuntimeException e) {
1212 final StackTraceElement[] frames = e.getStackTrace();
1213 // Start at 1 because the first frame is here and we don't care about it
1214 for (int j = 1; j < frames.length; ++j) {
1215 sb.append(frames[j].toString() + "\n");
1218 return sb.toString();