PageRenderTime 64ms CodeModel.GetById 6ms app.highlight 49ms RepoModel.GetById 1ms app.codeStats 0ms

/services/java/com/android/server/TextServicesManagerService.java

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