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