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 <androidfw/Input.h> 21 #include <androidfw/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/BitSet.h> 30 #include <cutils/atomic.h> 31 32 #include <stddef.h> 33 #include <unistd.h> 34 #include <limits.h> 35 36 #include "InputWindow.h" 37 #include "InputApplication.h" 38 #include "InputListener.h" 39 40 41 namespace android { 42 43 /* 44 * Constants used to report the outcome of input event injection. 45 */ 46 enum { 47 /* (INTERNAL USE ONLY) Specifies that injection is pending and its outcome is unknown. */ 48 INPUT_EVENT_INJECTION_PENDING = -1, 49 50 /* Injection succeeded. */ 51 INPUT_EVENT_INJECTION_SUCCEEDED = 0, 52 53 /* Injection failed because the injector did not have permission to inject 54 * into the application with input focus. */ 55 INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1, 56 57 /* Injection failed because there were no available input targets. */ 58 INPUT_EVENT_INJECTION_FAILED = 2, 59 60 /* Injection failed due to a timeout. */ 61 INPUT_EVENT_INJECTION_TIMED_OUT = 3 62 }; 63 64 /* 65 * Constants used to determine the input event injection synchronization mode. 66 */ 67 enum { 68 /* Injection is asynchronous and is assumed always to be successful. */ 69 INPUT_EVENT_INJECTION_SYNC_NONE = 0, 70 71 /* Waits for previous events to be dispatched so that the input dispatcher can determine 72 * whether input event injection willbe permitted based on the current input focus. 73 * Does not wait for the input event to finish processing. */ 74 INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_RESULT = 1, 75 76 /* Waits for the input event to be completely processed. */ 77 INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED = 2, 78 }; 79 80 81 /* 82 * An input target specifies how an input event is to be dispatched to a particular window 83 * including the window's input channel, control flags, a timeout, and an X / Y offset to 84 * be added to input event coordinates to compensate for the absolute position of the 85 * window area. 86 */ 87 struct InputTarget { 88 enum { 89 /* This flag indicates that the event is being delivered to a foreground application. */ 90 FLAG_FOREGROUND = 1 << 0, 91 92 /* This flag indicates that the target of a MotionEvent is partly or wholly 93 * obscured by another visible window above it. The motion event should be 94 * delivered with flag AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED. */ 95 FLAG_WINDOW_IS_OBSCURED = 1 << 1, 96 97 /* This flag indicates that a motion event is being split across multiple windows. */ 98 FLAG_SPLIT = 1 << 2, 99 100 /* This flag indicates that the pointer coordinates dispatched to the application 101 * will be zeroed out to avoid revealing information to an application. This is 102 * used in conjunction with FLAG_DISPATCH_AS_OUTSIDE to prevent apps not sharing 103 * the same UID from watching all touches. */ 104 FLAG_ZERO_COORDS = 1 << 3, 105 106 /* This flag indicates that the event should be sent as is. 107 * Should always be set unless the event is to be transmuted. */ 108 FLAG_DISPATCH_AS_IS = 1 << 8, 109 110 /* This flag indicates that a MotionEvent with AMOTION_EVENT_ACTION_DOWN falls outside 111 * of the area of this target and so should instead be delivered as an 112 * AMOTION_EVENT_ACTION_OUTSIDE to this target. */ 113 FLAG_DISPATCH_AS_OUTSIDE = 1 << 9, 114 115 /* This flag indicates that a hover sequence is starting in the given window. 116 * The event is transmuted into ACTION_HOVER_ENTER. */ 117 FLAG_DISPATCH_AS_HOVER_ENTER = 1 << 10, 118 119 /* This flag indicates that a hover event happened outside of a window which handled 120 * previous hover events, signifying the end of the current hover sequence for that 121 * window. 122 * The event is transmuted into ACTION_HOVER_ENTER. */ 123 FLAG_DISPATCH_AS_HOVER_EXIT = 1 << 11, 124 125 /* This flag indicates that the event should be canceled. 126 * It is used to transmute ACTION_MOVE into ACTION_CANCEL when a touch slips 127 * outside of a window. */ 128 FLAG_DISPATCH_AS_SLIPPERY_EXIT = 1 << 12, 129 130 /* This flag indicates that the event should be dispatched as an initial down. 131 * It is used to transmute ACTION_MOVE into ACTION_DOWN when a touch slips 132 * into a new window. */ 133 FLAG_DISPATCH_AS_SLIPPERY_ENTER = 1 << 13, 134 135 /* Mask for all dispatch modes. */ 136 FLAG_DISPATCH_MASK = FLAG_DISPATCH_AS_IS 137 | FLAG_DISPATCH_AS_OUTSIDE 138 | FLAG_DISPATCH_AS_HOVER_ENTER 139 | FLAG_DISPATCH_AS_HOVER_EXIT 140 | FLAG_DISPATCH_AS_SLIPPERY_EXIT 141 | FLAG_DISPATCH_AS_SLIPPERY_ENTER, 142 }; 143 144 // The input channel to be targeted. 145 sp<InputChannel> inputChannel; 146 147 // Flags for the input target. 148 int32_t flags; 149 150 // The x and y offset to add to a MotionEvent as it is delivered. 151 // (ignored for KeyEvents) 152 float xOffset, yOffset; 153 154 // Scaling factor to apply to MotionEvent as it is delivered. 155 // (ignored for KeyEvents) 156 float scaleFactor; 157 158 // The subset of pointer ids to include in motion events dispatched to this input target 159 // if FLAG_SPLIT is set. 160 BitSet32 pointerIds; 161 }; 162 163 164 /* 165 * Input dispatcher configuration. 166 * 167 * Specifies various options that modify the behavior of the input dispatcher. 168 * The values provided here are merely defaults. The actual values will come from ViewConfiguration 169 * and are passed into the dispatcher during initialization. 170 */ 171 struct InputDispatcherConfiguration { 172 // The key repeat initial timeout. 173 nsecs_t keyRepeatTimeout; 174 175 // The key repeat inter-key delay. 176 nsecs_t keyRepeatDelay; 177 178 InputDispatcherConfiguration() : 179 keyRepeatTimeout(500 * 1000000LL), 180 keyRepeatDelay(50 * 1000000LL) { } 181 }; 182 183 184 /* 185 * Input dispatcher policy interface. 186 * 187 * The input reader policy is used by the input reader to interact with the Window Manager 188 * and other system components. 189 * 190 * The actual implementation is partially supported by callbacks into the DVM 191 * via JNI. This interface is also mocked in the unit tests. 192 */ 193 class InputDispatcherPolicyInterface : public virtual RefBase { 194 protected: 195 InputDispatcherPolicyInterface() { } 196 virtual ~InputDispatcherPolicyInterface() { } 197 198 public: 199 /* Notifies the system that a configuration change has occurred. */ 200 virtual void notifyConfigurationChanged(nsecs_t when) = 0; 201 202 /* Notifies the system that an application is not responding. 203 * Returns a new timeout to continue waiting, or 0 to abort dispatch. */ 204 virtual nsecs_t notifyANR(const sp<InputApplicationHandle>& inputApplicationHandle, 205 const sp<InputWindowHandle>& inputWindowHandle) = 0; 206 207 /* Notifies the system that an input channel is unrecoverably broken. */ 208 virtual void notifyInputChannelBroken(const sp<InputWindowHandle>& inputWindowHandle) = 0; 209 210 /* Gets the input dispatcher configuration. */ 211 virtual void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) = 0; 212 213 /* Returns true if automatic key repeating is enabled. */ 214 virtual bool isKeyRepeatEnabled() = 0; 215 216 /* Filters an input event. 217 * Return true to dispatch the event unmodified, false to consume the event. 218 * A filter can also transform and inject events later by passing POLICY_FLAG_FILTERED 219 * to injectInputEvent. 220 */ 221 virtual bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) = 0; 222 223 /* Intercepts a key event immediately before queueing it. 224 * The policy can use this method as an opportunity to perform power management functions 225 * and early event preprocessing such as updating policy flags. 226 * 227 * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event 228 * should be dispatched to applications. 229 */ 230 virtual void interceptKeyBeforeQueueing(const KeyEvent* keyEvent, uint32_t& policyFlags) = 0; 231 232 /* Intercepts a touch, trackball or other motion event before queueing it. 233 * The policy can use this method as an opportunity to perform power management functions 234 * and early event preprocessing such as updating policy flags. 235 * 236 * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event 237 * should be dispatched to applications. 238 */ 239 virtual void interceptMotionBeforeQueueing(nsecs_t when, uint32_t& policyFlags) = 0; 240 241 /* Allows the policy a chance to intercept a key before dispatching. */ 242 virtual nsecs_t interceptKeyBeforeDispatching(const sp<InputWindowHandle>& inputWindowHandle, 243 const KeyEvent* keyEvent, uint32_t policyFlags) = 0; 244 245 /* Allows the policy a chance to perform default processing for an unhandled key. 246 * Returns an alternate keycode to redispatch as a fallback, or 0 to give up. */ 247 virtual bool dispatchUnhandledKey(const sp<InputWindowHandle>& inputWindowHandle, 248 const KeyEvent* keyEvent, uint32_t policyFlags, KeyEvent* outFallbackKeyEvent) = 0; 249 250 /* Notifies the policy about switch events. 251 */ 252 virtual void notifySwitch(nsecs_t when, 253 uint32_t switchValues, uint32_t switchMask, uint32_t policyFlags) = 0; 254 255 /* Poke user activity for an event dispatched to a window. */ 256 virtual void pokeUserActivity(nsecs_t eventTime, int32_t eventType) = 0; 257 258 /* Checks whether a given application pid/uid has permission to inject input events 259 * into other applications. 260 * 261 * This method is special in that its implementation promises to be non-reentrant and 262 * is safe to call while holding other locks. (Most other methods make no such guarantees!) 263 */ 264 virtual bool checkInjectEventsPermissionNonReentrant( 265 int32_t injectorPid, int32_t injectorUid) = 0; 266 }; 267 268 269 /* Notifies the system about input events generated by the input reader. 270 * The dispatcher is expected to be mostly asynchronous. */ 271 class InputDispatcherInterface : public virtual RefBase, public InputListenerInterface { 272 protected: 273 InputDispatcherInterface() { } 274 virtual ~InputDispatcherInterface() { } 275 276 public: 277 /* Dumps the state of the input dispatcher. 278 * 279 * This method may be called on any thread (usually by the input manager). */ 280 virtual void dump(String8& dump) = 0; 281 282 /* Called by the heatbeat to ensures that the dispatcher has not deadlocked. */ 283 virtual void monitor() = 0; 284 285 /* Runs a single iteration of the dispatch loop. 286 * Nominally processes one queued event, a timeout, or a response from an input consumer. 287 * 288 * This method should only be called on the input dispatcher thread. 289 */ 290 virtual void dispatchOnce() = 0; 291 292 /* Injects an input event and optionally waits for sync. 293 * The synchronization mode determines whether the method blocks while waiting for 294 * input injection to proceed. 295 * Returns one of the INPUT_EVENT_INJECTION_XXX constants. 296 * 297 * This method may be called on any thread (usually by the input manager). 298 */ 299 virtual int32_t injectInputEvent(const InputEvent* event, 300 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis, 301 uint32_t policyFlags) = 0; 302 303 /* Sets the list of input windows. 304 * 305 * This method may be called on any thread (usually by the input manager). 306 */ 307 virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) = 0; 308 309 /* Sets the focused application. 310 * 311 * This method may be called on any thread (usually by the input manager). 312 */ 313 virtual void setFocusedApplication( 314 const sp<InputApplicationHandle>& inputApplicationHandle) = 0; 315 316 /* Sets the input dispatching mode. 317 * 318 * This method may be called on any thread (usually by the input manager). 319 */ 320 virtual void setInputDispatchMode(bool enabled, bool frozen) = 0; 321 322 /* Sets whether input event filtering is enabled. 323 * When enabled, incoming input events are sent to the policy's filterInputEvent 324 * method instead of being dispatched. The filter is expected to use 325 * injectInputEvent to inject the events it would like to have dispatched. 326 * It should include POLICY_FLAG_FILTERED in the policy flags during injection. 327 */ 328 virtual void setInputFilterEnabled(bool enabled) = 0; 329 330 /* Transfers touch focus from the window associated with one channel to the 331 * window associated with the other channel. 332 * 333 * Returns true on success. False if the window did not actually have touch focus. 334 */ 335 virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel, 336 const sp<InputChannel>& toChannel) = 0; 337 338 /* Registers or unregister input channels that may be used as targets for input events. 339 * If monitor is true, the channel will receive a copy of all input events. 340 * 341 * These methods may be called on any thread (usually by the input manager). 342 */ 343 virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel, 344 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) = 0; 345 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel) = 0; 346 }; 347 348 /* Dispatches events to input targets. Some functions of the input dispatcher, such as 349 * identifying input targets, are controlled by a separate policy object. 350 * 351 * IMPORTANT INVARIANT: 352 * Because the policy can potentially block or cause re-entrance into the input dispatcher, 353 * the input dispatcher never calls into the policy while holding its internal locks. 354 * The implementation is also carefully designed to recover from scenarios such as an 355 * input channel becoming unregistered while identifying input targets or processing timeouts. 356 * 357 * Methods marked 'Locked' must be called with the lock acquired. 358 * 359 * Methods marked 'LockedInterruptible' must be called with the lock acquired but 360 * may during the course of their execution release the lock, call into the policy, and 361 * then reacquire the lock. The caller is responsible for recovering gracefully. 362 * 363 * A 'LockedInterruptible' method may called a 'Locked' method, but NOT vice-versa. 364 */ 365 class InputDispatcher : public InputDispatcherInterface { 366 protected: 367 virtual ~InputDispatcher(); 368 369 public: 370 explicit InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy); 371 372 virtual void dump(String8& dump); 373 virtual void monitor(); 374 375 virtual void dispatchOnce(); 376 377 virtual void notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args); 378 virtual void notifyKey(const NotifyKeyArgs* args); 379 virtual void notifyMotion(const NotifyMotionArgs* args); 380 virtual void notifySwitch(const NotifySwitchArgs* args); 381 virtual void notifyDeviceReset(const NotifyDeviceResetArgs* args); 382 383 virtual int32_t injectInputEvent(const InputEvent* event, 384 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis, 385 uint32_t policyFlags); 386 387 virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles); 388 virtual void setFocusedApplication(const sp<InputApplicationHandle>& inputApplicationHandle); 389 virtual void setInputDispatchMode(bool enabled, bool frozen); 390 virtual void setInputFilterEnabled(bool enabled); 391 392 virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel, 393 const sp<InputChannel>& toChannel); 394 395 virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel, 396 const sp<InputWindowHandle>& inputWindowHandle, bool monitor); 397 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel); 398 399 private: 400 template <typename T> 401 struct Link { 402 T* next; 403 T* prev; 404 405 protected: 406 inline Link() : next(NULL), prev(NULL) { } 407 }; 408 409 struct InjectionState { 410 mutable int32_t refCount; 411 412 int32_t injectorPid; 413 int32_t injectorUid; 414 int32_t injectionResult; // initially INPUT_EVENT_INJECTION_PENDING 415 bool injectionIsAsync; // set to true if injection is not waiting for the result 416 int32_t pendingForegroundDispatches; // the number of foreground dispatches in progress 417 418 InjectionState(int32_t injectorPid, int32_t injectorUid); 419 void release(); 420 421 private: 422 ~InjectionState(); 423 }; 424 425 struct EventEntry : Link<EventEntry> { 426 enum { 427 TYPE_CONFIGURATION_CHANGED, 428 TYPE_DEVICE_RESET, 429 TYPE_KEY, 430 TYPE_MOTION 431 }; 432 433 mutable int32_t refCount; 434 int32_t type; 435 nsecs_t eventTime; 436 uint32_t policyFlags; 437 InjectionState* injectionState; 438 439 bool dispatchInProgress; // initially false, set to true while dispatching 440 441 inline bool isInjected() const { return injectionState != NULL; } 442 443 void release(); 444 445 virtual void appendDescription(String8& msg) const = 0; 446 447 protected: 448 EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags); 449 virtual ~EventEntry(); 450 void releaseInjectionState(); 451 }; 452 453 struct ConfigurationChangedEntry : EventEntry { 454 ConfigurationChangedEntry(nsecs_t eventTime); 455 virtual void appendDescription(String8& msg) const; 456 457 protected: 458 virtual ~ConfigurationChangedEntry(); 459 }; 460 461 struct DeviceResetEntry : EventEntry { 462 int32_t deviceId; 463 464 DeviceResetEntry(nsecs_t eventTime, int32_t deviceId); 465 virtual void appendDescription(String8& msg) const; 466 467 protected: 468 virtual ~DeviceResetEntry(); 469 }; 470 471 struct KeyEntry : EventEntry { 472 int32_t deviceId; 473 uint32_t source; 474 int32_t action; 475 int32_t flags; 476 int32_t keyCode; 477 int32_t scanCode; 478 int32_t metaState; 479 int32_t repeatCount; 480 nsecs_t downTime; 481 482 bool syntheticRepeat; // set to true for synthetic key repeats 483 484 enum InterceptKeyResult { 485 INTERCEPT_KEY_RESULT_UNKNOWN, 486 INTERCEPT_KEY_RESULT_SKIP, 487 INTERCEPT_KEY_RESULT_CONTINUE, 488 INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER, 489 }; 490 InterceptKeyResult interceptKeyResult; // set based on the interception result 491 nsecs_t interceptKeyWakeupTime; // used with INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER 492 493 KeyEntry(nsecs_t eventTime, 494 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, 495 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState, 496 int32_t repeatCount, nsecs_t downTime); 497 virtual void appendDescription(String8& msg) const; 498 void recycle(); 499 500 protected: 501 virtual ~KeyEntry(); 502 }; 503 504 struct MotionEntry : EventEntry { 505 nsecs_t eventTime; 506 int32_t deviceId; 507 uint32_t source; 508 int32_t action; 509 int32_t flags; 510 int32_t metaState; 511 int32_t buttonState; 512 int32_t edgeFlags; 513 float xPrecision; 514 float yPrecision; 515 nsecs_t downTime; 516 int32_t displayId; 517 uint32_t pointerCount; 518 PointerProperties pointerProperties[MAX_POINTERS]; 519 PointerCoords pointerCoords[MAX_POINTERS]; 520 521 MotionEntry(nsecs_t eventTime, 522 int32_t deviceId, uint32_t source, uint32_t policyFlags, 523 int32_t action, int32_t flags, 524 int32_t metaState, int32_t buttonState, int32_t edgeFlags, 525 float xPrecision, float yPrecision, 526 nsecs_t downTime, int32_t displayId, uint32_t pointerCount, 527 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords); 528 virtual void appendDescription(String8& msg) const; 529 530 protected: 531 virtual ~MotionEntry(); 532 }; 533 534 // Tracks the progress of dispatching a particular event to a particular connection. 535 struct DispatchEntry : Link<DispatchEntry> { 536 const uint32_t seq; // unique sequence number, never 0 537 538 EventEntry* eventEntry; // the event to dispatch 539 int32_t targetFlags; 540 float xOffset; 541 float yOffset; 542 float scaleFactor; 543 nsecs_t deliveryTime; // time when the event was actually delivered 544 545 // Set to the resolved action and flags when the event is enqueued. 546 int32_t resolvedAction; 547 int32_t resolvedFlags; 548 549 DispatchEntry(EventEntry* eventEntry, 550 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor); 551 ~DispatchEntry(); 552 553 inline bool hasForegroundTarget() const { 554 return targetFlags & InputTarget::FLAG_FOREGROUND; 555 } 556 557 inline bool isSplit() const { 558 return targetFlags & InputTarget::FLAG_SPLIT; 559 } 560 561 private: 562 static volatile int32_t sNextSeqAtomic; 563 564 static uint32_t nextSeq(); 565 }; 566 567 // A command entry captures state and behavior for an action to be performed in the 568 // dispatch loop after the initial processing has taken place. It is essentially 569 // a kind of continuation used to postpone sensitive policy interactions to a point 570 // in the dispatch loop where it is safe to release the lock (generally after finishing 571 // the critical parts of the dispatch cycle). 572 // 573 // The special thing about commands is that they can voluntarily release and reacquire 574 // the dispatcher lock at will. Initially when the command starts running, the 575 // dispatcher lock is held. However, if the command needs to call into the policy to 576 // do some work, it can release the lock, do the work, then reacquire the lock again 577 // before returning. 578 // 579 // This mechanism is a bit clunky but it helps to preserve the invariant that the dispatch 580 // never calls into the policy while holding its lock. 581 // 582 // Commands are implicitly 'LockedInterruptible'. 583 struct CommandEntry; 584 typedef void (InputDispatcher::*Command)(CommandEntry* commandEntry); 585 586 class Connection; 587 struct CommandEntry : Link<CommandEntry> { 588 CommandEntry(Command command); 589 ~CommandEntry(); 590 591 Command command; 592 593 // parameters for the command (usage varies by command) 594 sp<Connection> connection; 595 nsecs_t eventTime; 596 KeyEntry* keyEntry; 597 sp<InputApplicationHandle> inputApplicationHandle; 598 sp<InputWindowHandle> inputWindowHandle; 599 int32_t userActivityEventType; 600 uint32_t seq; 601 bool handled; 602 }; 603 604 // Generic queue implementation. 605 template <typename T> 606 struct Queue { 607 T* head; 608 T* tail; 609 610 inline Queue() : head(NULL), tail(NULL) { 611 } 612 613 inline bool isEmpty() const { 614 return !head; 615 } 616 617 inline void enqueueAtTail(T* entry) { 618 entry->prev = tail; 619 if (tail) { 620 tail->next = entry; 621 } else { 622 head = entry; 623 } 624 entry->next = NULL; 625 tail = entry; 626 } 627 628 inline void enqueueAtHead(T* entry) { 629 entry->next = head; 630 if (head) { 631 head->prev = entry; 632 } else { 633 tail = entry; 634 } 635 entry->prev = NULL; 636 head = entry; 637 } 638 639 inline void dequeue(T* entry) { 640 if (entry->prev) { 641 entry->prev->next = entry->next; 642 } else { 643 head = entry->next; 644 } 645 if (entry->next) { 646 entry->next->prev = entry->prev; 647 } else { 648 tail = entry->prev; 649 } 650 } 651 652 inline T* dequeueAtHead() { 653 T* entry = head; 654 head = entry->next; 655 if (head) { 656 head->prev = NULL; 657 } else { 658 tail = NULL; 659 } 660 return entry; 661 } 662 663 uint32_t count() const; 664 }; 665 666 /* Specifies which events are to be canceled and why. */ 667 struct CancelationOptions { 668 enum Mode { 669 CANCEL_ALL_EVENTS = 0, 670 CANCEL_POINTER_EVENTS = 1, 671 CANCEL_NON_POINTER_EVENTS = 2, 672 CANCEL_FALLBACK_EVENTS = 3, 673 }; 674 675 // The criterion to use to determine which events should be canceled. 676 Mode mode; 677 678 // Descriptive reason for the cancelation. 679 const char* reason; 680 681 // The specific keycode of the key event to cancel, or -1 to cancel any key event. 682 int32_t keyCode; 683 684 // The specific device id of events to cancel, or -1 to cancel events from any device. 685 int32_t deviceId; 686 687 CancelationOptions(Mode mode, const char* reason) : 688 mode(mode), reason(reason), keyCode(-1), deviceId(-1) { } 689 }; 690 691 /* Tracks dispatched key and motion event state so that cancelation events can be 692 * synthesized when events are dropped. */ 693 class InputState { 694 public: 695 InputState(); 696 ~InputState(); 697 698 // Returns true if there is no state to be canceled. 699 bool isNeutral() const; 700 701 // Returns true if the specified source is known to have received a hover enter 702 // motion event. 703 bool isHovering(int32_t deviceId, uint32_t source, int32_t displayId) const; 704 705 // Records tracking information for a key event that has just been published. 706 // Returns true if the event should be delivered, false if it is inconsistent 707 // and should be skipped. 708 bool trackKey(const KeyEntry* entry, int32_t action, int32_t flags); 709 710 // Records tracking information for a motion event that has just been published. 711 // Returns true if the event should be delivered, false if it is inconsistent 712 // and should be skipped. 713 bool trackMotion(const MotionEntry* entry, int32_t action, int32_t flags); 714 715 // Synthesizes cancelation events for the current state and resets the tracked state. 716 void synthesizeCancelationEvents(nsecs_t currentTime, 717 Vector<EventEntry*>& outEvents, const CancelationOptions& options); 718 719 // Clears the current state. 720 void clear(); 721 722 // Copies pointer-related parts of the input state to another instance. 723 void copyPointerStateTo(InputState& other) const; 724 725 // Gets the fallback key associated with a keycode. 726 // Returns -1 if none. 727 // Returns AKEYCODE_UNKNOWN if we are only dispatching the unhandled key to the policy. 728 int32_t getFallbackKey(int32_t originalKeyCode); 729 730 // Sets the fallback key for a particular keycode. 731 void setFallbackKey(int32_t originalKeyCode, int32_t fallbackKeyCode); 732 733 // Removes the fallback key for a particular keycode. 734 void removeFallbackKey(int32_t originalKeyCode); 735 736 inline const KeyedVector<int32_t, int32_t>& getFallbackKeys() const { 737 return mFallbackKeys; 738 } 739 740 private: 741 struct KeyMemento { 742 int32_t deviceId; 743 uint32_t source; 744 int32_t keyCode; 745 int32_t scanCode; 746 int32_t metaState; 747 int32_t flags; 748 nsecs_t downTime; 749 uint32_t policyFlags; 750 }; 751 752 struct MotionMemento { 753 int32_t deviceId; 754 uint32_t source; 755 int32_t flags; 756 float xPrecision; 757 float yPrecision; 758 nsecs_t downTime; 759 int32_t displayId; 760 uint32_t pointerCount; 761 PointerProperties pointerProperties[MAX_POINTERS]; 762 PointerCoords pointerCoords[MAX_POINTERS]; 763 bool hovering; 764 uint32_t policyFlags; 765 766 void setPointers(const MotionEntry* entry); 767 }; 768 769 Vector<KeyMemento> mKeyMementos; 770 Vector<MotionMemento> mMotionMementos; 771 KeyedVector<int32_t, int32_t> mFallbackKeys; 772 773 ssize_t findKeyMemento(const KeyEntry* entry) const; 774 ssize_t findMotionMemento(const MotionEntry* entry, bool hovering) const; 775 776 void addKeyMemento(const KeyEntry* entry, int32_t flags); 777 void addMotionMemento(const MotionEntry* entry, int32_t flags, bool hovering); 778 779 static bool shouldCancelKey(const KeyMemento& memento, 780 const CancelationOptions& options); 781 static bool shouldCancelMotion(const MotionMemento& memento, 782 const CancelationOptions& options); 783 }; 784 785 /* Manages the dispatch state associated with a single input channel. */ 786 class Connection : public RefBase { 787 protected: 788 virtual ~Connection(); 789 790 public: 791 enum Status { 792 // Everything is peachy. 793 STATUS_NORMAL, 794 // An unrecoverable communication error has occurred. 795 STATUS_BROKEN, 796 // The input channel has been unregistered. 797 STATUS_ZOMBIE 798 }; 799 800 Status status; 801 sp<InputChannel> inputChannel; // never null 802 sp<InputWindowHandle> inputWindowHandle; // may be null 803 bool monitor; 804 InputPublisher inputPublisher; 805 InputState inputState; 806 807 // True if the socket is full and no further events can be published until 808 // the application consumes some of the input. 809 bool inputPublisherBlocked; 810 811 // Queue of events that need to be published to the connection. 812 Queue<DispatchEntry> outboundQueue; 813 814 // Queue of events that have been published to the connection but that have not 815 // yet received a "finished" response from the application. 816 Queue<DispatchEntry> waitQueue; 817 818 explicit Connection(const sp<InputChannel>& inputChannel, 819 const sp<InputWindowHandle>& inputWindowHandle, bool monitor); 820 821 inline const char* getInputChannelName() const { return inputChannel->getName().string(); } 822 823 const char* getWindowName() const; 824 const char* getStatusLabel() const; 825 826 DispatchEntry* findWaitQueueEntry(uint32_t seq); 827 }; 828 829 enum DropReason { 830 DROP_REASON_NOT_DROPPED = 0, 831 DROP_REASON_POLICY = 1, 832 DROP_REASON_APP_SWITCH = 2, 833 DROP_REASON_DISABLED = 3, 834 DROP_REASON_BLOCKED = 4, 835 DROP_REASON_STALE = 5, 836 }; 837 838 sp<InputDispatcherPolicyInterface> mPolicy; 839 InputDispatcherConfiguration mConfig; 840 841 Mutex mLock; 842 843 Condition mDispatcherIsAliveCondition; 844 845 sp<Looper> mLooper; 846 847 EventEntry* mPendingEvent; 848 Queue<EventEntry> mInboundQueue; 849 Queue<CommandEntry> mCommandQueue; 850 851 void dispatchOnceInnerLocked(nsecs_t* nextWakeupTime); 852 853 // Enqueues an inbound event. Returns true if mLooper->wake() should be called. 854 bool enqueueInboundEventLocked(EventEntry* entry); 855 856 // Cleans up input state when dropping an inbound event. 857 void dropInboundEventLocked(EventEntry* entry, DropReason dropReason); 858 859 // App switch latency optimization. 860 bool mAppSwitchSawKeyDown; 861 nsecs_t mAppSwitchDueTime; 862 863 static bool isAppSwitchKeyCode(int32_t keyCode); 864 bool isAppSwitchKeyEventLocked(KeyEntry* keyEntry); 865 bool isAppSwitchPendingLocked(); 866 void resetPendingAppSwitchLocked(bool handled); 867 868 // Stale event latency optimization. 869 static bool isStaleEventLocked(nsecs_t currentTime, EventEntry* entry); 870 871 // Blocked event latency optimization. Drops old events when the user intends 872 // to transfer focus to a new application. 873 EventEntry* mNextUnblockedEvent; 874 875 sp<InputWindowHandle> findTouchedWindowAtLocked(int32_t displayId, int32_t x, int32_t y); 876 877 // All registered connections mapped by channel file descriptor. 878 KeyedVector<int, sp<Connection> > mConnectionsByFd; 879 880 ssize_t getConnectionIndexLocked(const sp<InputChannel>& inputChannel); 881 882 // Input channels that will receive a copy of all input events. 883 Vector<sp<InputChannel> > mMonitoringChannels; 884 885 // Event injection and synchronization. 886 Condition mInjectionResultAvailableCondition; 887 bool hasInjectionPermission(int32_t injectorPid, int32_t injectorUid); 888 void setInjectionResultLocked(EventEntry* entry, int32_t injectionResult); 889 890 Condition mInjectionSyncFinishedCondition; 891 void incrementPendingForegroundDispatchesLocked(EventEntry* entry); 892 void decrementPendingForegroundDispatchesLocked(EventEntry* entry); 893 894 // Key repeat tracking. 895 struct KeyRepeatState { 896 KeyEntry* lastKeyEntry; // or null if no repeat 897 nsecs_t nextRepeatTime; 898 } mKeyRepeatState; 899 900 void resetKeyRepeatLocked(); 901 KeyEntry* synthesizeKeyRepeatLocked(nsecs_t currentTime); 902 903 // Deferred command processing. 904 bool haveCommandsLocked() const; 905 bool runCommandsLockedInterruptible(); 906 CommandEntry* postCommandLocked(Command command); 907 908 // Input filter processing. 909 bool shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args); 910 bool shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args); 911 912 // Inbound event processing. 913 void drainInboundQueueLocked(); 914 void releasePendingEventLocked(); 915 void releaseInboundEventLocked(EventEntry* entry); 916 917 // Dispatch state. 918 bool mDispatchEnabled; 919 bool mDispatchFrozen; 920 bool mInputFilterEnabled; 921 922 Vector<sp<InputWindowHandle> > mWindowHandles; 923 924 sp<InputWindowHandle> getWindowHandleLocked(const sp<InputChannel>& inputChannel) const; 925 bool hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const; 926 927 // Focus tracking for keys, trackball, etc. 928 sp<InputWindowHandle> mFocusedWindowHandle; 929 930 // Focus tracking for touch. 931 struct TouchedWindow { 932 sp<InputWindowHandle> windowHandle; 933 int32_t targetFlags; 934 BitSet32 pointerIds; // zero unless target flag FLAG_SPLIT is set 935 }; 936 struct TouchState { 937 bool down; 938 bool split; 939 int32_t deviceId; // id of the device that is currently down, others are rejected 940 uint32_t source; // source of the device that is current down, others are rejected 941 int32_t displayId; // id to the display that currently has a touch, others are rejected 942 Vector<TouchedWindow> windows; 943 944 TouchState(); 945 ~TouchState(); 946 void reset(); 947 void copyFrom(const TouchState& other); 948 void addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle, 949 int32_t targetFlags, BitSet32 pointerIds); 950 void removeWindow(const sp<InputWindowHandle>& windowHandle); 951 void filterNonAsIsTouchWindows(); 952 sp<InputWindowHandle> getFirstForegroundWindowHandle() const; 953 bool isSlippery() const; 954 }; 955 956 TouchState mTouchState; 957 TouchState mTempTouchState; 958 959 // Focused application. 960 sp<InputApplicationHandle> mFocusedApplicationHandle; 961 962 // Dispatcher state at time of last ANR. 963 String8 mLastANRState; 964 965 // Dispatch inbound events. 966 bool dispatchConfigurationChangedLocked( 967 nsecs_t currentTime, ConfigurationChangedEntry* entry); 968 bool dispatchDeviceResetLocked( 969 nsecs_t currentTime, DeviceResetEntry* entry); 970 bool dispatchKeyLocked( 971 nsecs_t currentTime, KeyEntry* entry, 972 DropReason* dropReason, nsecs_t* nextWakeupTime); 973 bool dispatchMotionLocked( 974 nsecs_t currentTime, MotionEntry* entry, 975 DropReason* dropReason, nsecs_t* nextWakeupTime); 976 void dispatchEventLocked(nsecs_t currentTime, EventEntry* entry, 977 const Vector<InputTarget>& inputTargets); 978 979 void logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry); 980 void logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry); 981 982 // Keeping track of ANR timeouts. 983 enum InputTargetWaitCause { 984 INPUT_TARGET_WAIT_CAUSE_NONE, 985 INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY, 986 INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY, 987 }; 988 989 InputTargetWaitCause mInputTargetWaitCause; 990 nsecs_t mInputTargetWaitStartTime; 991 nsecs_t mInputTargetWaitTimeoutTime; 992 bool mInputTargetWaitTimeoutExpired; 993 sp<InputApplicationHandle> mInputTargetWaitApplicationHandle; 994 995 // Contains the last window which received a hover event. 996 sp<InputWindowHandle> mLastHoverWindowHandle; 997 998 // Finding targets for input events. 999 int32_t handleTargetsNotReadyLocked(nsecs_t currentTime, const EventEntry* entry, 1000 const sp<InputApplicationHandle>& applicationHandle, 1001 const sp<InputWindowHandle>& windowHandle, 1002 nsecs_t* nextWakeupTime, const char* reason); 1003 void resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout, 1004 const sp<InputChannel>& inputChannel); 1005 nsecs_t getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime); 1006 void resetANRTimeoutsLocked(); 1007 1008 int32_t findFocusedWindowTargetsLocked(nsecs_t currentTime, const EventEntry* entry, 1009 Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime); 1010 int32_t findTouchedWindowTargetsLocked(nsecs_t currentTime, const MotionEntry* entry, 1011 Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime, 1012 bool* outConflictingPointerActions); 1013 1014 void addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle, 1015 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets); 1016 void addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets); 1017 1018 void pokeUserActivityLocked(const EventEntry* eventEntry); 1019 bool checkInjectionPermission(const sp<InputWindowHandle>& windowHandle, 1020 const InjectionState* injectionState); 1021 bool isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle, 1022 int32_t x, int32_t y) const; 1023 bool isWindowReadyForMoreInputLocked(nsecs_t currentTime, 1024 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry); 1025 String8 getApplicationWindowLabelLocked(const sp<InputApplicationHandle>& applicationHandle, 1026 const sp<InputWindowHandle>& windowHandle); 1027 1028 // Manage the dispatch cycle for a single connection. 1029 // These methods are deliberately not Interruptible because doing all of the work 1030 // with the mutex held makes it easier to ensure that connection invariants are maintained. 1031 // If needed, the methods post commands to run later once the critical bits are done. 1032 void prepareDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection, 1033 EventEntry* eventEntry, const InputTarget* inputTarget); 1034 void enqueueDispatchEntriesLocked(nsecs_t currentTime, const sp<Connection>& connection, 1035 EventEntry* eventEntry, const InputTarget* inputTarget); 1036 void enqueueDispatchEntryLocked(const sp<Connection>& connection, 1037 EventEntry* eventEntry, const InputTarget* inputTarget, int32_t dispatchMode); 1038 void startDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection); 1039 void finishDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection, 1040 uint32_t seq, bool handled); 1041 void abortBrokenDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection, 1042 bool notify); 1043 void drainDispatchQueueLocked(Queue<DispatchEntry>* queue); 1044 void releaseDispatchEntryLocked(DispatchEntry* dispatchEntry); 1045 static int handleReceiveCallback(int fd, int events, void* data); 1046 1047 void synthesizeCancelationEventsForAllConnectionsLocked( 1048 const CancelationOptions& options); 1049 void synthesizeCancelationEventsForInputChannelLocked(const sp<InputChannel>& channel, 1050 const CancelationOptions& options); 1051 void synthesizeCancelationEventsForConnectionLocked(const sp<Connection>& connection, 1052 const CancelationOptions& options); 1053 1054 // Splitting motion events across windows. 1055 MotionEntry* splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds); 1056 1057 // Reset and drop everything the dispatcher is doing. 1058 void resetAndDropEverythingLocked(const char* reason); 1059 1060 // Dump state. 1061 void dumpDispatchStateLocked(String8& dump); 1062 void logDispatchStateLocked(); 1063 1064 // Registration. 1065 void removeMonitorChannelLocked(const sp<InputChannel>& inputChannel); 1066 status_t unregisterInputChannelLocked(const sp<InputChannel>& inputChannel, bool notify); 1067 1068 // Add or remove a connection to the mActiveConnections vector. 1069 void activateConnectionLocked(Connection* connection); 1070 void deactivateConnectionLocked(Connection* connection); 1071 1072 // Interesting events that we might like to log or tell the framework about. 1073 void onDispatchCycleFinishedLocked( 1074 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled); 1075 void onDispatchCycleBrokenLocked( 1076 nsecs_t currentTime, const sp<Connection>& connection); 1077 void onANRLocked( 1078 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle, 1079 const sp<InputWindowHandle>& windowHandle, 1080 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason); 1081 1082 // Outbound policy interactions. 1083 void doNotifyConfigurationChangedInterruptible(CommandEntry* commandEntry); 1084 void doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry); 1085 void doNotifyANRLockedInterruptible(CommandEntry* commandEntry); 1086 void doInterceptKeyBeforeDispatchingLockedInterruptible(CommandEntry* commandEntry); 1087 void doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry); 1088 bool afterKeyEventLockedInterruptible(const sp<Connection>& connection, 1089 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled); 1090 bool afterMotionEventLockedInterruptible(const sp<Connection>& connection, 1091 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled); 1092 void doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry); 1093 void initializeKeyEvent(KeyEvent* event, const KeyEntry* entry); 1094 1095 // Statistics gathering. 1096 void updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry, 1097 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication); 1098 void traceInboundQueueLengthLocked(); 1099 void traceOutboundQueueLengthLocked(const sp<Connection>& connection); 1100 void traceWaitQueueLengthLocked(const sp<Connection>& connection); 1101 }; 1102 1103 /* Enqueues and dispatches input events, endlessly. */ 1104 class InputDispatcherThread : public Thread { 1105 public: 1106 explicit InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher); 1107 ~InputDispatcherThread(); 1108 1109 private: 1110 virtual bool threadLoop(); 1111 1112 sp<InputDispatcherInterface> mDispatcher; 1113 }; 1114 1115 } // namespace android 1116 1117 #endif // _UI_INPUT_DISPATCHER_H 1118