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