TextServicesManagerService.java revision 05f24700613fb4dce95fb6d5f8fe460d7a30c128
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.content.PackageMonitor;
20import com.android.internal.textservice.ISpellCheckerService;
21import com.android.internal.textservice.ISpellCheckerSession;
22import com.android.internal.textservice.ISpellCheckerSessionListener;
23import com.android.internal.textservice.ITextServicesManager;
24import com.android.internal.textservice.ITextServicesSessionListener;
25
26import org.xmlpull.v1.XmlPullParserException;
27
28import android.content.ComponentName;
29import android.content.Context;
30import android.content.Intent;
31import android.content.ServiceConnection;
32import android.content.pm.PackageManager;
33import android.content.pm.ResolveInfo;
34import android.content.pm.ServiceInfo;
35import android.os.Binder;
36import android.os.Bundle;
37import android.os.IBinder;
38import android.os.RemoteException;
39import android.provider.Settings;
40import android.service.textservice.SpellCheckerService;
41import android.text.TextUtils;
42import android.util.Slog;
43import android.view.inputmethod.InputMethodManager;
44import android.view.inputmethod.InputMethodSubtype;
45import android.view.textservice.SpellCheckerInfo;
46import android.view.textservice.SpellCheckerSubtype;
47
48import java.io.FileDescriptor;
49import java.io.IOException;
50import java.io.PrintWriter;
51import java.util.ArrayList;
52import java.util.HashMap;
53import java.util.List;
54import java.util.Map;
55
56public class TextServicesManagerService extends ITextServicesManager.Stub {
57    private static final String TAG = TextServicesManagerService.class.getSimpleName();
58    private static final boolean DBG = false;
59
60    private final Context mContext;
61    private boolean mSystemReady;
62    private final TextServicesMonitor mMonitor;
63    private final HashMap<String, SpellCheckerInfo> mSpellCheckerMap =
64            new HashMap<String, SpellCheckerInfo>();
65    private final ArrayList<SpellCheckerInfo> mSpellCheckerList = new ArrayList<SpellCheckerInfo>();
66    private final HashMap<String, SpellCheckerBindGroup> mSpellCheckerBindGroups =
67            new HashMap<String, SpellCheckerBindGroup>();
68
69    public void systemReady() {
70        if (!mSystemReady) {
71            mSystemReady = true;
72        }
73    }
74
75    public TextServicesManagerService(Context context) {
76        mSystemReady = false;
77        mContext = context;
78        mMonitor = new TextServicesMonitor();
79        mMonitor.register(context, true);
80        synchronized (mSpellCheckerMap) {
81            buildSpellCheckerMapLocked(context, mSpellCheckerList, mSpellCheckerMap);
82        }
83        SpellCheckerInfo sci = getCurrentSpellChecker(null);
84        if (sci == null) {
85            sci = findAvailSpellCheckerLocked(null, null);
86            if (sci != null) {
87                // Set the current spell checker if there is one or more spell checkers
88                // available. In this case, "sci" is the first one in the available spell
89                // checkers.
90                setCurrentSpellCheckerLocked(sci.getId());
91            }
92        }
93    }
94
95    private class TextServicesMonitor extends PackageMonitor {
96        @Override
97        public void onSomePackagesChanged() {
98            synchronized (mSpellCheckerMap) {
99                buildSpellCheckerMapLocked(mContext, mSpellCheckerList, mSpellCheckerMap);
100                // TODO: Update for each locale
101                SpellCheckerInfo sci = getCurrentSpellChecker(null);
102                if (sci == null) return;
103                final String packageName = sci.getPackageName();
104                final int change = isPackageDisappearing(packageName);
105                if (// Package disappearing
106                        change == PACKAGE_PERMANENT_CHANGE || change == PACKAGE_TEMPORARY_CHANGE
107                        // Package modified
108                        || isPackageModified(packageName)) {
109                    sci = findAvailSpellCheckerLocked(null, packageName);
110                    if (sci != null) {
111                        setCurrentSpellCheckerLocked(sci.getId());
112                    }
113                }
114            }
115        }
116    }
117
118    private static void buildSpellCheckerMapLocked(Context context,
119            ArrayList<SpellCheckerInfo> list, HashMap<String, SpellCheckerInfo> map) {
120        list.clear();
121        map.clear();
122        final PackageManager pm = context.getPackageManager();
123        List<ResolveInfo> services = pm.queryIntentServices(
124                new Intent(SpellCheckerService.SERVICE_INTERFACE), PackageManager.GET_META_DATA);
125        final int N = services.size();
126        for (int i = 0; i < N; ++i) {
127            final ResolveInfo ri = services.get(i);
128            final ServiceInfo si = ri.serviceInfo;
129            final ComponentName compName = new ComponentName(si.packageName, si.name);
130            if (!android.Manifest.permission.BIND_TEXT_SERVICE.equals(si.permission)) {
131                Slog.w(TAG, "Skipping text service " + compName
132                        + ": it does not require the permission "
133                        + android.Manifest.permission.BIND_TEXT_SERVICE);
134                continue;
135            }
136            if (DBG) Slog.d(TAG, "Add: " + compName);
137            try {
138                final SpellCheckerInfo sci = new SpellCheckerInfo(context, ri);
139                if (sci.getSubtypeCount() <= 0) {
140                    Slog.w(TAG, "Skipping text service " + compName
141                            + ": it does not contain subtypes.");
142                    continue;
143                }
144                list.add(sci);
145                map.put(sci.getId(), sci);
146            } catch (XmlPullParserException e) {
147                Slog.w(TAG, "Unable to load the spell checker " + compName, e);
148            } catch (IOException e) {
149                Slog.w(TAG, "Unable to load the spell checker " + compName, e);
150            }
151        }
152        if (DBG) {
153            Slog.d(TAG, "buildSpellCheckerMapLocked: " + list.size() + "," + map.size());
154        }
155    }
156
157    // TODO: find an appropriate spell checker for specified locale
158    private SpellCheckerInfo findAvailSpellCheckerLocked(String locale, String prefPackage) {
159        final int spellCheckersCount = mSpellCheckerList.size();
160        if (spellCheckersCount == 0) {
161            Slog.w(TAG, "no available spell checker services found");
162            return null;
163        }
164        if (prefPackage != null) {
165            for (int i = 0; i < spellCheckersCount; ++i) {
166                final SpellCheckerInfo sci = mSpellCheckerList.get(i);
167                if (prefPackage.equals(sci.getPackageName())) {
168                    if (DBG) {
169                        Slog.d(TAG, "findAvailSpellCheckerLocked: " + sci.getPackageName());
170                    }
171                    return sci;
172                }
173            }
174        }
175        if (spellCheckersCount > 1) {
176            Slog.w(TAG, "more than one spell checker service found, picking first");
177        }
178        return mSpellCheckerList.get(0);
179    }
180
181    // TODO: Save SpellCheckerService by supported languages. Currently only one spell
182    // checker is saved.
183    @Override
184    public SpellCheckerInfo getCurrentSpellChecker(String locale) {
185        synchronized (mSpellCheckerMap) {
186            final String curSpellCheckerId =
187                    Settings.Secure.getString(mContext.getContentResolver(),
188                            Settings.Secure.SELECTED_SPELL_CHECKER);
189            if (DBG) {
190                Slog.w(TAG, "getCurrentSpellChecker: " + curSpellCheckerId);
191            }
192            if (TextUtils.isEmpty(curSpellCheckerId)) {
193                return null;
194            }
195            return mSpellCheckerMap.get(curSpellCheckerId);
196        }
197    }
198
199    // TODO: Respect allowImplicitlySelectedSubtype
200    // TODO: Save SpellCheckerSubtype by supported languages.
201    @Override
202    public SpellCheckerSubtype getCurrentSpellCheckerSubtype(
203            String locale, boolean allowImplicitlySelectedSubtype) {
204        synchronized (mSpellCheckerMap) {
205            final String subtypeHashCodeStr =
206                    Settings.Secure.getString(mContext.getContentResolver(),
207                            Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE);
208            if (DBG) {
209                Slog.w(TAG, "getCurrentSpellCheckerSubtype: " + subtypeHashCodeStr);
210            }
211            final SpellCheckerInfo sci = getCurrentSpellChecker(null);
212            if (sci == null || sci.getSubtypeCount() == 0) {
213                if (DBG) {
214                    Slog.w(TAG, "Subtype not found.");
215                }
216                return null;
217            }
218            final int hashCode;
219            if (!TextUtils.isEmpty(subtypeHashCodeStr)) {
220                hashCode = Integer.valueOf(subtypeHashCodeStr);
221            } else {
222                hashCode = 0;
223            }
224            if (hashCode == 0 && !allowImplicitlySelectedSubtype) {
225                return null;
226            }
227            String candidateLocale = null;
228            if (hashCode == 0) {
229                // Spell checker language settings == "auto"
230                final InputMethodManager imm =
231                        (InputMethodManager)mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
232                if (imm != null) {
233                    final InputMethodSubtype currentInputMethodSubtype =
234                            imm.getCurrentInputMethodSubtype();
235                    if (currentInputMethodSubtype != null) {
236                        final String localeString = currentInputMethodSubtype.getLocale();
237                        if (!TextUtils.isEmpty(localeString)) {
238                            // 1. Use keyboard locale if available in the spell checker
239                            candidateLocale = localeString;
240                        }
241                    }
242                }
243                if (candidateLocale == null) {
244                    // 2. Use System locale if available in the spell checker
245                    candidateLocale = mContext.getResources().getConfiguration().locale.toString();
246                }
247            }
248            SpellCheckerSubtype candidate = null;
249            for (int i = 0; i < sci.getSubtypeCount(); ++i) {
250                final SpellCheckerSubtype scs = sci.getSubtypeAt(i);
251                if (hashCode == 0) {
252                    if (candidateLocale.equals(locale)) {
253                        return scs;
254                    } else if (candidate == null) {
255                        final String scsLocale = scs.getLocale();
256                        if (candidateLocale.length() >= 2
257                                && scsLocale.length() >= 2
258                                && candidateLocale.substring(0, 2).equals(
259                                        scsLocale.substring(0, 2))) {
260                            // Fall back to the applicable language
261                            candidate = scs;
262                        }
263                    }
264                } else if (scs.hashCode() == hashCode) {
265                    if (DBG) {
266                        Slog.w(TAG, "Return subtype " + scs.hashCode() + ", input= " + locale
267                                + ", " + scs.getLocale());
268                    }
269                    // 3. Use the user specified spell check language
270                    return scs;
271                }
272            }
273            // 4. Fall back to the applicable language and return it if not null
274            // 5. Simply just return it even if it's null which means we could find no suitable
275            // spell check languages
276            return candidate;
277        }
278    }
279
280    @Override
281    public void getSpellCheckerService(String sciId, String locale,
282            ITextServicesSessionListener tsListener, ISpellCheckerSessionListener scListener,
283            Bundle bundle) {
284        if (!mSystemReady) {
285            return;
286        }
287        if (TextUtils.isEmpty(sciId) || tsListener == null || scListener == null) {
288            Slog.e(TAG, "getSpellCheckerService: Invalid input.");
289            return;
290        }
291        synchronized(mSpellCheckerMap) {
292            if (!mSpellCheckerMap.containsKey(sciId)) {
293                return;
294            }
295            final SpellCheckerInfo sci = mSpellCheckerMap.get(sciId);
296            final int uid = Binder.getCallingUid();
297            if (mSpellCheckerBindGroups.containsKey(sciId)) {
298                final SpellCheckerBindGroup bindGroup = mSpellCheckerBindGroups.get(sciId);
299                if (bindGroup != null) {
300                    final InternalDeathRecipient recipient =
301                            mSpellCheckerBindGroups.get(sciId).addListener(
302                                    tsListener, locale, scListener, uid, bundle);
303                    if (recipient == null) {
304                        if (DBG) {
305                            Slog.w(TAG, "Didn't create a death recipient.");
306                        }
307                        return;
308                    }
309                    if (bindGroup.mSpellChecker == null & bindGroup.mConnected) {
310                        Slog.e(TAG, "The state of the spell checker bind group is illegal.");
311                        bindGroup.removeAll();
312                    } else if (bindGroup.mSpellChecker != null) {
313                        if (DBG) {
314                            Slog.w(TAG, "Existing bind found. Return a spell checker session now. "
315                                    + "Listeners count = " + bindGroup.mListeners.size());
316                        }
317                        try {
318                            final ISpellCheckerSession session =
319                                    bindGroup.mSpellChecker.getISpellCheckerSession(
320                                            recipient.mScLocale, recipient.mScListener, bundle);
321                            if (session != null) {
322                                tsListener.onServiceConnected(session);
323                                return;
324                            } else {
325                                if (DBG) {
326                                    Slog.w(TAG, "Existing bind already expired. ");
327                                }
328                                bindGroup.removeAll();
329                            }
330                        } catch (RemoteException e) {
331                            Slog.e(TAG, "Exception in getting spell checker session: " + e);
332                            bindGroup.removeAll();
333                        }
334                    }
335                }
336            }
337            final long ident = Binder.clearCallingIdentity();
338            try {
339                startSpellCheckerServiceInnerLocked(
340                        sci, locale, tsListener, scListener, uid, bundle);
341            } finally {
342                Binder.restoreCallingIdentity(ident);
343            }
344        }
345        return;
346    }
347
348    @Override
349    public boolean isSpellCheckerEnabled() {
350        synchronized(mSpellCheckerMap) {
351            return isSpellCheckerEnabledLocked();
352        }
353    }
354
355    private void startSpellCheckerServiceInnerLocked(SpellCheckerInfo info, String locale,
356            ITextServicesSessionListener tsListener, ISpellCheckerSessionListener scListener,
357            int uid, Bundle bundle) {
358        if (DBG) {
359            Slog.w(TAG, "Start spell checker session inner locked.");
360        }
361        final String sciId = info.getId();
362        final InternalServiceConnection connection = new InternalServiceConnection(
363                sciId, locale, scListener, bundle);
364        final Intent serviceIntent = new Intent(SpellCheckerService.SERVICE_INTERFACE);
365        serviceIntent.setComponent(info.getComponent());
366        if (DBG) {
367            Slog.w(TAG, "bind service: " + info.getId());
368        }
369        if (!mContext.bindService(serviceIntent, connection, Context.BIND_AUTO_CREATE)) {
370            Slog.e(TAG, "Failed to get a spell checker service.");
371            return;
372        }
373        final SpellCheckerBindGroup group = new SpellCheckerBindGroup(
374                connection, tsListener, locale, scListener, uid, bundle);
375        mSpellCheckerBindGroups.put(sciId, group);
376    }
377
378    @Override
379    public SpellCheckerInfo[] getEnabledSpellCheckers() {
380        if (DBG) {
381            Slog.d(TAG, "getEnabledSpellCheckers: " + mSpellCheckerList.size());
382            for (int i = 0; i < mSpellCheckerList.size(); ++i) {
383                Slog.d(TAG, "EnabledSpellCheckers: " + mSpellCheckerList.get(i).getPackageName());
384            }
385        }
386        return mSpellCheckerList.toArray(new SpellCheckerInfo[mSpellCheckerList.size()]);
387    }
388
389    @Override
390    public void finishSpellCheckerService(ISpellCheckerSessionListener listener) {
391        if (DBG) {
392            Slog.d(TAG, "FinishSpellCheckerService");
393        }
394        synchronized(mSpellCheckerMap) {
395            for (SpellCheckerBindGroup group : mSpellCheckerBindGroups.values()) {
396                if (group == null) continue;
397                group.removeListener(listener);
398            }
399        }
400    }
401
402    @Override
403    public void setCurrentSpellChecker(String locale, String sciId) {
404        synchronized(mSpellCheckerMap) {
405            if (mContext.checkCallingOrSelfPermission(
406                    android.Manifest.permission.WRITE_SECURE_SETTINGS)
407                    != PackageManager.PERMISSION_GRANTED) {
408                throw new SecurityException(
409                        "Requires permission "
410                        + android.Manifest.permission.WRITE_SECURE_SETTINGS);
411            }
412            setCurrentSpellCheckerLocked(sciId);
413        }
414    }
415
416    @Override
417    public void setCurrentSpellCheckerSubtype(String locale, int hashCode) {
418        synchronized(mSpellCheckerMap) {
419            if (mContext.checkCallingOrSelfPermission(
420                    android.Manifest.permission.WRITE_SECURE_SETTINGS)
421                    != PackageManager.PERMISSION_GRANTED) {
422                throw new SecurityException(
423                        "Requires permission "
424                        + android.Manifest.permission.WRITE_SECURE_SETTINGS);
425            }
426            setCurrentSpellCheckerSubtypeLocked(hashCode);
427        }
428    }
429
430    @Override
431    public void setSpellCheckerEnabled(boolean enabled) {
432        synchronized(mSpellCheckerMap) {
433            if (mContext.checkCallingOrSelfPermission(
434                    android.Manifest.permission.WRITE_SECURE_SETTINGS)
435                    != PackageManager.PERMISSION_GRANTED) {
436                throw new SecurityException(
437                        "Requires permission "
438                        + android.Manifest.permission.WRITE_SECURE_SETTINGS);
439            }
440            setSpellCheckerEnabledLocked(enabled);
441        }
442    }
443
444    private void setCurrentSpellCheckerLocked(String sciId) {
445        if (DBG) {
446            Slog.w(TAG, "setCurrentSpellChecker: " + sciId);
447        }
448        if (TextUtils.isEmpty(sciId) || !mSpellCheckerMap.containsKey(sciId)) return;
449        final SpellCheckerInfo currentSci = getCurrentSpellChecker(null);
450        if (currentSci != null && currentSci.getId().equals(sciId)) {
451            // Do nothing if the current spell checker is same as new spell checker.
452            return;
453        }
454        final long ident = Binder.clearCallingIdentity();
455        try {
456            Settings.Secure.putString(mContext.getContentResolver(),
457                    Settings.Secure.SELECTED_SPELL_CHECKER, sciId);
458            setCurrentSpellCheckerSubtypeLocked(0);
459        } finally {
460            Binder.restoreCallingIdentity(ident);
461        }
462    }
463
464    private void setCurrentSpellCheckerSubtypeLocked(int hashCode) {
465        if (DBG) {
466            Slog.w(TAG, "setCurrentSpellCheckerSubtype: " + hashCode);
467        }
468        final SpellCheckerInfo sci = getCurrentSpellChecker(null);
469        int tempHashCode = 0;
470        for (int i = 0; sci != null && i < sci.getSubtypeCount(); ++i) {
471            if(sci.getSubtypeAt(i).hashCode() == hashCode) {
472                tempHashCode = hashCode;
473                break;
474            }
475        }
476        final long ident = Binder.clearCallingIdentity();
477        try {
478            Settings.Secure.putString(mContext.getContentResolver(),
479                    Settings.Secure.SELECTED_SPELL_CHECKER_SUBTYPE, String.valueOf(tempHashCode));
480        } finally {
481            Binder.restoreCallingIdentity(ident);
482        }
483    }
484
485    private void setSpellCheckerEnabledLocked(boolean enabled) {
486        if (DBG) {
487            Slog.w(TAG, "setSpellCheckerEnabled: " + enabled);
488        }
489        final long ident = Binder.clearCallingIdentity();
490        try {
491            Settings.Secure.putInt(mContext.getContentResolver(),
492                    Settings.Secure.SPELL_CHECKER_ENABLED, enabled ? 1 : 0);
493        } finally {
494            Binder.restoreCallingIdentity(ident);
495        }
496    }
497
498    private boolean isSpellCheckerEnabledLocked() {
499        final long ident = Binder.clearCallingIdentity();
500        try {
501            final boolean retval = Settings.Secure.getInt(mContext.getContentResolver(),
502                    Settings.Secure.SPELL_CHECKER_ENABLED, 1) == 1;
503            if (DBG) {
504                Slog.w(TAG, "getSpellCheckerEnabled: " + retval);
505            }
506            return retval;
507        } finally {
508            Binder.restoreCallingIdentity(ident);
509        }
510    }
511
512    @Override
513    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
514        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
515                != PackageManager.PERMISSION_GRANTED) {
516
517            pw.println("Permission Denial: can't dump TextServicesManagerService from from pid="
518                    + Binder.getCallingPid()
519                    + ", uid=" + Binder.getCallingUid());
520            return;
521        }
522
523        synchronized(mSpellCheckerMap) {
524            pw.println("Current Text Services Manager state:");
525            pw.println("  Spell Checker Map:");
526            for (Map.Entry<String, SpellCheckerInfo> ent : mSpellCheckerMap.entrySet()) {
527                pw.print("    "); pw.print(ent.getKey()); pw.println(":");
528                SpellCheckerInfo info = ent.getValue();
529                pw.print("      "); pw.print("id="); pw.println(info.getId());
530                pw.print("      "); pw.print("comp=");
531                        pw.println(info.getComponent().toShortString());
532                int NS = info.getSubtypeCount();
533                for (int i=0; i<NS; i++) {
534                    SpellCheckerSubtype st = info.getSubtypeAt(i);
535                    pw.print("      "); pw.print("Subtype #"); pw.print(i); pw.println(":");
536                    pw.print("        "); pw.print("locale="); pw.println(st.getLocale());
537                    pw.print("        "); pw.print("extraValue=");
538                            pw.println(st.getExtraValue());
539                }
540            }
541            pw.println("");
542            pw.println("  Spell Checker Bind Groups:");
543            for (Map.Entry<String, SpellCheckerBindGroup> ent
544                    : mSpellCheckerBindGroups.entrySet()) {
545                SpellCheckerBindGroup grp = ent.getValue();
546                pw.print("    "); pw.print(ent.getKey()); pw.print(" ");
547                        pw.print(grp); pw.println(":");
548                pw.print("      "); pw.print("mInternalConnection=");
549                        pw.println(grp.mInternalConnection);
550                pw.print("      "); pw.print("mSpellChecker=");
551                        pw.println(grp.mSpellChecker);
552                pw.print("      "); pw.print("mBound="); pw.print(grp.mBound);
553                        pw.print(" mConnected="); pw.println(grp.mConnected);
554                int NL = grp.mListeners.size();
555                for (int i=0; i<NL; i++) {
556                    InternalDeathRecipient listener = grp.mListeners.get(i);
557                    pw.print("      "); pw.print("Listener #"); pw.print(i); pw.println(":");
558                    pw.print("        "); pw.print("mTsListener=");
559                            pw.println(listener.mTsListener);
560                    pw.print("        "); pw.print("mScListener=");
561                            pw.println(listener.mScListener);
562                    pw.print("        "); pw.print("mGroup=");
563                            pw.println(listener.mGroup);
564                    pw.print("        "); pw.print("mScLocale=");
565                            pw.print(listener.mScLocale);
566                            pw.print(" mUid="); pw.println(listener.mUid);
567                }
568            }
569        }
570    }
571
572    // SpellCheckerBindGroup contains active text service session listeners.
573    // If there are no listeners anymore, the SpellCheckerBindGroup instance will be removed from
574    // mSpellCheckerBindGroups
575    private class SpellCheckerBindGroup {
576        private final String TAG = SpellCheckerBindGroup.class.getSimpleName();
577        private final InternalServiceConnection mInternalConnection;
578        private final ArrayList<InternalDeathRecipient> mListeners =
579                new ArrayList<InternalDeathRecipient>();
580        public boolean mBound;
581        public ISpellCheckerService mSpellChecker;
582        public boolean mConnected;
583
584        public SpellCheckerBindGroup(InternalServiceConnection connection,
585                ITextServicesSessionListener listener, String locale,
586                ISpellCheckerSessionListener scListener, int uid, Bundle bundle) {
587            mInternalConnection = connection;
588            mBound = true;
589            mConnected = false;
590            addListener(listener, locale, scListener, uid, bundle);
591        }
592
593        public void onServiceConnected(ISpellCheckerService spellChecker) {
594            if (DBG) {
595                Slog.d(TAG, "onServiceConnected");
596            }
597            synchronized(mSpellCheckerMap) {
598                for (InternalDeathRecipient listener : mListeners) {
599                    try {
600                        final ISpellCheckerSession session = spellChecker.getISpellCheckerSession(
601                                listener.mScLocale, listener.mScListener, listener.mBundle);
602                        listener.mTsListener.onServiceConnected(session);
603                    } catch (RemoteException e) {
604                        Slog.e(TAG, "Exception in getting the spell checker session."
605                                + "Reconnect to the spellchecker. ", e);
606                        removeAll();
607                        return;
608                    }
609                }
610                mSpellChecker = spellChecker;
611                mConnected = true;
612            }
613        }
614
615        public InternalDeathRecipient addListener(ITextServicesSessionListener tsListener,
616                String locale, ISpellCheckerSessionListener scListener, int uid, Bundle bundle) {
617            if (DBG) {
618                Slog.d(TAG, "addListener: " + locale);
619            }
620            InternalDeathRecipient recipient = null;
621            synchronized(mSpellCheckerMap) {
622                try {
623                    final int size = mListeners.size();
624                    for (int i = 0; i < size; ++i) {
625                        if (mListeners.get(i).hasSpellCheckerListener(scListener)) {
626                            // do not add the lister if the group already contains this.
627                            return null;
628                        }
629                    }
630                    recipient = new InternalDeathRecipient(
631                            this, tsListener, locale, scListener, uid, bundle);
632                    scListener.asBinder().linkToDeath(recipient, 0);
633                    mListeners.add(recipient);
634                } catch(RemoteException e) {
635                    // do nothing
636                }
637                cleanLocked();
638            }
639            return recipient;
640        }
641
642        public void removeListener(ISpellCheckerSessionListener listener) {
643            if (DBG) {
644                Slog.w(TAG, "remove listener: " + listener.hashCode());
645            }
646            synchronized(mSpellCheckerMap) {
647                final int size = mListeners.size();
648                final ArrayList<InternalDeathRecipient> removeList =
649                        new ArrayList<InternalDeathRecipient>();
650                for (int i = 0; i < size; ++i) {
651                    final InternalDeathRecipient tempRecipient = mListeners.get(i);
652                    if(tempRecipient.hasSpellCheckerListener(listener)) {
653                        if (DBG) {
654                            Slog.w(TAG, "found existing listener.");
655                        }
656                        removeList.add(tempRecipient);
657                    }
658                }
659                final int removeSize = removeList.size();
660                for (int i = 0; i < removeSize; ++i) {
661                    if (DBG) {
662                        Slog.w(TAG, "Remove " + removeList.get(i));
663                    }
664                    final InternalDeathRecipient idr = removeList.get(i);
665                    idr.mScListener.asBinder().unlinkToDeath(idr, 0);
666                    mListeners.remove(idr);
667                }
668                cleanLocked();
669            }
670        }
671
672        private void cleanLocked() {
673            if (DBG) {
674                Slog.d(TAG, "cleanLocked");
675            }
676            // If there are no more active listeners, clean up.  Only do this
677            // once.
678            if (mBound && mListeners.isEmpty()) {
679                mBound = false;
680                final String sciId = mInternalConnection.mSciId;
681                SpellCheckerBindGroup cur = mSpellCheckerBindGroups.get(sciId);
682                if (cur == this) {
683                    if (DBG) {
684                        Slog.d(TAG, "Remove bind group.");
685                    }
686                    mSpellCheckerBindGroups.remove(sciId);
687                }
688                mContext.unbindService(mInternalConnection);
689            }
690        }
691
692        public void removeAll() {
693            Slog.e(TAG, "Remove the spell checker bind unexpectedly.");
694            synchronized(mSpellCheckerMap) {
695                final int size = mListeners.size();
696                for (int i = 0; i < size; ++i) {
697                    final InternalDeathRecipient idr = mListeners.get(i);
698                    idr.mScListener.asBinder().unlinkToDeath(idr, 0);
699                }
700                mListeners.clear();
701                cleanLocked();
702            }
703        }
704    }
705
706    private class InternalServiceConnection implements ServiceConnection {
707        private final ISpellCheckerSessionListener mListener;
708        private final String mSciId;
709        private final String mLocale;
710        private final Bundle mBundle;
711        public InternalServiceConnection(
712                String id, String locale, ISpellCheckerSessionListener listener, Bundle bundle) {
713            mSciId = id;
714            mLocale = locale;
715            mListener = listener;
716            mBundle = bundle;
717        }
718
719        @Override
720        public void onServiceConnected(ComponentName name, IBinder service) {
721            synchronized(mSpellCheckerMap) {
722                if (DBG) {
723                    Slog.w(TAG, "onServiceConnected: " + name);
724                }
725                ISpellCheckerService spellChecker = ISpellCheckerService.Stub.asInterface(service);
726                final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId);
727                if (group != null && this == group.mInternalConnection) {
728                    group.onServiceConnected(spellChecker);
729                }
730            }
731        }
732
733        @Override
734        public void onServiceDisconnected(ComponentName name) {
735            synchronized(mSpellCheckerMap) {
736                final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId);
737                if (group != null && this == group.mInternalConnection) {
738                    mSpellCheckerBindGroups.remove(mSciId);
739                }
740            }
741        }
742    }
743
744    private class InternalDeathRecipient implements IBinder.DeathRecipient {
745        public final ITextServicesSessionListener mTsListener;
746        public final ISpellCheckerSessionListener mScListener;
747        public final String mScLocale;
748        private final SpellCheckerBindGroup mGroup;
749        public final int mUid;
750        public final Bundle mBundle;
751        public InternalDeathRecipient(SpellCheckerBindGroup group,
752                ITextServicesSessionListener tsListener, String scLocale,
753                ISpellCheckerSessionListener scListener, int uid, Bundle bundle) {
754            mTsListener = tsListener;
755            mScListener = scListener;
756            mScLocale = scLocale;
757            mGroup = group;
758            mUid = uid;
759            mBundle = bundle;
760        }
761
762        public boolean hasSpellCheckerListener(ISpellCheckerSessionListener listener) {
763            return listener.asBinder().equals(mScListener.asBinder());
764        }
765
766        @Override
767        public void binderDied() {
768            mGroup.removeListener(mScListener);
769        }
770    }
771}
772