OSDN Git Service

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