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