1 /* 2 * Copyright (C) 2010 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 #ifndef _UI_INPUT_DISPATCHER_H 18 #define _UI_INPUT_DISPATCHER_H 19 20 #include <ui/Input.h> 21 #include <ui/InputTransport.h> 22 #include <utils/KeyedVector.h> 23 #include <utils/Vector.h> 24 #include <utils/threads.h> 25 #include <utils/Timers.h> 26 #include <utils/RefBase.h> 27 #include <utils/String8.h> 28 #include <utils/Looper.h> 29 #include <utils/Pool.h> 30 #include <utils/BitSet.h> 31 32 #include <stddef.h> 33 #include <unistd.h> 34 #include <limits.h> 35 36 37 namespace android { 38 39 /* 40 * Constants used to report the outcome of input event injection. 41 */ 42 enum { 43 /* (INTERNAL USE ONLY) Specifies that injection is pending and its outcome is unknown. */ 44 INPUT_EVENT_INJECTION_PENDING = -1, 45 46 /* Injection succeeded. */ 47 INPUT_EVENT_INJECTION_SUCCEEDED = 0, 48 49 /* Injection failed because the injector did not have permission to inject 50 * into the application with input focus. */ 51 INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1, 52 53 /* Injection failed because there were no available input targets. */ 54 INPUT_EVENT_INJECTION_FAILED = 2, 55 56 /* Injection failed due to a timeout. */ 57 INPUT_EVENT_INJECTION_TIMED_OUT = 3 58 }; 59 60 /* 61 * Constants used to determine the input event injection synchronization mode. 62 */ 63 enum { 64 /* Injection is asynchronous and is assumed always to be successful. */ 65 INPUT_EVENT_INJECTION_SYNC_NONE = 0, 66 67 /* Waits for previous events to be dispatched so that the input dispatcher can determine 68 * whether input event injection willbe permitted based on the current input focus. 69 * Does not wait for the input event to finish processing. */ 70 INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_RESULT = 1, 71 72 /* Waits for the input event to be completely processed. */ 73 INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED = 2, 74 }; 75 76 77 /* 78 * An input target specifies how an input event is to be dispatched to a particular window 79 * including the window's input channel, control flags, a timeout, and an X / Y offset to 80 * be added to input event coordinates to compensate for the absolute position of the 81 * window area. 82 */ 83 struct InputTarget { 84 enum { 85 /* This flag indicates that the event is being delivered to a foreground application. */ 86 FLAG_FOREGROUND = 0x01, 87 88 /* This flag indicates that a MotionEvent with AMOTION_EVENT_ACTION_DOWN falls outside 89 * of the area of this target and so should instead be delivered as an 90 * AMOTION_EVENT_ACTION_OUTSIDE to this target. */ 91 FLAG_OUTSIDE = 0x02, 92 93 /* This flag indicates that the target of a MotionEvent is partly or wholly 94 * obscured by another visible window above it. The motion event should be 95 * delivered with flag AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED. */ 96 FLAG_WINDOW_IS_OBSCURED = 0x04, 97 98 /* This flag indicates that a motion event is being split across multiple windows. */ 99 FLAG_SPLIT = 0x08, 100 }; 101 102 // The input channel to be targeted. 103 sp<InputChannel> inputChannel; 104 105 // Flags for the input target. 106 int32_t flags; 107 108 // The x and y offset to add to a MotionEvent as it is delivered. 109 // (ignored for KeyEvents) 110 float xOffset, yOffset; 111 112 // The subset of pointer ids to include in motion events dispatched to this input target 113 // if FLAG_SPLIT is set. 114 BitSet32 pointerIds; 115 }; 116 117 118 /* 119 * An input window describes the bounds of a window that can receive input. 120 */ 121 struct InputWindow { 122 // Window flags from WindowManager.LayoutParams 123 enum { 124 FLAG_ALLOW_LOCK_WHILE_SCREEN_ON = 0x00000001, 125 FLAG_DIM_BEHIND = 0x00000002, 126 FLAG_BLUR_BEHIND = 0x00000004, 127 FLAG_NOT_FOCUSABLE = 0x00000008, 128 FLAG_NOT_TOUCHABLE = 0x00000010, 129 FLAG_NOT_TOUCH_MODAL = 0x00000020, 130 FLAG_TOUCHABLE_WHEN_WAKING = 0x00000040, 131 FLAG_KEEP_SCREEN_ON = 0x00000080, 132 FLAG_LAYOUT_IN_SCREEN = 0x00000100, 133 FLAG_LAYOUT_NO_LIMITS = 0x00000200, 134 FLAG_FULLSCREEN = 0x00000400, 135 FLAG_FORCE_NOT_FULLSCREEN = 0x00000800, 136 FLAG_DITHER = 0x00001000, 137 FLAG_SECURE = 0x00002000, 138 FLAG_SCALED = 0x00004000, 139 FLAG_IGNORE_CHEEK_PRESSES = 0x00008000, 140 FLAG_LAYOUT_INSET_DECOR = 0x00010000, 141 FLAG_ALT_FOCUSABLE_IM = 0x00020000, 142 FLAG_WATCH_OUTSIDE_TOUCH = 0x00040000, 143 FLAG_SHOW_WHEN_LOCKED = 0x00080000, 144 FLAG_SHOW_WALLPAPER = 0x00100000, 145 FLAG_TURN_SCREEN_ON = 0x00200000, 146 FLAG_DISMISS_KEYGUARD = 0x00400000, 147 FLAG_SPLIT_TOUCH = 0x00800000, 148 FLAG_KEEP_SURFACE_WHILE_ANIMATING = 0x10000000, 149 FLAG_COMPATIBLE_WINDOW = 0x20000000, 150 FLAG_SYSTEM_ERROR = 0x40000000, 151 }; 152 153 // Window types from WindowManager.LayoutParams 154 enum { 155 FIRST_APPLICATION_WINDOW = 1, 156 TYPE_BASE_APPLICATION = 1, 157 TYPE_APPLICATION = 2, 158 TYPE_APPLICATION_STARTING = 3, 159 LAST_APPLICATION_WINDOW = 99, 160 FIRST_SUB_WINDOW = 1000, 161 TYPE_APPLICATION_PANEL = FIRST_SUB_WINDOW, 162 TYPE_APPLICATION_MEDIA = FIRST_SUB_WINDOW+1, 163 TYPE_APPLICATION_SUB_PANEL = FIRST_SUB_WINDOW+2, 164 TYPE_APPLICATION_ATTACHED_DIALOG = FIRST_SUB_WINDOW+3, 165 TYPE_APPLICATION_MEDIA_OVERLAY = FIRST_SUB_WINDOW+4, 166 LAST_SUB_WINDOW = 1999, 167 FIRST_SYSTEM_WINDOW = 2000, 168 TYPE_STATUS_BAR = FIRST_SYSTEM_WINDOW, 169 TYPE_SEARCH_BAR = FIRST_SYSTEM_WINDOW+1, 170 TYPE_PHONE = FIRST_SYSTEM_WINDOW+2, 171 TYPE_SYSTEM_ALERT = FIRST_SYSTEM_WINDOW+3, 172 TYPE_KEYGUARD = FIRST_SYSTEM_WINDOW+4, 173 TYPE_TOAST = FIRST_SYSTEM_WINDOW+5, 174 TYPE_SYSTEM_OVERLAY = FIRST_SYSTEM_WINDOW+6, 175 TYPE_PRIORITY_PHONE = FIRST_SYSTEM_WINDOW+7, 176 TYPE_SYSTEM_DIALOG = FIRST_SYSTEM_WINDOW+8, 177 TYPE_KEYGUARD_DIALOG = FIRST_SYSTEM_WINDOW+9, 178 TYPE_SYSTEM_ERROR = FIRST_SYSTEM_WINDOW+10, 179 TYPE_INPUT_METHOD = FIRST_SYSTEM_WINDOW+11, 180 TYPE_INPUT_METHOD_DIALOG= FIRST_SYSTEM_WINDOW+12, 181 TYPE_WALLPAPER = FIRST_SYSTEM_WINDOW+13, 182 TYPE_STATUS_BAR_PANEL = FIRST_SYSTEM_WINDOW+14, 183 TYPE_SECURE_SYSTEM_OVERLAY = FIRST_SYSTEM_WINDOW+15, 184 LAST_SYSTEM_WINDOW = 2999, 185 }; 186 187 sp<InputChannel> inputChannel; 188 String8 name; 189 int32_t layoutParamsFlags; 190 int32_t layoutParamsType; 191 nsecs_t dispatchingTimeout; 192 int32_t frameLeft; 193 int32_t frameTop; 194 int32_t frameRight; 195 int32_t frameBottom; 196 int32_t visibleFrameLeft; 197 int32_t visibleFrameTop; 198 int32_t visibleFrameRight; 199 int32_t visibleFrameBottom; 200 int32_t touchableAreaLeft; 201 int32_t touchableAreaTop; 202 int32_t touchableAreaRight; 203 int32_t touchableAreaBottom; 204 bool visible; 205 bool canReceiveKeys; 206 bool hasFocus; 207 bool hasWallpaper; 208 bool paused; 209 int32_t layer; 210 int32_t ownerPid; 211 int32_t ownerUid; 212 213 bool touchableAreaContainsPoint(int32_t x, int32_t y) const; 214 bool frameContainsPoint(int32_t x, int32_t y) const; 215 216 /* Returns true if the window is of a trusted type that is allowed to silently 217 * overlay other windows for the purpose of implementing the secure views feature. 218 * Trusted overlays, such as IME windows, can partly obscure other windows without causing 219 * motion events to be delivered to them with AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED. 220 */ 221 bool isTrustedOverlay() const; 222 }; 223 224 225 /* 226 * A private handle type used by the input manager to track the window. 227 */ 228 class InputApplicationHandle : public RefBase { 229 protected: 230 InputApplicationHandle() { } 231 virtual ~InputApplicationHandle() { } 232 }; 233 234 235 /* 236 * An input application describes properties of an application that can receive input. 237 */ 238 struct InputApplication { 239 String8 name; 240 nsecs_t dispatchingTimeout; 241 sp<InputApplicationHandle> handle; 242 }; 243 244 245 /* 246 * Input dispatcher policy interface. 247 * 248 * The input reader policy is used by the input reader to interact with the Window Manager 249 * and other system components. 250 * 251 * The actual implementation is partially supported by callbacks into the DVM 252 * via JNI. This interface is also mocked in the unit tests. 253 */ 254 class InputDispatcherPolicyInterface : public virtual RefBase { 255 protected: 256 InputDispatcherPolicyInterface() { } 257 virtual ~InputDispatcherPolicyInterface() { } 258 259 public: 260 /* Notifies the system that a configuration change has occurred. */ 261 virtual void notifyConfigurationChanged(nsecs_t when) = 0; 262 263 /* Notifies the system that an application is not responding. 264 * Returns a new timeout to continue waiting, or 0 to abort dispatch. */ 265 virtual nsecs_t notifyANR(const sp<InputApplicationHandle>& inputApplicationHandle, 266 const sp<InputChannel>& inputChannel) = 0; 267 268 /* Notifies the system that an input channel is unrecoverably broken. */ 269 virtual void notifyInputChannelBroken(const sp<InputChannel>& inputChannel) = 0; 270 271 /* Gets the key repeat initial timeout or -1 if automatic key repeating is disabled. */ 272 virtual nsecs_t getKeyRepeatTimeout() = 0; 273 274 /* Gets the key repeat inter-key delay. */ 275 virtual nsecs_t getKeyRepeatDelay() = 0; 276 277 /* Gets the maximum suggested event delivery rate per second. 278 * This value is used to throttle motion event movement actions on a per-device 279 * basis. It is not intended to be a hard limit. 280 */ 281 virtual int32_t getMaxEventsPerSecond() = 0; 282 283 /* Intercepts a key event immediately before queueing it. 284 * The policy can use this method as an opportunity to perform power management functions 285 * and early event preprocessing such as updating policy flags. 286 * 287 * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event 288 * should be dispatched to applications. 289 */ 290 virtual void interceptKeyBeforeQueueing(nsecs_t when, int32_t deviceId, 291 int32_t action, int32_t& flags, int32_t keyCode, int32_t scanCode, 292 uint32_t& policyFlags) = 0; 293 294 /* Intercepts a generic touch, trackball or other event before queueing it. 295 * The policy can use this method as an opportunity to perform power management functions 296 * and early event preprocessing such as updating policy flags. 297 * 298 * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event 299 * should be dispatched to applications. 300 */ 301 virtual void interceptGenericBeforeQueueing(nsecs_t when, uint32_t& policyFlags) = 0; 302 303 /* Allows the policy a chance to intercept a key before dispatching. */ 304 virtual bool interceptKeyBeforeDispatching(const sp<InputChannel>& inputChannel, 305 const KeyEvent* keyEvent, uint32_t policyFlags) = 0; 306 307 /* Notifies the policy about switch events. 308 */ 309 virtual void notifySwitch(nsecs_t when, 310 int32_t switchCode, int32_t switchValue, uint32_t policyFlags) = 0; 311 312 /* Poke user activity for an event dispatched to a window. */ 313 virtual void pokeUserActivity(nsecs_t eventTime, int32_t eventType) = 0; 314 315 /* Checks whether a given application pid/uid has permission to inject input events 316 * into other applications. 317 * 318 * This method is special in that its implementation promises to be non-reentrant and 319 * is safe to call while holding other locks. (Most other methods make no such guarantees!) 320 */ 321 virtual bool checkInjectEventsPermissionNonReentrant( 322 int32_t injectorPid, int32_t injectorUid) = 0; 323 }; 324 325 326 /* Notifies the system about input events generated by the input reader. 327 * The dispatcher is expected to be mostly asynchronous. */ 328 class InputDispatcherInterface : public virtual RefBase { 329 protected: 330 InputDispatcherInterface() { } 331 virtual ~InputDispatcherInterface() { } 332 333 public: 334 /* Dumps the state of the input dispatcher. 335 * 336 * This method may be called on any thread (usually by the input manager). */ 337 virtual void dump(String8& dump) = 0; 338 339 /* Runs a single iteration of the dispatch loop. 340 * Nominally processes one queued event, a timeout, or a response from an input consumer. 341 * 342 * This method should only be called on the input dispatcher thread. 343 */ 344 virtual void dispatchOnce() = 0; 345 346 /* Notifies the dispatcher about new events. 347 * 348 * These methods should only be called on the input reader thread. 349 */ 350 virtual void notifyConfigurationChanged(nsecs_t eventTime) = 0; 351 virtual void notifyKey(nsecs_t eventTime, int32_t deviceId, int32_t source, 352 uint32_t policyFlags, int32_t action, int32_t flags, int32_t keyCode, 353 int32_t scanCode, int32_t metaState, nsecs_t downTime) = 0; 354 virtual void notifyMotion(nsecs_t eventTime, int32_t deviceId, int32_t source, 355 uint32_t policyFlags, int32_t action, int32_t flags, 356 int32_t metaState, int32_t edgeFlags, 357 uint32_t pointerCount, const int32_t* pointerIds, const PointerCoords* pointerCoords, 358 float xPrecision, float yPrecision, nsecs_t downTime) = 0; 359 virtual void notifySwitch(nsecs_t when, 360 int32_t switchCode, int32_t switchValue, uint32_t policyFlags) = 0; 361 362 /* Injects an input event and optionally waits for sync. 363 * The synchronization mode determines whether the method blocks while waiting for 364 * input injection to proceed. 365 * Returns one of the INPUT_EVENT_INJECTION_XXX constants. 366 * 367 * This method may be called on any thread (usually by the input manager). 368 */ 369 virtual int32_t injectInputEvent(const InputEvent* event, 370 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis) = 0; 371 372 /* Sets the list of input windows. 373 * 374 * This method may be called on any thread (usually by the input manager). 375 */ 376 virtual void setInputWindows(const Vector<InputWindow>& inputWindows) = 0; 377 378 /* Sets the focused application. 379 * 380 * This method may be called on any thread (usually by the input manager). 381 */ 382 virtual void setFocusedApplication(const InputApplication* inputApplication) = 0; 383 384 /* Sets the input dispatching mode. 385 * 386 * This method may be called on any thread (usually by the input manager). 387 */ 388 virtual void setInputDispatchMode(bool enabled, bool frozen) = 0; 389 390 /* Registers or unregister input channels that may be used as targets for input events. 391 * If monitor is true, the channel will receive a copy of all input events. 392 * 393 * These methods may be called on any thread (usually by the input manager). 394 */ 395 virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel, bool monitor) = 0; 396 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel) = 0; 397 }; 398 399 /* Dispatches events to input targets. Some functions of the input dispatcher, such as 400 * identifying input targets, are controlled by a separate policy object. 401 * 402 * IMPORTANT INVARIANT: 403 * Because the policy can potentially block or cause re-entrance into the input dispatcher, 404 * the input dispatcher never calls into the policy while holding its internal locks. 405 * The implementation is also carefully designed to recover from scenarios such as an 406 * input channel becoming unregistered while identifying input targets or processing timeouts. 407 * 408 * Methods marked 'Locked' must be called with the lock acquired. 409 * 410 * Methods marked 'LockedInterruptible' must be called with the lock acquired but 411 * may during the course of their execution release the lock, call into the policy, and 412 * then reacquire the lock. The caller is responsible for recovering gracefully. 413 * 414 * A 'LockedInterruptible' method may called a 'Locked' method, but NOT vice-versa. 415 */ 416 class InputDispatcher : public InputDispatcherInterface { 417 protected: 418 virtual ~InputDispatcher(); 419 420 public: 421 explicit InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy); 422 423 virtual void dump(String8& dump); 424 425 virtual void dispatchOnce(); 426 427 virtual void notifyConfigurationChanged(nsecs_t eventTime); 428 virtual void notifyKey(nsecs_t eventTime, int32_t deviceId, int32_t source, 429 uint32_t policyFlags, int32_t action, int32_t flags, int32_t keyCode, 430 int32_t scanCode, int32_t metaState, nsecs_t downTime); 431 virtual void notifyMotion(nsecs_t eventTime, int32_t deviceId, int32_t source, 432 uint32_t policyFlags, int32_t action, int32_t flags, 433 int32_t metaState, int32_t edgeFlags, 434 uint32_t pointerCount, const int32_t* pointerIds, const PointerCoords* pointerCoords, 435 float xPrecision, float yPrecision, nsecs_t downTime); 436 virtual void notifySwitch(nsecs_t when, 437 int32_t switchCode, int32_t switchValue, uint32_t policyFlags) ; 438 439 virtual int32_t injectInputEvent(const InputEvent* event, 440 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis); 441 442 virtual void setInputWindows(const Vector<InputWindow>& inputWindows); 443 virtual void setFocusedApplication(const InputApplication* inputApplication); 444 virtual void setInputDispatchMode(bool enabled, bool frozen); 445 446 virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel, bool monitor); 447 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel); 448 449 private: 450 template <typename T> 451 struct Link { 452 T* next; 453 T* prev; 454 }; 455 456 struct InjectionState { 457 mutable int32_t refCount; 458 459 int32_t injectorPid; 460 int32_t injectorUid; 461 int32_t injectionResult; // initially INPUT_EVENT_INJECTION_PENDING 462 bool injectionIsAsync; // set to true if injection is not waiting for the result 463 int32_t pendingForegroundDispatches; // the number of foreground dispatches in progress 464 }; 465 466 struct EventEntry : Link<EventEntry> { 467 enum { 468 TYPE_SENTINEL, 469 TYPE_CONFIGURATION_CHANGED, 470 TYPE_KEY, 471 TYPE_MOTION 472 }; 473 474 mutable int32_t refCount; 475 int32_t type; 476 nsecs_t eventTime; 477 uint32_t policyFlags; 478 InjectionState* injectionState; 479 480 bool dispatchInProgress; // initially false, set to true while dispatching 481 482 inline bool isInjected() { return injectionState != NULL; } 483 }; 484 485 struct ConfigurationChangedEntry : EventEntry { 486 }; 487 488 struct KeyEntry : EventEntry { 489 int32_t deviceId; 490 int32_t source; 491 int32_t action; 492 int32_t flags; 493 int32_t keyCode; 494 int32_t scanCode; 495 int32_t metaState; 496 int32_t repeatCount; 497 nsecs_t downTime; 498 499 bool syntheticRepeat; // set to true for synthetic key repeats 500 501 enum InterceptKeyResult { 502 INTERCEPT_KEY_RESULT_UNKNOWN, 503 INTERCEPT_KEY_RESULT_SKIP, 504 INTERCEPT_KEY_RESULT_CONTINUE, 505 }; 506 InterceptKeyResult interceptKeyResult; // set based on the interception result 507 }; 508 509 struct MotionSample { 510 MotionSample* next; 511 512 nsecs_t eventTime; 513 PointerCoords pointerCoords[MAX_POINTERS]; 514 }; 515 516 struct MotionEntry : EventEntry { 517 int32_t deviceId; 518 int32_t source; 519 int32_t action; 520 int32_t flags; 521 int32_t metaState; 522 int32_t edgeFlags; 523 float xPrecision; 524 float yPrecision; 525 nsecs_t downTime; 526 uint32_t pointerCount; 527 int32_t pointerIds[MAX_POINTERS]; 528 529 // Linked list of motion samples associated with this motion event. 530 MotionSample firstSample; 531 MotionSample* lastSample; 532 533 uint32_t countSamples() const; 534 }; 535 536 // Tracks the progress of dispatching a particular event to a particular connection. 537 struct DispatchEntry : Link<DispatchEntry> { 538 EventEntry* eventEntry; // the event to dispatch 539 int32_t targetFlags; 540 float xOffset; 541 float yOffset; 542 543 // True if dispatch has started. 544 bool inProgress; 545 546 // For motion events: 547 // Pointer to the first motion sample to dispatch in this cycle. 548 // Usually NULL to indicate that the list of motion samples begins at 549 // MotionEntry::firstSample. Otherwise, some samples were dispatched in a previous 550 // cycle and this pointer indicates the location of the first remainining sample 551 // to dispatch during the current cycle. 552 MotionSample* headMotionSample; 553 // Pointer to a motion sample to dispatch in the next cycle if the dispatcher was 554 // unable to send all motion samples during this cycle. On the next cycle, 555 // headMotionSample will be initialized to tailMotionSample and tailMotionSample 556 // will be set to NULL. 557 MotionSample* tailMotionSample; 558 559 inline bool hasForegroundTarget() const { 560 return targetFlags & InputTarget::FLAG_FOREGROUND; 561 } 562 563 inline bool isSplit() const { 564 return targetFlags & InputTarget::FLAG_SPLIT; 565 } 566 }; 567 568 // A command entry captures state and behavior for an action to be performed in the 569 // dispatch loop after the initial processing has taken place. It is essentially 570 // a kind of continuation used to postpone sensitive policy interactions to a point 571 // in the dispatch loop where it is safe to release the lock (generally after finishing 572 // the critical parts of the dispatch cycle). 573 // 574 // The special thing about commands is that they can voluntarily release and reacquire 575 // the dispatcher lock at will. Initially when the command starts running, the 576 // dispatcher lock is held. However, if the command needs to call into the policy to 577 // do some work, it can release the lock, do the work, then reacquire the lock again 578 // before returning. 579 // 580 // This mechanism is a bit clunky but it helps to preserve the invariant that the dispatch 581 // never calls into the policy while holding its lock. 582 // 583 // Commands are implicitly 'LockedInterruptible'. 584 struct CommandEntry; 585 typedef void (InputDispatcher::*Command)(CommandEntry* commandEntry); 586 587 class Connection; 588 struct CommandEntry : Link<CommandEntry> { 589 CommandEntry(); 590 ~CommandEntry(); 591 592 Command command; 593 594 // parameters for the command (usage varies by command) 595 sp<Connection> connection; 596 nsecs_t eventTime; 597 KeyEntry* keyEntry; 598 sp<InputChannel> inputChannel; 599 sp<InputApplicationHandle> inputApplicationHandle; 600 int32_t userActivityEventType; 601 }; 602 603 // Generic queue implementation. 604 template <typename T> 605 struct Queue { 606 T headSentinel; 607 T tailSentinel; 608 609 inline Queue() { 610 headSentinel.prev = NULL; 611 headSentinel.next = & tailSentinel; 612 tailSentinel.prev = & headSentinel; 613 tailSentinel.next = NULL; 614 } 615 616 inline bool isEmpty() const { 617 return headSentinel.next == & tailSentinel; 618 } 619 620 inline void enqueueAtTail(T* entry) { 621 T* last = tailSentinel.prev; 622 last->next = entry; 623 entry->prev = last; 624 entry->next = & tailSentinel; 625 tailSentinel.prev = entry; 626 } 627 628 inline void enqueueAtHead(T* entry) { 629 T* first = headSentinel.next; 630 headSentinel.next = entry; 631 entry->prev = & headSentinel; 632 entry->next = first; 633 first->prev = entry; 634 } 635 636 inline void dequeue(T* entry) { 637 entry->prev->next = entry->next; 638 entry->next->prev = entry->prev; 639 } 640 641 inline T* dequeueAtHead() { 642 T* first = headSentinel.next; 643 dequeue(first); 644 return first; 645 } 646 647 uint32_t count() const; 648 }; 649 650 /* Allocates queue entries and performs reference counting as needed. */ 651 class Allocator { 652 public: 653 Allocator(); 654 655 InjectionState* obtainInjectionState(int32_t injectorPid, int32_t injectorUid); 656 ConfigurationChangedEntry* obtainConfigurationChangedEntry(nsecs_t eventTime); 657 KeyEntry* obtainKeyEntry(nsecs_t eventTime, 658 int32_t deviceId, int32_t source, uint32_t policyFlags, int32_t action, 659 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState, 660 int32_t repeatCount, nsecs_t downTime); 661 MotionEntry* obtainMotionEntry(nsecs_t eventTime, 662 int32_t deviceId, int32_t source, uint32_t policyFlags, int32_t action, 663 int32_t flags, int32_t metaState, int32_t edgeFlags, 664 float xPrecision, float yPrecision, 665 nsecs_t downTime, uint32_t pointerCount, 666 const int32_t* pointerIds, const PointerCoords* pointerCoords); 667 DispatchEntry* obtainDispatchEntry(EventEntry* eventEntry, 668 int32_t targetFlags, float xOffset, float yOffset); 669 CommandEntry* obtainCommandEntry(Command command); 670 671 void releaseInjectionState(InjectionState* injectionState); 672 void releaseEventEntry(EventEntry* entry); 673 void releaseConfigurationChangedEntry(ConfigurationChangedEntry* entry); 674 void releaseKeyEntry(KeyEntry* entry); 675 void releaseMotionEntry(MotionEntry* entry); 676 void releaseDispatchEntry(DispatchEntry* entry); 677 void releaseCommandEntry(CommandEntry* entry); 678 679 void recycleKeyEntry(KeyEntry* entry); 680 681 void appendMotionSample(MotionEntry* motionEntry, 682 nsecs_t eventTime, const PointerCoords* pointerCoords); 683 684 private: 685 Pool<InjectionState> mInjectionStatePool; 686 Pool<ConfigurationChangedEntry> mConfigurationChangeEntryPool; 687 Pool<KeyEntry> mKeyEntryPool; 688 Pool<MotionEntry> mMotionEntryPool; 689 Pool<MotionSample> mMotionSamplePool; 690 Pool<DispatchEntry> mDispatchEntryPool; 691 Pool<CommandEntry> mCommandEntryPool; 692 693 void initializeEventEntry(EventEntry* entry, int32_t type, nsecs_t eventTime, 694 uint32_t policyFlags); 695 void releaseEventEntryInjectionState(EventEntry* entry); 696 }; 697 698 /* Tracks dispatched key and motion event state so that cancelation events can be 699 * synthesized when events are dropped. */ 700 class InputState { 701 public: 702 // Specifies whether a given event will violate input state consistency. 703 enum Consistency { 704 // The event is consistent with the current input state. 705 CONSISTENT, 706 // The event is inconsistent with the current input state but applications 707 // will tolerate it. eg. Down followed by another down. 708 TOLERABLE, 709 // The event is inconsistent with the current input state and will probably 710 // cause applications to crash. eg. Up without prior down, move with 711 // unexpected number of pointers. 712 BROKEN 713 }; 714 715 // Specifies the sources to cancel. 716 enum CancelationOptions { 717 CANCEL_ALL_EVENTS = 0, 718 CANCEL_POINTER_EVENTS = 1, 719 CANCEL_NON_POINTER_EVENTS = 2, 720 }; 721 722 InputState(); 723 ~InputState(); 724 725 // Returns true if there is no state to be canceled. 726 bool isNeutral() const; 727 728 // Records tracking information for an event that has just been published. 729 // Returns whether the event is consistent with the current input state. 730 Consistency trackEvent(const EventEntry* entry); 731 732 // Records tracking information for a key event that has just been published. 733 // Returns whether the event is consistent with the current input state. 734 Consistency trackKey(const KeyEntry* entry); 735 736 // Records tracking information for a motion event that has just been published. 737 // Returns whether the event is consistent with the current input state. 738 Consistency trackMotion(const MotionEntry* entry); 739 740 // Synthesizes cancelation events for the current state and resets the tracked state. 741 void synthesizeCancelationEvents(nsecs_t currentTime, Allocator* allocator, 742 Vector<EventEntry*>& outEvents, CancelationOptions options); 743 744 // Clears the current state. 745 void clear(); 746 747 private: 748 struct KeyMemento { 749 int32_t deviceId; 750 int32_t source; 751 int32_t keyCode; 752 int32_t scanCode; 753 nsecs_t downTime; 754 }; 755 756 struct MotionMemento { 757 int32_t deviceId; 758 int32_t source; 759 float xPrecision; 760 float yPrecision; 761 nsecs_t downTime; 762 uint32_t pointerCount; 763 int32_t pointerIds[MAX_POINTERS]; 764 PointerCoords pointerCoords[MAX_POINTERS]; 765 766 void setPointers(const MotionEntry* entry); 767 }; 768 769 Vector<KeyMemento> mKeyMementos; 770 Vector<MotionMemento> mMotionMementos; 771 772 static bool shouldCancelEvent(int32_t eventSource, CancelationOptions options); 773 }; 774 775 /* Manages the dispatch state associated with a single input channel. */ 776 class Connection : public RefBase { 777 protected: 778 virtual ~Connection(); 779 780 public: 781 enum Status { 782 // Everything is peachy. 783 STATUS_NORMAL, 784 // An unrecoverable communication error has occurred. 785 STATUS_BROKEN, 786 // The input channel has been unregistered. 787 STATUS_ZOMBIE 788 }; 789 790 Status status; 791 sp<InputChannel> inputChannel; 792 InputPublisher inputPublisher; 793 InputState inputState; 794 Queue<DispatchEntry> outboundQueue; 795 796 nsecs_t lastEventTime; // the time when the event was originally captured 797 nsecs_t lastDispatchTime; // the time when the last event was dispatched 798 799 explicit Connection(const sp<InputChannel>& inputChannel); 800 801 inline const char* getInputChannelName() const { return inputChannel->getName().string(); } 802 803 const char* getStatusLabel() const; 804 805 // Finds a DispatchEntry in the outbound queue associated with the specified event. 806 // Returns NULL if not found. 807 DispatchEntry* findQueuedDispatchEntryForEvent(const EventEntry* eventEntry) const; 808 809 // Gets the time since the current event was originally obtained from the input driver. 810 inline double getEventLatencyMillis(nsecs_t currentTime) const { 811 return (currentTime - lastEventTime) / 1000000.0; 812 } 813 814 // Gets the time since the current event entered the outbound dispatch queue. 815 inline double getDispatchLatencyMillis(nsecs_t currentTime) const { 816 return (currentTime - lastDispatchTime) / 1000000.0; 817 } 818 819 status_t initialize(); 820 }; 821 822 enum DropReason { 823 DROP_REASON_NOT_DROPPED = 0, 824 DROP_REASON_POLICY = 1, 825 DROP_REASON_APP_SWITCH = 2, 826 DROP_REASON_DISABLED = 3, 827 }; 828 829 sp<InputDispatcherPolicyInterface> mPolicy; 830 831 Mutex mLock; 832 833 Allocator mAllocator; 834 sp<Looper> mLooper; 835 836 EventEntry* mPendingEvent; 837 Queue<EventEntry> mInboundQueue; 838 Queue<CommandEntry> mCommandQueue; 839 840 Vector<EventEntry*> mTempCancelationEvents; 841 842 void dispatchOnceInnerLocked(nsecs_t keyRepeatTimeout, nsecs_t keyRepeatDelay, 843 nsecs_t* nextWakeupTime); 844 845 // Enqueues an inbound event. Returns true if mLooper->wake() should be called. 846 bool enqueueInboundEventLocked(EventEntry* entry); 847 848 // Cleans up input state when dropping an inbound event. 849 void dropInboundEventLocked(EventEntry* entry, DropReason dropReason); 850 851 // App switch latency optimization. 852 bool mAppSwitchSawKeyDown; 853 nsecs_t mAppSwitchDueTime; 854 855 static bool isAppSwitchKeyCode(int32_t keyCode); 856 bool isAppSwitchKeyEventLocked(KeyEntry* keyEntry); 857 bool isAppSwitchPendingLocked(); 858 void resetPendingAppSwitchLocked(bool handled); 859 860 // All registered connections mapped by receive pipe file descriptor. 861 KeyedVector<int, sp<Connection> > mConnectionsByReceiveFd; 862 863 ssize_t getConnectionIndexLocked(const sp<InputChannel>& inputChannel); 864 865 // Active connections are connections that have a non-empty outbound queue. 866 // We don't use a ref-counted pointer here because we explicitly abort connections 867 // during unregistration which causes the connection's outbound queue to be cleared 868 // and the connection itself to be deactivated. 869 Vector<Connection*> mActiveConnections; 870 871 // Input channels that will receive a copy of all input events. 872 Vector<sp<InputChannel> > mMonitoringChannels; 873 874 // Preallocated key event object used for policy inquiries. 875 KeyEvent mReusableKeyEvent; 876 877 // Event injection and synchronization. 878 Condition mInjectionResultAvailableCondition; 879 bool hasInjectionPermission(int32_t injectorPid, int32_t injectorUid); 880 void setInjectionResultLocked(EventEntry* entry, int32_t injectionResult); 881 882 Condition mInjectionSyncFinishedCondition; 883 void incrementPendingForegroundDispatchesLocked(EventEntry* entry); 884 void decrementPendingForegroundDispatchesLocked(EventEntry* entry); 885 886 // Throttling state. 887 struct ThrottleState { 888 nsecs_t minTimeBetweenEvents; 889 890 nsecs_t lastEventTime; 891 int32_t lastDeviceId; 892 uint32_t lastSource; 893 894 uint32_t originalSampleCount; // only collected during debugging 895 } mThrottleState; 896 897 // Key repeat tracking. 898 struct KeyRepeatState { 899 KeyEntry* lastKeyEntry; // or null if no repeat 900 nsecs_t nextRepeatTime; 901 } mKeyRepeatState; 902 903 void resetKeyRepeatLocked(); 904 KeyEntry* synthesizeKeyRepeatLocked(nsecs_t currentTime, nsecs_t keyRepeatTimeout); 905 906 // Deferred command processing. 907 bool runCommandsLockedInterruptible(); 908 CommandEntry* postCommandLocked(Command command); 909 910 // Inbound event processing. 911 void drainInboundQueueLocked(); 912 void releasePendingEventLocked(); 913 void releaseInboundEventLocked(EventEntry* entry); 914 915 // Dispatch state. 916 bool mDispatchEnabled; 917 bool mDispatchFrozen; 918 919 Vector<InputWindow> mWindows; 920 921 const InputWindow* getWindowLocked(const sp<InputChannel>& inputChannel); 922 923 // Focus tracking for keys, trackball, etc. 924 const InputWindow* mFocusedWindow; 925 926 // Focus tracking for touch. 927 struct TouchedWindow { 928 const InputWindow* window; 929 int32_t targetFlags; 930 BitSet32 pointerIds; 931 sp<InputChannel> channel; 932 }; 933 struct TouchState { 934 bool down; 935 bool split; 936 Vector<TouchedWindow> windows; 937 938 TouchState(); 939 ~TouchState(); 940 void reset(); 941 void copyFrom(const TouchState& other); 942 void addOrUpdateWindow(const InputWindow* window, int32_t targetFlags, BitSet32 pointerIds); 943 void removeOutsideTouchWindows(); 944 const InputWindow* getFirstForegroundWindow(); 945 }; 946 947 TouchState mTouchState; 948 TouchState mTempTouchState; 949 950 // Focused application. 951 InputApplication* mFocusedApplication; 952 InputApplication mFocusedApplicationStorage; // preallocated storage for mFocusedApplication 953 void releaseFocusedApplicationLocked(); 954 955 // Dispatch inbound events. 956 bool dispatchConfigurationChangedLocked( 957 nsecs_t currentTime, ConfigurationChangedEntry* entry); 958 bool dispatchKeyLocked( 959 nsecs_t currentTime, KeyEntry* entry, nsecs_t keyRepeatTimeout, 960 DropReason* dropReason, nsecs_t* nextWakeupTime); 961 bool dispatchMotionLocked( 962 nsecs_t currentTime, MotionEntry* entry, 963 DropReason* dropReason, nsecs_t* nextWakeupTime); 964 void dispatchEventToCurrentInputTargetsLocked( 965 nsecs_t currentTime, EventEntry* entry, bool resumeWithAppendedMotionSample); 966 967 void logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry); 968 void logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry); 969 970 // The input targets that were most recently identified for dispatch. 971 bool mCurrentInputTargetsValid; // false while targets are being recomputed 972 Vector<InputTarget> mCurrentInputTargets; 973 974 enum InputTargetWaitCause { 975 INPUT_TARGET_WAIT_CAUSE_NONE, 976 INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY, 977 INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY, 978 }; 979 980 InputTargetWaitCause mInputTargetWaitCause; 981 nsecs_t mInputTargetWaitStartTime; 982 nsecs_t mInputTargetWaitTimeoutTime; 983 bool mInputTargetWaitTimeoutExpired; 984 985 // Finding targets for input events. 986 void resetTargetsLocked(); 987 void commitTargetsLocked(); 988 int32_t handleTargetsNotReadyLocked(nsecs_t currentTime, const EventEntry* entry, 989 const InputApplication* application, const InputWindow* window, 990 nsecs_t* nextWakeupTime); 991 void resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout, 992 const sp<InputChannel>& inputChannel); 993 nsecs_t getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime); 994 void resetANRTimeoutsLocked(); 995 996 int32_t findFocusedWindowTargetsLocked(nsecs_t currentTime, const EventEntry* entry, 997 nsecs_t* nextWakeupTime); 998 int32_t findTouchedWindowTargetsLocked(nsecs_t currentTime, const MotionEntry* entry, 999 nsecs_t* nextWakeupTime); 1000 1001 void addWindowTargetLocked(const InputWindow* window, int32_t targetFlags, 1002 BitSet32 pointerIds); 1003 void addMonitoringTargetsLocked(); 1004 void pokeUserActivityLocked(const EventEntry* eventEntry); 1005 bool checkInjectionPermission(const InputWindow* window, const InjectionState* injectionState); 1006 bool isWindowObscuredAtPointLocked(const InputWindow* window, int32_t x, int32_t y) const; 1007 bool isWindowFinishedWithPreviousInputLocked(const InputWindow* window); 1008 String8 getApplicationWindowLabelLocked(const InputApplication* application, 1009 const InputWindow* window); 1010 1011 // Manage the dispatch cycle for a single connection. 1012 // These methods are deliberately not Interruptible because doing all of the work 1013 // with the mutex held makes it easier to ensure that connection invariants are maintained. 1014 // If needed, the methods post commands to run later once the critical bits are done. 1015 void prepareDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection, 1016 EventEntry* eventEntry, const InputTarget* inputTarget, 1017 bool resumeWithAppendedMotionSample); 1018 void startDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection); 1019 void finishDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection); 1020 void startNextDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection); 1021 void abortBrokenDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection); 1022 void drainOutboundQueueLocked(Connection* connection); 1023 static int handleReceiveCallback(int receiveFd, int events, void* data); 1024 1025 void synthesizeCancelationEventsForAllConnectionsLocked( 1026 InputState::CancelationOptions options, const char* reason); 1027 void synthesizeCancelationEventsForInputChannelLocked(const sp<InputChannel>& channel, 1028 InputState::CancelationOptions options, const char* reason); 1029 void synthesizeCancelationEventsForConnectionLocked(const sp<Connection>& connection, 1030 InputState::CancelationOptions options, const char* reason); 1031 1032 // Splitting motion events across windows. 1033 MotionEntry* splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds); 1034 1035 // Reset and drop everything the dispatcher is doing. 1036 void resetAndDropEverythingLocked(const char* reason); 1037 1038 // Dump state. 1039 void dumpDispatchStateLocked(String8& dump); 1040 void logDispatchStateLocked(); 1041 1042 // Add or remove a connection to the mActiveConnections vector. 1043 void activateConnectionLocked(Connection* connection); 1044 void deactivateConnectionLocked(Connection* connection); 1045 1046 // Interesting events that we might like to log or tell the framework about. 1047 void onDispatchCycleStartedLocked( 1048 nsecs_t currentTime, const sp<Connection>& connection); 1049 void onDispatchCycleFinishedLocked( 1050 nsecs_t currentTime, const sp<Connection>& connection); 1051 void onDispatchCycleBrokenLocked( 1052 nsecs_t currentTime, const sp<Connection>& connection); 1053 void onANRLocked( 1054 nsecs_t currentTime, const InputApplication* application, const InputWindow* window, 1055 nsecs_t eventTime, nsecs_t waitStartTime); 1056 1057 // Outbound policy interactions. 1058 void doNotifyConfigurationChangedInterruptible(CommandEntry* commandEntry); 1059 void doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry); 1060 void doNotifyANRLockedInterruptible(CommandEntry* commandEntry); 1061 void doInterceptKeyBeforeDispatchingLockedInterruptible(CommandEntry* commandEntry); 1062 void doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry); 1063 1064 // Statistics gathering. 1065 void updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry, 1066 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication); 1067 }; 1068 1069 /* Enqueues and dispatches input events, endlessly. */ 1070 class InputDispatcherThread : public Thread { 1071 public: 1072 explicit InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher); 1073 ~InputDispatcherThread(); 1074 1075 private: 1076 virtual bool threadLoop(); 1077 1078 sp<InputDispatcherInterface> mDispatcher; 1079 }; 1080 1081 } // namespace android 1082 1083 #endif // _UI_INPUT_DISPATCHER_H 1084