OSDN Git Service

Remove a redundant synchronized block
[android-x86/frameworks-base.git] / services / core / java / com / android / server / TextServicesManagerService.java
1 /*
2  * Copyright (C) 2011 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.android.server;
18
19 import com.android.internal.annotations.GuardedBy;
20 import com.android.internal.content.PackageMonitor;
21 import com.android.internal.inputmethod.InputMethodUtils;
22 import com.android.internal.textservice.ISpellCheckerService;
23 import com.android.internal.textservice.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;
29
30 import org.xmlpull.v1.XmlPullParserException;
31
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;
64
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;
73 import java.util.Map;
74
75 public class TextServicesManagerService extends ITextServicesManager.Stub {
76     private static final String TAG = TextServicesManagerService.class.getSimpleName();
77     private static final boolean DBG = false;
78
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;
86     @NonNull
87     private final UserManager mUserManager;
88
89     public static final class Lifecycle extends SystemService {
90         private TextServicesManagerService mService;
91
92         public Lifecycle(Context context) {
93             super(context);
94             mService = new TextServicesManagerService(context);
95         }
96
97         @Override
98         public void onStart() {
99             publishBinderService(Context.TEXT_SERVICES_MANAGER_SERVICE, mService);
100         }
101
102         @Override
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);
107         }
108
109         @Override
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();
115             }
116         }
117
118         @Override
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);
123         }
124     }
125
126     void systemRunning() {
127         synchronized (mSpellCheckerMap) {
128             if (!mSystemReady) {
129                 mSystemReady = true;
130                 resetInternalState(mSettings.getCurrentUserId());
131             }
132         }
133     }
134
135     void onSwitchUser(@UserIdInt int userId) {
136         synchronized (mSpellCheckerMap) {
137             resetInternalState(userId);
138         }
139     }
140
141     void onUnlockUser(@UserIdInt int userId) {
142         synchronized(mSpellCheckerMap) {
143             final int currentUserId = mSettings.getCurrentUserId();
144             if (userId != currentUserId) {
145                 return;
146             }
147             resetInternalState(currentUserId);
148         }
149     }
150
151     public TextServicesManagerService(Context context) {
152         mSystemReady = false;
153         mContext = context;
154
155         mUserManager = mContext.getSystemService(UserManager.class);
156
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);
161
162         int userId = UserHandle.USER_SYSTEM;
163         try {
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);
167         }
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);
174
175         // "resetInternalState" initializes the states for the foreground user
176         resetInternalState(userId);
177     }
178
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);
187         if (sci == null) {
188             sci = findAvailSpellCheckerLocked(null);
189             if (sci != 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
192                 // checkers.
193                 setCurrentSpellCheckerLocked(sci.getId());
194             }
195         }
196     }
197
198     void updateCurrentProfileIds() {
199         mSettings.setCurrentProfileIds(
200                 mUserManager.getProfileIdsWithDisabled(mSettings.getCurrentUserId()));
201     }
202
203     private final class TextServicesMonitor extends PackageMonitor {
204         private boolean isChangingPackagesOfCurrentUser() {
205             final int userId = getChangingUserId();
206             final boolean retval = userId == mSettings.getCurrentUserId();
207             if (DBG) {
208                 Slog.d(TAG, "--- ignore this call back from a background user: " + userId);
209             }
210             return retval;
211         }
212
213         @Override
214         public void onSomePackagesChanged() {
215             if (!isChangingPackagesOfCurrentUser()) {
216                 return;
217             }
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
230                         // Package modified
231                         || isPackageModified(packageName)) {
232                     sci = findAvailSpellCheckerLocked(packageName);
233                     if (sci != null) {
234                         setCurrentSpellCheckerLocked(sci.getId());
235                     }
236                 }
237             }
238         }
239     }
240
241     private final class TextServicesBroadcastReceiver extends BroadcastReceiver {
242         @Override
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();
248                 return;
249             }
250             Slog.w(TAG, "Unexpected intent " + intent);
251         }
252     }
253
254     private static void buildSpellCheckerMapLocked(Context context,
255             ArrayList<SpellCheckerInfo> list, HashMap<String, SpellCheckerInfo> map,
256             TextServicesSettings settings) {
257         list.clear();
258         map.clear();
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);
275                 continue;
276             }
277             if (DBG) Slog.d(TAG, "Add: " + compName);
278             try {
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.");
283                     continue;
284                 }
285                 list.add(sci);
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);
291             }
292         }
293         if (DBG) {
294             Slog.d(TAG, "buildSpellCheckerMapLocked: " + list.size() + "," + map.size());
295         }
296     }
297
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);
305         if (DBG) {
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());
310             try {
311                 final String[] packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
312                 for (int i = 0; i < packageNames.length; ++i) {
313                     if (DBG) {
314                         Slog.d(TAG, "--- process name for "+ uid + " = " + packageNames[i]);
315                     }
316                 }
317             } catch (RemoteException e) {
318             }
319         }
320
321         if (uid == Process.SYSTEM_UID || userId == mSettings.getCurrentUserId()) {
322             return true;
323         }
324
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
327         // support.
328         // TODO: Implement multiuser support in TSMS.
329         final boolean isCurrentProfile = mSettings.isCurrentProfile(userId);
330         if (DBG) {
331             Slog.d(TAG, "--- userId = "+ userId + " isCurrentProfile = " + isCurrentProfile);
332         }
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;
339                 if (DBG) {
340                     Slog.d(TAG, "--- current spell checker = "+ spellCheckerInfo.getPackageName()
341                             + " isSystem = " + isSystemSpellChecker);
342                 }
343                 if (isSystemSpellChecker) {
344                     return true;
345                 }
346             }
347         }
348
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.
352         if (DBG) {
353             Slog.d(TAG, "--- IPC from userId:" + userId + " is being ignored. \n"
354                     + getStackTrace());
355         }
356         return false;
357     }
358
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);
363             return false;
364         }
365         return mContext.bindServiceAsUser(service, conn, flags,
366                 new UserHandle(mSettings.getCurrentUserId()));
367     }
368
369     private void unbindServiceLocked() {
370         for (SpellCheckerBindGroup scbg : mSpellCheckerBindGroups.values()) {
371             scbg.removeAll();
372         }
373         mSpellCheckerBindGroups.clear();
374     }
375
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");
380             return null;
381         }
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())) {
386                     if (DBG) {
387                         Slog.d(TAG, "findAvailSpellCheckerLocked: " + sci.getPackageName());
388                     }
389                     return sci;
390                 }
391             }
392         }
393
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);
400         if (DBG) {
401             Slog.w(TAG, "findAvailSpellCheckerLocked suitableLocales="
402                     + Arrays.toString(suitableLocales.toArray(new Locale[suitableLocales.size()])));
403         }
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.
419                         return info;
420                     }
421                 }
422             }
423         }
424
425         if (spellCheckersCount > 1) {
426             Slog.w(TAG, "more than one spell checker service found, picking first");
427         }
428         return mSpellCheckerList.get(0);
429     }
430
431     // TODO: Save SpellCheckerService by supported languages. Currently only one spell
432     // checker is saved.
433     @Override
434     public SpellCheckerInfo getCurrentSpellChecker(String locale) {
435         // TODO: Make this work even for non-current users?
436         if (!calledFromValidUser()) {
437             return null;
438         }
439         return getCurrentSpellCheckerWithoutVerification();
440     }
441
442     private SpellCheckerInfo getCurrentSpellCheckerWithoutVerification() {
443         synchronized (mSpellCheckerMap) {
444             final String curSpellCheckerId = mSettings.getSelectedSpellChecker();
445             if (DBG) {
446                 Slog.w(TAG, "getCurrentSpellChecker: " + curSpellCheckerId);
447             }
448             if (TextUtils.isEmpty(curSpellCheckerId)) {
449                 return null;
450             }
451             return mSpellCheckerMap.get(curSpellCheckerId);
452         }
453     }
454
455     // TODO: Respect allowImplicitlySelectedSubtype
456     // TODO: Save SpellCheckerSubtype by supported languages by looking at "locale".
457     @Override
458     public SpellCheckerSubtype getCurrentSpellCheckerSubtype(
459             String locale, boolean allowImplicitlySelectedSubtype) {
460         // TODO: Make this work even for non-current users?
461         if (!calledFromValidUser()) {
462             return null;
463         }
464         final int subtypeHashCode;
465         final SpellCheckerInfo sci;
466         final Locale systemLocale;
467         synchronized (mSpellCheckerMap) {
468             subtypeHashCode =
469                     mSettings.getSelectedSpellCheckerSubtype(SpellCheckerSubtype.SUBTYPE_ID_NONE);
470             if (DBG) {
471                 Slog.w(TAG, "getCurrentSpellCheckerSubtype: " + subtypeHashCode);
472             }
473             sci = getCurrentSpellChecker(null);
474             systemLocale = mContext.getResources().getConfiguration().locale;
475         }
476         if (sci == null || sci.getSubtypeCount() == 0) {
477             if (DBG) {
478                 Slog.w(TAG, "Subtype not found.");
479             }
480             return null;
481         }
482         if (subtypeHashCode == SpellCheckerSubtype.SUBTYPE_ID_NONE
483                 && !allowImplicitlySelectedSubtype) {
484             return null;
485         }
486         String candidateLocale = null;
487         if (subtypeHashCode == 0) {
488             // Spell checker language settings == "auto"
489             final InputMethodManager imm = mContext.getSystemService(InputMethodManager.class);
490             if (imm != null) {
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;
498                     }
499                 }
500             }
501             if (candidateLocale == null) {
502                 // 2. Use System locale if available in the spell checker
503                 candidateLocale = systemLocale.toString();
504             }
505         }
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)) {
512                     return scs;
513                 } else if (candidate == null) {
514                     if (candidateLocale.length() >= 2 && scsLocale.length() >= 2
515                             && candidateLocale.startsWith(scsLocale)) {
516                         // Fall back to the applicable language
517                         candidate = scs;
518                     }
519                 }
520             } else if (scs.hashCode() == subtypeHashCode) {
521                 if (DBG) {
522                     Slog.w(TAG, "Return subtype " + scs.hashCode() + ", input= " + locale
523                             + ", " + scs.getLocale());
524                 }
525                 // 3. Use the user specified spell check language
526                 return scs;
527             }
528         }
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
532         return candidate;
533     }
534
535     @Override
536     public void getSpellCheckerService(String sciId, String locale,
537             ITextServicesSessionListener tsListener, ISpellCheckerSessionListener scListener,
538             Bundle bundle) {
539         if (!calledFromValidUser()) {
540             return;
541         }
542         if (!mSystemReady) {
543             return;
544         }
545         if (TextUtils.isEmpty(sciId) || tsListener == null || scListener == null) {
546             Slog.e(TAG, "getSpellCheckerService: Invalid input.");
547             return;
548         }
549         synchronized(mSpellCheckerMap) {
550             if (!mSpellCheckerMap.containsKey(sciId)) {
551                 return;
552             }
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();
558                 try {
559                     bindGroup = startSpellCheckerServiceInnerLocked(sci);
560                 } finally {
561                     Binder.restoreCallingIdentity(ident);
562                 }
563                 if (bindGroup == null) {
564                     // startSpellCheckerServiceInnerLocked failed.
565                     return;
566                 }
567             }
568
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));
573         }
574     }
575
576     @Override
577     public boolean isSpellCheckerEnabled() {
578         if (!calledFromValidUser()) {
579             return false;
580         }
581         synchronized(mSpellCheckerMap) {
582             return isSpellCheckerEnabledLocked();
583         }
584     }
585
586     @Nullable
587     private SpellCheckerBindGroup startSpellCheckerServiceInnerLocked(SpellCheckerInfo info) {
588         if (DBG) {
589             Slog.w(TAG, "Start spell checker session inner locked.");
590         }
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());
595         if (DBG) {
596             Slog.w(TAG, "bind service: " + info.getId());
597         }
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.");
601             return null;
602         }
603         final SpellCheckerBindGroup group = new SpellCheckerBindGroup(connection);
604         mSpellCheckerBindGroups.put(sciId, group);
605         return group;
606     }
607
608     @Override
609     public SpellCheckerInfo[] getEnabledSpellCheckers() {
610         // TODO: Make this work even for non-current users?
611         if (!calledFromValidUser()) {
612             return null;
613         }
614         if (DBG) {
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());
618             }
619         }
620         return mSpellCheckerList.toArray(new SpellCheckerInfo[mSpellCheckerList.size()]);
621     }
622
623     @Override
624     public void finishSpellCheckerService(ISpellCheckerSessionListener listener) {
625         if (!calledFromValidUser()) {
626             return;
627         }
628         if (DBG) {
629             Slog.d(TAG, "FinishSpellCheckerService");
630         }
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);
637             }
638             final int removeSize = removeList.size();
639             for (int i = 0; i < removeSize; ++i) {
640                 removeList.get(i).removeListener(listener);
641             }
642         }
643     }
644
645     @Override
646     public void setCurrentSpellChecker(String locale, String sciId) {
647         if (!calledFromValidUser()) {
648             return;
649         }
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);
657             }
658             setCurrentSpellCheckerLocked(sciId);
659         }
660     }
661
662     @Override
663     public void setCurrentSpellCheckerSubtype(String locale, int hashCode) {
664         if (!calledFromValidUser()) {
665             return;
666         }
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);
674             }
675             setCurrentSpellCheckerSubtypeLocked(hashCode);
676         }
677     }
678
679     @Override
680     public void setSpellCheckerEnabled(boolean enabled) {
681         if (!calledFromValidUser()) {
682             return;
683         }
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);
691             }
692             setSpellCheckerEnabledLocked(enabled);
693         }
694     }
695
696     private void setCurrentSpellCheckerLocked(String sciId) {
697         if (DBG) {
698             Slog.w(TAG, "setCurrentSpellChecker: " + sciId);
699         }
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.
704             return;
705         }
706         final long ident = Binder.clearCallingIdentity();
707         try {
708             mSettings.putSelectedSpellChecker(sciId);
709             setCurrentSpellCheckerSubtypeLocked(0);
710         } finally {
711             Binder.restoreCallingIdentity(ident);
712         }
713     }
714
715     private void setCurrentSpellCheckerSubtypeLocked(int hashCode) {
716         if (DBG) {
717             Slog.w(TAG, "setCurrentSpellCheckerSubtype: " + hashCode);
718         }
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;
724                 break;
725             }
726         }
727         final long ident = Binder.clearCallingIdentity();
728         try {
729             mSettings.putSelectedSpellCheckerSubtype(tempHashCode);
730         } finally {
731             Binder.restoreCallingIdentity(ident);
732         }
733     }
734
735     private void setSpellCheckerEnabledLocked(boolean enabled) {
736         if (DBG) {
737             Slog.w(TAG, "setSpellCheckerEnabled: " + enabled);
738         }
739         final long ident = Binder.clearCallingIdentity();
740         try {
741             mSettings.setSpellCheckerEnabled(enabled);
742         } finally {
743             Binder.restoreCallingIdentity(ident);
744         }
745     }
746
747     private boolean isSpellCheckerEnabledLocked() {
748         final long ident = Binder.clearCallingIdentity();
749         try {
750             final boolean retval = mSettings.isSpellCheckerEnabled();
751             if (DBG) {
752                 Slog.w(TAG, "getSpellCheckerEnabled: " + retval);
753             }
754             return retval;
755         } finally {
756             Binder.restoreCallingIdentity(ident);
757         }
758     }
759
760     @Override
761     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
762         if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
763
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);
770                 info.dump(pw, "    ");
771                 ++spellCheckerIndex;
772             }
773             pw.println("");
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);
790                 }
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 + ":");
795                     ++i;
796                     pw.println("        " + "mTsListener=" + req.mTsListener);
797                     pw.println("        " + "mScListener=" + req.mScListener);
798                     pw.println(
799                             "        " + "mScLocale=" + req.mLocale + " mUid=" + req.mUserId);
800                 }
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);
808                 }
809             }
810             pw.println("");
811             pw.println("  mSettings:");
812             mSettings.dumpLocked(pw, "    ");
813         }
814     }
815
816     private static final class SessionRequest {
817         @UserIdInt
818         public final int mUserId;
819         @Nullable
820         public final String mLocale;
821         @NonNull
822         public final ITextServicesSessionListener mTsListener;
823         @NonNull
824         public final ISpellCheckerSessionListener mScListener;
825         @Nullable
826         public final Bundle mBundle;
827
828         SessionRequest(@UserIdInt final int userId, @Nullable String locale,
829                 @NonNull ITextServicesSessionListener tsListener,
830                 @NonNull ISpellCheckerSessionListener scListener, @Nullable Bundle bundle) {
831             mUserId = userId;
832             mLocale = locale;
833             mTsListener = tsListener;
834             mScListener = scListener;
835             mBundle = bundle;
836         }
837     }
838
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<>();
851
852         public SpellCheckerBindGroup(InternalServiceConnection connection) {
853             mInternalConnection = connection;
854             mListeners = new InternalDeathRecipients(this);
855         }
856
857         public void onServiceConnected(ISpellCheckerService spellChecker) {
858             if (DBG) {
859                 Slog.d(TAG, "onServiceConnected");
860             }
861
862             synchronized(mSpellCheckerMap) {
863                 mSpellChecker = spellChecker;
864                 mConnected = true;
865                 // Dispatch pending getISpellCheckerSession requests.
866                 mPendingSessionRequests.forEach(this::getISpellCheckerSessionLocked);
867                 mPendingSessionRequests.clear();
868             }
869         }
870
871         public void onServiceDisconnected() {
872             if (DBG) {
873                 Slog.d(TAG, "onServiceDisconnected");
874             }
875
876             synchronized(mSpellCheckerMap) {
877                 mSpellChecker = null;
878                 mConnected = false;
879             }
880         }
881
882         public void removeListener(ISpellCheckerSessionListener listener) {
883             if (DBG) {
884                 Slog.w(TAG, "remove listener: " + listener.hashCode());
885             }
886             synchronized(mSpellCheckerMap) {
887                 mListeners.unregister(listener);
888                 cleanLocked();
889             }
890         }
891
892         // cleanLocked may remove elements from mSpellCheckerBindGroups
893         private void cleanLocked() {
894             if (DBG) {
895                 Slog.d(TAG, "cleanLocked");
896             }
897             if (mUnbindCalled) {
898                 return;
899             }
900             // If there are no more active listeners, clean up.  Only do this once.
901             if (mListeners.getRegisteredCallbackCount() > 0) {
902                 return;
903             }
904             if (!mPendingSessionRequests.isEmpty()) {
905                 return;
906             }
907             if (!mOnGoingSessionRequests.isEmpty()) {
908                 return;
909             }
910             final String sciId = mInternalConnection.mSciId;
911             final SpellCheckerBindGroup cur = mSpellCheckerBindGroups.get(sciId);
912             if (cur == this) {
913                 if (DBG) {
914                     Slog.d(TAG, "Remove bind group.");
915                 }
916                 mSpellCheckerBindGroups.remove(sciId);
917             }
918             mContext.unbindService(mInternalConnection);
919             mUnbindCalled = true;
920         }
921
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));
928                 }
929                 mPendingSessionRequests.clear();
930                 mOnGoingSessionRequests.clear();
931                 cleanLocked();
932             }
933         }
934
935         public void getISpellCheckerSessionOrQueueLocked(@NonNull SessionRequest request) {
936             if (mUnbindCalled) {
937                 return;
938             }
939             if (!mConnected) {
940                 mPendingSessionRequests.add(request);
941                 return;
942             }
943             getISpellCheckerSessionLocked(request);
944         }
945
946         private void getISpellCheckerSessionLocked(@NonNull SessionRequest request) {
947             if (mUnbindCalled) {
948                 return;
949             }
950             try {
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.
957                 removeAll();
958             }
959             cleanLocked();
960         }
961
962         void onSessionCreated(@Nullable final ISpellCheckerSession newSession,
963                 @NonNull final SessionRequest request) {
964             synchronized (mSpellCheckerMap) {
965                 if (mUnbindCalled) {
966                     return;
967                 }
968                 if (mOnGoingSessionRequests.remove(request)) {
969                     try {
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.
977                     }
978                 }
979                 cleanLocked();
980             }
981         }
982     }
983
984     private final class InternalServiceConnection implements ServiceConnection {
985         private final String mSciId;
986         public InternalServiceConnection(String id) {
987             mSciId = id;
988         }
989
990         @Override
991         public void onServiceConnected(ComponentName name, IBinder service) {
992             synchronized(mSpellCheckerMap) {
993                 onServiceConnectedInnerLocked(name, service);
994             }
995         }
996
997         private void onServiceConnectedInnerLocked(ComponentName name, IBinder service) {
998             if (DBG) {
999                 Slog.w(TAG, "onServiceConnected: " + name);
1000             }
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);
1006             }
1007         }
1008
1009         @Override
1010         public void onServiceDisconnected(ComponentName name) {
1011             synchronized(mSpellCheckerMap) {
1012                 onServiceDisconnectedInnerLocked(name);
1013             }
1014         }
1015
1016         private void onServiceDisconnectedInnerLocked(ComponentName name) {
1017             if (DBG) {
1018                 Slog.w(TAG, "onServiceDisconnected: " + name);
1019             }
1020             final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId);
1021             if (group != null && this == group.mInternalConnection) {
1022                 group.onServiceDisconnected();
1023             }
1024         }
1025     }
1026
1027     private static final class InternalDeathRecipients extends
1028             RemoteCallbackList<ISpellCheckerSessionListener> {
1029         private final SpellCheckerBindGroup mGroup;
1030
1031         public InternalDeathRecipients(SpellCheckerBindGroup group) {
1032             mGroup = group;
1033         }
1034
1035         @Override
1036         public void onCallbackDied(ISpellCheckerSessionListener listener) {
1037             mGroup.removeListener(listener);
1038         }
1039     }
1040
1041     private static final class ISpellCheckerServiceCallbackBinder
1042             extends ISpellCheckerServiceCallback.Stub {
1043         @NonNull
1044         private final SpellCheckerBindGroup mBindGroup;
1045         @NonNull
1046         private final SessionRequest mRequest;
1047
1048         ISpellCheckerServiceCallbackBinder(@NonNull final SpellCheckerBindGroup bindGroup,
1049                 @NonNull final SessionRequest request) {
1050             mBindGroup = bindGroup;
1051             mRequest = request;
1052         }
1053
1054         @Override
1055         public void onSessionCreated(@Nullable ISpellCheckerSession newSession) {
1056             mBindGroup.onSessionCreated(newSession, mRequest);
1057         }
1058     }
1059
1060     private static final class TextServicesSettings {
1061         private final ContentResolver mResolver;
1062         @UserIdInt
1063         private int mCurrentUserId;
1064         @GuardedBy("mLock")
1065         private int[] mCurrentProfileIds = new int[0];
1066         private Object mLock = new Object();
1067
1068         /**
1069          * On-memory data store to emulate when {@link #mCopyOnWrite} is {@code true}.
1070          */
1071         private final HashMap<String, String> mCopyOnWriteDataStore = new HashMap<>();
1072         private boolean mCopyOnWrite = false;
1073
1074         public TextServicesSettings(ContentResolver resolver, @UserIdInt int userId,
1075                 boolean copyOnWrite) {
1076             mResolver = resolver;
1077             switchCurrentUser(userId, copyOnWrite);
1078         }
1079
1080         /**
1081          * Must be called when the current user is changed.
1082          *
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.
1087          */
1088         public void switchCurrentUser(@UserIdInt int userId, boolean copyOnWrite) {
1089             if (DBG) {
1090                 Slog.d(TAG, "--- Swtich the current user from " + mCurrentUserId + " to "
1091                         + userId + ", new ime = " + getSelectedSpellChecker());
1092             }
1093             if (mCurrentUserId != userId || mCopyOnWrite != copyOnWrite) {
1094                 mCopyOnWriteDataStore.clear();
1095                 // TODO: mCurrentProfileIds should be cleared here.
1096             }
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.
1101         }
1102
1103         private void putString(final String key, final String str) {
1104             if (mCopyOnWrite) {
1105                 mCopyOnWriteDataStore.put(key, str);
1106             } else {
1107                 Settings.Secure.putStringForUser(mResolver, key, str, mCurrentUserId);
1108             }
1109         }
1110
1111         @Nullable
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);
1116             } else {
1117                 result = Settings.Secure.getStringForUser(mResolver, key, mCurrentUserId);
1118             }
1119             return result != null ? result : defaultValue;
1120         }
1121
1122         private void putInt(final String key, final int value) {
1123             if (mCopyOnWrite) {
1124                 mCopyOnWriteDataStore.put(key, String.valueOf(value));
1125             } else {
1126                 Settings.Secure.putIntForUser(mResolver, key, value, mCurrentUserId);
1127             }
1128         }
1129
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;
1134             }
1135             return Settings.Secure.getIntForUser(mResolver, key, defaultValue, mCurrentUserId);
1136         }
1137
1138         private void putBoolean(final String key, final boolean value) {
1139             putInt(key, value ? 1 : 0);
1140         }
1141
1142         private boolean getBoolean(final String key, final boolean defaultValue) {
1143             return getInt(key, defaultValue ? 1 : 0) == 1;
1144         }
1145
1146         public void setCurrentProfileIds(int[] currentProfileIds) {
1147             synchronized (mLock) {
1148                 mCurrentProfileIds = currentProfileIds;
1149             }
1150         }
1151
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;
1157                 }
1158                 return false;
1159             }
1160         }
1161
1162         @UserIdInt
1163         public int getCurrentUserId() {
1164             return mCurrentUserId;
1165         }
1166
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);
1172             } else {
1173                 putString(Settings.Secure.SELECTED_SPELL_CHECKER, sciId);
1174             }
1175         }
1176
1177         public void putSelectedSpellCheckerSubtype(int hashCode) {
1178             putInt(Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE, hashCode);
1179         }
1180
1181         public void setSpellCheckerEnabled(boolean enabled) {
1182             putBoolean(Settings.Secure.SPELL_CHECKER_ENABLED, enabled);
1183         }
1184
1185         @NonNull
1186         public String getSelectedSpellChecker() {
1187             return getString(Settings.Secure.SELECTED_SPELL_CHECKER, "");
1188         }
1189
1190         public int getSelectedSpellCheckerSubtype(final int defaultValue) {
1191             return getInt(Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE, defaultValue);
1192         }
1193
1194         public boolean isSpellCheckerEnabled() {
1195             return getBoolean(Settings.Secure.SPELL_CHECKER_ENABLED, true);
1196         }
1197
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);
1202         }
1203     }
1204
1205     // ----------------------------------------------------------------------
1206     // Utilities for debug
1207     private static String getStackTrace() {
1208         final StringBuilder sb = new StringBuilder();
1209         try {
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");
1216             }
1217         }
1218         return sb.toString();
1219     }
1220 }