AccessibilityManagerService.java revision 58fd9f8d6ad6bf1975e834f1a69e68673db9a452
1/*
2 ** Copyright 2009, 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.accessibility;
18
19import static android.accessibilityservice.AccessibilityServiceInfo.DEFAULT;
20import static android.accessibilityservice.AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS;
21
22import android.Manifest;
23import android.accessibilityservice.AccessibilityService;
24import android.accessibilityservice.AccessibilityServiceInfo;
25import android.accessibilityservice.IAccessibilityServiceClient;
26import android.accessibilityservice.IAccessibilityServiceConnection;
27import android.app.AlertDialog;
28import android.app.PendingIntent;
29import android.app.StatusBarManager;
30import android.content.BroadcastReceiver;
31import android.content.ComponentName;
32import android.content.ContentResolver;
33import android.content.Context;
34import android.content.DialogInterface;
35import android.content.DialogInterface.OnClickListener;
36import android.content.Intent;
37import android.content.IntentFilter;
38import android.content.ServiceConnection;
39import android.content.pm.PackageManager;
40import android.content.pm.ResolveInfo;
41import android.content.pm.ServiceInfo;
42import android.database.ContentObserver;
43import android.graphics.Rect;
44import android.hardware.input.InputManager;
45import android.net.Uri;
46import android.os.Binder;
47import android.os.Build;
48import android.os.Bundle;
49import android.os.Handler;
50import android.os.IBinder;
51import android.os.Looper;
52import android.os.Message;
53import android.os.Process;
54import android.os.RemoteCallbackList;
55import android.os.RemoteException;
56import android.os.ServiceManager;
57import android.os.SystemClock;
58import android.os.UserHandle;
59import android.os.UserManager;
60import android.provider.Settings;
61import android.text.TextUtils;
62import android.text.TextUtils.SimpleStringSplitter;
63import android.util.Slog;
64import android.util.SparseArray;
65import android.view.IWindow;
66import android.view.IWindowManager;
67import android.view.InputDevice;
68import android.view.KeyCharacterMap;
69import android.view.KeyEvent;
70import android.view.WindowInfo;
71import android.view.WindowManager;
72import android.view.accessibility.AccessibilityEvent;
73import android.view.accessibility.AccessibilityInteractionClient;
74import android.view.accessibility.AccessibilityManager;
75import android.view.accessibility.AccessibilityNodeInfo;
76import android.view.accessibility.IAccessibilityInteractionConnection;
77import android.view.accessibility.IAccessibilityInteractionConnectionCallback;
78import android.view.accessibility.IAccessibilityManager;
79import android.view.accessibility.IAccessibilityManagerClient;
80
81import com.android.internal.R;
82import com.android.internal.content.PackageMonitor;
83import com.android.internal.statusbar.IStatusBarService;
84
85import org.xmlpull.v1.XmlPullParserException;
86
87import java.io.IOException;
88import java.util.ArrayList;
89import java.util.Arrays;
90import java.util.HashMap;
91import java.util.HashSet;
92import java.util.Iterator;
93import java.util.List;
94import java.util.Map;
95import java.util.Set;
96import java.util.concurrent.CopyOnWriteArrayList;
97
98/**
99 * This class is instantiated by the system as a system level service and can be
100 * accessed only by the system. The task of this service is to be a centralized
101 * event dispatch for {@link AccessibilityEvent}s generated across all processes
102 * on the device. Events are dispatched to {@link AccessibilityService}s.
103 *
104 * @hide
105 */
106public class AccessibilityManagerService extends IAccessibilityManager.Stub {
107
108    private static final boolean DEBUG = false;
109
110    private static final String LOG_TAG = "AccessibilityManagerService";
111
112    // TODO: This is arbitrary. When there is time implement this by watching
113    //       when that accessibility services are bound.
114    private static final int WAIT_FOR_USER_STATE_FULLY_INITIALIZED_MILLIS = 3000;
115
116    private static final String FUNCTION_REGISTER_UI_TEST_AUTOMATION_SERVICE =
117        "registerUiTestAutomationService";
118
119    private static final String TEMPORARY_ENABLE_ACCESSIBILITY_UNTIL_KEYGUARD_REMOVED =
120            "temporaryEnableAccessibilityStateUntilKeyguardRemoved";
121
122    private static final char COMPONENT_NAME_SEPARATOR = ':';
123
124    private static final int OWN_PROCESS_ID = android.os.Process.myPid();
125
126    private static int sIdCounter = 0;
127
128    private static int sNextWindowId;
129
130    private final Context mContext;
131
132    private final Object mLock = new Object();
133
134    private final SimpleStringSplitter mStringColonSplitter =
135            new SimpleStringSplitter(COMPONENT_NAME_SEPARATOR);
136
137    private final List<AccessibilityServiceInfo> mEnabledServicesForFeedbackTempList =
138            new ArrayList<AccessibilityServiceInfo>();
139
140    private final PackageManager mPackageManager;
141
142    private final IWindowManager mWindowManagerService;
143
144    private final SecurityPolicy mSecurityPolicy;
145
146    private final MainHandler mMainHandler;
147
148    private Service mUiAutomationService;
149
150    private Service mQueryBridge;
151
152    private AlertDialog mEnableTouchExplorationDialog;
153
154    private AccessibilityInputFilter mInputFilter;
155
156    private boolean mHasInputFilter;
157
158    private final RemoteCallbackList<IAccessibilityManagerClient> mGlobalClients =
159            new RemoteCallbackList<IAccessibilityManagerClient>();
160
161    private final SparseArray<AccessibilityConnectionWrapper> mGlobalInteractionConnections =
162            new SparseArray<AccessibilityConnectionWrapper>();
163
164    private final SparseArray<IBinder> mGlobalWindowTokens = new SparseArray<IBinder>();
165
166    private final SparseArray<UserState> mUserStates = new SparseArray<UserState>();
167
168    private final TempUserStateChangeMemento mTempStateChangeForCurrentUserMemento =
169            new TempUserStateChangeMemento();
170
171    private int mCurrentUserId = UserHandle.USER_OWNER;
172
173    private UserState getCurrentUserStateLocked() {
174        return getUserStateLocked(mCurrentUserId);
175    }
176
177    private UserState getUserStateLocked(int userId) {
178        UserState state = mUserStates.get(userId);
179        if (state == null) {
180            state = new UserState(userId);
181            mUserStates.put(userId, state);
182        }
183        return state;
184    }
185
186    /**
187     * Creates a new instance.
188     *
189     * @param context A {@link Context} instance.
190     */
191    public AccessibilityManagerService(Context context) {
192        mContext = context;
193        mPackageManager = mContext.getPackageManager();
194        mWindowManagerService = (IWindowManager) ServiceManager.getService(Context.WINDOW_SERVICE);
195        mSecurityPolicy = new SecurityPolicy();
196        mMainHandler = new MainHandler(mContext.getMainLooper());
197        registerBroadcastReceivers();
198        new AccessibilityContentObserver(mMainHandler).register(
199                context.getContentResolver());
200    }
201
202    private void registerBroadcastReceivers() {
203        PackageMonitor monitor = new PackageMonitor() {
204            @Override
205            public void onSomePackagesChanged() {
206                synchronized (mLock) {
207                    if (getChangingUserId() != mCurrentUserId) {
208                        return;
209                    }
210                    // We will update when the automation service dies.
211                    if (mUiAutomationService == null) {
212                        UserState userState = getCurrentUserStateLocked();
213                        populateInstalledAccessibilityServiceLocked(userState);
214                        manageServicesLocked(userState);
215                    }
216                }
217            }
218
219            @Override
220            public void onPackageRemoved(String packageName, int uid) {
221                synchronized (mLock) {
222                    final int userId = getChangingUserId();
223                    if (userId != mCurrentUserId) {
224                        return;
225                    }
226                    UserState state = getUserStateLocked(userId);
227                    Iterator<ComponentName> it = state.mEnabledServices.iterator();
228                    while (it.hasNext()) {
229                        ComponentName comp = it.next();
230                        String compPkg = comp.getPackageName();
231                        if (compPkg.equals(packageName)) {
232                            it.remove();
233                            // Update the enabled services setting.
234                            persistComponentNamesToSettingLocked(
235                                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,
236                                    state.mEnabledServices, userId);
237                            // Update the touch exploration granted services setting.
238                            state.mTouchExplorationGrantedServices.remove(comp);
239                            persistComponentNamesToSettingLocked(
240                                    Settings.Secure.
241                                            TOUCH_EXPLORATION_GRANTED_ACCESSIBILITY_SERVICES,
242                                    state.mEnabledServices, userId);
243                            return;
244                        }
245                    }
246                }
247            }
248
249            @Override
250            public boolean onHandleForceStop(Intent intent, String[] packages,
251                    int uid, boolean doit) {
252                synchronized (mLock) {
253                    final int userId = getChangingUserId();
254                    if (userId != mCurrentUserId) {
255                        return false;
256                    }
257                    UserState state = getUserStateLocked(userId);
258                    Iterator<ComponentName> it = state.mEnabledServices.iterator();
259                    while (it.hasNext()) {
260                        ComponentName comp = it.next();
261                        String compPkg = comp.getPackageName();
262                        for (String pkg : packages) {
263                            if (compPkg.equals(pkg)) {
264                                if (!doit) {
265                                    return true;
266                                }
267                                it.remove();
268                                persistComponentNamesToSettingLocked(
269                                        Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,
270                                        state.mEnabledServices, userId);
271                            }
272                        }
273                    }
274                    return false;
275                }
276            }
277        };
278
279        // package changes
280        monitor.register(mContext, null,  UserHandle.ALL, true);
281
282        // user change and unlock
283        IntentFilter intentFilter = new IntentFilter();
284        intentFilter.addAction(Intent.ACTION_USER_SWITCHED);
285        intentFilter.addAction(Intent.ACTION_USER_REMOVED);
286        intentFilter.addAction(Intent.ACTION_USER_PRESENT);
287
288        mContext.registerReceiverAsUser(new BroadcastReceiver() {
289            @Override
290            public void onReceive(Context context, Intent intent) {
291                String action = intent.getAction();
292                if (Intent.ACTION_USER_SWITCHED.equals(action)) {
293                    switchUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
294                } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
295                    removeUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
296                } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
297                    restoreStateFromMementoIfNeeded();
298                }
299            }
300        }, UserHandle.ALL, intentFilter, null, null);
301    }
302
303    public int addClient(IAccessibilityManagerClient client, int userId) {
304        synchronized (mLock) {
305            final int resolvedUserId = mSecurityPolicy
306                    .resolveCallingUserIdEnforcingPermissionsLocked(userId);
307            // If the client is from a process that runs across users such as
308            // the system UI or the system we add it to the global state that
309            // is shared across users.
310            UserState userState = getUserStateLocked(resolvedUserId);
311            if (mSecurityPolicy.isCallerInteractingAcrossUsers(userId)) {
312                mGlobalClients.register(client);
313                if (DEBUG) {
314                    Slog.i(LOG_TAG, "Added global client for pid:" + Binder.getCallingPid());
315                }
316                return getClientState(userState);
317            } else {
318                userState.mClients.register(client);
319                // If this client is not for the current user we do not
320                // return a state since it is not for the foreground user.
321                // We will send the state to the client on a user switch.
322                if (DEBUG) {
323                    Slog.i(LOG_TAG, "Added user client for pid:" + Binder.getCallingPid()
324                            + " and userId:" + mCurrentUserId);
325                }
326                return (resolvedUserId == mCurrentUserId) ? getClientState(userState) : 0;
327            }
328        }
329    }
330
331    public boolean sendAccessibilityEvent(AccessibilityEvent event, int userId) {
332        synchronized (mLock) {
333            final int resolvedUserId = mSecurityPolicy
334                    .resolveCallingUserIdEnforcingPermissionsLocked(userId);
335            // This method does nothing for a background user.
336            if (resolvedUserId != mCurrentUserId) {
337                return true; // yes, recycle the event
338            }
339            if (mSecurityPolicy.canDispatchAccessibilityEvent(event)) {
340                mSecurityPolicy.updateEventSourceLocked(event);
341                mMainHandler.obtainMessage(MainHandler.MSG_UPDATE_ACTIVE_WINDOW,
342                        event.getWindowId(), event.getEventType()).sendToTarget();
343                notifyAccessibilityServicesDelayedLocked(event, false);
344                notifyAccessibilityServicesDelayedLocked(event, true);
345            }
346            if (mHasInputFilter && mInputFilter != null) {
347                mMainHandler.obtainMessage(MainHandler.MSG_SEND_ACCESSIBILITY_EVENT_TO_INPUT_FILTER,
348                        AccessibilityEvent.obtain(event)).sendToTarget();
349            }
350            event.recycle();
351            getUserStateLocked(resolvedUserId).mHandledFeedbackTypes = 0;
352        }
353        return (OWN_PROCESS_ID != Binder.getCallingPid());
354    }
355
356    public List<AccessibilityServiceInfo> getInstalledAccessibilityServiceList(int userId) {
357        synchronized (mLock) {
358            final int resolvedUserId = mSecurityPolicy
359                    .resolveCallingUserIdEnforcingPermissionsLocked(userId);
360            return getUserStateLocked(resolvedUserId).mInstalledServices;
361        }
362    }
363
364    public List<AccessibilityServiceInfo> getEnabledAccessibilityServiceList(int feedbackType,
365            int userId) {
366        List<AccessibilityServiceInfo> result = null;
367        synchronized (mLock) {
368            final int resolvedUserId = mSecurityPolicy
369                    .resolveCallingUserIdEnforcingPermissionsLocked(userId);
370            result = mEnabledServicesForFeedbackTempList;
371            result.clear();
372            List<Service> services = getUserStateLocked(resolvedUserId).mServices;
373            while (feedbackType != 0) {
374                final int feedbackTypeBit = (1 << Integer.numberOfTrailingZeros(feedbackType));
375                feedbackType &= ~feedbackTypeBit;
376                final int serviceCount = services.size();
377                for (int i = 0; i < serviceCount; i++) {
378                    Service service = services.get(i);
379                    if ((service.mFeedbackType & feedbackTypeBit) != 0) {
380                        result.add(service.mAccessibilityServiceInfo);
381                    }
382                }
383            }
384        }
385        return result;
386    }
387
388    public void interrupt(int userId) {
389        CopyOnWriteArrayList<Service> services;
390        synchronized (mLock) {
391            final int resolvedUserId = mSecurityPolicy
392                    .resolveCallingUserIdEnforcingPermissionsLocked(userId);
393            // This method does nothing for a background user.
394            if (resolvedUserId != mCurrentUserId) {
395                return;
396            }
397            services = getUserStateLocked(resolvedUserId).mServices;
398        }
399        for (int i = 0, count = services.size(); i < count; i++) {
400            Service service = services.get(i);
401            try {
402                service.mServiceInterface.onInterrupt();
403            } catch (RemoteException re) {
404                Slog.e(LOG_TAG, "Error during sending interrupt request to "
405                    + service.mService, re);
406            }
407        }
408    }
409
410    public int addAccessibilityInteractionConnection(IWindow windowToken,
411            IAccessibilityInteractionConnection connection, int userId) throws RemoteException {
412        synchronized (mLock) {
413            final int resolvedUserId = mSecurityPolicy
414                    .resolveCallingUserIdEnforcingPermissionsLocked(userId);
415            final int windowId = sNextWindowId++;
416            // If the window is from a process that runs across users such as
417            // the system UI or the system we add it to the global state that
418            // is shared across users.
419            if (mSecurityPolicy.isCallerInteractingAcrossUsers(userId)) {
420                AccessibilityConnectionWrapper wrapper = new AccessibilityConnectionWrapper(
421                        windowId, connection, UserHandle.USER_ALL);
422                wrapper.linkToDeath();
423                mGlobalInteractionConnections.put(windowId, wrapper);
424                mGlobalWindowTokens.put(windowId, windowToken.asBinder());
425                if (DEBUG) {
426                    Slog.i(LOG_TAG, "Added global connection for pid:" + Binder.getCallingPid()
427                            + " with windowId: " + windowId);
428                }
429            } else {
430                AccessibilityConnectionWrapper wrapper = new AccessibilityConnectionWrapper(
431                        windowId, connection, resolvedUserId);
432                wrapper.linkToDeath();
433                UserState userState = getUserStateLocked(resolvedUserId);
434                userState.mInteractionConnections.put(windowId, wrapper);
435                userState.mWindowTokens.put(windowId, windowToken.asBinder());
436                if (DEBUG) {
437                    Slog.i(LOG_TAG, "Added user connection for pid:" + Binder.getCallingPid()
438                            + " with windowId: " + windowId + " and userId:" + mCurrentUserId);
439                }
440            }
441            if (DEBUG) {
442                Slog.i(LOG_TAG, "Adding interaction connection to windowId: " + windowId);
443            }
444            return windowId;
445        }
446    }
447
448    public void removeAccessibilityInteractionConnection(IWindow window) {
449        synchronized (mLock) {
450            mSecurityPolicy.resolveCallingUserIdEnforcingPermissionsLocked(
451                    UserHandle.getCallingUserId());
452            IBinder token = window.asBinder();
453            final int removedWindowId = removeAccessibilityInteractionConnectionInternalLocked(
454                    token, mGlobalWindowTokens, mGlobalInteractionConnections);
455            if (removedWindowId >= 0) {
456                if (DEBUG) {
457                    Slog.i(LOG_TAG, "Removed global connection for pid:" + Binder.getCallingPid()
458                            + " with windowId: " + removedWindowId);
459                }
460                return;
461            }
462            final int userCount = mUserStates.size();
463            for (int i = 0; i < userCount; i++) {
464                UserState userState = mUserStates.valueAt(i);
465                final int removedWindowIdForUser =
466                        removeAccessibilityInteractionConnectionInternalLocked(
467                        token, userState.mWindowTokens, userState.mInteractionConnections);
468                if (removedWindowIdForUser >= 0) {
469                    if (DEBUG) {
470                        Slog.i(LOG_TAG, "Removed user connection for pid:" + Binder.getCallingPid()
471                                + " with windowId: " + removedWindowIdForUser + " and userId:"
472                                + mUserStates.keyAt(i));
473                    }
474                    return;
475                }
476            }
477        }
478    }
479
480    private int removeAccessibilityInteractionConnectionInternalLocked(IBinder windowToken,
481            SparseArray<IBinder> windowTokens,
482            SparseArray<AccessibilityConnectionWrapper> interactionConnections) {
483        final int count = windowTokens.size();
484        for (int i = 0; i < count; i++) {
485            if (windowTokens.valueAt(i) == windowToken) {
486                final int windowId = windowTokens.keyAt(i);
487                windowTokens.removeAt(i);
488                AccessibilityConnectionWrapper wrapper = interactionConnections.get(windowId);
489                wrapper.unlinkToDeath();
490                interactionConnections.remove(windowId);
491                return windowId;
492            }
493        }
494        return -1;
495    }
496
497    public void registerUiTestAutomationService(IAccessibilityServiceClient serviceClient,
498            AccessibilityServiceInfo accessibilityServiceInfo) {
499        mSecurityPolicy.enforceCallingPermission(Manifest.permission.RETRIEVE_WINDOW_CONTENT,
500                FUNCTION_REGISTER_UI_TEST_AUTOMATION_SERVICE);
501        ComponentName componentName = new ComponentName("foo.bar",
502                "AutomationAccessibilityService");
503        synchronized (mLock) {
504            // If an automation services is connected to the system all services are stopped
505            // so the automation one is the only one running. Settings are not changed so when
506            // the automation service goes away the state is restored from the settings.
507            UserState userState = getCurrentUserStateLocked();
508            unbindAllServicesLocked(userState);
509
510            // If necessary enable accessibility and announce that.
511            if (!userState.mIsAccessibilityEnabled) {
512                userState.mIsAccessibilityEnabled = true;
513            }
514            // No touch exploration.
515            userState.mIsTouchExplorationEnabled = false;
516
517            // Hook the automation service up.
518            mUiAutomationService = new Service(mCurrentUserId, componentName,
519                    accessibilityServiceInfo, true);
520            mUiAutomationService.onServiceConnected(componentName, serviceClient.asBinder());
521
522            updateInputFilterLocked(userState);
523            scheduleSendStateToClientsLocked(userState);
524        }
525    }
526
527    public void temporaryEnableAccessibilityStateUntilKeyguardRemoved(
528            ComponentName service, boolean touchExplorationEnabled) {
529        mSecurityPolicy.enforceCallingPermission(
530                Manifest.permission.TEMPORARY_ENABLE_ACCESSIBILITY,
531                TEMPORARY_ENABLE_ACCESSIBILITY_UNTIL_KEYGUARD_REMOVED);
532        try {
533            if (!mWindowManagerService.isKeyguardLocked()) {
534                return;
535            }
536        } catch (RemoteException re) {
537            return;
538        }
539        synchronized (mLock) {
540            UserState userState = getCurrentUserStateLocked();
541            // Stash the old state so we can restore it when the keyguard is gone.
542            mTempStateChangeForCurrentUserMemento.initialize(mCurrentUserId, getCurrentUserStateLocked());
543            // Set the temporary state.
544            userState.mIsAccessibilityEnabled = true;
545            userState.mIsTouchExplorationEnabled= touchExplorationEnabled;
546            userState.mIsDisplayMagnificationEnabled = false;
547            userState.mEnabledServices.clear();
548            userState.mEnabledServices.add(service);
549            userState.mTouchExplorationGrantedServices.clear();
550            userState.mTouchExplorationGrantedServices.add(service);
551            // Update the internal state.
552            performServiceManagementLocked(userState);
553            updateInputFilterLocked(userState);
554            scheduleSendStateToClientsLocked(userState);
555        }
556    }
557
558    public void unregisterUiTestAutomationService(IAccessibilityServiceClient serviceClient) {
559        synchronized (mLock) {
560            // Automation service is not bound, so pretend it died to perform clean up.
561            if (mUiAutomationService != null
562                    && mUiAutomationService.mServiceInterface == serviceClient) {
563                mUiAutomationService.binderDied();
564            }
565        }
566    }
567
568    boolean onGesture(int gestureId) {
569        synchronized (mLock) {
570            boolean handled = notifyGestureLocked(gestureId, false);
571            if (!handled) {
572                handled = notifyGestureLocked(gestureId, true);
573            }
574            return handled;
575        }
576    }
577
578    /**
579     * Gets the bounds of the accessibility focus in the active window.
580     *
581     * @param outBounds The output to which to write the focus bounds.
582     * @return Whether accessibility focus was found and the bounds are populated.
583     */
584    boolean getAccessibilityFocusBoundsInActiveWindow(Rect outBounds) {
585        // Instead of keeping track of accessibility focus events per
586        // window to be able to find the focus in the active window,
587        // we take a stateless approach and look it up. This is fine
588        // since we do this only when the user clicks/long presses.
589        Service service = getQueryBridge();
590        final int connectionId = service.mId;
591        AccessibilityInteractionClient client = AccessibilityInteractionClient.getInstance();
592        client.addConnection(connectionId, service);
593        try {
594            AccessibilityNodeInfo root = AccessibilityInteractionClient.getInstance()
595                    .getRootInActiveWindow(connectionId);
596            if (root == null) {
597                return false;
598            }
599            AccessibilityNodeInfo focus = root.findFocus(
600                    AccessibilityNodeInfo.FOCUS_ACCESSIBILITY);
601            if (focus == null) {
602                return false;
603            }
604            focus.getBoundsInScreen(outBounds);
605            return true;
606        } finally {
607            client.removeConnection(connectionId);
608        }
609    }
610
611    /**
612     * Gets the bounds of the active window.
613     *
614     * @param outBounds The output to which to write the bounds.
615     */
616    boolean getActiveWindowBounds(Rect outBounds) {
617        IBinder token;
618        synchronized (mLock) {
619            final int windowId = mSecurityPolicy.mActiveWindowId;
620            token = mGlobalWindowTokens.get(windowId);
621            if (token == null) {
622                token = getCurrentUserStateLocked().mWindowTokens.get(windowId);
623            }
624        }
625        WindowInfo info = null;
626        try {
627            info = mWindowManagerService.getWindowInfo(token);
628            if (info != null) {
629                outBounds.set(info.frame);
630                return true;
631            }
632        } catch (RemoteException re) {
633            /* ignore */
634        } finally {
635            if (info != null) {
636                info.recycle();
637            }
638        }
639        return false;
640    }
641
642    int getActiveWindowId() {
643        return mSecurityPolicy.mActiveWindowId;
644    }
645
646    private void switchUser(int userId) {
647        synchronized (mLock) {
648            // The user switched so we do not need to restore the current user
649            // state since we will fully rebuild it when he becomes current again.
650            mTempStateChangeForCurrentUserMemento.clear();
651
652            // Disconnect from services for the old user.
653            UserState oldUserState = getUserStateLocked(mCurrentUserId);
654            unbindAllServicesLocked(oldUserState);
655
656            // Disable the local managers for the old user.
657            if (oldUserState.mClients.getRegisteredCallbackCount() > 0) {
658                mMainHandler.obtainMessage(MainHandler.MSG_SEND_CLEARED_STATE_TO_CLIENTS_FOR_USER,
659                        oldUserState.mUserId, 0).sendToTarget();
660            }
661
662            // Announce user changes only if more that one exist.
663            UserManager userManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
664            final boolean announceNewUser = userManager.getUsers().size() > 1;
665
666            // The user changed.
667            mCurrentUserId = userId;
668
669            // Recreate the internal state for the new user.
670            mMainHandler.obtainMessage(MainHandler.MSG_SEND_RECREATE_INTERNAL_STATE,
671                    mCurrentUserId, 0).sendToTarget();
672
673            if (announceNewUser) {
674                // Schedule announcement of the current user if needed.
675                mMainHandler.sendEmptyMessageDelayed(MainHandler.MSG_ANNOUNCE_NEW_USER_IF_NEEDED,
676                        WAIT_FOR_USER_STATE_FULLY_INITIALIZED_MILLIS);
677            }
678        }
679    }
680
681    private void removeUser(int userId) {
682        synchronized (mLock) {
683            mUserStates.remove(userId);
684        }
685    }
686
687    private void restoreStateFromMementoIfNeeded() {
688        synchronized (mLock) {
689            if (mTempStateChangeForCurrentUserMemento.mUserId != UserHandle.USER_NULL) {
690                UserState userState = getCurrentUserStateLocked();
691                // Restore the state from the memento.
692                mTempStateChangeForCurrentUserMemento.applyTo(userState);
693                mTempStateChangeForCurrentUserMemento.clear();
694                // Update the internal state.
695                performServiceManagementLocked(userState);
696                updateInputFilterLocked(userState);
697                scheduleSendStateToClientsLocked(userState);
698            }
699        }
700    }
701
702    private Service getQueryBridge() {
703        if (mQueryBridge == null) {
704            AccessibilityServiceInfo info = new AccessibilityServiceInfo();
705            mQueryBridge = new Service(UserHandle.USER_NULL, null, info, true);
706        }
707        return mQueryBridge;
708    }
709
710    private boolean notifyGestureLocked(int gestureId, boolean isDefault) {
711        // TODO: Now we are giving the gestures to the last enabled
712        //       service that can handle them which is the last one
713        //       in our list since we write the last enabled as the
714        //       last record in the enabled services setting. Ideally,
715        //       the user should make the call which service handles
716        //       gestures. However, only one service should handle
717        //       gestures to avoid user frustration when different
718        //       behavior is observed from different combinations of
719        //       enabled accessibility services.
720        UserState state = getCurrentUserStateLocked();
721        for (int i = state.mServices.size() - 1; i >= 0; i--) {
722            Service service = state.mServices.get(i);
723            if (service.mRequestTouchExplorationMode && service.mIsDefault == isDefault) {
724                service.notifyGesture(gestureId);
725                return true;
726            }
727        }
728        return false;
729    }
730
731    /**
732     * Removes an AccessibilityInteractionConnection.
733     *
734     * @param windowId The id of the window to which the connection is targeted.
735     * @param userId The id of the user owning the connection. UserHandle.USER_ALL
736     *     if global.
737     */
738    private void removeAccessibilityInteractionConnectionLocked(int windowId, int userId) {
739        if (userId == UserHandle.USER_ALL) {
740            mGlobalWindowTokens.remove(windowId);
741            mGlobalInteractionConnections.remove(windowId);
742        } else {
743            UserState userState = getCurrentUserStateLocked();
744            userState.mWindowTokens.remove(windowId);
745            userState.mInteractionConnections.remove(windowId);
746        }
747        if (DEBUG) {
748            Slog.i(LOG_TAG, "Removing interaction connection to windowId: " + windowId);
749        }
750    }
751
752    private void populateInstalledAccessibilityServiceLocked(UserState userState) {
753        userState.mInstalledServices.clear();
754
755        List<ResolveInfo> installedServices = mPackageManager.queryIntentServicesAsUser(
756                new Intent(AccessibilityService.SERVICE_INTERFACE),
757                PackageManager.GET_SERVICES | PackageManager.GET_META_DATA,
758                mCurrentUserId);
759
760        for (int i = 0, count = installedServices.size(); i < count; i++) {
761            ResolveInfo resolveInfo = installedServices.get(i);
762            ServiceInfo serviceInfo = resolveInfo.serviceInfo;
763            if (!android.Manifest.permission.BIND_ACCESSIBILITY_SERVICE.equals(
764                    serviceInfo.permission)) {
765                Slog.w(LOG_TAG, "Skipping accessibilty service " + new ComponentName(
766                        serviceInfo.packageName, serviceInfo.name).flattenToShortString()
767                        + ": it does not require the permission "
768                        + android.Manifest.permission.BIND_ACCESSIBILITY_SERVICE);
769                continue;
770            }
771            AccessibilityServiceInfo accessibilityServiceInfo;
772            try {
773                accessibilityServiceInfo = new AccessibilityServiceInfo(resolveInfo, mContext);
774                userState.mInstalledServices.add(accessibilityServiceInfo);
775            } catch (XmlPullParserException xppe) {
776                Slog.e(LOG_TAG, "Error while initializing AccessibilityServiceInfo", xppe);
777            } catch (IOException ioe) {
778                Slog.e(LOG_TAG, "Error while initializing AccessibilityServiceInfo", ioe);
779            }
780        }
781    }
782
783    private void populateEnabledAccessibilityServicesLocked(UserState userState) {
784        populateComponentNamesFromSettingLocked(
785                Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,
786                userState.mUserId,
787                userState.mEnabledServices);
788    }
789
790    private void populateTouchExplorationGrantedAccessibilityServicesLocked(
791            UserState userState) {
792        populateComponentNamesFromSettingLocked(
793                Settings.Secure.TOUCH_EXPLORATION_GRANTED_ACCESSIBILITY_SERVICES,
794                userState.mUserId,
795                userState.mTouchExplorationGrantedServices);
796    }
797
798    /**
799     * Performs {@link AccessibilityService}s delayed notification. The delay is configurable
800     * and denotes the period after the last event before notifying the service.
801     *
802     * @param event The event.
803     * @param isDefault True to notify default listeners, not default services.
804     */
805    private void notifyAccessibilityServicesDelayedLocked(AccessibilityEvent event,
806            boolean isDefault) {
807        try {
808            UserState state = getCurrentUserStateLocked();
809            for (int i = 0, count = state.mServices.size(); i < count; i++) {
810                Service service = state.mServices.get(i);
811
812                if (service.mIsDefault == isDefault) {
813                    if (canDispathEventLocked(service, event, state.mHandledFeedbackTypes)) {
814                        state.mHandledFeedbackTypes |= service.mFeedbackType;
815                        service.notifyAccessibilityEvent(event);
816                    }
817                }
818            }
819        } catch (IndexOutOfBoundsException oobe) {
820            // An out of bounds exception can happen if services are going away
821            // as the for loop is running. If that happens, just bail because
822            // there are no more services to notify.
823            return;
824        }
825    }
826
827    /**
828     * Adds a service for a user.
829     *
830     * @param service The service to add.
831     * @param userId The user id.
832     */
833    private void tryAddServiceLocked(Service service, int userId) {
834        try {
835            UserState userState = getUserStateLocked(userId);
836            if (userState.mServices.contains(service)) {
837                return;
838            }
839            service.linkToOwnDeath();
840            userState.mServices.add(service);
841            userState.mComponentNameToServiceMap.put(service.mComponentName, service);
842            updateInputFilterLocked(userState);
843            tryEnableTouchExplorationLocked(service);
844        } catch (RemoteException e) {
845            /* do nothing */
846        }
847    }
848
849    /**
850     * Removes a service.
851     *
852     * @param service The service.
853     * @return True if the service was removed, false otherwise.
854     */
855    private boolean tryRemoveServiceLocked(Service service) {
856        UserState userState = getUserStateLocked(service.mUserId);
857        final boolean removed = userState.mServices.remove(service);
858        if (!removed) {
859            return false;
860        }
861        userState.mComponentNameToServiceMap.remove(service.mComponentName);
862        service.unlinkToOwnDeath();
863        service.dispose();
864        updateInputFilterLocked(userState);
865        tryDisableTouchExplorationLocked(service);
866        return removed;
867    }
868
869    /**
870     * Determines if given event can be dispatched to a service based on the package of the
871     * event source and already notified services for that event type. Specifically, a
872     * service is notified if it is interested in events from the package and no other service
873     * providing the same feedback type has been notified. Exception are services the
874     * provide generic feedback (feedback type left as a safety net for unforeseen feedback
875     * types) which are always notified.
876     *
877     * @param service The potential receiver.
878     * @param event The event.
879     * @param handledFeedbackTypes The feedback types for which services have been notified.
880     * @return True if the listener should be notified, false otherwise.
881     */
882    private boolean canDispathEventLocked(Service service, AccessibilityEvent event,
883            int handledFeedbackTypes) {
884
885        if (!service.canReceiveEvents()) {
886            return false;
887        }
888
889        if (!event.isImportantForAccessibility()
890                && !service.mIncludeNotImportantViews) {
891            return false;
892        }
893
894        int eventType = event.getEventType();
895        if ((service.mEventTypes & eventType) != eventType) {
896            return false;
897        }
898
899        Set<String> packageNames = service.mPackageNames;
900        CharSequence packageName = event.getPackageName();
901
902        if (packageNames.isEmpty() || packageNames.contains(packageName)) {
903            int feedbackType = service.mFeedbackType;
904            if ((handledFeedbackTypes & feedbackType) != feedbackType
905                    || feedbackType == AccessibilityServiceInfo.FEEDBACK_GENERIC) {
906                return true;
907            }
908        }
909
910        return false;
911    }
912
913    /**
914     * Manages services by starting enabled ones and stopping disabled ones.
915     */
916    private void manageServicesLocked(UserState userState) {
917        final int enabledInstalledServicesCount = updateServicesStateLocked(userState);
918        // No enabled installed services => disable accessibility to avoid
919        // sending accessibility events with no recipient across processes.
920        if (userState.mIsAccessibilityEnabled && enabledInstalledServicesCount == 0) {
921            Settings.Secure.putIntForUser(mContext.getContentResolver(),
922                    Settings.Secure.ACCESSIBILITY_ENABLED, 0, userState.mUserId);
923        }
924    }
925
926    /**
927     * Unbinds all bound services for a user.
928     *
929     * @param userState The user state.
930     */
931    private void unbindAllServicesLocked(UserState userState) {
932        List<Service> services = userState.mServices;
933        for (int i = 0, count = services.size(); i < count; i++) {
934            Service service = services.get(i);
935            if (service.unbind()) {
936                i--;
937                count--;
938            }
939        }
940    }
941
942    /**
943     * Populates a set with the {@link ComponentName}s stored in a colon
944     * separated value setting for a given user.
945     *
946     * @param settingName The setting to parse.
947     * @param userId The user id.
948     * @param outComponentNames The output component names.
949     */
950    private void populateComponentNamesFromSettingLocked(String settingName, int userId,
951            Set<ComponentName> outComponentNames) {
952        String settingValue = Settings.Secure.getStringForUser(mContext.getContentResolver(),
953                settingName, userId);
954        outComponentNames.clear();
955        if (settingValue != null) {
956            TextUtils.SimpleStringSplitter splitter = mStringColonSplitter;
957            splitter.setString(settingValue);
958            while (splitter.hasNext()) {
959                String str = splitter.next();
960                if (str == null || str.length() <= 0) {
961                    continue;
962                }
963                ComponentName enabledService = ComponentName.unflattenFromString(str);
964                if (enabledService != null) {
965                    outComponentNames.add(enabledService);
966                }
967            }
968        }
969    }
970
971    /**
972     * Persists the component names in the specified setting in a
973     * colon separated fashion.
974     *
975     * @param settingName The setting name.
976     * @param componentNames The component names.
977     */
978    private void persistComponentNamesToSettingLocked(String settingName,
979            Set<ComponentName> componentNames, int userId) {
980        StringBuilder builder = new StringBuilder();
981        for (ComponentName componentName : componentNames) {
982            if (builder.length() > 0) {
983                builder.append(COMPONENT_NAME_SEPARATOR);
984            }
985            builder.append(componentName.flattenToShortString());
986        }
987        Settings.Secure.putStringForUser(mContext.getContentResolver(),
988                settingName, builder.toString(), userId);
989    }
990
991    /**
992     * Updates the state of each service by starting (or keeping running) enabled ones and
993     * stopping the rest.
994     *
995     * @param userState The user state for which to do that.
996     * @return The number of enabled installed services.
997     */
998    private int updateServicesStateLocked(UserState userState) {
999        Map<ComponentName, Service> componentNameToServiceMap =
1000                userState.mComponentNameToServiceMap;
1001        boolean isEnabled = userState.mIsAccessibilityEnabled;
1002
1003        int enabledInstalledServices = 0;
1004        for (int i = 0, count = userState.mInstalledServices.size(); i < count; i++) {
1005            AccessibilityServiceInfo installedService = userState.mInstalledServices.get(i);
1006            ComponentName componentName = ComponentName.unflattenFromString(
1007                    installedService.getId());
1008            Service service = componentNameToServiceMap.get(componentName);
1009
1010            if (isEnabled) {
1011                if (userState.mEnabledServices.contains(componentName)) {
1012                    if (service == null) {
1013                        service = new Service(userState.mUserId, componentName,
1014                                installedService, false);
1015                    }
1016                    service.bind();
1017                    enabledInstalledServices++;
1018                } else {
1019                    if (service != null) {
1020                        service.unbind();
1021                    }
1022                }
1023            } else {
1024                if (service != null) {
1025                    service.unbind();
1026                }
1027            }
1028        }
1029
1030        return enabledInstalledServices;
1031    }
1032
1033    private void scheduleSendStateToClientsLocked(UserState userState) {
1034        if (mGlobalClients.getRegisteredCallbackCount() > 0
1035                || userState.mClients.getRegisteredCallbackCount() > 0) {
1036            final int clientState = getClientState(userState);
1037            mMainHandler.obtainMessage(MainHandler.MSG_SEND_STATE_TO_CLIENTS,
1038                    clientState, userState.mUserId) .sendToTarget();
1039        }
1040    }
1041
1042    private void updateInputFilterLocked(UserState userState) {
1043        boolean setInputFilter = false;
1044        AccessibilityInputFilter inputFilter = null;
1045        synchronized (mLock) {
1046            if ((userState.mIsAccessibilityEnabled && userState.mIsTouchExplorationEnabled)
1047                    || userState.mIsDisplayMagnificationEnabled) {
1048                if (!mHasInputFilter) {
1049                    mHasInputFilter = true;
1050                    if (mInputFilter == null) {
1051                        mInputFilter = new AccessibilityInputFilter(mContext,
1052                                AccessibilityManagerService.this);
1053                    }
1054                    inputFilter = mInputFilter;
1055                    setInputFilter = true;
1056                }
1057                int flags = 0;
1058                if (userState.mIsDisplayMagnificationEnabled) {
1059                    flags |= AccessibilityInputFilter.FLAG_FEATURE_SCREEN_MAGNIFIER;
1060                }
1061                if (userState.mIsTouchExplorationEnabled) {
1062                    flags |= AccessibilityInputFilter.FLAG_FEATURE_TOUCH_EXPLORATION;
1063                }
1064                mInputFilter.setEnabledFeatures(flags);
1065            } else {
1066                if (mHasInputFilter) {
1067                    mHasInputFilter = false;
1068                    mInputFilter.setEnabledFeatures(0);
1069                    inputFilter = null;
1070                    setInputFilter = true;
1071                }
1072            }
1073        }
1074        if (setInputFilter) {
1075            try {
1076                mWindowManagerService.setInputFilter(inputFilter);
1077            } catch (RemoteException re) {
1078                /* ignore */
1079            }
1080        }
1081    }
1082
1083    private void showEnableTouchExplorationDialog(final Service service) {
1084        String label = service.mResolveInfo.loadLabel(
1085                mContext.getPackageManager()).toString();
1086        synchronized (mLock) {
1087            final UserState state = getCurrentUserStateLocked();
1088            if (state.mIsTouchExplorationEnabled) {
1089                return;
1090            }
1091            if (mEnableTouchExplorationDialog != null
1092                    && mEnableTouchExplorationDialog.isShowing()) {
1093                return;
1094            }
1095            mEnableTouchExplorationDialog = new AlertDialog.Builder(mContext)
1096                .setIcon(android.R.drawable.ic_dialog_alert)
1097                .setPositiveButton(android.R.string.ok, new OnClickListener() {
1098                    @Override
1099                    public void onClick(DialogInterface dialog, int which) {
1100                        // The user allowed the service to toggle touch exploration.
1101                        state.mTouchExplorationGrantedServices.add(service.mComponentName);
1102                        persistComponentNamesToSettingLocked(
1103                                Settings.Secure.TOUCH_EXPLORATION_GRANTED_ACCESSIBILITY_SERVICES,
1104                                       state.mTouchExplorationGrantedServices, state.mUserId);
1105                        // Enable touch exploration.
1106                        Settings.Secure.putIntForUser(mContext.getContentResolver(),
1107                                Settings.Secure.TOUCH_EXPLORATION_ENABLED, 1,
1108                                service.mUserId);
1109                    }
1110                })
1111                .setNegativeButton(android.R.string.cancel, new OnClickListener() {
1112                    @Override
1113                    public void onClick(DialogInterface dialog, int which) {
1114                        dialog.dismiss();
1115                    }
1116                })
1117                .setTitle(R.string.enable_explore_by_touch_warning_title)
1118                .setMessage(mContext.getString(
1119                        R.string.enable_explore_by_touch_warning_message, label))
1120                .create();
1121            mEnableTouchExplorationDialog.getWindow().setType(
1122                    WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG);
1123            mEnableTouchExplorationDialog.setCanceledOnTouchOutside(true);
1124            mEnableTouchExplorationDialog.show();
1125        }
1126    }
1127
1128    private int getClientState(UserState userState) {
1129        int clientState = 0;
1130        if (userState.mIsAccessibilityEnabled) {
1131            clientState |= AccessibilityManager.STATE_FLAG_ACCESSIBILITY_ENABLED;
1132        }
1133        // Touch exploration relies on enabled accessibility.
1134        if (userState.mIsAccessibilityEnabled && userState.mIsTouchExplorationEnabled) {
1135            clientState |= AccessibilityManager.STATE_FLAG_TOUCH_EXPLORATION_ENABLED;
1136        }
1137        return clientState;
1138    }
1139
1140    private void recreateInternalStateLocked(UserState userState) {
1141        populateInstalledAccessibilityServiceLocked(userState);
1142        populateEnabledAccessibilityServicesLocked(userState);
1143        populateTouchExplorationGrantedAccessibilityServicesLocked(userState);
1144
1145        handleTouchExplorationEnabledSettingChangedLocked(userState);
1146        handleDisplayMagnificationEnabledSettingChangedLocked(userState);
1147        handleAccessibilityEnabledSettingChangedLocked(userState);
1148
1149        performServiceManagementLocked(userState);
1150        updateInputFilterLocked(userState);
1151        scheduleSendStateToClientsLocked(userState);
1152    }
1153
1154    private void handleAccessibilityEnabledSettingChangedLocked(UserState userState) {
1155        userState.mIsAccessibilityEnabled = Settings.Secure.getIntForUser(
1156               mContext.getContentResolver(),
1157               Settings.Secure.ACCESSIBILITY_ENABLED, 0, userState.mUserId) == 1;
1158    }
1159
1160    private void performServiceManagementLocked(UserState userState) {
1161        if (userState.mIsAccessibilityEnabled ) {
1162            manageServicesLocked(userState);
1163        } else {
1164            unbindAllServicesLocked(userState);
1165        }
1166    }
1167
1168    private void handleTouchExplorationEnabledSettingChangedLocked(UserState userState) {
1169        userState.mIsTouchExplorationEnabled = Settings.Secure.getIntForUser(
1170                mContext.getContentResolver(),
1171                Settings.Secure.TOUCH_EXPLORATION_ENABLED, 0, userState.mUserId) == 1;
1172    }
1173
1174    private void handleDisplayMagnificationEnabledSettingChangedLocked(UserState userState) {
1175        userState.mIsDisplayMagnificationEnabled = Settings.Secure.getIntForUser(
1176                mContext.getContentResolver(),
1177                Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED,
1178                0, userState.mUserId) == 1;
1179    }
1180
1181    private void handleTouchExplorationGrantedAccessibilityServicesChangedLocked(
1182            UserState userState) {
1183        final int serviceCount = userState.mServices.size();
1184        for (int i = 0; i < serviceCount; i++) {
1185            Service service = userState.mServices.get(i);
1186            if (service.mRequestTouchExplorationMode
1187                    && userState.mTouchExplorationGrantedServices.contains(
1188                            service.mComponentName)) {
1189                tryEnableTouchExplorationLocked(service);
1190                return;
1191            }
1192        }
1193        if (userState.mIsTouchExplorationEnabled) {
1194            Settings.Secure.putIntForUser(mContext.getContentResolver(),
1195                    Settings.Secure.TOUCH_EXPLORATION_ENABLED, 0, userState.mUserId);
1196        }
1197    }
1198
1199    private void tryEnableTouchExplorationLocked(final Service service) {
1200        UserState userState = getUserStateLocked(service.mUserId);
1201        if (!userState.mIsTouchExplorationEnabled && service.mRequestTouchExplorationMode
1202                && service.canReceiveEvents()) {
1203            final boolean canToggleTouchExploration =
1204                    userState.mTouchExplorationGrantedServices.contains(service.mComponentName);
1205            if (!service.mIsAutomation && !canToggleTouchExploration) {
1206                showEnableTouchExplorationDialog(service);
1207            } else {
1208                Settings.Secure.putIntForUser(mContext.getContentResolver(),
1209                        Settings.Secure.TOUCH_EXPLORATION_ENABLED, 1, userState.mUserId);
1210            }
1211        }
1212    }
1213
1214    private void tryDisableTouchExplorationLocked(Service service) {
1215        UserState userState = getUserStateLocked(service.mUserId);
1216        if (userState.mIsTouchExplorationEnabled) {
1217            final int serviceCount = userState.mServices.size();
1218            for (int i = 0; i < serviceCount; i++) {
1219                Service other = userState.mServices.get(i);
1220                if (other != service && other.mRequestTouchExplorationMode) {
1221                    return;
1222                }
1223            }
1224            Settings.Secure.putIntForUser(mContext.getContentResolver(),
1225                    Settings.Secure.TOUCH_EXPLORATION_ENABLED, 0, userState.mUserId);
1226        }
1227    }
1228
1229    private class AccessibilityConnectionWrapper implements DeathRecipient {
1230        private final int mWindowId;
1231        private final int mUserId;
1232        private final IAccessibilityInteractionConnection mConnection;
1233
1234        public AccessibilityConnectionWrapper(int windowId,
1235                IAccessibilityInteractionConnection connection, int userId) {
1236            mWindowId = windowId;
1237            mUserId = userId;
1238            mConnection = connection;
1239        }
1240
1241        public void linkToDeath() throws RemoteException {
1242            mConnection.asBinder().linkToDeath(this, 0);
1243        }
1244
1245        public void unlinkToDeath() {
1246            mConnection.asBinder().unlinkToDeath(this, 0);
1247        }
1248
1249        @Override
1250        public void binderDied() {
1251            unlinkToDeath();
1252            synchronized (mLock) {
1253                removeAccessibilityInteractionConnectionLocked(mWindowId, mUserId);
1254            }
1255        }
1256    }
1257
1258    private final class MainHandler extends Handler {
1259        public static final int MSG_SEND_ACCESSIBILITY_EVENT_TO_INPUT_FILTER = 1;
1260        public static final int MSG_SEND_STATE_TO_CLIENTS = 2;
1261        public static final int MSG_SEND_CLEARED_STATE_TO_CLIENTS_FOR_USER = 3;
1262        public static final int MSG_SEND_RECREATE_INTERNAL_STATE = 4;
1263        public static final int MSG_UPDATE_ACTIVE_WINDOW = 5;
1264        public static final int MSG_ANNOUNCE_NEW_USER_IF_NEEDED = 6;
1265
1266        public MainHandler(Looper looper) {
1267            super(looper);
1268        }
1269
1270        @Override
1271        public void handleMessage(Message msg) {
1272            final int type = msg.what;
1273            switch (type) {
1274                case MSG_SEND_ACCESSIBILITY_EVENT_TO_INPUT_FILTER: {
1275                    AccessibilityEvent event = (AccessibilityEvent) msg.obj;
1276                    synchronized (mLock) {
1277                        if (mHasInputFilter && mInputFilter != null) {
1278                            mInputFilter.notifyAccessibilityEvent(event);
1279                        }
1280                    }
1281                    event.recycle();
1282                } break;
1283                case MSG_SEND_STATE_TO_CLIENTS: {
1284                    final int clientState = msg.arg1;
1285                    final int userId = msg.arg2;
1286                    sendStateToClients(clientState, mGlobalClients);
1287                    sendStateToClientsForUser(clientState, userId);
1288                } break;
1289                case MSG_SEND_CLEARED_STATE_TO_CLIENTS_FOR_USER: {
1290                    final int userId = msg.arg1;
1291                    sendStateToClientsForUser(0, userId);
1292                } break;
1293                case MSG_SEND_RECREATE_INTERNAL_STATE: {
1294                    final int userId = msg.arg1;
1295                    synchronized (mLock) {
1296                        UserState userState = getUserStateLocked(userId);
1297                        recreateInternalStateLocked(userState);
1298                    }
1299                } break;
1300                case MSG_UPDATE_ACTIVE_WINDOW: {
1301                    final int windowId = msg.arg1;
1302                    final int eventType = msg.arg2;
1303                    mSecurityPolicy.updateActiveWindow(windowId, eventType);
1304                } break;
1305                case MSG_ANNOUNCE_NEW_USER_IF_NEEDED: {
1306                    announceNewUserIfNeeded();
1307                } break;
1308            }
1309        }
1310
1311        private void announceNewUserIfNeeded() {
1312            synchronized (mLock) {
1313                UserState userState = getCurrentUserStateLocked();
1314                if (userState.mIsAccessibilityEnabled) {
1315                    UserManager userManager = (UserManager) mContext.getSystemService(
1316                            Context.USER_SERVICE);
1317                    String message = mContext.getString(R.string.user_switched,
1318                            userManager.getUserInfo(mCurrentUserId).name);
1319                    AccessibilityEvent event = AccessibilityEvent.obtain(
1320                            AccessibilityEvent.TYPE_ANNOUNCEMENT);
1321                    event.getText().add(message);
1322                    sendAccessibilityEvent(event, mCurrentUserId);
1323                }
1324            }
1325        }
1326
1327        private void sendStateToClientsForUser(int clientState, int userId) {
1328            final UserState userState;
1329            synchronized (mLock) {
1330                userState = getUserStateLocked(userId);
1331            }
1332            sendStateToClients(clientState, userState.mClients);
1333        }
1334
1335        private void sendStateToClients(int clientState,
1336                RemoteCallbackList<IAccessibilityManagerClient> clients) {
1337            try {
1338                final int userClientCount = clients.beginBroadcast();
1339                for (int i = 0; i < userClientCount; i++) {
1340                    IAccessibilityManagerClient client = clients.getBroadcastItem(i);
1341                    try {
1342                        client.setState(clientState);
1343                    } catch (RemoteException re) {
1344                        /* ignore */
1345                    }
1346                }
1347            } finally {
1348                clients.finishBroadcast();
1349            }
1350        }
1351    }
1352
1353    /**
1354     * This class represents an accessibility service. It stores all per service
1355     * data required for the service management, provides API for starting/stopping the
1356     * service and is responsible for adding/removing the service in the data structures
1357     * for service management. The class also exposes configuration interface that is
1358     * passed to the service it represents as soon it is bound. It also serves as the
1359     * connection for the service.
1360     */
1361    class Service extends IAccessibilityServiceConnection.Stub
1362            implements ServiceConnection, DeathRecipient {
1363
1364        // We pick the MSB to avoid collision since accessibility event types are
1365        // used as message types allowing us to remove messages per event type.
1366        private static final int MSG_ON_GESTURE = 0x80000000;
1367
1368        final int mUserId;
1369
1370        int mId = 0;
1371
1372        AccessibilityServiceInfo mAccessibilityServiceInfo;
1373
1374        IBinder mService;
1375
1376        IAccessibilityServiceClient mServiceInterface;
1377
1378        int mEventTypes;
1379
1380        int mFeedbackType;
1381
1382        Set<String> mPackageNames = new HashSet<String>();
1383
1384        boolean mIsDefault;
1385
1386        boolean mRequestTouchExplorationMode;
1387
1388        boolean mIncludeNotImportantViews;
1389
1390        long mNotificationTimeout;
1391
1392        ComponentName mComponentName;
1393
1394        Intent mIntent;
1395
1396        boolean mCanRetrieveScreenContent;
1397
1398        boolean mIsAutomation;
1399
1400        final Rect mTempBounds = new Rect();
1401
1402        final ResolveInfo mResolveInfo;
1403
1404        // the events pending events to be dispatched to this service
1405        final SparseArray<AccessibilityEvent> mPendingEvents =
1406            new SparseArray<AccessibilityEvent>();
1407
1408        /**
1409         * Handler for delayed event dispatch.
1410         */
1411        public Handler mHandler = new Handler(mMainHandler.getLooper()) {
1412            @Override
1413            public void handleMessage(Message message) {
1414                final int type = message.what;
1415                switch (type) {
1416                    case MSG_ON_GESTURE: {
1417                        final int gestureId = message.arg1;
1418                        notifyGestureInternal(gestureId);
1419                    } break;
1420                    default: {
1421                        final int eventType = type;
1422                        notifyAccessibilityEventInternal(eventType);
1423                    } break;
1424                }
1425            }
1426        };
1427
1428        public Service(int userId, ComponentName componentName,
1429                AccessibilityServiceInfo accessibilityServiceInfo, boolean isAutomation) {
1430            mUserId = userId;
1431            mResolveInfo = accessibilityServiceInfo.getResolveInfo();
1432            mId = sIdCounter++;
1433            mComponentName = componentName;
1434            mAccessibilityServiceInfo = accessibilityServiceInfo;
1435            mIsAutomation = isAutomation;
1436            if (!isAutomation) {
1437                mCanRetrieveScreenContent = accessibilityServiceInfo.getCanRetrieveWindowContent();
1438                mRequestTouchExplorationMode =
1439                    (accessibilityServiceInfo.flags
1440                            & AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE) != 0;
1441                mIntent = new Intent().setComponent(mComponentName);
1442                mIntent.putExtra(Intent.EXTRA_CLIENT_LABEL,
1443                        com.android.internal.R.string.accessibility_binding_label);
1444                mIntent.putExtra(Intent.EXTRA_CLIENT_INTENT, PendingIntent.getActivity(
1445                        mContext, 0, new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS), 0));
1446            } else {
1447                mCanRetrieveScreenContent = true;
1448            }
1449            setDynamicallyConfigurableProperties(accessibilityServiceInfo);
1450        }
1451
1452        public void setDynamicallyConfigurableProperties(AccessibilityServiceInfo info) {
1453            mEventTypes = info.eventTypes;
1454            mFeedbackType = info.feedbackType;
1455            String[] packageNames = info.packageNames;
1456            if (packageNames != null) {
1457                mPackageNames.addAll(Arrays.asList(packageNames));
1458            }
1459            mNotificationTimeout = info.notificationTimeout;
1460            mIsDefault = (info.flags & DEFAULT) != 0;
1461
1462            if (mIsAutomation || info.getResolveInfo().serviceInfo.applicationInfo.targetSdkVersion
1463                    >= Build.VERSION_CODES.JELLY_BEAN) {
1464                mIncludeNotImportantViews =
1465                    (info.flags & FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0;
1466            }
1467
1468            mRequestTouchExplorationMode = (info.flags
1469                    & AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE) != 0;
1470
1471            // If this service is up and running we may have to enable touch
1472            // exploration, otherwise this will happen when the service connects.
1473            synchronized (mLock) {
1474                if (canReceiveEvents()) {
1475                    if (mRequestTouchExplorationMode) {
1476                        tryEnableTouchExplorationLocked(this);
1477                    } else {
1478                        tryDisableTouchExplorationLocked(this);
1479                    }
1480                }
1481            }
1482        }
1483
1484        /**
1485         * Binds to the accessibility service.
1486         *
1487         * @return True if binding is successful.
1488         */
1489        public boolean bind() {
1490            if (!mIsAutomation && mService == null) {
1491                return mContext.bindService(mIntent, this, Context.BIND_AUTO_CREATE, mUserId);
1492            }
1493            return false;
1494        }
1495
1496        /**
1497         * Unbinds form the accessibility service and removes it from the data
1498         * structures for service management.
1499         *
1500         * @return True if unbinding is successful.
1501         */
1502        public boolean unbind() {
1503            if (mService != null) {
1504                synchronized (mLock) {
1505                    tryRemoveServiceLocked(this);
1506                }
1507                if (!mIsAutomation) {
1508                    mContext.unbindService(this);
1509                }
1510                return true;
1511            }
1512            return false;
1513        }
1514
1515        public boolean canReceiveEvents() {
1516            return (mEventTypes != 0 && mFeedbackType != 0 && mService != null);
1517        }
1518
1519        @Override
1520        public AccessibilityServiceInfo getServiceInfo() {
1521            synchronized (mLock) {
1522                return mAccessibilityServiceInfo;
1523            }
1524        }
1525
1526        @Override
1527        public void setServiceInfo(AccessibilityServiceInfo info) {
1528            final long identity = Binder.clearCallingIdentity();
1529            try {
1530                synchronized (mLock) {
1531                    // If the XML manifest had data to configure the service its info
1532                    // should be already set. In such a case update only the dynamically
1533                    // configurable properties.
1534                    AccessibilityServiceInfo oldInfo = mAccessibilityServiceInfo;
1535                    if (oldInfo != null) {
1536                        oldInfo.updateDynamicallyConfigurableProperties(info);
1537                        setDynamicallyConfigurableProperties(oldInfo);
1538                    } else {
1539                        setDynamicallyConfigurableProperties(info);
1540                    }
1541                }
1542            } finally {
1543                Binder.restoreCallingIdentity(identity);
1544            }
1545        }
1546
1547        @Override
1548        public void onServiceConnected(ComponentName componentName, IBinder service) {
1549            mService = service;
1550            mServiceInterface = IAccessibilityServiceClient.Stub.asInterface(service);
1551            try {
1552                mServiceInterface.setConnection(this, mId);
1553                synchronized (mLock) {
1554                    tryAddServiceLocked(this, mUserId);
1555                }
1556            } catch (RemoteException re) {
1557                Slog.w(LOG_TAG, "Error while setting Controller for service: " + service, re);
1558            }
1559        }
1560
1561        @Override
1562        public float findAccessibilityNodeInfoByViewId(int accessibilityWindowId,
1563                long accessibilityNodeId, int viewId, int interactionId,
1564                IAccessibilityInteractionConnectionCallback callback, long interrogatingTid)
1565                throws RemoteException {
1566            final int resolvedWindowId;
1567            IAccessibilityInteractionConnection connection = null;
1568            synchronized (mLock) {
1569                final int resolvedUserId = mSecurityPolicy
1570                        .resolveCallingUserIdEnforcingPermissionsLocked(
1571                                UserHandle.getCallingUserId());
1572                if (resolvedUserId != mCurrentUserId) {
1573                    return -1;
1574                }
1575                mSecurityPolicy.enforceCanRetrieveWindowContent(this);
1576                final boolean permissionGranted = mSecurityPolicy.canRetrieveWindowContent(this);
1577                if (!permissionGranted) {
1578                    return 0;
1579                } else {
1580                    resolvedWindowId = resolveAccessibilityWindowIdLocked(accessibilityWindowId);
1581                    connection = getConnectionLocked(resolvedWindowId);
1582                    if (connection == null) {
1583                        return 0;
1584                    }
1585                }
1586            }
1587            final int flags = (mIncludeNotImportantViews) ?
1588                    AccessibilityNodeInfo.INCLUDE_NOT_IMPORTANT_VIEWS : 0;
1589            final int interrogatingPid = Binder.getCallingPid();
1590            final long identityToken = Binder.clearCallingIdentity();
1591            try {
1592                connection.findAccessibilityNodeInfoByViewId(accessibilityNodeId, viewId,
1593                        interactionId, callback, flags, interrogatingPid, interrogatingTid);
1594                return getCompatibilityScale(resolvedWindowId);
1595            } catch (RemoteException re) {
1596                if (DEBUG) {
1597                    Slog.e(LOG_TAG, "Error findAccessibilityNodeInfoByViewId().");
1598                }
1599            } finally {
1600                Binder.restoreCallingIdentity(identityToken);
1601            }
1602            return 0;
1603        }
1604
1605        @Override
1606        public float findAccessibilityNodeInfosByText(int accessibilityWindowId,
1607                long accessibilityNodeId, String text, int interactionId,
1608                IAccessibilityInteractionConnectionCallback callback, long interrogatingTid)
1609                throws RemoteException {
1610            final int resolvedWindowId;
1611            IAccessibilityInteractionConnection connection = null;
1612            synchronized (mLock) {
1613                final int resolvedUserId = mSecurityPolicy
1614                        .resolveCallingUserIdEnforcingPermissionsLocked(
1615                        UserHandle.getCallingUserId());
1616                if (resolvedUserId != mCurrentUserId) {
1617                    return -1;
1618                }
1619                mSecurityPolicy.enforceCanRetrieveWindowContent(this);
1620                resolvedWindowId = resolveAccessibilityWindowIdLocked(accessibilityWindowId);
1621                final boolean permissionGranted =
1622                    mSecurityPolicy.canGetAccessibilityNodeInfoLocked(this, resolvedWindowId);
1623                if (!permissionGranted) {
1624                    return 0;
1625                } else {
1626                    connection = getConnectionLocked(resolvedWindowId);
1627                    if (connection == null) {
1628                        return 0;
1629                    }
1630                }
1631            }
1632            final int flags = (mIncludeNotImportantViews) ?
1633                    AccessibilityNodeInfo.INCLUDE_NOT_IMPORTANT_VIEWS : 0;
1634            final int interrogatingPid = Binder.getCallingPid();
1635            final long identityToken = Binder.clearCallingIdentity();
1636            try {
1637                connection.findAccessibilityNodeInfosByText(accessibilityNodeId, text,
1638                        interactionId, callback, flags, interrogatingPid,
1639                        interrogatingTid);
1640                return getCompatibilityScale(resolvedWindowId);
1641            } catch (RemoteException re) {
1642                if (DEBUG) {
1643                    Slog.e(LOG_TAG, "Error calling findAccessibilityNodeInfosByText()");
1644                }
1645            } finally {
1646                Binder.restoreCallingIdentity(identityToken);
1647            }
1648            return 0;
1649        }
1650
1651        @Override
1652        public float findAccessibilityNodeInfoByAccessibilityId(int accessibilityWindowId,
1653                long accessibilityNodeId, int interactionId,
1654                IAccessibilityInteractionConnectionCallback callback, int flags,
1655                long interrogatingTid) throws RemoteException {
1656            final int resolvedWindowId;
1657            IAccessibilityInteractionConnection connection = null;
1658            synchronized (mLock) {
1659                final int resolvedUserId = mSecurityPolicy
1660                        .resolveCallingUserIdEnforcingPermissionsLocked(
1661                        UserHandle.getCallingUserId());
1662                if (resolvedUserId != mCurrentUserId) {
1663                    return -1;
1664                }
1665                mSecurityPolicy.enforceCanRetrieveWindowContent(this);
1666                resolvedWindowId = resolveAccessibilityWindowIdLocked(accessibilityWindowId);
1667                final boolean permissionGranted =
1668                    mSecurityPolicy.canGetAccessibilityNodeInfoLocked(this, resolvedWindowId);
1669                if (!permissionGranted) {
1670                    return 0;
1671                } else {
1672                    connection = getConnectionLocked(resolvedWindowId);
1673                    if (connection == null) {
1674                        return 0;
1675                    }
1676                }
1677            }
1678            final int allFlags = flags | ((mIncludeNotImportantViews) ?
1679                    AccessibilityNodeInfo.INCLUDE_NOT_IMPORTANT_VIEWS : 0);
1680            final int interrogatingPid = Binder.getCallingPid();
1681            final long identityToken = Binder.clearCallingIdentity();
1682            try {
1683                connection.findAccessibilityNodeInfoByAccessibilityId(accessibilityNodeId,
1684                        interactionId, callback, allFlags, interrogatingPid, interrogatingTid);
1685                return getCompatibilityScale(resolvedWindowId);
1686            } catch (RemoteException re) {
1687                if (DEBUG) {
1688                    Slog.e(LOG_TAG, "Error calling findAccessibilityNodeInfoByAccessibilityId()");
1689                }
1690            } finally {
1691                Binder.restoreCallingIdentity(identityToken);
1692            }
1693            return 0;
1694        }
1695
1696        @Override
1697        public float findFocus(int accessibilityWindowId, long accessibilityNodeId,
1698                int focusType, int interactionId,
1699                IAccessibilityInteractionConnectionCallback callback, long interrogatingTid)
1700                throws RemoteException {
1701            final int resolvedWindowId;
1702            IAccessibilityInteractionConnection connection = null;
1703            synchronized (mLock) {
1704                final int resolvedUserId = mSecurityPolicy
1705                        .resolveCallingUserIdEnforcingPermissionsLocked(
1706                        UserHandle.getCallingUserId());
1707                if (resolvedUserId != mCurrentUserId) {
1708                    return -1;
1709                }
1710                mSecurityPolicy.enforceCanRetrieveWindowContent(this);
1711                resolvedWindowId = resolveAccessibilityWindowIdLocked(accessibilityWindowId);
1712                final boolean permissionGranted =
1713                    mSecurityPolicy.canGetAccessibilityNodeInfoLocked(this, resolvedWindowId);
1714                if (!permissionGranted) {
1715                    return 0;
1716                } else {
1717                    connection = getConnectionLocked(resolvedWindowId);
1718                    if (connection == null) {
1719                        return 0;
1720                    }
1721                }
1722            }
1723            final int flags = (mIncludeNotImportantViews) ?
1724                    AccessibilityNodeInfo.INCLUDE_NOT_IMPORTANT_VIEWS : 0;
1725            final int interrogatingPid = Binder.getCallingPid();
1726            final long identityToken = Binder.clearCallingIdentity();
1727            try {
1728                connection.findFocus(accessibilityNodeId, focusType, interactionId, callback,
1729                        flags, interrogatingPid, interrogatingTid);
1730                return getCompatibilityScale(resolvedWindowId);
1731            } catch (RemoteException re) {
1732                if (DEBUG) {
1733                    Slog.e(LOG_TAG, "Error calling findAccessibilityFocus()");
1734                }
1735            } finally {
1736                Binder.restoreCallingIdentity(identityToken);
1737            }
1738            return 0;
1739        }
1740
1741        @Override
1742        public float focusSearch(int accessibilityWindowId, long accessibilityNodeId,
1743                int direction, int interactionId,
1744                IAccessibilityInteractionConnectionCallback callback, long interrogatingTid)
1745                throws RemoteException {
1746            final int resolvedWindowId;
1747            IAccessibilityInteractionConnection connection = null;
1748            synchronized (mLock) {
1749                final int resolvedUserId = mSecurityPolicy
1750                        .resolveCallingUserIdEnforcingPermissionsLocked(
1751                        UserHandle.getCallingUserId());
1752                if (resolvedUserId != mCurrentUserId) {
1753                    return -1;
1754                }
1755                mSecurityPolicy.enforceCanRetrieveWindowContent(this);
1756                resolvedWindowId = resolveAccessibilityWindowIdLocked(accessibilityWindowId);
1757                final boolean permissionGranted =
1758                    mSecurityPolicy.canGetAccessibilityNodeInfoLocked(this, resolvedWindowId);
1759                if (!permissionGranted) {
1760                    return 0;
1761                } else {
1762                    connection = getConnectionLocked(resolvedWindowId);
1763                    if (connection == null) {
1764                        return 0;
1765                    }
1766                }
1767            }
1768            final int flags = (mIncludeNotImportantViews) ?
1769                    AccessibilityNodeInfo.INCLUDE_NOT_IMPORTANT_VIEWS : 0;
1770            final int interrogatingPid = Binder.getCallingPid();
1771            final long identityToken = Binder.clearCallingIdentity();
1772            try {
1773                connection.focusSearch(accessibilityNodeId, direction, interactionId, callback,
1774                        flags, interrogatingPid, interrogatingTid);
1775                return getCompatibilityScale(resolvedWindowId);
1776            } catch (RemoteException re) {
1777                if (DEBUG) {
1778                    Slog.e(LOG_TAG, "Error calling accessibilityFocusSearch()");
1779                }
1780            } finally {
1781                Binder.restoreCallingIdentity(identityToken);
1782            }
1783            return 0;
1784        }
1785
1786        @Override
1787        public boolean performAccessibilityAction(int accessibilityWindowId,
1788                long accessibilityNodeId, int action, Bundle arguments, int interactionId,
1789                IAccessibilityInteractionConnectionCallback callback, long interrogatingTid)
1790                throws RemoteException {
1791            final int resolvedWindowId;
1792            IAccessibilityInteractionConnection connection = null;
1793            synchronized (mLock) {
1794                final int resolvedUserId = mSecurityPolicy
1795                        .resolveCallingUserIdEnforcingPermissionsLocked(
1796                        UserHandle.getCallingUserId());
1797                if (resolvedUserId != mCurrentUserId) {
1798                    return false;
1799                }
1800                mSecurityPolicy.enforceCanRetrieveWindowContent(this);
1801                resolvedWindowId = resolveAccessibilityWindowIdLocked(accessibilityWindowId);
1802                final boolean permissionGranted = mSecurityPolicy.canPerformActionLocked(this,
1803                        resolvedWindowId, action, arguments);
1804                if (!permissionGranted) {
1805                    return false;
1806                } else {
1807                    connection = getConnectionLocked(resolvedWindowId);
1808                    if (connection == null) {
1809                        return false;
1810                    }
1811                }
1812            }
1813            final int flags = (mIncludeNotImportantViews) ?
1814                    AccessibilityNodeInfo.INCLUDE_NOT_IMPORTANT_VIEWS : 0;
1815            final int interrogatingPid = Binder.getCallingPid();
1816            final long identityToken = Binder.clearCallingIdentity();
1817            try {
1818                connection.performAccessibilityAction(accessibilityNodeId, action, arguments,
1819                        interactionId, callback, flags, interrogatingPid, interrogatingTid);
1820            } catch (RemoteException re) {
1821                if (DEBUG) {
1822                    Slog.e(LOG_TAG, "Error calling performAccessibilityAction()");
1823                }
1824            } finally {
1825                Binder.restoreCallingIdentity(identityToken);
1826            }
1827            return true;
1828        }
1829
1830        public boolean performGlobalAction(int action) {
1831            synchronized (mLock) {
1832                final int resolvedUserId = mSecurityPolicy
1833                        .resolveCallingUserIdEnforcingPermissionsLocked(
1834                        UserHandle.getCallingUserId());
1835                if (resolvedUserId != mCurrentUserId) {
1836                    return false;
1837                }
1838            }
1839            final long identity = Binder.clearCallingIdentity();
1840            try {
1841                switch (action) {
1842                    case AccessibilityService.GLOBAL_ACTION_BACK: {
1843                        sendDownAndUpKeyEvents(KeyEvent.KEYCODE_BACK);
1844                    } return true;
1845                    case AccessibilityService.GLOBAL_ACTION_HOME: {
1846                        sendDownAndUpKeyEvents(KeyEvent.KEYCODE_HOME);
1847                    } return true;
1848                    case AccessibilityService.GLOBAL_ACTION_RECENTS: {
1849                        openRecents();
1850                    } return true;
1851                    case AccessibilityService.GLOBAL_ACTION_NOTIFICATIONS: {
1852                        expandNotifications();
1853                    } return true;
1854                    case AccessibilityService.GLOBAL_ACTION_QUICK_SETTINGS: {
1855                        expandQuickSettings();
1856                    } return true;
1857                }
1858                return false;
1859            } finally {
1860                Binder.restoreCallingIdentity(identity);
1861            }
1862        }
1863
1864        public void onServiceDisconnected(ComponentName componentName) {
1865            /* do nothing - #binderDied takes care */
1866        }
1867
1868        public void linkToOwnDeath() throws RemoteException {
1869            mService.linkToDeath(this, 0);
1870        }
1871
1872        public void unlinkToOwnDeath() {
1873            mService.unlinkToDeath(this, 0);
1874        }
1875
1876        public void dispose() {
1877            try {
1878                // Clear the proxy in the other process so this
1879                // IAccessibilityServiceConnection can be garbage collected.
1880                mServiceInterface.setConnection(null, mId);
1881            } catch (RemoteException re) {
1882                /* ignore */
1883            }
1884            mService = null;
1885            mServiceInterface = null;
1886        }
1887
1888        public void binderDied() {
1889            synchronized (mLock) {
1890                // The death recipient is unregistered in tryRemoveServiceLocked
1891                tryRemoveServiceLocked(this);
1892                // We no longer have an automation service, so restore
1893                // the state based on values in the settings database.
1894                if (mIsAutomation) {
1895                    mUiAutomationService = null;
1896                    recreateInternalStateLocked(getUserStateLocked(mUserId));
1897                }
1898            }
1899        }
1900
1901        /**
1902         * Performs a notification for an {@link AccessibilityEvent}.
1903         *
1904         * @param event The event.
1905         */
1906        public void notifyAccessibilityEvent(AccessibilityEvent event) {
1907            synchronized (mLock) {
1908                final int eventType = event.getEventType();
1909                // Make a copy since during dispatch it is possible the event to
1910                // be modified to remove its source if the receiving service does
1911                // not have permission to access the window content.
1912                AccessibilityEvent newEvent = AccessibilityEvent.obtain(event);
1913                AccessibilityEvent oldEvent = mPendingEvents.get(eventType);
1914                mPendingEvents.put(eventType, newEvent);
1915
1916                final int what = eventType;
1917                if (oldEvent != null) {
1918                    mHandler.removeMessages(what);
1919                    oldEvent.recycle();
1920                }
1921
1922                Message message = mHandler.obtainMessage(what);
1923                mHandler.sendMessageDelayed(message, mNotificationTimeout);
1924            }
1925        }
1926
1927        /**
1928         * Notifies an accessibility service client for a scheduled event given the event type.
1929         *
1930         * @param eventType The type of the event to dispatch.
1931         */
1932        private void notifyAccessibilityEventInternal(int eventType) {
1933            IAccessibilityServiceClient listener;
1934            AccessibilityEvent event;
1935
1936            synchronized (mLock) {
1937                listener = mServiceInterface;
1938
1939                // If the service died/was disabled while the message for dispatching
1940                // the accessibility event was propagating the listener may be null.
1941                if (listener == null) {
1942                    return;
1943                }
1944
1945                event = mPendingEvents.get(eventType);
1946
1947                // Check for null here because there is a concurrent scenario in which this
1948                // happens: 1) A binder thread calls notifyAccessibilityServiceDelayedLocked
1949                // which posts a message for dispatching an event. 2) The message is pulled
1950                // from the queue by the handler on the service thread and the latter is
1951                // just about to acquire the lock and call this method. 3) Now another binder
1952                // thread acquires the lock calling notifyAccessibilityServiceDelayedLocked
1953                // so the service thread waits for the lock; 4) The binder thread replaces
1954                // the event with a more recent one (assume the same event type) and posts a
1955                // dispatch request releasing the lock. 5) Now the main thread is unblocked and
1956                // dispatches the event which is removed from the pending ones. 6) And ... now
1957                // the service thread handles the last message posted by the last binder call
1958                // but the event is already dispatched and hence looking it up in the pending
1959                // ones yields null. This check is much simpler that keeping count for each
1960                // event type of each service to catch such a scenario since only one message
1961                // is processed at a time.
1962                if (event == null) {
1963                    return;
1964                }
1965
1966                mPendingEvents.remove(eventType);
1967                if (mSecurityPolicy.canRetrieveWindowContent(this)) {
1968                    event.setConnectionId(mId);
1969                } else {
1970                    event.setSource(null);
1971                }
1972                event.setSealed(true);
1973            }
1974
1975            try {
1976                listener.onAccessibilityEvent(event);
1977                if (DEBUG) {
1978                    Slog.i(LOG_TAG, "Event " + event + " sent to " + listener);
1979                }
1980            } catch (RemoteException re) {
1981                Slog.e(LOG_TAG, "Error during sending " + event + " to " + listener, re);
1982            } finally {
1983                event.recycle();
1984            }
1985        }
1986
1987        public void notifyGesture(int gestureId) {
1988            mHandler.obtainMessage(MSG_ON_GESTURE, gestureId, 0).sendToTarget();
1989        }
1990
1991        private void notifyGestureInternal(int gestureId) {
1992            IAccessibilityServiceClient listener = mServiceInterface;
1993            if (listener != null) {
1994                try {
1995                    listener.onGesture(gestureId);
1996                } catch (RemoteException re) {
1997                    Slog.e(LOG_TAG, "Error during sending gesture " + gestureId
1998                            + " to " + mService, re);
1999                }
2000            }
2001        }
2002
2003        private void sendDownAndUpKeyEvents(int keyCode) {
2004            final long token = Binder.clearCallingIdentity();
2005
2006            // Inject down.
2007            final long downTime = SystemClock.uptimeMillis();
2008            KeyEvent down = KeyEvent.obtain(downTime, downTime, KeyEvent.ACTION_DOWN, keyCode, 0, 0,
2009                    KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FROM_SYSTEM,
2010                    InputDevice.SOURCE_KEYBOARD, null);
2011            InputManager.getInstance().injectInputEvent(down,
2012                    InputManager.INJECT_INPUT_EVENT_MODE_ASYNC);
2013            down.recycle();
2014
2015            // Inject up.
2016            final long upTime = SystemClock.uptimeMillis();
2017            KeyEvent up = KeyEvent.obtain(downTime, upTime, KeyEvent.ACTION_UP, keyCode, 0, 0,
2018                    KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FROM_SYSTEM,
2019                    InputDevice.SOURCE_KEYBOARD, null);
2020            InputManager.getInstance().injectInputEvent(up,
2021                    InputManager.INJECT_INPUT_EVENT_MODE_ASYNC);
2022            up.recycle();
2023
2024            Binder.restoreCallingIdentity(token);
2025        }
2026
2027        private void expandNotifications() {
2028            final long token = Binder.clearCallingIdentity();
2029
2030            StatusBarManager statusBarManager = (StatusBarManager) mContext.getSystemService(
2031                    android.app.Service.STATUS_BAR_SERVICE);
2032            statusBarManager.expandNotificationsPanel();
2033
2034            Binder.restoreCallingIdentity(token);
2035        }
2036
2037        private void expandQuickSettings() {
2038            final long token = Binder.clearCallingIdentity();
2039
2040            StatusBarManager statusBarManager = (StatusBarManager) mContext.getSystemService(
2041                    android.app.Service.STATUS_BAR_SERVICE);
2042            statusBarManager.expandSettingsPanel();
2043
2044            Binder.restoreCallingIdentity(token);
2045        }
2046
2047        private void openRecents() {
2048            final long token = Binder.clearCallingIdentity();
2049
2050            IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
2051                    ServiceManager.getService("statusbar"));
2052            try {
2053                statusBarService.toggleRecentApps();
2054            } catch (RemoteException e) {
2055                Slog.e(LOG_TAG, "Error toggling recent apps.");
2056            }
2057
2058            Binder.restoreCallingIdentity(token);
2059        }
2060
2061        private IAccessibilityInteractionConnection getConnectionLocked(int windowId) {
2062            if (DEBUG) {
2063                Slog.i(LOG_TAG, "Trying to get interaction connection to windowId: " + windowId);
2064            }
2065            AccessibilityConnectionWrapper wrapper = mGlobalInteractionConnections.get(windowId);
2066            if (wrapper == null) {
2067                wrapper = getCurrentUserStateLocked().mInteractionConnections.get(windowId);
2068            }
2069            if (wrapper != null && wrapper.mConnection != null) {
2070                return wrapper.mConnection;
2071            }
2072            if (DEBUG) {
2073                Slog.e(LOG_TAG, "No interaction connection to window: " + windowId);
2074            }
2075            return null;
2076        }
2077
2078        private int resolveAccessibilityWindowIdLocked(int accessibilityWindowId) {
2079            if (accessibilityWindowId == AccessibilityNodeInfo.ACTIVE_WINDOW_ID) {
2080                return mSecurityPolicy.mActiveWindowId;
2081            }
2082            return accessibilityWindowId;
2083        }
2084
2085        private float getCompatibilityScale(int windowId) {
2086            try {
2087                IBinder windowToken = mGlobalWindowTokens.get(windowId);
2088                if (windowToken != null) {
2089                    return mWindowManagerService.getWindowCompatibilityScale(windowToken);
2090                }
2091                windowToken = getCurrentUserStateLocked().mWindowTokens.get(windowId);
2092                if (windowToken != null) {
2093                    return mWindowManagerService.getWindowCompatibilityScale(windowToken);
2094                }
2095            } catch (RemoteException re) {
2096                /* ignore */
2097            }
2098            return 1.0f;
2099        }
2100    }
2101
2102    final class SecurityPolicy {
2103        private static final int VALID_ACTIONS =
2104            AccessibilityNodeInfo.ACTION_CLICK
2105            | AccessibilityNodeInfo.ACTION_LONG_CLICK
2106            | AccessibilityNodeInfo.ACTION_FOCUS
2107            | AccessibilityNodeInfo.ACTION_CLEAR_FOCUS
2108            | AccessibilityNodeInfo.ACTION_SELECT
2109            | AccessibilityNodeInfo.ACTION_CLEAR_SELECTION
2110            | AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS
2111            | AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS
2112            | AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
2113            | AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY
2114            | AccessibilityNodeInfo.ACTION_NEXT_HTML_ELEMENT
2115            | AccessibilityNodeInfo.ACTION_PREVIOUS_HTML_ELEMENT
2116            | AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
2117            | AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD;
2118
2119        private static final int RETRIEVAL_ALLOWING_EVENT_TYPES =
2120            AccessibilityEvent.TYPE_VIEW_CLICKED
2121            | AccessibilityEvent.TYPE_VIEW_FOCUSED
2122            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
2123            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
2124            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
2125            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
2126            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
2127            | AccessibilityEvent.TYPE_VIEW_SELECTED
2128            | AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED
2129            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
2130            | AccessibilityEvent.TYPE_VIEW_SCROLLED
2131            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
2132            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED;
2133
2134        private int mActiveWindowId;
2135
2136        private boolean canDispatchAccessibilityEvent(AccessibilityEvent event) {
2137            final int eventType = event.getEventType();
2138            switch (eventType) {
2139                // All events that are for changes in a global window
2140                // state should *always* be dispatched.
2141                case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
2142                case AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED:
2143                // All events generated by the user touching the
2144                // screen should *always* be dispatched.
2145                case AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_START:
2146                case AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_END:
2147                case AccessibilityEvent.TYPE_GESTURE_DETECTION_START:
2148                case AccessibilityEvent.TYPE_GESTURE_DETECTION_END:
2149                case AccessibilityEvent.TYPE_TOUCH_INTERACTION_START:
2150                case AccessibilityEvent.TYPE_TOUCH_INTERACTION_END:
2151                // These will change the active window, so dispatch.
2152                case AccessibilityEvent.TYPE_VIEW_HOVER_ENTER:
2153                case AccessibilityEvent.TYPE_VIEW_HOVER_EXIT: {
2154                    return true;
2155                }
2156                // All events for changes in window content should be
2157                // dispatched *only* if this window is the active one.
2158                default:
2159                    return event.getWindowId() == mActiveWindowId;
2160            }
2161        }
2162
2163        public void updateEventSourceLocked(AccessibilityEvent event) {
2164            if ((event.getEventType() & RETRIEVAL_ALLOWING_EVENT_TYPES) == 0) {
2165                event.setSource(null);
2166            }
2167        }
2168
2169        public void updateActiveWindow(int windowId, int eventType) {
2170            // The active window is either the window that has input focus or
2171            // the window that the user is currently touching. If the user is
2172            // touching a window that does not have input focus as soon as the
2173            // the user stops touching that window the focused window becomes
2174            // the active one.
2175            switch (eventType) {
2176                case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED: {
2177                    if (getFocusedWindowId() == windowId) {
2178                        mActiveWindowId = windowId;
2179                    }
2180                } break;
2181                case AccessibilityEvent.TYPE_VIEW_HOVER_ENTER:
2182                case AccessibilityEvent.TYPE_VIEW_HOVER_EXIT: {
2183                    mActiveWindowId = windowId;
2184                } break;
2185                case AccessibilityEvent.TYPE_TOUCH_INTERACTION_END: {
2186                    mActiveWindowId = getFocusedWindowId();
2187                } break;
2188            }
2189        }
2190
2191        public int getRetrievalAllowingWindowLocked() {
2192            return mActiveWindowId;
2193        }
2194
2195        public boolean canGetAccessibilityNodeInfoLocked(Service service, int windowId) {
2196            return canRetrieveWindowContent(service) && isRetrievalAllowingWindow(windowId);
2197        }
2198
2199        public boolean canPerformActionLocked(Service service, int windowId, int action,
2200                Bundle arguments) {
2201            return canRetrieveWindowContent(service)
2202                && isRetrievalAllowingWindow(windowId)
2203                && isActionPermitted(action);
2204        }
2205
2206        public boolean canRetrieveWindowContent(Service service) {
2207            return service.mCanRetrieveScreenContent;
2208        }
2209
2210        public void enforceCanRetrieveWindowContent(Service service) throws RemoteException {
2211            // This happens due to incorrect registration so make it apparent.
2212            if (!canRetrieveWindowContent(service)) {
2213                Slog.e(LOG_TAG, "Accessibility serivce " + service.mComponentName + " does not " +
2214                        "declare android:canRetrieveWindowContent.");
2215                throw new RemoteException();
2216            }
2217        }
2218
2219        public int resolveCallingUserIdEnforcingPermissionsLocked(int userId) {
2220            final int callingUid = Binder.getCallingUid();
2221            if (callingUid == Process.SYSTEM_UID
2222                    || callingUid == Process.SHELL_UID) {
2223                return mCurrentUserId;
2224            }
2225            final int callingUserId = UserHandle.getUserId(callingUid);
2226            if (callingUserId == userId) {
2227                return userId;
2228            }
2229            if (!hasPermission(Manifest.permission.INTERACT_ACROSS_USERS)
2230                    && !hasPermission(Manifest.permission.INTERACT_ACROSS_USERS_FULL)) {
2231                throw new SecurityException("Call from user " + callingUserId + " as user "
2232                        + userId + " without permission INTERACT_ACROSS_USERS or "
2233                        + "INTERACT_ACROSS_USERS_FULL not allowed.");
2234            }
2235            if (userId == UserHandle.USER_CURRENT
2236                    || userId == UserHandle.USER_CURRENT_OR_SELF) {
2237                return mCurrentUserId;
2238            }
2239            throw new IllegalArgumentException("Calling user can be changed to only "
2240                    + "UserHandle.USER_CURRENT or UserHandle.USER_CURRENT_OR_SELF.");
2241        }
2242
2243        public boolean isCallerInteractingAcrossUsers(int userId) {
2244            final int callingUid = Binder.getCallingUid();
2245            return (Binder.getCallingPid() == android.os.Process.myPid()
2246                    || callingUid == Process.SHELL_UID
2247                    || userId == UserHandle.USER_CURRENT
2248                    || userId == UserHandle.USER_CURRENT_OR_SELF);
2249        }
2250
2251        private boolean isRetrievalAllowingWindow(int windowId) {
2252            return (mActiveWindowId == windowId);
2253        }
2254
2255        private boolean isActionPermitted(int action) {
2256             return (VALID_ACTIONS & action) != 0;
2257        }
2258
2259        private void enforceCallingPermission(String permission, String function) {
2260            if (OWN_PROCESS_ID == Binder.getCallingPid()) {
2261                return;
2262            }
2263            if (!hasPermission(permission)) {
2264                throw new SecurityException("You do not have " + permission
2265                        + " required to call " + function);
2266            }
2267        }
2268
2269        private boolean hasPermission(String permission) {
2270            return mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED;
2271        }
2272
2273        private int getFocusedWindowId() {
2274            try {
2275                // We call this only on window focus change or after touch
2276                // exploration gesture end and the shown windows are not that
2277                // many, so the linear look up is just fine.
2278                IBinder token = mWindowManagerService.getFocusedWindowToken();
2279                if (token != null) {
2280                    synchronized (mLock) {
2281                        int windowId = getFocusedWindowIdLocked(token, mGlobalWindowTokens);
2282                        if (windowId < 0) {
2283                            windowId = getFocusedWindowIdLocked(token,
2284                                    getCurrentUserStateLocked().mWindowTokens);
2285                        }
2286                        return windowId;
2287                    }
2288                }
2289            } catch (RemoteException re) {
2290                /* ignore */
2291            }
2292            return -1;
2293        }
2294
2295        private int getFocusedWindowIdLocked(IBinder token, SparseArray<IBinder> windows) {
2296            final int windowCount = windows.size();
2297            for (int i = 0; i < windowCount; i++) {
2298                if (windows.valueAt(i) == token) {
2299                    return windows.keyAt(i);
2300                }
2301            }
2302            return -1;
2303        }
2304    }
2305
2306    private class UserState {
2307        public final int mUserId;
2308
2309        public final CopyOnWriteArrayList<Service> mServices = new CopyOnWriteArrayList<Service>();
2310
2311        public final RemoteCallbackList<IAccessibilityManagerClient> mClients =
2312            new RemoteCallbackList<IAccessibilityManagerClient>();
2313
2314        public final Map<ComponentName, Service> mComponentNameToServiceMap =
2315                new HashMap<ComponentName, Service>();
2316
2317        public final List<AccessibilityServiceInfo> mInstalledServices =
2318                new ArrayList<AccessibilityServiceInfo>();
2319
2320        public final Set<ComponentName> mEnabledServices = new HashSet<ComponentName>();
2321
2322        public final Set<ComponentName> mTouchExplorationGrantedServices =
2323                new HashSet<ComponentName>();
2324
2325        public final SparseArray<AccessibilityConnectionWrapper>
2326                mInteractionConnections =
2327                new SparseArray<AccessibilityConnectionWrapper>();
2328
2329        public final SparseArray<IBinder> mWindowTokens = new SparseArray<IBinder>();
2330
2331        public int mHandledFeedbackTypes = 0;
2332
2333        public boolean mIsAccessibilityEnabled;
2334        public boolean mIsTouchExplorationEnabled;
2335        public boolean mIsDisplayMagnificationEnabled;
2336
2337        public UserState(int userId) {
2338            mUserId = userId;
2339        }
2340    }
2341
2342    private class TempUserStateChangeMemento {
2343        public int mUserId = UserHandle.USER_NULL;
2344        public boolean mIsAccessibilityEnabled;
2345        public boolean mIsTouchExplorationEnabled;
2346        public boolean mIsDisplayMagnificationEnabled;
2347        public final Set<ComponentName> mEnabledServices = new HashSet<ComponentName>();
2348        public final Set<ComponentName> mTouchExplorationGrantedServices =
2349                new HashSet<ComponentName>();
2350
2351        public void initialize(int userId, UserState userState) {
2352            mUserId = userId;
2353            mIsAccessibilityEnabled = userState.mIsAccessibilityEnabled;
2354            mIsTouchExplorationEnabled = userState.mIsTouchExplorationEnabled;
2355            mIsDisplayMagnificationEnabled = userState.mIsDisplayMagnificationEnabled;
2356            mEnabledServices.clear();
2357            mEnabledServices.addAll(userState.mEnabledServices);
2358            mTouchExplorationGrantedServices.clear();
2359            mTouchExplorationGrantedServices.addAll(userState.mTouchExplorationGrantedServices);
2360        }
2361
2362        public void applyTo(UserState userState) {
2363            userState.mIsAccessibilityEnabled = mIsAccessibilityEnabled;
2364            userState.mIsTouchExplorationEnabled = mIsTouchExplorationEnabled;
2365            userState.mIsDisplayMagnificationEnabled = mIsDisplayMagnificationEnabled;
2366            userState.mEnabledServices.clear();
2367            userState.mEnabledServices.addAll(mEnabledServices);
2368            userState.mTouchExplorationGrantedServices.clear();
2369            userState.mTouchExplorationGrantedServices.addAll(mTouchExplorationGrantedServices);
2370        }
2371
2372        public void clear() {
2373            mUserId = UserHandle.USER_NULL;
2374            mIsAccessibilityEnabled = false;
2375            mIsTouchExplorationEnabled = false;
2376            mIsDisplayMagnificationEnabled = false;
2377            mEnabledServices.clear();
2378            mTouchExplorationGrantedServices.clear();
2379        }
2380    }
2381
2382    private final class AccessibilityContentObserver extends ContentObserver {
2383
2384        private final Uri mAccessibilityEnabledUri = Settings.Secure.getUriFor(
2385                Settings.Secure.ACCESSIBILITY_ENABLED);
2386
2387        private final Uri mTouchExplorationEnabledUri = Settings.Secure.getUriFor(
2388                Settings.Secure.TOUCH_EXPLORATION_ENABLED);
2389
2390        private final Uri mDisplayMagnificationEnabledUri = Settings.Secure.getUriFor(
2391                Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED);
2392
2393        private final Uri mEnabledAccessibilityServicesUri = Settings.Secure.getUriFor(
2394                Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
2395
2396        private final Uri mTouchExplorationGrantedAccessibilityServicesUri = Settings.Secure
2397                .getUriFor(Settings.Secure.TOUCH_EXPLORATION_GRANTED_ACCESSIBILITY_SERVICES);
2398
2399        public AccessibilityContentObserver(Handler handler) {
2400            super(handler);
2401        }
2402
2403        public void register(ContentResolver contentResolver) {
2404            contentResolver.registerContentObserver(mAccessibilityEnabledUri,
2405                    false, this, UserHandle.USER_ALL);
2406            contentResolver.registerContentObserver(mTouchExplorationEnabledUri,
2407                    false, this, UserHandle.USER_ALL);
2408            contentResolver.registerContentObserver(mDisplayMagnificationEnabledUri,
2409                    false, this, UserHandle.USER_ALL);
2410            contentResolver.registerContentObserver(mEnabledAccessibilityServicesUri,
2411                    false, this, UserHandle.USER_ALL);
2412            contentResolver.registerContentObserver(
2413                    mTouchExplorationGrantedAccessibilityServicesUri,
2414                    false, this, UserHandle.USER_ALL);
2415        }
2416
2417        @Override
2418        public void onChange(boolean selfChange, Uri uri) {
2419            if (mAccessibilityEnabledUri.equals(uri)) {
2420                synchronized (mLock) {
2421                    // We will update when the automation service dies.
2422                    if (mUiAutomationService == null) {
2423                        UserState userState = getCurrentUserStateLocked();
2424                        handleAccessibilityEnabledSettingChangedLocked(userState);
2425                        performServiceManagementLocked(userState);
2426                        updateInputFilterLocked(userState);
2427                        scheduleSendStateToClientsLocked(userState);
2428                    }
2429                }
2430            } else if (mTouchExplorationEnabledUri.equals(uri)) {
2431                synchronized (mLock) {
2432                    // We will update when the automation service dies.
2433                    if (mUiAutomationService == null) {
2434                        UserState userState = getCurrentUserStateLocked();
2435                        handleTouchExplorationEnabledSettingChangedLocked(userState);
2436                        updateInputFilterLocked(userState);
2437                        scheduleSendStateToClientsLocked(userState);
2438                    }
2439                }
2440            } else if (mDisplayMagnificationEnabledUri.equals(uri)) {
2441                synchronized (mLock) {
2442                    // We will update when the automation service dies.
2443                    if (mUiAutomationService == null) {
2444                        UserState userState = getCurrentUserStateLocked();
2445                        handleDisplayMagnificationEnabledSettingChangedLocked(userState);
2446                        updateInputFilterLocked(userState);
2447                        scheduleSendStateToClientsLocked(userState);
2448                    }
2449                }
2450            } else if (mEnabledAccessibilityServicesUri.equals(uri)) {
2451                synchronized (mLock) {
2452                    // We will update when the automation service dies.
2453                    if (mUiAutomationService == null) {
2454                        UserState userState = getCurrentUserStateLocked();
2455                        populateEnabledAccessibilityServicesLocked(userState);
2456                        manageServicesLocked(userState);
2457                    }
2458                }
2459            } else if (mTouchExplorationGrantedAccessibilityServicesUri.equals(uri)) {
2460                synchronized (mLock) {
2461                    // We will update when the automation service dies.
2462                    if (mUiAutomationService == null) {
2463                        UserState userState = getCurrentUserStateLocked();
2464                        populateTouchExplorationGrantedAccessibilityServicesLocked(userState);
2465                        handleTouchExplorationGrantedAccessibilityServicesChangedLocked(userState);
2466                    }
2467                }
2468            }
2469        }
2470    }
2471}
2472