AccessibilityManagerService.java revision f772cba59760d1ad9eb5cb9205b2e2e9126e488d
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    void onTouchInteractionEnd() {
647        mSecurityPolicy.onTouchInteractionEnd();
648    }
649
650    private void switchUser(int userId) {
651        synchronized (mLock) {
652            // The user switched so we do not need to restore the current user
653            // state since we will fully rebuild it when he becomes current again.
654            mTempStateChangeForCurrentUserMemento.clear();
655
656            // Disconnect from services for the old user.
657            UserState oldUserState = getUserStateLocked(mCurrentUserId);
658            unbindAllServicesLocked(oldUserState);
659
660            // Disable the local managers for the old user.
661            if (oldUserState.mClients.getRegisteredCallbackCount() > 0) {
662                mMainHandler.obtainMessage(MainHandler.MSG_SEND_CLEARED_STATE_TO_CLIENTS_FOR_USER,
663                        oldUserState.mUserId, 0).sendToTarget();
664            }
665
666            // Announce user changes only if more that one exist.
667            UserManager userManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
668            final boolean announceNewUser = userManager.getUsers().size() > 1;
669
670            // The user changed.
671            mCurrentUserId = userId;
672
673            // Recreate the internal state for the new user.
674            mMainHandler.obtainMessage(MainHandler.MSG_SEND_RECREATE_INTERNAL_STATE,
675                    mCurrentUserId, 0).sendToTarget();
676
677            if (announceNewUser) {
678                // Schedule announcement of the current user if needed.
679                mMainHandler.sendEmptyMessageDelayed(MainHandler.MSG_ANNOUNCE_NEW_USER_IF_NEEDED,
680                        WAIT_FOR_USER_STATE_FULLY_INITIALIZED_MILLIS);
681            }
682        }
683    }
684
685    private void removeUser(int userId) {
686        synchronized (mLock) {
687            mUserStates.remove(userId);
688        }
689    }
690
691    private void restoreStateFromMementoIfNeeded() {
692        synchronized (mLock) {
693            if (mTempStateChangeForCurrentUserMemento.mUserId != UserHandle.USER_NULL) {
694                UserState userState = getCurrentUserStateLocked();
695                // Restore the state from the memento.
696                mTempStateChangeForCurrentUserMemento.applyTo(userState);
697                mTempStateChangeForCurrentUserMemento.clear();
698                // Update the internal state.
699                performServiceManagementLocked(userState);
700                updateInputFilterLocked(userState);
701                scheduleSendStateToClientsLocked(userState);
702            }
703        }
704    }
705
706    private Service getQueryBridge() {
707        if (mQueryBridge == null) {
708            AccessibilityServiceInfo info = new AccessibilityServiceInfo();
709            mQueryBridge = new Service(UserHandle.USER_NULL, null, info, true);
710        }
711        return mQueryBridge;
712    }
713
714    private boolean notifyGestureLocked(int gestureId, boolean isDefault) {
715        // TODO: Now we are giving the gestures to the last enabled
716        //       service that can handle them which is the last one
717        //       in our list since we write the last enabled as the
718        //       last record in the enabled services setting. Ideally,
719        //       the user should make the call which service handles
720        //       gestures. However, only one service should handle
721        //       gestures to avoid user frustration when different
722        //       behavior is observed from different combinations of
723        //       enabled accessibility services.
724        UserState state = getCurrentUserStateLocked();
725        for (int i = state.mServices.size() - 1; i >= 0; i--) {
726            Service service = state.mServices.get(i);
727            if (service.mRequestTouchExplorationMode && service.mIsDefault == isDefault) {
728                service.notifyGesture(gestureId);
729                return true;
730            }
731        }
732        return false;
733    }
734
735    /**
736     * Removes an AccessibilityInteractionConnection.
737     *
738     * @param windowId The id of the window to which the connection is targeted.
739     * @param userId The id of the user owning the connection. UserHandle.USER_ALL
740     *     if global.
741     */
742    private void removeAccessibilityInteractionConnectionLocked(int windowId, int userId) {
743        if (userId == UserHandle.USER_ALL) {
744            mGlobalWindowTokens.remove(windowId);
745            mGlobalInteractionConnections.remove(windowId);
746        } else {
747            UserState userState = getCurrentUserStateLocked();
748            userState.mWindowTokens.remove(windowId);
749            userState.mInteractionConnections.remove(windowId);
750        }
751        if (DEBUG) {
752            Slog.i(LOG_TAG, "Removing interaction connection to windowId: " + windowId);
753        }
754    }
755
756    private void populateInstalledAccessibilityServiceLocked(UserState userState) {
757        userState.mInstalledServices.clear();
758
759        List<ResolveInfo> installedServices = mPackageManager.queryIntentServicesAsUser(
760                new Intent(AccessibilityService.SERVICE_INTERFACE),
761                PackageManager.GET_SERVICES | PackageManager.GET_META_DATA,
762                mCurrentUserId);
763
764        for (int i = 0, count = installedServices.size(); i < count; i++) {
765            ResolveInfo resolveInfo = installedServices.get(i);
766            ServiceInfo serviceInfo = resolveInfo.serviceInfo;
767            if (!android.Manifest.permission.BIND_ACCESSIBILITY_SERVICE.equals(
768                    serviceInfo.permission)) {
769                Slog.w(LOG_TAG, "Skipping accessibilty service " + new ComponentName(
770                        serviceInfo.packageName, serviceInfo.name).flattenToShortString()
771                        + ": it does not require the permission "
772                        + android.Manifest.permission.BIND_ACCESSIBILITY_SERVICE);
773                continue;
774            }
775            AccessibilityServiceInfo accessibilityServiceInfo;
776            try {
777                accessibilityServiceInfo = new AccessibilityServiceInfo(resolveInfo, mContext);
778                userState.mInstalledServices.add(accessibilityServiceInfo);
779            } catch (XmlPullParserException xppe) {
780                Slog.e(LOG_TAG, "Error while initializing AccessibilityServiceInfo", xppe);
781            } catch (IOException ioe) {
782                Slog.e(LOG_TAG, "Error while initializing AccessibilityServiceInfo", ioe);
783            }
784        }
785    }
786
787    private void populateEnabledAccessibilityServicesLocked(UserState userState) {
788        populateComponentNamesFromSettingLocked(
789                Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,
790                userState.mUserId,
791                userState.mEnabledServices);
792    }
793
794    private void populateTouchExplorationGrantedAccessibilityServicesLocked(
795            UserState userState) {
796        populateComponentNamesFromSettingLocked(
797                Settings.Secure.TOUCH_EXPLORATION_GRANTED_ACCESSIBILITY_SERVICES,
798                userState.mUserId,
799                userState.mTouchExplorationGrantedServices);
800    }
801
802    /**
803     * Performs {@link AccessibilityService}s delayed notification. The delay is configurable
804     * and denotes the period after the last event before notifying the service.
805     *
806     * @param event The event.
807     * @param isDefault True to notify default listeners, not default services.
808     */
809    private void notifyAccessibilityServicesDelayedLocked(AccessibilityEvent event,
810            boolean isDefault) {
811        try {
812            UserState state = getCurrentUserStateLocked();
813            for (int i = 0, count = state.mServices.size(); i < count; i++) {
814                Service service = state.mServices.get(i);
815
816                if (service.mIsDefault == isDefault) {
817                    if (canDispathEventLocked(service, event, state.mHandledFeedbackTypes)) {
818                        state.mHandledFeedbackTypes |= service.mFeedbackType;
819                        service.notifyAccessibilityEvent(event);
820                    }
821                }
822            }
823        } catch (IndexOutOfBoundsException oobe) {
824            // An out of bounds exception can happen if services are going away
825            // as the for loop is running. If that happens, just bail because
826            // there are no more services to notify.
827            return;
828        }
829    }
830
831    /**
832     * Adds a service for a user.
833     *
834     * @param service The service to add.
835     * @param userId The user id.
836     */
837    private void tryAddServiceLocked(Service service, int userId) {
838        try {
839            UserState userState = getUserStateLocked(userId);
840            if (userState.mServices.contains(service)) {
841                return;
842            }
843            service.linkToOwnDeath();
844            userState.mServices.add(service);
845            userState.mComponentNameToServiceMap.put(service.mComponentName, service);
846            updateInputFilterLocked(userState);
847            tryEnableTouchExplorationLocked(service);
848        } catch (RemoteException e) {
849            /* do nothing */
850        }
851    }
852
853    /**
854     * Removes a service.
855     *
856     * @param service The service.
857     * @return True if the service was removed, false otherwise.
858     */
859    private boolean tryRemoveServiceLocked(Service service) {
860        UserState userState = getUserStateLocked(service.mUserId);
861        final boolean removed = userState.mServices.remove(service);
862        if (!removed) {
863            return false;
864        }
865        userState.mComponentNameToServiceMap.remove(service.mComponentName);
866        service.unlinkToOwnDeath();
867        service.dispose();
868        updateInputFilterLocked(userState);
869        tryDisableTouchExplorationLocked(service);
870        return removed;
871    }
872
873    /**
874     * Determines if given event can be dispatched to a service based on the package of the
875     * event source and already notified services for that event type. Specifically, a
876     * service is notified if it is interested in events from the package and no other service
877     * providing the same feedback type has been notified. Exception are services the
878     * provide generic feedback (feedback type left as a safety net for unforeseen feedback
879     * types) which are always notified.
880     *
881     * @param service The potential receiver.
882     * @param event The event.
883     * @param handledFeedbackTypes The feedback types for which services have been notified.
884     * @return True if the listener should be notified, false otherwise.
885     */
886    private boolean canDispathEventLocked(Service service, AccessibilityEvent event,
887            int handledFeedbackTypes) {
888
889        if (!service.canReceiveEvents()) {
890            return false;
891        }
892
893        if (!event.isImportantForAccessibility()
894                && !service.mIncludeNotImportantViews) {
895            return false;
896        }
897
898        int eventType = event.getEventType();
899        if ((service.mEventTypes & eventType) != eventType) {
900            return false;
901        }
902
903        Set<String> packageNames = service.mPackageNames;
904        CharSequence packageName = event.getPackageName();
905
906        if (packageNames.isEmpty() || packageNames.contains(packageName)) {
907            int feedbackType = service.mFeedbackType;
908            if ((handledFeedbackTypes & feedbackType) != feedbackType
909                    || feedbackType == AccessibilityServiceInfo.FEEDBACK_GENERIC) {
910                return true;
911            }
912        }
913
914        return false;
915    }
916
917    /**
918     * Manages services by starting enabled ones and stopping disabled ones.
919     */
920    private void manageServicesLocked(UserState userState) {
921        final int enabledInstalledServicesCount = updateServicesStateLocked(userState);
922        // No enabled installed services => disable accessibility to avoid
923        // sending accessibility events with no recipient across processes.
924        if (userState.mIsAccessibilityEnabled && enabledInstalledServicesCount == 0) {
925            Settings.Secure.putIntForUser(mContext.getContentResolver(),
926                    Settings.Secure.ACCESSIBILITY_ENABLED, 0, userState.mUserId);
927        }
928    }
929
930    /**
931     * Unbinds all bound services for a user.
932     *
933     * @param userState The user state.
934     */
935    private void unbindAllServicesLocked(UserState userState) {
936        List<Service> services = userState.mServices;
937        for (int i = 0, count = services.size(); i < count; i++) {
938            Service service = services.get(i);
939            if (service.unbind()) {
940                i--;
941                count--;
942            }
943        }
944    }
945
946    /**
947     * Populates a set with the {@link ComponentName}s stored in a colon
948     * separated value setting for a given user.
949     *
950     * @param settingName The setting to parse.
951     * @param userId The user id.
952     * @param outComponentNames The output component names.
953     */
954    private void populateComponentNamesFromSettingLocked(String settingName, int userId,
955            Set<ComponentName> outComponentNames) {
956        String settingValue = Settings.Secure.getStringForUser(mContext.getContentResolver(),
957                settingName, userId);
958        outComponentNames.clear();
959        if (settingValue != null) {
960            TextUtils.SimpleStringSplitter splitter = mStringColonSplitter;
961            splitter.setString(settingValue);
962            while (splitter.hasNext()) {
963                String str = splitter.next();
964                if (str == null || str.length() <= 0) {
965                    continue;
966                }
967                ComponentName enabledService = ComponentName.unflattenFromString(str);
968                if (enabledService != null) {
969                    outComponentNames.add(enabledService);
970                }
971            }
972        }
973    }
974
975    /**
976     * Persists the component names in the specified setting in a
977     * colon separated fashion.
978     *
979     * @param settingName The setting name.
980     * @param componentNames The component names.
981     */
982    private void persistComponentNamesToSettingLocked(String settingName,
983            Set<ComponentName> componentNames, int userId) {
984        StringBuilder builder = new StringBuilder();
985        for (ComponentName componentName : componentNames) {
986            if (builder.length() > 0) {
987                builder.append(COMPONENT_NAME_SEPARATOR);
988            }
989            builder.append(componentName.flattenToShortString());
990        }
991        Settings.Secure.putStringForUser(mContext.getContentResolver(),
992                settingName, builder.toString(), userId);
993    }
994
995    /**
996     * Updates the state of each service by starting (or keeping running) enabled ones and
997     * stopping the rest.
998     *
999     * @param userState The user state for which to do that.
1000     * @return The number of enabled installed services.
1001     */
1002    private int updateServicesStateLocked(UserState userState) {
1003        Map<ComponentName, Service> componentNameToServiceMap =
1004                userState.mComponentNameToServiceMap;
1005        boolean isEnabled = userState.mIsAccessibilityEnabled;
1006
1007        int enabledInstalledServices = 0;
1008        for (int i = 0, count = userState.mInstalledServices.size(); i < count; i++) {
1009            AccessibilityServiceInfo installedService = userState.mInstalledServices.get(i);
1010            ComponentName componentName = ComponentName.unflattenFromString(
1011                    installedService.getId());
1012            Service service = componentNameToServiceMap.get(componentName);
1013
1014            if (isEnabled) {
1015                if (userState.mEnabledServices.contains(componentName)) {
1016                    if (service == null) {
1017                        service = new Service(userState.mUserId, componentName,
1018                                installedService, false);
1019                    }
1020                    service.bind();
1021                    enabledInstalledServices++;
1022                } else {
1023                    if (service != null) {
1024                        service.unbind();
1025                    }
1026                }
1027            } else {
1028                if (service != null) {
1029                    service.unbind();
1030                }
1031            }
1032        }
1033
1034        return enabledInstalledServices;
1035    }
1036
1037    private void scheduleSendStateToClientsLocked(UserState userState) {
1038        if (mGlobalClients.getRegisteredCallbackCount() > 0
1039                || userState.mClients.getRegisteredCallbackCount() > 0) {
1040            final int clientState = getClientState(userState);
1041            mMainHandler.obtainMessage(MainHandler.MSG_SEND_STATE_TO_CLIENTS,
1042                    clientState, userState.mUserId) .sendToTarget();
1043        }
1044    }
1045
1046    private void updateInputFilterLocked(UserState userState) {
1047        boolean setInputFilter = false;
1048        AccessibilityInputFilter inputFilter = null;
1049        synchronized (mLock) {
1050            if ((userState.mIsAccessibilityEnabled && userState.mIsTouchExplorationEnabled)
1051                    || userState.mIsDisplayMagnificationEnabled) {
1052                if (!mHasInputFilter) {
1053                    mHasInputFilter = true;
1054                    if (mInputFilter == null) {
1055                        mInputFilter = new AccessibilityInputFilter(mContext,
1056                                AccessibilityManagerService.this);
1057                    }
1058                    inputFilter = mInputFilter;
1059                    setInputFilter = true;
1060                }
1061                int flags = 0;
1062                if (userState.mIsDisplayMagnificationEnabled) {
1063                    flags |= AccessibilityInputFilter.FLAG_FEATURE_SCREEN_MAGNIFIER;
1064                }
1065                if (userState.mIsTouchExplorationEnabled) {
1066                    flags |= AccessibilityInputFilter.FLAG_FEATURE_TOUCH_EXPLORATION;
1067                }
1068                mInputFilter.setEnabledFeatures(flags);
1069            } else {
1070                if (mHasInputFilter) {
1071                    mHasInputFilter = false;
1072                    mInputFilter.setEnabledFeatures(0);
1073                    inputFilter = null;
1074                    setInputFilter = true;
1075                }
1076            }
1077        }
1078        if (setInputFilter) {
1079            try {
1080                mWindowManagerService.setInputFilter(inputFilter);
1081            } catch (RemoteException re) {
1082                /* ignore */
1083            }
1084        }
1085    }
1086
1087    private void showEnableTouchExplorationDialog(final Service service) {
1088        String label = service.mResolveInfo.loadLabel(
1089                mContext.getPackageManager()).toString();
1090        synchronized (mLock) {
1091            final UserState state = getCurrentUserStateLocked();
1092            if (state.mIsTouchExplorationEnabled) {
1093                return;
1094            }
1095            if (mEnableTouchExplorationDialog != null
1096                    && mEnableTouchExplorationDialog.isShowing()) {
1097                return;
1098            }
1099            mEnableTouchExplorationDialog = new AlertDialog.Builder(mContext)
1100                .setIcon(android.R.drawable.ic_dialog_alert)
1101                .setPositiveButton(android.R.string.ok, new OnClickListener() {
1102                    @Override
1103                    public void onClick(DialogInterface dialog, int which) {
1104                        // The user allowed the service to toggle touch exploration.
1105                        state.mTouchExplorationGrantedServices.add(service.mComponentName);
1106                        persistComponentNamesToSettingLocked(
1107                                Settings.Secure.TOUCH_EXPLORATION_GRANTED_ACCESSIBILITY_SERVICES,
1108                                       state.mTouchExplorationGrantedServices, state.mUserId);
1109                        // Enable touch exploration.
1110                        Settings.Secure.putIntForUser(mContext.getContentResolver(),
1111                                Settings.Secure.TOUCH_EXPLORATION_ENABLED, 1,
1112                                service.mUserId);
1113                    }
1114                })
1115                .setNegativeButton(android.R.string.cancel, new OnClickListener() {
1116                    @Override
1117                    public void onClick(DialogInterface dialog, int which) {
1118                        dialog.dismiss();
1119                    }
1120                })
1121                .setTitle(R.string.enable_explore_by_touch_warning_title)
1122                .setMessage(mContext.getString(
1123                        R.string.enable_explore_by_touch_warning_message, label))
1124                .create();
1125            mEnableTouchExplorationDialog.getWindow().setType(
1126                    WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG);
1127            mEnableTouchExplorationDialog.setCanceledOnTouchOutside(true);
1128            mEnableTouchExplorationDialog.show();
1129        }
1130    }
1131
1132    private int getClientState(UserState userState) {
1133        int clientState = 0;
1134        if (userState.mIsAccessibilityEnabled) {
1135            clientState |= AccessibilityManager.STATE_FLAG_ACCESSIBILITY_ENABLED;
1136        }
1137        // Touch exploration relies on enabled accessibility.
1138        if (userState.mIsAccessibilityEnabled && userState.mIsTouchExplorationEnabled) {
1139            clientState |= AccessibilityManager.STATE_FLAG_TOUCH_EXPLORATION_ENABLED;
1140        }
1141        return clientState;
1142    }
1143
1144    private void recreateInternalStateLocked(UserState userState) {
1145        populateInstalledAccessibilityServiceLocked(userState);
1146        populateEnabledAccessibilityServicesLocked(userState);
1147        populateTouchExplorationGrantedAccessibilityServicesLocked(userState);
1148
1149        handleTouchExplorationEnabledSettingChangedLocked(userState);
1150        handleDisplayMagnificationEnabledSettingChangedLocked(userState);
1151        handleAccessibilityEnabledSettingChangedLocked(userState);
1152
1153        performServiceManagementLocked(userState);
1154        updateInputFilterLocked(userState);
1155        scheduleSendStateToClientsLocked(userState);
1156    }
1157
1158    private void handleAccessibilityEnabledSettingChangedLocked(UserState userState) {
1159        userState.mIsAccessibilityEnabled = Settings.Secure.getIntForUser(
1160               mContext.getContentResolver(),
1161               Settings.Secure.ACCESSIBILITY_ENABLED, 0, userState.mUserId) == 1;
1162    }
1163
1164    private void performServiceManagementLocked(UserState userState) {
1165        if (userState.mIsAccessibilityEnabled ) {
1166            manageServicesLocked(userState);
1167        } else {
1168            unbindAllServicesLocked(userState);
1169        }
1170    }
1171
1172    private void handleTouchExplorationEnabledSettingChangedLocked(UserState userState) {
1173        userState.mIsTouchExplorationEnabled = Settings.Secure.getIntForUser(
1174                mContext.getContentResolver(),
1175                Settings.Secure.TOUCH_EXPLORATION_ENABLED, 0, userState.mUserId) == 1;
1176    }
1177
1178    private void handleDisplayMagnificationEnabledSettingChangedLocked(UserState userState) {
1179        userState.mIsDisplayMagnificationEnabled = Settings.Secure.getIntForUser(
1180                mContext.getContentResolver(),
1181                Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED,
1182                0, userState.mUserId) == 1;
1183    }
1184
1185    private void handleTouchExplorationGrantedAccessibilityServicesChangedLocked(
1186            UserState userState) {
1187        final int serviceCount = userState.mServices.size();
1188        for (int i = 0; i < serviceCount; i++) {
1189            Service service = userState.mServices.get(i);
1190            if (service.mRequestTouchExplorationMode
1191                    && userState.mTouchExplorationGrantedServices.contains(
1192                            service.mComponentName)) {
1193                tryEnableTouchExplorationLocked(service);
1194                return;
1195            }
1196        }
1197        if (userState.mIsTouchExplorationEnabled) {
1198            Settings.Secure.putIntForUser(mContext.getContentResolver(),
1199                    Settings.Secure.TOUCH_EXPLORATION_ENABLED, 0, userState.mUserId);
1200        }
1201    }
1202
1203    private void tryEnableTouchExplorationLocked(final Service service) {
1204        UserState userState = getUserStateLocked(service.mUserId);
1205        if (!userState.mIsTouchExplorationEnabled && service.mRequestTouchExplorationMode
1206                && service.canReceiveEvents()) {
1207            final boolean canToggleTouchExploration =
1208                    userState.mTouchExplorationGrantedServices.contains(service.mComponentName);
1209            if (!service.mIsAutomation && !canToggleTouchExploration) {
1210                showEnableTouchExplorationDialog(service);
1211            } else {
1212                Settings.Secure.putIntForUser(mContext.getContentResolver(),
1213                        Settings.Secure.TOUCH_EXPLORATION_ENABLED, 1, userState.mUserId);
1214            }
1215        }
1216    }
1217
1218    private void tryDisableTouchExplorationLocked(Service service) {
1219        UserState userState = getUserStateLocked(service.mUserId);
1220        if (userState.mIsTouchExplorationEnabled) {
1221            final int serviceCount = userState.mServices.size();
1222            for (int i = 0; i < serviceCount; i++) {
1223                Service other = userState.mServices.get(i);
1224                if (other != service && other.mRequestTouchExplorationMode) {
1225                    return;
1226                }
1227            }
1228            Settings.Secure.putIntForUser(mContext.getContentResolver(),
1229                    Settings.Secure.TOUCH_EXPLORATION_ENABLED, 0, userState.mUserId);
1230        }
1231    }
1232
1233    private class AccessibilityConnectionWrapper implements DeathRecipient {
1234        private final int mWindowId;
1235        private final int mUserId;
1236        private final IAccessibilityInteractionConnection mConnection;
1237
1238        public AccessibilityConnectionWrapper(int windowId,
1239                IAccessibilityInteractionConnection connection, int userId) {
1240            mWindowId = windowId;
1241            mUserId = userId;
1242            mConnection = connection;
1243        }
1244
1245        public void linkToDeath() throws RemoteException {
1246            mConnection.asBinder().linkToDeath(this, 0);
1247        }
1248
1249        public void unlinkToDeath() {
1250            mConnection.asBinder().unlinkToDeath(this, 0);
1251        }
1252
1253        @Override
1254        public void binderDied() {
1255            unlinkToDeath();
1256            synchronized (mLock) {
1257                removeAccessibilityInteractionConnectionLocked(mWindowId, mUserId);
1258            }
1259        }
1260    }
1261
1262    private final class MainHandler extends Handler {
1263        public static final int MSG_SEND_ACCESSIBILITY_EVENT_TO_INPUT_FILTER = 1;
1264        public static final int MSG_SEND_STATE_TO_CLIENTS = 2;
1265        public static final int MSG_SEND_CLEARED_STATE_TO_CLIENTS_FOR_USER = 3;
1266        public static final int MSG_SEND_RECREATE_INTERNAL_STATE = 4;
1267        public static final int MSG_UPDATE_ACTIVE_WINDOW = 5;
1268        public static final int MSG_ANNOUNCE_NEW_USER_IF_NEEDED = 6;
1269
1270        public MainHandler(Looper looper) {
1271            super(looper);
1272        }
1273
1274        @Override
1275        public void handleMessage(Message msg) {
1276            final int type = msg.what;
1277            switch (type) {
1278                case MSG_SEND_ACCESSIBILITY_EVENT_TO_INPUT_FILTER: {
1279                    AccessibilityEvent event = (AccessibilityEvent) msg.obj;
1280                    synchronized (mLock) {
1281                        if (mHasInputFilter && mInputFilter != null) {
1282                            mInputFilter.notifyAccessibilityEvent(event);
1283                        }
1284                    }
1285                    event.recycle();
1286                } break;
1287                case MSG_SEND_STATE_TO_CLIENTS: {
1288                    final int clientState = msg.arg1;
1289                    final int userId = msg.arg2;
1290                    sendStateToClients(clientState, mGlobalClients);
1291                    sendStateToClientsForUser(clientState, userId);
1292                } break;
1293                case MSG_SEND_CLEARED_STATE_TO_CLIENTS_FOR_USER: {
1294                    final int userId = msg.arg1;
1295                    sendStateToClientsForUser(0, userId);
1296                } break;
1297                case MSG_SEND_RECREATE_INTERNAL_STATE: {
1298                    final int userId = msg.arg1;
1299                    synchronized (mLock) {
1300                        UserState userState = getUserStateLocked(userId);
1301                        recreateInternalStateLocked(userState);
1302                    }
1303                } break;
1304                case MSG_UPDATE_ACTIVE_WINDOW: {
1305                    final int windowId = msg.arg1;
1306                    final int eventType = msg.arg2;
1307                    mSecurityPolicy.updateActiveWindow(windowId, eventType);
1308                } break;
1309                case MSG_ANNOUNCE_NEW_USER_IF_NEEDED: {
1310                    announceNewUserIfNeeded();
1311                } break;
1312            }
1313        }
1314
1315        private void announceNewUserIfNeeded() {
1316            synchronized (mLock) {
1317                UserState userState = getCurrentUserStateLocked();
1318                if (userState.mIsAccessibilityEnabled) {
1319                    UserManager userManager = (UserManager) mContext.getSystemService(
1320                            Context.USER_SERVICE);
1321                    String message = mContext.getString(R.string.user_switched,
1322                            userManager.getUserInfo(mCurrentUserId).name);
1323                    AccessibilityEvent event = AccessibilityEvent.obtain(
1324                            AccessibilityEvent.TYPE_ANNOUNCEMENT);
1325                    event.getText().add(message);
1326                    sendAccessibilityEvent(event, mCurrentUserId);
1327                }
1328            }
1329        }
1330
1331        private void sendStateToClientsForUser(int clientState, int userId) {
1332            final UserState userState;
1333            synchronized (mLock) {
1334                userState = getUserStateLocked(userId);
1335            }
1336            sendStateToClients(clientState, userState.mClients);
1337        }
1338
1339        private void sendStateToClients(int clientState,
1340                RemoteCallbackList<IAccessibilityManagerClient> clients) {
1341            try {
1342                final int userClientCount = clients.beginBroadcast();
1343                for (int i = 0; i < userClientCount; i++) {
1344                    IAccessibilityManagerClient client = clients.getBroadcastItem(i);
1345                    try {
1346                        client.setState(clientState);
1347                    } catch (RemoteException re) {
1348                        /* ignore */
1349                    }
1350                }
1351            } finally {
1352                clients.finishBroadcast();
1353            }
1354        }
1355    }
1356
1357    /**
1358     * This class represents an accessibility service. It stores all per service
1359     * data required for the service management, provides API for starting/stopping the
1360     * service and is responsible for adding/removing the service in the data structures
1361     * for service management. The class also exposes configuration interface that is
1362     * passed to the service it represents as soon it is bound. It also serves as the
1363     * connection for the service.
1364     */
1365    class Service extends IAccessibilityServiceConnection.Stub
1366            implements ServiceConnection, DeathRecipient {
1367
1368        // We pick the MSB to avoid collision since accessibility event types are
1369        // used as message types allowing us to remove messages per event type.
1370        private static final int MSG_ON_GESTURE = 0x80000000;
1371
1372        final int mUserId;
1373
1374        int mId = 0;
1375
1376        AccessibilityServiceInfo mAccessibilityServiceInfo;
1377
1378        IBinder mService;
1379
1380        IAccessibilityServiceClient mServiceInterface;
1381
1382        int mEventTypes;
1383
1384        int mFeedbackType;
1385
1386        Set<String> mPackageNames = new HashSet<String>();
1387
1388        boolean mIsDefault;
1389
1390        boolean mRequestTouchExplorationMode;
1391
1392        boolean mIncludeNotImportantViews;
1393
1394        long mNotificationTimeout;
1395
1396        ComponentName mComponentName;
1397
1398        Intent mIntent;
1399
1400        boolean mCanRetrieveScreenContent;
1401
1402        boolean mIsAutomation;
1403
1404        final Rect mTempBounds = new Rect();
1405
1406        final ResolveInfo mResolveInfo;
1407
1408        // the events pending events to be dispatched to this service
1409        final SparseArray<AccessibilityEvent> mPendingEvents =
1410            new SparseArray<AccessibilityEvent>();
1411
1412        /**
1413         * Handler for delayed event dispatch.
1414         */
1415        public Handler mHandler = new Handler(mMainHandler.getLooper()) {
1416            @Override
1417            public void handleMessage(Message message) {
1418                final int type = message.what;
1419                switch (type) {
1420                    case MSG_ON_GESTURE: {
1421                        final int gestureId = message.arg1;
1422                        notifyGestureInternal(gestureId);
1423                    } break;
1424                    default: {
1425                        final int eventType = type;
1426                        notifyAccessibilityEventInternal(eventType);
1427                    } break;
1428                }
1429            }
1430        };
1431
1432        public Service(int userId, ComponentName componentName,
1433                AccessibilityServiceInfo accessibilityServiceInfo, boolean isAutomation) {
1434            mUserId = userId;
1435            mResolveInfo = accessibilityServiceInfo.getResolveInfo();
1436            mId = sIdCounter++;
1437            mComponentName = componentName;
1438            mAccessibilityServiceInfo = accessibilityServiceInfo;
1439            mIsAutomation = isAutomation;
1440            if (!isAutomation) {
1441                mCanRetrieveScreenContent = accessibilityServiceInfo.getCanRetrieveWindowContent();
1442                mRequestTouchExplorationMode =
1443                    (accessibilityServiceInfo.flags
1444                            & AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE) != 0;
1445                mIntent = new Intent().setComponent(mComponentName);
1446                mIntent.putExtra(Intent.EXTRA_CLIENT_LABEL,
1447                        com.android.internal.R.string.accessibility_binding_label);
1448                mIntent.putExtra(Intent.EXTRA_CLIENT_INTENT, PendingIntent.getActivity(
1449                        mContext, 0, new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS), 0));
1450            } else {
1451                mCanRetrieveScreenContent = true;
1452            }
1453            setDynamicallyConfigurableProperties(accessibilityServiceInfo);
1454        }
1455
1456        public void setDynamicallyConfigurableProperties(AccessibilityServiceInfo info) {
1457            mEventTypes = info.eventTypes;
1458            mFeedbackType = info.feedbackType;
1459            String[] packageNames = info.packageNames;
1460            if (packageNames != null) {
1461                mPackageNames.addAll(Arrays.asList(packageNames));
1462            }
1463            mNotificationTimeout = info.notificationTimeout;
1464            mIsDefault = (info.flags & DEFAULT) != 0;
1465
1466            if (mIsAutomation || info.getResolveInfo().serviceInfo.applicationInfo.targetSdkVersion
1467                    >= Build.VERSION_CODES.JELLY_BEAN) {
1468                mIncludeNotImportantViews =
1469                    (info.flags & FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0;
1470            }
1471
1472            mRequestTouchExplorationMode = (info.flags
1473                    & AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE) != 0;
1474
1475            // If this service is up and running we may have to enable touch
1476            // exploration, otherwise this will happen when the service connects.
1477            synchronized (mLock) {
1478                if (canReceiveEvents()) {
1479                    if (mRequestTouchExplorationMode) {
1480                        tryEnableTouchExplorationLocked(this);
1481                    } else {
1482                        tryDisableTouchExplorationLocked(this);
1483                    }
1484                }
1485            }
1486        }
1487
1488        /**
1489         * Binds to the accessibility service.
1490         *
1491         * @return True if binding is successful.
1492         */
1493        public boolean bind() {
1494            if (!mIsAutomation && mService == null) {
1495                return mContext.bindService(mIntent, this, Context.BIND_AUTO_CREATE, mUserId);
1496            }
1497            return false;
1498        }
1499
1500        /**
1501         * Unbinds form the accessibility service and removes it from the data
1502         * structures for service management.
1503         *
1504         * @return True if unbinding is successful.
1505         */
1506        public boolean unbind() {
1507            if (mService != null) {
1508                synchronized (mLock) {
1509                    tryRemoveServiceLocked(this);
1510                }
1511                if (!mIsAutomation) {
1512                    mContext.unbindService(this);
1513                }
1514                return true;
1515            }
1516            return false;
1517        }
1518
1519        public boolean canReceiveEvents() {
1520            return (mEventTypes != 0 && mFeedbackType != 0 && mService != null);
1521        }
1522
1523        @Override
1524        public AccessibilityServiceInfo getServiceInfo() {
1525            synchronized (mLock) {
1526                return mAccessibilityServiceInfo;
1527            }
1528        }
1529
1530        @Override
1531        public void setServiceInfo(AccessibilityServiceInfo info) {
1532            final long identity = Binder.clearCallingIdentity();
1533            try {
1534                synchronized (mLock) {
1535                    // If the XML manifest had data to configure the service its info
1536                    // should be already set. In such a case update only the dynamically
1537                    // configurable properties.
1538                    AccessibilityServiceInfo oldInfo = mAccessibilityServiceInfo;
1539                    if (oldInfo != null) {
1540                        oldInfo.updateDynamicallyConfigurableProperties(info);
1541                        setDynamicallyConfigurableProperties(oldInfo);
1542                    } else {
1543                        setDynamicallyConfigurableProperties(info);
1544                    }
1545                }
1546            } finally {
1547                Binder.restoreCallingIdentity(identity);
1548            }
1549        }
1550
1551        @Override
1552        public void onServiceConnected(ComponentName componentName, IBinder service) {
1553            mService = service;
1554            mServiceInterface = IAccessibilityServiceClient.Stub.asInterface(service);
1555            try {
1556                mServiceInterface.setConnection(this, mId);
1557                synchronized (mLock) {
1558                    tryAddServiceLocked(this, mUserId);
1559                }
1560            } catch (RemoteException re) {
1561                Slog.w(LOG_TAG, "Error while setting Controller for service: " + service, re);
1562            }
1563        }
1564
1565        @Override
1566        public float findAccessibilityNodeInfoByViewId(int accessibilityWindowId,
1567                long accessibilityNodeId, int viewId, int interactionId,
1568                IAccessibilityInteractionConnectionCallback callback, long interrogatingTid)
1569                throws RemoteException {
1570            final int resolvedWindowId;
1571            IAccessibilityInteractionConnection connection = null;
1572            synchronized (mLock) {
1573                final int resolvedUserId = mSecurityPolicy
1574                        .resolveCallingUserIdEnforcingPermissionsLocked(
1575                                UserHandle.getCallingUserId());
1576                if (resolvedUserId != mCurrentUserId) {
1577                    return -1;
1578                }
1579                mSecurityPolicy.enforceCanRetrieveWindowContent(this);
1580                final boolean permissionGranted = mSecurityPolicy.canRetrieveWindowContent(this);
1581                if (!permissionGranted) {
1582                    return 0;
1583                } else {
1584                    resolvedWindowId = resolveAccessibilityWindowIdLocked(accessibilityWindowId);
1585                    connection = getConnectionLocked(resolvedWindowId);
1586                    if (connection == null) {
1587                        return 0;
1588                    }
1589                }
1590            }
1591            final int flags = (mIncludeNotImportantViews) ?
1592                    AccessibilityNodeInfo.INCLUDE_NOT_IMPORTANT_VIEWS : 0;
1593            final int interrogatingPid = Binder.getCallingPid();
1594            final long identityToken = Binder.clearCallingIdentity();
1595            try {
1596                connection.findAccessibilityNodeInfoByViewId(accessibilityNodeId, viewId,
1597                        interactionId, callback, flags, interrogatingPid, interrogatingTid);
1598                return getCompatibilityScale(resolvedWindowId);
1599            } catch (RemoteException re) {
1600                if (DEBUG) {
1601                    Slog.e(LOG_TAG, "Error findAccessibilityNodeInfoByViewId().");
1602                }
1603            } finally {
1604                Binder.restoreCallingIdentity(identityToken);
1605            }
1606            return 0;
1607        }
1608
1609        @Override
1610        public float findAccessibilityNodeInfosByText(int accessibilityWindowId,
1611                long accessibilityNodeId, String text, int interactionId,
1612                IAccessibilityInteractionConnectionCallback callback, long interrogatingTid)
1613                throws RemoteException {
1614            final int resolvedWindowId;
1615            IAccessibilityInteractionConnection connection = null;
1616            synchronized (mLock) {
1617                final int resolvedUserId = mSecurityPolicy
1618                        .resolveCallingUserIdEnforcingPermissionsLocked(
1619                        UserHandle.getCallingUserId());
1620                if (resolvedUserId != mCurrentUserId) {
1621                    return -1;
1622                }
1623                mSecurityPolicy.enforceCanRetrieveWindowContent(this);
1624                resolvedWindowId = resolveAccessibilityWindowIdLocked(accessibilityWindowId);
1625                final boolean permissionGranted =
1626                    mSecurityPolicy.canGetAccessibilityNodeInfoLocked(this, resolvedWindowId);
1627                if (!permissionGranted) {
1628                    return 0;
1629                } else {
1630                    connection = getConnectionLocked(resolvedWindowId);
1631                    if (connection == null) {
1632                        return 0;
1633                    }
1634                }
1635            }
1636            final int flags = (mIncludeNotImportantViews) ?
1637                    AccessibilityNodeInfo.INCLUDE_NOT_IMPORTANT_VIEWS : 0;
1638            final int interrogatingPid = Binder.getCallingPid();
1639            final long identityToken = Binder.clearCallingIdentity();
1640            try {
1641                connection.findAccessibilityNodeInfosByText(accessibilityNodeId, text,
1642                        interactionId, callback, flags, interrogatingPid,
1643                        interrogatingTid);
1644                return getCompatibilityScale(resolvedWindowId);
1645            } catch (RemoteException re) {
1646                if (DEBUG) {
1647                    Slog.e(LOG_TAG, "Error calling findAccessibilityNodeInfosByText()");
1648                }
1649            } finally {
1650                Binder.restoreCallingIdentity(identityToken);
1651            }
1652            return 0;
1653        }
1654
1655        @Override
1656        public float findAccessibilityNodeInfoByAccessibilityId(int accessibilityWindowId,
1657                long accessibilityNodeId, int interactionId,
1658                IAccessibilityInteractionConnectionCallback callback, int flags,
1659                long interrogatingTid) throws RemoteException {
1660            final int resolvedWindowId;
1661            IAccessibilityInteractionConnection connection = null;
1662            synchronized (mLock) {
1663                final int resolvedUserId = mSecurityPolicy
1664                        .resolveCallingUserIdEnforcingPermissionsLocked(
1665                        UserHandle.getCallingUserId());
1666                if (resolvedUserId != mCurrentUserId) {
1667                    return -1;
1668                }
1669                mSecurityPolicy.enforceCanRetrieveWindowContent(this);
1670                resolvedWindowId = resolveAccessibilityWindowIdLocked(accessibilityWindowId);
1671                final boolean permissionGranted =
1672                    mSecurityPolicy.canGetAccessibilityNodeInfoLocked(this, resolvedWindowId);
1673                if (!permissionGranted) {
1674                    return 0;
1675                } else {
1676                    connection = getConnectionLocked(resolvedWindowId);
1677                    if (connection == null) {
1678                        return 0;
1679                    }
1680                }
1681            }
1682            final int allFlags = flags | ((mIncludeNotImportantViews) ?
1683                    AccessibilityNodeInfo.INCLUDE_NOT_IMPORTANT_VIEWS : 0);
1684            final int interrogatingPid = Binder.getCallingPid();
1685            final long identityToken = Binder.clearCallingIdentity();
1686            try {
1687                connection.findAccessibilityNodeInfoByAccessibilityId(accessibilityNodeId,
1688                        interactionId, callback, allFlags, interrogatingPid, interrogatingTid);
1689                return getCompatibilityScale(resolvedWindowId);
1690            } catch (RemoteException re) {
1691                if (DEBUG) {
1692                    Slog.e(LOG_TAG, "Error calling findAccessibilityNodeInfoByAccessibilityId()");
1693                }
1694            } finally {
1695                Binder.restoreCallingIdentity(identityToken);
1696            }
1697            return 0;
1698        }
1699
1700        @Override
1701        public float findFocus(int accessibilityWindowId, long accessibilityNodeId,
1702                int focusType, int interactionId,
1703                IAccessibilityInteractionConnectionCallback callback, long interrogatingTid)
1704                throws RemoteException {
1705            final int resolvedWindowId;
1706            IAccessibilityInteractionConnection connection = null;
1707            synchronized (mLock) {
1708                final int resolvedUserId = mSecurityPolicy
1709                        .resolveCallingUserIdEnforcingPermissionsLocked(
1710                        UserHandle.getCallingUserId());
1711                if (resolvedUserId != mCurrentUserId) {
1712                    return -1;
1713                }
1714                mSecurityPolicy.enforceCanRetrieveWindowContent(this);
1715                resolvedWindowId = resolveAccessibilityWindowIdLocked(accessibilityWindowId);
1716                final boolean permissionGranted =
1717                    mSecurityPolicy.canGetAccessibilityNodeInfoLocked(this, resolvedWindowId);
1718                if (!permissionGranted) {
1719                    return 0;
1720                } else {
1721                    connection = getConnectionLocked(resolvedWindowId);
1722                    if (connection == null) {
1723                        return 0;
1724                    }
1725                }
1726            }
1727            final int flags = (mIncludeNotImportantViews) ?
1728                    AccessibilityNodeInfo.INCLUDE_NOT_IMPORTANT_VIEWS : 0;
1729            final int interrogatingPid = Binder.getCallingPid();
1730            final long identityToken = Binder.clearCallingIdentity();
1731            try {
1732                connection.findFocus(accessibilityNodeId, focusType, interactionId, callback,
1733                        flags, interrogatingPid, interrogatingTid);
1734                return getCompatibilityScale(resolvedWindowId);
1735            } catch (RemoteException re) {
1736                if (DEBUG) {
1737                    Slog.e(LOG_TAG, "Error calling findAccessibilityFocus()");
1738                }
1739            } finally {
1740                Binder.restoreCallingIdentity(identityToken);
1741            }
1742            return 0;
1743        }
1744
1745        @Override
1746        public float focusSearch(int accessibilityWindowId, long accessibilityNodeId,
1747                int direction, int interactionId,
1748                IAccessibilityInteractionConnectionCallback callback, long interrogatingTid)
1749                throws RemoteException {
1750            final int resolvedWindowId;
1751            IAccessibilityInteractionConnection connection = null;
1752            synchronized (mLock) {
1753                final int resolvedUserId = mSecurityPolicy
1754                        .resolveCallingUserIdEnforcingPermissionsLocked(
1755                        UserHandle.getCallingUserId());
1756                if (resolvedUserId != mCurrentUserId) {
1757                    return -1;
1758                }
1759                mSecurityPolicy.enforceCanRetrieveWindowContent(this);
1760                resolvedWindowId = resolveAccessibilityWindowIdLocked(accessibilityWindowId);
1761                final boolean permissionGranted =
1762                    mSecurityPolicy.canGetAccessibilityNodeInfoLocked(this, resolvedWindowId);
1763                if (!permissionGranted) {
1764                    return 0;
1765                } else {
1766                    connection = getConnectionLocked(resolvedWindowId);
1767                    if (connection == null) {
1768                        return 0;
1769                    }
1770                }
1771            }
1772            final int flags = (mIncludeNotImportantViews) ?
1773                    AccessibilityNodeInfo.INCLUDE_NOT_IMPORTANT_VIEWS : 0;
1774            final int interrogatingPid = Binder.getCallingPid();
1775            final long identityToken = Binder.clearCallingIdentity();
1776            try {
1777                connection.focusSearch(accessibilityNodeId, direction, interactionId, callback,
1778                        flags, interrogatingPid, interrogatingTid);
1779                return getCompatibilityScale(resolvedWindowId);
1780            } catch (RemoteException re) {
1781                if (DEBUG) {
1782                    Slog.e(LOG_TAG, "Error calling accessibilityFocusSearch()");
1783                }
1784            } finally {
1785                Binder.restoreCallingIdentity(identityToken);
1786            }
1787            return 0;
1788        }
1789
1790        @Override
1791        public boolean performAccessibilityAction(int accessibilityWindowId,
1792                long accessibilityNodeId, int action, Bundle arguments, int interactionId,
1793                IAccessibilityInteractionConnectionCallback callback, long interrogatingTid)
1794                throws RemoteException {
1795            final int resolvedWindowId;
1796            IAccessibilityInteractionConnection connection = null;
1797            synchronized (mLock) {
1798                final int resolvedUserId = mSecurityPolicy
1799                        .resolveCallingUserIdEnforcingPermissionsLocked(
1800                        UserHandle.getCallingUserId());
1801                if (resolvedUserId != mCurrentUserId) {
1802                    return false;
1803                }
1804                mSecurityPolicy.enforceCanRetrieveWindowContent(this);
1805                resolvedWindowId = resolveAccessibilityWindowIdLocked(accessibilityWindowId);
1806                final boolean permissionGranted = mSecurityPolicy.canPerformActionLocked(this,
1807                        resolvedWindowId, action, arguments);
1808                if (!permissionGranted) {
1809                    return false;
1810                } else {
1811                    connection = getConnectionLocked(resolvedWindowId);
1812                    if (connection == null) {
1813                        return false;
1814                    }
1815                }
1816            }
1817            final int flags = (mIncludeNotImportantViews) ?
1818                    AccessibilityNodeInfo.INCLUDE_NOT_IMPORTANT_VIEWS : 0;
1819            final int interrogatingPid = Binder.getCallingPid();
1820            final long identityToken = Binder.clearCallingIdentity();
1821            try {
1822                connection.performAccessibilityAction(accessibilityNodeId, action, arguments,
1823                        interactionId, callback, flags, interrogatingPid, interrogatingTid);
1824            } catch (RemoteException re) {
1825                if (DEBUG) {
1826                    Slog.e(LOG_TAG, "Error calling performAccessibilityAction()");
1827                }
1828            } finally {
1829                Binder.restoreCallingIdentity(identityToken);
1830            }
1831            return true;
1832        }
1833
1834        public boolean performGlobalAction(int action) {
1835            synchronized (mLock) {
1836                final int resolvedUserId = mSecurityPolicy
1837                        .resolveCallingUserIdEnforcingPermissionsLocked(
1838                        UserHandle.getCallingUserId());
1839                if (resolvedUserId != mCurrentUserId) {
1840                    return false;
1841                }
1842            }
1843            final long identity = Binder.clearCallingIdentity();
1844            try {
1845                switch (action) {
1846                    case AccessibilityService.GLOBAL_ACTION_BACK: {
1847                        sendDownAndUpKeyEvents(KeyEvent.KEYCODE_BACK);
1848                    } return true;
1849                    case AccessibilityService.GLOBAL_ACTION_HOME: {
1850                        sendDownAndUpKeyEvents(KeyEvent.KEYCODE_HOME);
1851                    } return true;
1852                    case AccessibilityService.GLOBAL_ACTION_RECENTS: {
1853                        openRecents();
1854                    } return true;
1855                    case AccessibilityService.GLOBAL_ACTION_NOTIFICATIONS: {
1856                        expandNotifications();
1857                    } return true;
1858                    case AccessibilityService.GLOBAL_ACTION_QUICK_SETTINGS: {
1859                        expandQuickSettings();
1860                    } return true;
1861                }
1862                return false;
1863            } finally {
1864                Binder.restoreCallingIdentity(identity);
1865            }
1866        }
1867
1868        public void onServiceDisconnected(ComponentName componentName) {
1869            /* do nothing - #binderDied takes care */
1870        }
1871
1872        public void linkToOwnDeath() throws RemoteException {
1873            mService.linkToDeath(this, 0);
1874        }
1875
1876        public void unlinkToOwnDeath() {
1877            mService.unlinkToDeath(this, 0);
1878        }
1879
1880        public void dispose() {
1881            try {
1882                // Clear the proxy in the other process so this
1883                // IAccessibilityServiceConnection can be garbage collected.
1884                mServiceInterface.setConnection(null, mId);
1885            } catch (RemoteException re) {
1886                /* ignore */
1887            }
1888            mService = null;
1889            mServiceInterface = null;
1890        }
1891
1892        public void binderDied() {
1893            synchronized (mLock) {
1894                // The death recipient is unregistered in tryRemoveServiceLocked
1895                tryRemoveServiceLocked(this);
1896                // We no longer have an automation service, so restore
1897                // the state based on values in the settings database.
1898                if (mIsAutomation) {
1899                    mUiAutomationService = null;
1900                    recreateInternalStateLocked(getUserStateLocked(mUserId));
1901                }
1902            }
1903        }
1904
1905        /**
1906         * Performs a notification for an {@link AccessibilityEvent}.
1907         *
1908         * @param event The event.
1909         */
1910        public void notifyAccessibilityEvent(AccessibilityEvent event) {
1911            synchronized (mLock) {
1912                final int eventType = event.getEventType();
1913                // Make a copy since during dispatch it is possible the event to
1914                // be modified to remove its source if the receiving service does
1915                // not have permission to access the window content.
1916                AccessibilityEvent newEvent = AccessibilityEvent.obtain(event);
1917                AccessibilityEvent oldEvent = mPendingEvents.get(eventType);
1918                mPendingEvents.put(eventType, newEvent);
1919
1920                final int what = eventType;
1921                if (oldEvent != null) {
1922                    mHandler.removeMessages(what);
1923                    oldEvent.recycle();
1924                }
1925
1926                Message message = mHandler.obtainMessage(what);
1927                mHandler.sendMessageDelayed(message, mNotificationTimeout);
1928            }
1929        }
1930
1931        /**
1932         * Notifies an accessibility service client for a scheduled event given the event type.
1933         *
1934         * @param eventType The type of the event to dispatch.
1935         */
1936        private void notifyAccessibilityEventInternal(int eventType) {
1937            IAccessibilityServiceClient listener;
1938            AccessibilityEvent event;
1939
1940            synchronized (mLock) {
1941                listener = mServiceInterface;
1942
1943                // If the service died/was disabled while the message for dispatching
1944                // the accessibility event was propagating the listener may be null.
1945                if (listener == null) {
1946                    return;
1947                }
1948
1949                event = mPendingEvents.get(eventType);
1950
1951                // Check for null here because there is a concurrent scenario in which this
1952                // happens: 1) A binder thread calls notifyAccessibilityServiceDelayedLocked
1953                // which posts a message for dispatching an event. 2) The message is pulled
1954                // from the queue by the handler on the service thread and the latter is
1955                // just about to acquire the lock and call this method. 3) Now another binder
1956                // thread acquires the lock calling notifyAccessibilityServiceDelayedLocked
1957                // so the service thread waits for the lock; 4) The binder thread replaces
1958                // the event with a more recent one (assume the same event type) and posts a
1959                // dispatch request releasing the lock. 5) Now the main thread is unblocked and
1960                // dispatches the event which is removed from the pending ones. 6) And ... now
1961                // the service thread handles the last message posted by the last binder call
1962                // but the event is already dispatched and hence looking it up in the pending
1963                // ones yields null. This check is much simpler that keeping count for each
1964                // event type of each service to catch such a scenario since only one message
1965                // is processed at a time.
1966                if (event == null) {
1967                    return;
1968                }
1969
1970                mPendingEvents.remove(eventType);
1971                if (mSecurityPolicy.canRetrieveWindowContent(this)) {
1972                    event.setConnectionId(mId);
1973                } else {
1974                    event.setSource(null);
1975                }
1976                event.setSealed(true);
1977            }
1978
1979            try {
1980                listener.onAccessibilityEvent(event);
1981                if (DEBUG) {
1982                    Slog.i(LOG_TAG, "Event " + event + " sent to " + listener);
1983                }
1984            } catch (RemoteException re) {
1985                Slog.e(LOG_TAG, "Error during sending " + event + " to " + listener, re);
1986            } finally {
1987                event.recycle();
1988            }
1989        }
1990
1991        public void notifyGesture(int gestureId) {
1992            mHandler.obtainMessage(MSG_ON_GESTURE, gestureId, 0).sendToTarget();
1993        }
1994
1995        private void notifyGestureInternal(int gestureId) {
1996            IAccessibilityServiceClient listener = mServiceInterface;
1997            if (listener != null) {
1998                try {
1999                    listener.onGesture(gestureId);
2000                } catch (RemoteException re) {
2001                    Slog.e(LOG_TAG, "Error during sending gesture " + gestureId
2002                            + " to " + mService, re);
2003                }
2004            }
2005        }
2006
2007        private void sendDownAndUpKeyEvents(int keyCode) {
2008            final long token = Binder.clearCallingIdentity();
2009
2010            // Inject down.
2011            final long downTime = SystemClock.uptimeMillis();
2012            KeyEvent down = KeyEvent.obtain(downTime, downTime, KeyEvent.ACTION_DOWN, keyCode, 0, 0,
2013                    KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FROM_SYSTEM,
2014                    InputDevice.SOURCE_KEYBOARD, null);
2015            InputManager.getInstance().injectInputEvent(down,
2016                    InputManager.INJECT_INPUT_EVENT_MODE_ASYNC);
2017            down.recycle();
2018
2019            // Inject up.
2020            final long upTime = SystemClock.uptimeMillis();
2021            KeyEvent up = KeyEvent.obtain(downTime, upTime, KeyEvent.ACTION_UP, keyCode, 0, 0,
2022                    KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FROM_SYSTEM,
2023                    InputDevice.SOURCE_KEYBOARD, null);
2024            InputManager.getInstance().injectInputEvent(up,
2025                    InputManager.INJECT_INPUT_EVENT_MODE_ASYNC);
2026            up.recycle();
2027
2028            Binder.restoreCallingIdentity(token);
2029        }
2030
2031        private void expandNotifications() {
2032            final long token = Binder.clearCallingIdentity();
2033
2034            StatusBarManager statusBarManager = (StatusBarManager) mContext.getSystemService(
2035                    android.app.Service.STATUS_BAR_SERVICE);
2036            statusBarManager.expandNotificationsPanel();
2037
2038            Binder.restoreCallingIdentity(token);
2039        }
2040
2041        private void expandQuickSettings() {
2042            final long token = Binder.clearCallingIdentity();
2043
2044            StatusBarManager statusBarManager = (StatusBarManager) mContext.getSystemService(
2045                    android.app.Service.STATUS_BAR_SERVICE);
2046            statusBarManager.expandSettingsPanel();
2047
2048            Binder.restoreCallingIdentity(token);
2049        }
2050
2051        private void openRecents() {
2052            final long token = Binder.clearCallingIdentity();
2053
2054            IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
2055                    ServiceManager.getService("statusbar"));
2056            try {
2057                statusBarService.toggleRecentApps();
2058            } catch (RemoteException e) {
2059                Slog.e(LOG_TAG, "Error toggling recent apps.");
2060            }
2061
2062            Binder.restoreCallingIdentity(token);
2063        }
2064
2065        private IAccessibilityInteractionConnection getConnectionLocked(int windowId) {
2066            if (DEBUG) {
2067                Slog.i(LOG_TAG, "Trying to get interaction connection to windowId: " + windowId);
2068            }
2069            AccessibilityConnectionWrapper wrapper = mGlobalInteractionConnections.get(windowId);
2070            if (wrapper == null) {
2071                wrapper = getCurrentUserStateLocked().mInteractionConnections.get(windowId);
2072            }
2073            if (wrapper != null && wrapper.mConnection != null) {
2074                return wrapper.mConnection;
2075            }
2076            if (DEBUG) {
2077                Slog.e(LOG_TAG, "No interaction connection to window: " + windowId);
2078            }
2079            return null;
2080        }
2081
2082        private int resolveAccessibilityWindowIdLocked(int accessibilityWindowId) {
2083            if (accessibilityWindowId == AccessibilityNodeInfo.ACTIVE_WINDOW_ID) {
2084                return mSecurityPolicy.mActiveWindowId;
2085            }
2086            return accessibilityWindowId;
2087        }
2088
2089        private float getCompatibilityScale(int windowId) {
2090            try {
2091                IBinder windowToken = mGlobalWindowTokens.get(windowId);
2092                if (windowToken != null) {
2093                    return mWindowManagerService.getWindowCompatibilityScale(windowToken);
2094                }
2095                windowToken = getCurrentUserStateLocked().mWindowTokens.get(windowId);
2096                if (windowToken != null) {
2097                    return mWindowManagerService.getWindowCompatibilityScale(windowToken);
2098                }
2099            } catch (RemoteException re) {
2100                /* ignore */
2101            }
2102            return 1.0f;
2103        }
2104    }
2105
2106    final class SecurityPolicy {
2107        private static final int VALID_ACTIONS =
2108            AccessibilityNodeInfo.ACTION_CLICK
2109            | AccessibilityNodeInfo.ACTION_LONG_CLICK
2110            | AccessibilityNodeInfo.ACTION_FOCUS
2111            | AccessibilityNodeInfo.ACTION_CLEAR_FOCUS
2112            | AccessibilityNodeInfo.ACTION_SELECT
2113            | AccessibilityNodeInfo.ACTION_CLEAR_SELECTION
2114            | AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS
2115            | AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS
2116            | AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
2117            | AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY
2118            | AccessibilityNodeInfo.ACTION_NEXT_HTML_ELEMENT
2119            | AccessibilityNodeInfo.ACTION_PREVIOUS_HTML_ELEMENT
2120            | AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
2121            | AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD;
2122
2123        private static final int RETRIEVAL_ALLOWING_EVENT_TYPES =
2124            AccessibilityEvent.TYPE_VIEW_CLICKED
2125            | AccessibilityEvent.TYPE_VIEW_FOCUSED
2126            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
2127            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
2128            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
2129            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
2130            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
2131            | AccessibilityEvent.TYPE_VIEW_SELECTED
2132            | AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED
2133            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
2134            | AccessibilityEvent.TYPE_VIEW_SCROLLED
2135            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
2136            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED;
2137
2138        private int mActiveWindowId;
2139
2140        private boolean canDispatchAccessibilityEvent(AccessibilityEvent event) {
2141            final int eventType = event.getEventType();
2142            switch (eventType) {
2143                // All events that are for changes in a global window
2144                // state should *always* be dispatched.
2145                case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
2146                case AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED:
2147                // All events generated by the user touching the
2148                // screen should *always* be dispatched.
2149                case AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_START:
2150                case AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_END:
2151                case AccessibilityEvent.TYPE_GESTURE_DETECTION_START:
2152                case AccessibilityEvent.TYPE_GESTURE_DETECTION_END:
2153                case AccessibilityEvent.TYPE_TOUCH_INTERACTION_START:
2154                case AccessibilityEvent.TYPE_TOUCH_INTERACTION_END:
2155                // These will change the active window, so dispatch.
2156                case AccessibilityEvent.TYPE_VIEW_HOVER_ENTER:
2157                case AccessibilityEvent.TYPE_VIEW_HOVER_EXIT: {
2158                    return true;
2159                }
2160                // All events for changes in window content should be
2161                // dispatched *only* if this window is the active one.
2162                default:
2163                    return event.getWindowId() == mActiveWindowId;
2164            }
2165        }
2166
2167        public void updateEventSourceLocked(AccessibilityEvent event) {
2168            if ((event.getEventType() & RETRIEVAL_ALLOWING_EVENT_TYPES) == 0) {
2169                event.setSource(null);
2170            }
2171        }
2172
2173        public void updateActiveWindow(int windowId, int eventType) {
2174            // The active window is either the window that has input focus or
2175            // the window that the user is currently touching. If the user is
2176            // touching a window that does not have input focus as soon as the
2177            // the user stops touching that window the focused window becomes
2178            // the active one.
2179            switch (eventType) {
2180                case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED: {
2181                    if (getFocusedWindowId() == windowId) {
2182                        mActiveWindowId = windowId;
2183                    }
2184                } break;
2185                case AccessibilityEvent.TYPE_VIEW_HOVER_ENTER: {
2186                    mActiveWindowId = windowId;
2187                } break;
2188            }
2189        }
2190
2191        public void onTouchInteractionEnd() {
2192            // We want to set the active window to be current immediately
2193            // after the user has stopped touching the screen since if the
2194            // user types with the IME he should get a feedback for the
2195            // letter typed in the text view which is in the input focused
2196            // window. Note that we always deliver hover accessibility events
2197            // (they are a result of user touching the screen) so change of
2198            // the active window before all hover accessibility events from
2199            // the touched window are delivered is fine.
2200            mActiveWindowId = getFocusedWindowId();
2201        }
2202
2203        public int getRetrievalAllowingWindowLocked() {
2204            return mActiveWindowId;
2205        }
2206
2207        public boolean canGetAccessibilityNodeInfoLocked(Service service, int windowId) {
2208            return canRetrieveWindowContent(service) && isRetrievalAllowingWindow(windowId);
2209        }
2210
2211        public boolean canPerformActionLocked(Service service, int windowId, int action,
2212                Bundle arguments) {
2213            return canRetrieveWindowContent(service)
2214                && isRetrievalAllowingWindow(windowId)
2215                && isActionPermitted(action);
2216        }
2217
2218        public boolean canRetrieveWindowContent(Service service) {
2219            return service.mCanRetrieveScreenContent;
2220        }
2221
2222        public void enforceCanRetrieveWindowContent(Service service) throws RemoteException {
2223            // This happens due to incorrect registration so make it apparent.
2224            if (!canRetrieveWindowContent(service)) {
2225                Slog.e(LOG_TAG, "Accessibility serivce " + service.mComponentName + " does not " +
2226                        "declare android:canRetrieveWindowContent.");
2227                throw new RemoteException();
2228            }
2229        }
2230
2231        public int resolveCallingUserIdEnforcingPermissionsLocked(int userId) {
2232            final int callingUid = Binder.getCallingUid();
2233            if (callingUid == Process.SYSTEM_UID
2234                    || callingUid == Process.SHELL_UID) {
2235                return mCurrentUserId;
2236            }
2237            final int callingUserId = UserHandle.getUserId(callingUid);
2238            if (callingUserId == userId) {
2239                return userId;
2240            }
2241            if (!hasPermission(Manifest.permission.INTERACT_ACROSS_USERS)
2242                    && !hasPermission(Manifest.permission.INTERACT_ACROSS_USERS_FULL)) {
2243                throw new SecurityException("Call from user " + callingUserId + " as user "
2244                        + userId + " without permission INTERACT_ACROSS_USERS or "
2245                        + "INTERACT_ACROSS_USERS_FULL not allowed.");
2246            }
2247            if (userId == UserHandle.USER_CURRENT
2248                    || userId == UserHandle.USER_CURRENT_OR_SELF) {
2249                return mCurrentUserId;
2250            }
2251            throw new IllegalArgumentException("Calling user can be changed to only "
2252                    + "UserHandle.USER_CURRENT or UserHandle.USER_CURRENT_OR_SELF.");
2253        }
2254
2255        public boolean isCallerInteractingAcrossUsers(int userId) {
2256            final int callingUid = Binder.getCallingUid();
2257            return (Binder.getCallingPid() == android.os.Process.myPid()
2258                    || callingUid == Process.SHELL_UID
2259                    || userId == UserHandle.USER_CURRENT
2260                    || userId == UserHandle.USER_CURRENT_OR_SELF);
2261        }
2262
2263        private boolean isRetrievalAllowingWindow(int windowId) {
2264            return (mActiveWindowId == windowId);
2265        }
2266
2267        private boolean isActionPermitted(int action) {
2268             return (VALID_ACTIONS & action) != 0;
2269        }
2270
2271        private void enforceCallingPermission(String permission, String function) {
2272            if (OWN_PROCESS_ID == Binder.getCallingPid()) {
2273                return;
2274            }
2275            if (!hasPermission(permission)) {
2276                throw new SecurityException("You do not have " + permission
2277                        + " required to call " + function);
2278            }
2279        }
2280
2281        private boolean hasPermission(String permission) {
2282            return mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED;
2283        }
2284
2285        private int getFocusedWindowId() {
2286            try {
2287                // We call this only on window focus change or after touch
2288                // exploration gesture end and the shown windows are not that
2289                // many, so the linear look up is just fine.
2290                IBinder token = mWindowManagerService.getFocusedWindowToken();
2291                if (token != null) {
2292                    synchronized (mLock) {
2293                        int windowId = getFocusedWindowIdLocked(token, mGlobalWindowTokens);
2294                        if (windowId < 0) {
2295                            windowId = getFocusedWindowIdLocked(token,
2296                                    getCurrentUserStateLocked().mWindowTokens);
2297                        }
2298                        return windowId;
2299                    }
2300                }
2301            } catch (RemoteException re) {
2302                /* ignore */
2303            }
2304            return -1;
2305        }
2306
2307        private int getFocusedWindowIdLocked(IBinder token, SparseArray<IBinder> windows) {
2308            final int windowCount = windows.size();
2309            for (int i = 0; i < windowCount; i++) {
2310                if (windows.valueAt(i) == token) {
2311                    return windows.keyAt(i);
2312                }
2313            }
2314            return -1;
2315        }
2316    }
2317
2318    private class UserState {
2319        public final int mUserId;
2320
2321        public final CopyOnWriteArrayList<Service> mServices = new CopyOnWriteArrayList<Service>();
2322
2323        public final RemoteCallbackList<IAccessibilityManagerClient> mClients =
2324            new RemoteCallbackList<IAccessibilityManagerClient>();
2325
2326        public final Map<ComponentName, Service> mComponentNameToServiceMap =
2327                new HashMap<ComponentName, Service>();
2328
2329        public final List<AccessibilityServiceInfo> mInstalledServices =
2330                new ArrayList<AccessibilityServiceInfo>();
2331
2332        public final Set<ComponentName> mEnabledServices = new HashSet<ComponentName>();
2333
2334        public final Set<ComponentName> mTouchExplorationGrantedServices =
2335                new HashSet<ComponentName>();
2336
2337        public final SparseArray<AccessibilityConnectionWrapper>
2338                mInteractionConnections =
2339                new SparseArray<AccessibilityConnectionWrapper>();
2340
2341        public final SparseArray<IBinder> mWindowTokens = new SparseArray<IBinder>();
2342
2343        public int mHandledFeedbackTypes = 0;
2344
2345        public boolean mIsAccessibilityEnabled;
2346        public boolean mIsTouchExplorationEnabled;
2347        public boolean mIsDisplayMagnificationEnabled;
2348
2349        public UserState(int userId) {
2350            mUserId = userId;
2351        }
2352    }
2353
2354    private class TempUserStateChangeMemento {
2355        public int mUserId = UserHandle.USER_NULL;
2356        public boolean mIsAccessibilityEnabled;
2357        public boolean mIsTouchExplorationEnabled;
2358        public boolean mIsDisplayMagnificationEnabled;
2359        public final Set<ComponentName> mEnabledServices = new HashSet<ComponentName>();
2360        public final Set<ComponentName> mTouchExplorationGrantedServices =
2361                new HashSet<ComponentName>();
2362
2363        public void initialize(int userId, UserState userState) {
2364            mUserId = userId;
2365            mIsAccessibilityEnabled = userState.mIsAccessibilityEnabled;
2366            mIsTouchExplorationEnabled = userState.mIsTouchExplorationEnabled;
2367            mIsDisplayMagnificationEnabled = userState.mIsDisplayMagnificationEnabled;
2368            mEnabledServices.clear();
2369            mEnabledServices.addAll(userState.mEnabledServices);
2370            mTouchExplorationGrantedServices.clear();
2371            mTouchExplorationGrantedServices.addAll(userState.mTouchExplorationGrantedServices);
2372        }
2373
2374        public void applyTo(UserState userState) {
2375            userState.mIsAccessibilityEnabled = mIsAccessibilityEnabled;
2376            userState.mIsTouchExplorationEnabled = mIsTouchExplorationEnabled;
2377            userState.mIsDisplayMagnificationEnabled = mIsDisplayMagnificationEnabled;
2378            userState.mEnabledServices.clear();
2379            userState.mEnabledServices.addAll(mEnabledServices);
2380            userState.mTouchExplorationGrantedServices.clear();
2381            userState.mTouchExplorationGrantedServices.addAll(mTouchExplorationGrantedServices);
2382        }
2383
2384        public void clear() {
2385            mUserId = UserHandle.USER_NULL;
2386            mIsAccessibilityEnabled = false;
2387            mIsTouchExplorationEnabled = false;
2388            mIsDisplayMagnificationEnabled = false;
2389            mEnabledServices.clear();
2390            mTouchExplorationGrantedServices.clear();
2391        }
2392    }
2393
2394    private final class AccessibilityContentObserver extends ContentObserver {
2395
2396        private final Uri mAccessibilityEnabledUri = Settings.Secure.getUriFor(
2397                Settings.Secure.ACCESSIBILITY_ENABLED);
2398
2399        private final Uri mTouchExplorationEnabledUri = Settings.Secure.getUriFor(
2400                Settings.Secure.TOUCH_EXPLORATION_ENABLED);
2401
2402        private final Uri mDisplayMagnificationEnabledUri = Settings.Secure.getUriFor(
2403                Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED);
2404
2405        private final Uri mEnabledAccessibilityServicesUri = Settings.Secure.getUriFor(
2406                Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
2407
2408        private final Uri mTouchExplorationGrantedAccessibilityServicesUri = Settings.Secure
2409                .getUriFor(Settings.Secure.TOUCH_EXPLORATION_GRANTED_ACCESSIBILITY_SERVICES);
2410
2411        public AccessibilityContentObserver(Handler handler) {
2412            super(handler);
2413        }
2414
2415        public void register(ContentResolver contentResolver) {
2416            contentResolver.registerContentObserver(mAccessibilityEnabledUri,
2417                    false, this, UserHandle.USER_ALL);
2418            contentResolver.registerContentObserver(mTouchExplorationEnabledUri,
2419                    false, this, UserHandle.USER_ALL);
2420            contentResolver.registerContentObserver(mDisplayMagnificationEnabledUri,
2421                    false, this, UserHandle.USER_ALL);
2422            contentResolver.registerContentObserver(mEnabledAccessibilityServicesUri,
2423                    false, this, UserHandle.USER_ALL);
2424            contentResolver.registerContentObserver(
2425                    mTouchExplorationGrantedAccessibilityServicesUri,
2426                    false, this, UserHandle.USER_ALL);
2427        }
2428
2429        @Override
2430        public void onChange(boolean selfChange, Uri uri) {
2431            if (mAccessibilityEnabledUri.equals(uri)) {
2432                synchronized (mLock) {
2433                    // We will update when the automation service dies.
2434                    if (mUiAutomationService == null) {
2435                        UserState userState = getCurrentUserStateLocked();
2436                        handleAccessibilityEnabledSettingChangedLocked(userState);
2437                        performServiceManagementLocked(userState);
2438                        updateInputFilterLocked(userState);
2439                        scheduleSendStateToClientsLocked(userState);
2440                    }
2441                }
2442            } else if (mTouchExplorationEnabledUri.equals(uri)) {
2443                synchronized (mLock) {
2444                    // We will update when the automation service dies.
2445                    if (mUiAutomationService == null) {
2446                        UserState userState = getCurrentUserStateLocked();
2447                        handleTouchExplorationEnabledSettingChangedLocked(userState);
2448                        updateInputFilterLocked(userState);
2449                        scheduleSendStateToClientsLocked(userState);
2450                    }
2451                }
2452            } else if (mDisplayMagnificationEnabledUri.equals(uri)) {
2453                synchronized (mLock) {
2454                    // We will update when the automation service dies.
2455                    if (mUiAutomationService == null) {
2456                        UserState userState = getCurrentUserStateLocked();
2457                        handleDisplayMagnificationEnabledSettingChangedLocked(userState);
2458                        updateInputFilterLocked(userState);
2459                        scheduleSendStateToClientsLocked(userState);
2460                    }
2461                }
2462            } else if (mEnabledAccessibilityServicesUri.equals(uri)) {
2463                synchronized (mLock) {
2464                    // We will update when the automation service dies.
2465                    if (mUiAutomationService == null) {
2466                        UserState userState = getCurrentUserStateLocked();
2467                        populateEnabledAccessibilityServicesLocked(userState);
2468                        manageServicesLocked(userState);
2469                    }
2470                }
2471            } else if (mTouchExplorationGrantedAccessibilityServicesUri.equals(uri)) {
2472                synchronized (mLock) {
2473                    // We will update when the automation service dies.
2474                    if (mUiAutomationService == null) {
2475                        UserState userState = getCurrentUserStateLocked();
2476                        populateTouchExplorationGrantedAccessibilityServicesLocked(userState);
2477                        handleTouchExplorationGrantedAccessibilityServicesChangedLocked(userState);
2478                    }
2479                }
2480            }
2481        }
2482    }
2483}
2484