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