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