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