OSDN Git Service

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