2 * Copyright (C) 2010 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #ifndef _UI_INPUT_DISPATCHER_H
18 #define _UI_INPUT_DISPATCHER_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>
40 * Constants used to report the outcome of input event injection.
43 /* (INTERNAL USE ONLY) Specifies that injection is pending and its outcome is unknown. */
44 INPUT_EVENT_INJECTION_PENDING = -1,
46 /* Injection succeeded. */
47 INPUT_EVENT_INJECTION_SUCCEEDED = 0,
49 /* Injection failed because the injector did not have permission to inject
50 * into the application with input focus. */
51 INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1,
53 /* Injection failed because there were no available input targets. */
54 INPUT_EVENT_INJECTION_FAILED = 2,
56 /* Injection failed due to a timeout. */
57 INPUT_EVENT_INJECTION_TIMED_OUT = 3
61 * Constants used to determine the input event injection synchronization mode.
64 /* Injection is asynchronous and is assumed always to be successful. */
65 INPUT_EVENT_INJECTION_SYNC_NONE = 0,
67 /* Waits for previous events to be dispatched so that the input dispatcher can determine
68 * whether input event injection willbe permitted based on the current input focus.
69 * Does not wait for the input event to finish processing. */
70 INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_RESULT = 1,
72 /* Waits for the input event to be completely processed. */
73 INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED = 2,
78 * An input target specifies how an input event is to be dispatched to a particular window
79 * including the window's input channel, control flags, a timeout, and an X / Y offset to
80 * be added to input event coordinates to compensate for the absolute position of the
85 /* This flag indicates that the event is being delivered to a foreground application. */
86 FLAG_FOREGROUND = 0x01,
88 /* This flag indicates that a MotionEvent with AMOTION_EVENT_ACTION_DOWN falls outside
89 * of the area of this target and so should instead be delivered as an
90 * AMOTION_EVENT_ACTION_OUTSIDE to this target. */
93 /* This flag indicates that the target of a MotionEvent is partly or wholly
94 * obscured by another visible window above it. The motion event should be
95 * delivered with flag AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED. */
96 FLAG_WINDOW_IS_OBSCURED = 0x04,
98 /* This flag indicates that a motion event is being split across multiple windows. */
102 // The input channel to be targeted.
103 sp<InputChannel> inputChannel;
105 // Flags for the input target.
108 // The x and y offset to add to a MotionEvent as it is delivered.
109 // (ignored for KeyEvents)
110 float xOffset, yOffset;
112 // The subset of pointer ids to include in motion events dispatched to this input target
113 // if FLAG_SPLIT is set.
119 * An input window describes the bounds of a window that can receive input.
122 // Window flags from WindowManager.LayoutParams
124 FLAG_ALLOW_LOCK_WHILE_SCREEN_ON = 0x00000001,
125 FLAG_DIM_BEHIND = 0x00000002,
126 FLAG_BLUR_BEHIND = 0x00000004,
127 FLAG_NOT_FOCUSABLE = 0x00000008,
128 FLAG_NOT_TOUCHABLE = 0x00000010,
129 FLAG_NOT_TOUCH_MODAL = 0x00000020,
130 FLAG_TOUCHABLE_WHEN_WAKING = 0x00000040,
131 FLAG_KEEP_SCREEN_ON = 0x00000080,
132 FLAG_LAYOUT_IN_SCREEN = 0x00000100,
133 FLAG_LAYOUT_NO_LIMITS = 0x00000200,
134 FLAG_FULLSCREEN = 0x00000400,
135 FLAG_FORCE_NOT_FULLSCREEN = 0x00000800,
136 FLAG_DITHER = 0x00001000,
137 FLAG_SECURE = 0x00002000,
138 FLAG_SCALED = 0x00004000,
139 FLAG_IGNORE_CHEEK_PRESSES = 0x00008000,
140 FLAG_LAYOUT_INSET_DECOR = 0x00010000,
141 FLAG_ALT_FOCUSABLE_IM = 0x00020000,
142 FLAG_WATCH_OUTSIDE_TOUCH = 0x00040000,
143 FLAG_SHOW_WHEN_LOCKED = 0x00080000,
144 FLAG_SHOW_WALLPAPER = 0x00100000,
145 FLAG_TURN_SCREEN_ON = 0x00200000,
146 FLAG_DISMISS_KEYGUARD = 0x00400000,
147 FLAG_SPLIT_TOUCH = 0x00800000,
148 FLAG_KEEP_SURFACE_WHILE_ANIMATING = 0x10000000,
149 FLAG_COMPATIBLE_WINDOW = 0x20000000,
150 FLAG_SYSTEM_ERROR = 0x40000000,
153 // Window types from WindowManager.LayoutParams
155 FIRST_APPLICATION_WINDOW = 1,
156 TYPE_BASE_APPLICATION = 1,
157 TYPE_APPLICATION = 2,
158 TYPE_APPLICATION_STARTING = 3,
159 LAST_APPLICATION_WINDOW = 99,
160 FIRST_SUB_WINDOW = 1000,
161 TYPE_APPLICATION_PANEL = FIRST_SUB_WINDOW,
162 TYPE_APPLICATION_MEDIA = FIRST_SUB_WINDOW+1,
163 TYPE_APPLICATION_SUB_PANEL = FIRST_SUB_WINDOW+2,
164 TYPE_APPLICATION_ATTACHED_DIALOG = FIRST_SUB_WINDOW+3,
165 TYPE_APPLICATION_MEDIA_OVERLAY = FIRST_SUB_WINDOW+4,
166 LAST_SUB_WINDOW = 1999,
167 FIRST_SYSTEM_WINDOW = 2000,
168 TYPE_STATUS_BAR = FIRST_SYSTEM_WINDOW,
169 TYPE_SEARCH_BAR = FIRST_SYSTEM_WINDOW+1,
170 TYPE_PHONE = FIRST_SYSTEM_WINDOW+2,
171 TYPE_SYSTEM_ALERT = FIRST_SYSTEM_WINDOW+3,
172 TYPE_KEYGUARD = FIRST_SYSTEM_WINDOW+4,
173 TYPE_TOAST = FIRST_SYSTEM_WINDOW+5,
174 TYPE_SYSTEM_OVERLAY = FIRST_SYSTEM_WINDOW+6,
175 TYPE_PRIORITY_PHONE = FIRST_SYSTEM_WINDOW+7,
176 TYPE_SYSTEM_DIALOG = FIRST_SYSTEM_WINDOW+8,
177 TYPE_KEYGUARD_DIALOG = FIRST_SYSTEM_WINDOW+9,
178 TYPE_SYSTEM_ERROR = FIRST_SYSTEM_WINDOW+10,
179 TYPE_INPUT_METHOD = FIRST_SYSTEM_WINDOW+11,
180 TYPE_INPUT_METHOD_DIALOG= FIRST_SYSTEM_WINDOW+12,
181 TYPE_WALLPAPER = FIRST_SYSTEM_WINDOW+13,
182 TYPE_STATUS_BAR_PANEL = FIRST_SYSTEM_WINDOW+14,
183 TYPE_SECURE_SYSTEM_OVERLAY = FIRST_SYSTEM_WINDOW+15,
184 LAST_SYSTEM_WINDOW = 2999,
187 sp<InputChannel> inputChannel;
189 int32_t layoutParamsFlags;
190 int32_t layoutParamsType;
191 nsecs_t dispatchingTimeout;
196 int32_t visibleFrameLeft;
197 int32_t visibleFrameTop;
198 int32_t visibleFrameRight;
199 int32_t visibleFrameBottom;
200 int32_t touchableAreaLeft;
201 int32_t touchableAreaTop;
202 int32_t touchableAreaRight;
203 int32_t touchableAreaBottom;
213 bool touchableAreaContainsPoint(int32_t x, int32_t y) const;
214 bool frameContainsPoint(int32_t x, int32_t y) const;
216 /* Returns true if the window is of a trusted type that is allowed to silently
217 * overlay other windows for the purpose of implementing the secure views feature.
218 * Trusted overlays, such as IME windows, can partly obscure other windows without causing
219 * motion events to be delivered to them with AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED.
221 bool isTrustedOverlay() const;
226 * A private handle type used by the input manager to track the window.
228 class InputApplicationHandle : public RefBase {
230 InputApplicationHandle() { }
231 virtual ~InputApplicationHandle() { }
236 * An input application describes properties of an application that can receive input.
238 struct InputApplication {
240 nsecs_t dispatchingTimeout;
241 sp<InputApplicationHandle> handle;
246 * Input dispatcher policy interface.
248 * The input reader policy is used by the input reader to interact with the Window Manager
249 * and other system components.
251 * The actual implementation is partially supported by callbacks into the DVM
252 * via JNI. This interface is also mocked in the unit tests.
254 class InputDispatcherPolicyInterface : public virtual RefBase {
256 InputDispatcherPolicyInterface() { }
257 virtual ~InputDispatcherPolicyInterface() { }
260 /* Notifies the system that a configuration change has occurred. */
261 virtual void notifyConfigurationChanged(nsecs_t when) = 0;
263 /* Notifies the system that an application is not responding.
264 * Returns a new timeout to continue waiting, or 0 to abort dispatch. */
265 virtual nsecs_t notifyANR(const sp<InputApplicationHandle>& inputApplicationHandle,
266 const sp<InputChannel>& inputChannel) = 0;
268 /* Notifies the system that an input channel is unrecoverably broken. */
269 virtual void notifyInputChannelBroken(const sp<InputChannel>& inputChannel) = 0;
271 /* Gets the key repeat initial timeout or -1 if automatic key repeating is disabled. */
272 virtual nsecs_t getKeyRepeatTimeout() = 0;
274 /* Gets the key repeat inter-key delay. */
275 virtual nsecs_t getKeyRepeatDelay() = 0;
277 /* Gets the maximum suggested event delivery rate per second.
278 * This value is used to throttle motion event movement actions on a per-device
279 * basis. It is not intended to be a hard limit.
281 virtual int32_t getMaxEventsPerSecond() = 0;
283 /* Intercepts a key event immediately before queueing it.
284 * The policy can use this method as an opportunity to perform power management functions
285 * and early event preprocessing such as updating policy flags.
287 * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
288 * should be dispatched to applications.
290 virtual void interceptKeyBeforeQueueing(nsecs_t when, int32_t deviceId,
291 int32_t action, int32_t& flags, int32_t keyCode, int32_t scanCode,
292 uint32_t& policyFlags) = 0;
294 /* Intercepts a generic touch, trackball or other event before queueing it.
295 * The policy can use this method as an opportunity to perform power management functions
296 * and early event preprocessing such as updating policy flags.
298 * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
299 * should be dispatched to applications.
301 virtual void interceptGenericBeforeQueueing(nsecs_t when, uint32_t& policyFlags) = 0;
303 /* Allows the policy a chance to intercept a key before dispatching. */
304 virtual bool interceptKeyBeforeDispatching(const sp<InputChannel>& inputChannel,
305 const KeyEvent* keyEvent, uint32_t policyFlags) = 0;
307 /* Notifies the policy about switch events.
309 virtual void notifySwitch(nsecs_t when,
310 int32_t switchCode, int32_t switchValue, uint32_t policyFlags) = 0;
312 /* Poke user activity for an event dispatched to a window. */
313 virtual void pokeUserActivity(nsecs_t eventTime, int32_t eventType) = 0;
315 /* Checks whether a given application pid/uid has permission to inject input events
316 * into other applications.
318 * This method is special in that its implementation promises to be non-reentrant and
319 * is safe to call while holding other locks. (Most other methods make no such guarantees!)
321 virtual bool checkInjectEventsPermissionNonReentrant(
322 int32_t injectorPid, int32_t injectorUid) = 0;
326 /* Notifies the system about input events generated by the input reader.
327 * The dispatcher is expected to be mostly asynchronous. */
328 class InputDispatcherInterface : public virtual RefBase {
330 InputDispatcherInterface() { }
331 virtual ~InputDispatcherInterface() { }
334 /* Dumps the state of the input dispatcher.
336 * This method may be called on any thread (usually by the input manager). */
337 virtual void dump(String8& dump) = 0;
339 /* Runs a single iteration of the dispatch loop.
340 * Nominally processes one queued event, a timeout, or a response from an input consumer.
342 * This method should only be called on the input dispatcher thread.
344 virtual void dispatchOnce() = 0;
346 /* Notifies the dispatcher about new events.
348 * These methods should only be called on the input reader thread.
350 virtual void notifyConfigurationChanged(nsecs_t eventTime) = 0;
351 virtual void notifyKey(nsecs_t eventTime, int32_t deviceId, int32_t source,
352 uint32_t policyFlags, int32_t action, int32_t flags, int32_t keyCode,
353 int32_t scanCode, int32_t metaState, nsecs_t downTime) = 0;
354 virtual void notifyMotion(nsecs_t eventTime, int32_t deviceId, int32_t source,
355 uint32_t policyFlags, int32_t action, int32_t flags,
356 int32_t metaState, int32_t edgeFlags,
357 uint32_t pointerCount, const int32_t* pointerIds, const PointerCoords* pointerCoords,
358 float xPrecision, float yPrecision, nsecs_t downTime) = 0;
359 virtual void notifySwitch(nsecs_t when,
360 int32_t switchCode, int32_t switchValue, uint32_t policyFlags) = 0;
362 /* Injects an input event and optionally waits for sync.
363 * The synchronization mode determines whether the method blocks while waiting for
364 * input injection to proceed.
365 * Returns one of the INPUT_EVENT_INJECTION_XXX constants.
367 * This method may be called on any thread (usually by the input manager).
369 virtual int32_t injectInputEvent(const InputEvent* event,
370 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis) = 0;
372 /* Sets the list of input windows.
374 * This method may be called on any thread (usually by the input manager).
376 virtual void setInputWindows(const Vector<InputWindow>& inputWindows) = 0;
378 /* Sets the focused application.
380 * This method may be called on any thread (usually by the input manager).
382 virtual void setFocusedApplication(const InputApplication* inputApplication) = 0;
384 /* Sets the input dispatching mode.
386 * This method may be called on any thread (usually by the input manager).
388 virtual void setInputDispatchMode(bool enabled, bool frozen) = 0;
390 /* Registers or unregister input channels that may be used as targets for input events.
391 * If monitor is true, the channel will receive a copy of all input events.
393 * These methods may be called on any thread (usually by the input manager).
395 virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel, bool monitor) = 0;
396 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel) = 0;
399 /* Dispatches events to input targets. Some functions of the input dispatcher, such as
400 * identifying input targets, are controlled by a separate policy object.
402 * IMPORTANT INVARIANT:
403 * Because the policy can potentially block or cause re-entrance into the input dispatcher,
404 * the input dispatcher never calls into the policy while holding its internal locks.
405 * The implementation is also carefully designed to recover from scenarios such as an
406 * input channel becoming unregistered while identifying input targets or processing timeouts.
408 * Methods marked 'Locked' must be called with the lock acquired.
410 * Methods marked 'LockedInterruptible' must be called with the lock acquired but
411 * may during the course of their execution release the lock, call into the policy, and
412 * then reacquire the lock. The caller is responsible for recovering gracefully.
414 * A 'LockedInterruptible' method may called a 'Locked' method, but NOT vice-versa.
416 class InputDispatcher : public InputDispatcherInterface {
418 virtual ~InputDispatcher();
421 explicit InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy);
423 virtual void dump(String8& dump);
425 virtual void dispatchOnce();
427 virtual void notifyConfigurationChanged(nsecs_t eventTime);
428 virtual void notifyKey(nsecs_t eventTime, int32_t deviceId, int32_t source,
429 uint32_t policyFlags, int32_t action, int32_t flags, int32_t keyCode,
430 int32_t scanCode, int32_t metaState, nsecs_t downTime);
431 virtual void notifyMotion(nsecs_t eventTime, int32_t deviceId, int32_t source,
432 uint32_t policyFlags, int32_t action, int32_t flags,
433 int32_t metaState, int32_t edgeFlags,
434 uint32_t pointerCount, const int32_t* pointerIds, const PointerCoords* pointerCoords,
435 float xPrecision, float yPrecision, nsecs_t downTime);
436 virtual void notifySwitch(nsecs_t when,
437 int32_t switchCode, int32_t switchValue, uint32_t policyFlags) ;
439 virtual int32_t injectInputEvent(const InputEvent* event,
440 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis);
442 virtual void setInputWindows(const Vector<InputWindow>& inputWindows);
443 virtual void setFocusedApplication(const InputApplication* inputApplication);
444 virtual void setInputDispatchMode(bool enabled, bool frozen);
446 virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel, bool monitor);
447 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel);
450 template <typename T>
456 struct InjectionState {
457 mutable int32_t refCount;
461 int32_t injectionResult; // initially INPUT_EVENT_INJECTION_PENDING
462 bool injectionIsAsync; // set to true if injection is not waiting for the result
463 int32_t pendingForegroundDispatches; // the number of foreground dispatches in progress
466 struct EventEntry : Link<EventEntry> {
469 TYPE_CONFIGURATION_CHANGED,
474 mutable int32_t refCount;
477 uint32_t policyFlags;
478 InjectionState* injectionState;
480 bool dispatchInProgress; // initially false, set to true while dispatching
482 inline bool isInjected() { return injectionState != NULL; }
485 struct ConfigurationChangedEntry : EventEntry {
488 struct KeyEntry : EventEntry {
499 bool syntheticRepeat; // set to true for synthetic key repeats
501 enum InterceptKeyResult {
502 INTERCEPT_KEY_RESULT_UNKNOWN,
503 INTERCEPT_KEY_RESULT_SKIP,
504 INTERCEPT_KEY_RESULT_CONTINUE,
506 InterceptKeyResult interceptKeyResult; // set based on the interception result
509 struct MotionSample {
513 PointerCoords pointerCoords[MAX_POINTERS];
516 struct MotionEntry : EventEntry {
526 uint32_t pointerCount;
527 int32_t pointerIds[MAX_POINTERS];
529 // Linked list of motion samples associated with this motion event.
530 MotionSample firstSample;
531 MotionSample* lastSample;
533 uint32_t countSamples() const;
536 // Tracks the progress of dispatching a particular event to a particular connection.
537 struct DispatchEntry : Link<DispatchEntry> {
538 EventEntry* eventEntry; // the event to dispatch
543 // True if dispatch has started.
546 // For motion events:
547 // Pointer to the first motion sample to dispatch in this cycle.
548 // Usually NULL to indicate that the list of motion samples begins at
549 // MotionEntry::firstSample. Otherwise, some samples were dispatched in a previous
550 // cycle and this pointer indicates the location of the first remainining sample
551 // to dispatch during the current cycle.
552 MotionSample* headMotionSample;
553 // Pointer to a motion sample to dispatch in the next cycle if the dispatcher was
554 // unable to send all motion samples during this cycle. On the next cycle,
555 // headMotionSample will be initialized to tailMotionSample and tailMotionSample
556 // will be set to NULL.
557 MotionSample* tailMotionSample;
559 inline bool hasForegroundTarget() const {
560 return targetFlags & InputTarget::FLAG_FOREGROUND;
563 inline bool isSplit() const {
564 return targetFlags & InputTarget::FLAG_SPLIT;
568 // A command entry captures state and behavior for an action to be performed in the
569 // dispatch loop after the initial processing has taken place. It is essentially
570 // a kind of continuation used to postpone sensitive policy interactions to a point
571 // in the dispatch loop where it is safe to release the lock (generally after finishing
572 // the critical parts of the dispatch cycle).
574 // The special thing about commands is that they can voluntarily release and reacquire
575 // the dispatcher lock at will. Initially when the command starts running, the
576 // dispatcher lock is held. However, if the command needs to call into the policy to
577 // do some work, it can release the lock, do the work, then reacquire the lock again
580 // This mechanism is a bit clunky but it helps to preserve the invariant that the dispatch
581 // never calls into the policy while holding its lock.
583 // Commands are implicitly 'LockedInterruptible'.
585 typedef void (InputDispatcher::*Command)(CommandEntry* commandEntry);
588 struct CommandEntry : Link<CommandEntry> {
594 // parameters for the command (usage varies by command)
595 sp<Connection> connection;
598 sp<InputChannel> inputChannel;
599 sp<InputApplicationHandle> inputApplicationHandle;
600 int32_t userActivityEventType;
603 // Generic queue implementation.
604 template <typename T>
610 headSentinel.prev = NULL;
611 headSentinel.next = & tailSentinel;
612 tailSentinel.prev = & headSentinel;
613 tailSentinel.next = NULL;
616 inline bool isEmpty() const {
617 return headSentinel.next == & tailSentinel;
620 inline void enqueueAtTail(T* entry) {
621 T* last = tailSentinel.prev;
624 entry->next = & tailSentinel;
625 tailSentinel.prev = entry;
628 inline void enqueueAtHead(T* entry) {
629 T* first = headSentinel.next;
630 headSentinel.next = entry;
631 entry->prev = & headSentinel;
636 inline void dequeue(T* entry) {
637 entry->prev->next = entry->next;
638 entry->next->prev = entry->prev;
641 inline T* dequeueAtHead() {
642 T* first = headSentinel.next;
647 uint32_t count() const;
650 /* Allocates queue entries and performs reference counting as needed. */
655 InjectionState* obtainInjectionState(int32_t injectorPid, int32_t injectorUid);
656 ConfigurationChangedEntry* obtainConfigurationChangedEntry(nsecs_t eventTime);
657 KeyEntry* obtainKeyEntry(nsecs_t eventTime,
658 int32_t deviceId, int32_t source, uint32_t policyFlags, int32_t action,
659 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
660 int32_t repeatCount, nsecs_t downTime);
661 MotionEntry* obtainMotionEntry(nsecs_t eventTime,
662 int32_t deviceId, int32_t source, uint32_t policyFlags, int32_t action,
663 int32_t flags, int32_t metaState, int32_t edgeFlags,
664 float xPrecision, float yPrecision,
665 nsecs_t downTime, uint32_t pointerCount,
666 const int32_t* pointerIds, const PointerCoords* pointerCoords);
667 DispatchEntry* obtainDispatchEntry(EventEntry* eventEntry,
668 int32_t targetFlags, float xOffset, float yOffset);
669 CommandEntry* obtainCommandEntry(Command command);
671 void releaseInjectionState(InjectionState* injectionState);
672 void releaseEventEntry(EventEntry* entry);
673 void releaseConfigurationChangedEntry(ConfigurationChangedEntry* entry);
674 void releaseKeyEntry(KeyEntry* entry);
675 void releaseMotionEntry(MotionEntry* entry);
676 void releaseDispatchEntry(DispatchEntry* entry);
677 void releaseCommandEntry(CommandEntry* entry);
679 void recycleKeyEntry(KeyEntry* entry);
681 void appendMotionSample(MotionEntry* motionEntry,
682 nsecs_t eventTime, const PointerCoords* pointerCoords);
685 Pool<InjectionState> mInjectionStatePool;
686 Pool<ConfigurationChangedEntry> mConfigurationChangeEntryPool;
687 Pool<KeyEntry> mKeyEntryPool;
688 Pool<MotionEntry> mMotionEntryPool;
689 Pool<MotionSample> mMotionSamplePool;
690 Pool<DispatchEntry> mDispatchEntryPool;
691 Pool<CommandEntry> mCommandEntryPool;
693 void initializeEventEntry(EventEntry* entry, int32_t type, nsecs_t eventTime,
694 uint32_t policyFlags);
695 void releaseEventEntryInjectionState(EventEntry* entry);
698 /* Tracks dispatched key and motion event state so that cancelation events can be
699 * synthesized when events are dropped. */
702 // Specifies whether a given event will violate input state consistency.
704 // The event is consistent with the current input state.
706 // The event is inconsistent with the current input state but applications
707 // will tolerate it. eg. Down followed by another down.
709 // The event is inconsistent with the current input state and will probably
710 // cause applications to crash. eg. Up without prior down, move with
711 // unexpected number of pointers.
715 // Specifies the sources to cancel.
716 enum CancelationOptions {
717 CANCEL_ALL_EVENTS = 0,
718 CANCEL_POINTER_EVENTS = 1,
719 CANCEL_NON_POINTER_EVENTS = 2,
725 // Returns true if there is no state to be canceled.
726 bool isNeutral() const;
728 // Records tracking information for an event that has just been published.
729 // Returns whether the event is consistent with the current input state.
730 Consistency trackEvent(const EventEntry* entry);
732 // Records tracking information for a key event that has just been published.
733 // Returns whether the event is consistent with the current input state.
734 Consistency trackKey(const KeyEntry* entry);
736 // Records tracking information for a motion event that has just been published.
737 // Returns whether the event is consistent with the current input state.
738 Consistency trackMotion(const MotionEntry* entry);
740 // Synthesizes cancelation events for the current state and resets the tracked state.
741 void synthesizeCancelationEvents(nsecs_t currentTime, Allocator* allocator,
742 Vector<EventEntry*>& outEvents, CancelationOptions options);
744 // Clears the current state.
756 struct MotionMemento {
762 uint32_t pointerCount;
763 int32_t pointerIds[MAX_POINTERS];
764 PointerCoords pointerCoords[MAX_POINTERS];
766 void setPointers(const MotionEntry* entry);
769 Vector<KeyMemento> mKeyMementos;
770 Vector<MotionMemento> mMotionMementos;
772 static bool shouldCancelEvent(int32_t eventSource, CancelationOptions options);
775 /* Manages the dispatch state associated with a single input channel. */
776 class Connection : public RefBase {
778 virtual ~Connection();
782 // Everything is peachy.
784 // An unrecoverable communication error has occurred.
786 // The input channel has been unregistered.
791 sp<InputChannel> inputChannel;
792 InputPublisher inputPublisher;
793 InputState inputState;
794 Queue<DispatchEntry> outboundQueue;
796 nsecs_t lastEventTime; // the time when the event was originally captured
797 nsecs_t lastDispatchTime; // the time when the last event was dispatched
799 explicit Connection(const sp<InputChannel>& inputChannel);
801 inline const char* getInputChannelName() const { return inputChannel->getName().string(); }
803 const char* getStatusLabel() const;
805 // Finds a DispatchEntry in the outbound queue associated with the specified event.
806 // Returns NULL if not found.
807 DispatchEntry* findQueuedDispatchEntryForEvent(const EventEntry* eventEntry) const;
809 // Gets the time since the current event was originally obtained from the input driver.
810 inline double getEventLatencyMillis(nsecs_t currentTime) const {
811 return (currentTime - lastEventTime) / 1000000.0;
814 // Gets the time since the current event entered the outbound dispatch queue.
815 inline double getDispatchLatencyMillis(nsecs_t currentTime) const {
816 return (currentTime - lastDispatchTime) / 1000000.0;
819 status_t initialize();
823 DROP_REASON_NOT_DROPPED = 0,
824 DROP_REASON_POLICY = 1,
825 DROP_REASON_APP_SWITCH = 2,
826 DROP_REASON_DISABLED = 3,
829 sp<InputDispatcherPolicyInterface> mPolicy;
833 Allocator mAllocator;
836 EventEntry* mPendingEvent;
837 Queue<EventEntry> mInboundQueue;
838 Queue<CommandEntry> mCommandQueue;
840 Vector<EventEntry*> mTempCancelationEvents;
842 void dispatchOnceInnerLocked(nsecs_t keyRepeatTimeout, nsecs_t keyRepeatDelay,
843 nsecs_t* nextWakeupTime);
845 // Enqueues an inbound event. Returns true if mLooper->wake() should be called.
846 bool enqueueInboundEventLocked(EventEntry* entry);
848 // Cleans up input state when dropping an inbound event.
849 void dropInboundEventLocked(EventEntry* entry, DropReason dropReason);
851 // App switch latency optimization.
852 bool mAppSwitchSawKeyDown;
853 nsecs_t mAppSwitchDueTime;
855 static bool isAppSwitchKeyCode(int32_t keyCode);
856 bool isAppSwitchKeyEventLocked(KeyEntry* keyEntry);
857 bool isAppSwitchPendingLocked();
858 void resetPendingAppSwitchLocked(bool handled);
860 // All registered connections mapped by receive pipe file descriptor.
861 KeyedVector<int, sp<Connection> > mConnectionsByReceiveFd;
863 ssize_t getConnectionIndexLocked(const sp<InputChannel>& inputChannel);
865 // Active connections are connections that have a non-empty outbound queue.
866 // We don't use a ref-counted pointer here because we explicitly abort connections
867 // during unregistration which causes the connection's outbound queue to be cleared
868 // and the connection itself to be deactivated.
869 Vector<Connection*> mActiveConnections;
871 // Input channels that will receive a copy of all input events.
872 Vector<sp<InputChannel> > mMonitoringChannels;
874 // Preallocated key event object used for policy inquiries.
875 KeyEvent mReusableKeyEvent;
877 // Event injection and synchronization.
878 Condition mInjectionResultAvailableCondition;
879 bool hasInjectionPermission(int32_t injectorPid, int32_t injectorUid);
880 void setInjectionResultLocked(EventEntry* entry, int32_t injectionResult);
882 Condition mInjectionSyncFinishedCondition;
883 void incrementPendingForegroundDispatchesLocked(EventEntry* entry);
884 void decrementPendingForegroundDispatchesLocked(EventEntry* entry);
887 struct ThrottleState {
888 nsecs_t minTimeBetweenEvents;
890 nsecs_t lastEventTime;
891 int32_t lastDeviceId;
894 uint32_t originalSampleCount; // only collected during debugging
897 // Key repeat tracking.
898 struct KeyRepeatState {
899 KeyEntry* lastKeyEntry; // or null if no repeat
900 nsecs_t nextRepeatTime;
903 void resetKeyRepeatLocked();
904 KeyEntry* synthesizeKeyRepeatLocked(nsecs_t currentTime, nsecs_t keyRepeatTimeout);
906 // Deferred command processing.
907 bool runCommandsLockedInterruptible();
908 CommandEntry* postCommandLocked(Command command);
910 // Inbound event processing.
911 void drainInboundQueueLocked();
912 void releasePendingEventLocked();
913 void releaseInboundEventLocked(EventEntry* entry);
916 bool mDispatchEnabled;
917 bool mDispatchFrozen;
919 Vector<InputWindow> mWindows;
921 const InputWindow* getWindowLocked(const sp<InputChannel>& inputChannel);
923 // Focus tracking for keys, trackball, etc.
924 const InputWindow* mFocusedWindow;
926 // Focus tracking for touch.
927 struct TouchedWindow {
928 const InputWindow* window;
931 sp<InputChannel> channel;
936 Vector<TouchedWindow> windows;
941 void copyFrom(const TouchState& other);
942 void addOrUpdateWindow(const InputWindow* window, int32_t targetFlags, BitSet32 pointerIds);
943 void removeOutsideTouchWindows();
944 const InputWindow* getFirstForegroundWindow();
947 TouchState mTouchState;
948 TouchState mTempTouchState;
950 // Focused application.
951 InputApplication* mFocusedApplication;
952 InputApplication mFocusedApplicationStorage; // preallocated storage for mFocusedApplication
953 void releaseFocusedApplicationLocked();
955 // Dispatch inbound events.
956 bool dispatchConfigurationChangedLocked(
957 nsecs_t currentTime, ConfigurationChangedEntry* entry);
958 bool dispatchKeyLocked(
959 nsecs_t currentTime, KeyEntry* entry, nsecs_t keyRepeatTimeout,
960 DropReason* dropReason, nsecs_t* nextWakeupTime);
961 bool dispatchMotionLocked(
962 nsecs_t currentTime, MotionEntry* entry,
963 DropReason* dropReason, nsecs_t* nextWakeupTime);
964 void dispatchEventToCurrentInputTargetsLocked(
965 nsecs_t currentTime, EventEntry* entry, bool resumeWithAppendedMotionSample);
967 void logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry);
968 void logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry);
970 // The input targets that were most recently identified for dispatch.
971 bool mCurrentInputTargetsValid; // false while targets are being recomputed
972 Vector<InputTarget> mCurrentInputTargets;
974 enum InputTargetWaitCause {
975 INPUT_TARGET_WAIT_CAUSE_NONE,
976 INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY,
977 INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY,
980 InputTargetWaitCause mInputTargetWaitCause;
981 nsecs_t mInputTargetWaitStartTime;
982 nsecs_t mInputTargetWaitTimeoutTime;
983 bool mInputTargetWaitTimeoutExpired;
985 // Finding targets for input events.
986 void resetTargetsLocked();
987 void commitTargetsLocked();
988 int32_t handleTargetsNotReadyLocked(nsecs_t currentTime, const EventEntry* entry,
989 const InputApplication* application, const InputWindow* window,
990 nsecs_t* nextWakeupTime);
991 void resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
992 const sp<InputChannel>& inputChannel);
993 nsecs_t getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime);
994 void resetANRTimeoutsLocked();
996 int32_t findFocusedWindowTargetsLocked(nsecs_t currentTime, const EventEntry* entry,
997 nsecs_t* nextWakeupTime);
998 int32_t findTouchedWindowTargetsLocked(nsecs_t currentTime, const MotionEntry* entry,
999 nsecs_t* nextWakeupTime);
1001 void addWindowTargetLocked(const InputWindow* window, int32_t targetFlags,
1002 BitSet32 pointerIds);
1003 void addMonitoringTargetsLocked();
1004 void pokeUserActivityLocked(const EventEntry* eventEntry);
1005 bool checkInjectionPermission(const InputWindow* window, const InjectionState* injectionState);
1006 bool isWindowObscuredAtPointLocked(const InputWindow* window, int32_t x, int32_t y) const;
1007 bool isWindowFinishedWithPreviousInputLocked(const InputWindow* window);
1008 String8 getApplicationWindowLabelLocked(const InputApplication* application,
1009 const InputWindow* window);
1011 // Manage the dispatch cycle for a single connection.
1012 // These methods are deliberately not Interruptible because doing all of the work
1013 // with the mutex held makes it easier to ensure that connection invariants are maintained.
1014 // If needed, the methods post commands to run later once the critical bits are done.
1015 void prepareDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1016 EventEntry* eventEntry, const InputTarget* inputTarget,
1017 bool resumeWithAppendedMotionSample);
1018 void startDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
1019 void finishDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
1020 void startNextDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
1021 void abortBrokenDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
1022 void drainOutboundQueueLocked(Connection* connection);
1023 static int handleReceiveCallback(int receiveFd, int events, void* data);
1025 void synthesizeCancelationEventsForAllConnectionsLocked(
1026 InputState::CancelationOptions options, const char* reason);
1027 void synthesizeCancelationEventsForInputChannelLocked(const sp<InputChannel>& channel,
1028 InputState::CancelationOptions options, const char* reason);
1029 void synthesizeCancelationEventsForConnectionLocked(const sp<Connection>& connection,
1030 InputState::CancelationOptions options, const char* reason);
1032 // Splitting motion events across windows.
1033 MotionEntry* splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds);
1035 // Reset and drop everything the dispatcher is doing.
1036 void resetAndDropEverythingLocked(const char* reason);
1039 void dumpDispatchStateLocked(String8& dump);
1040 void logDispatchStateLocked();
1042 // Add or remove a connection to the mActiveConnections vector.
1043 void activateConnectionLocked(Connection* connection);
1044 void deactivateConnectionLocked(Connection* connection);
1046 // Interesting events that we might like to log or tell the framework about.
1047 void onDispatchCycleStartedLocked(
1048 nsecs_t currentTime, const sp<Connection>& connection);
1049 void onDispatchCycleFinishedLocked(
1050 nsecs_t currentTime, const sp<Connection>& connection);
1051 void onDispatchCycleBrokenLocked(
1052 nsecs_t currentTime, const sp<Connection>& connection);
1054 nsecs_t currentTime, const InputApplication* application, const InputWindow* window,
1055 nsecs_t eventTime, nsecs_t waitStartTime);
1057 // Outbound policy interactions.
1058 void doNotifyConfigurationChangedInterruptible(CommandEntry* commandEntry);
1059 void doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry);
1060 void doNotifyANRLockedInterruptible(CommandEntry* commandEntry);
1061 void doInterceptKeyBeforeDispatchingLockedInterruptible(CommandEntry* commandEntry);
1062 void doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry);
1064 // Statistics gathering.
1065 void updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
1066 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication);
1069 /* Enqueues and dispatches input events, endlessly. */
1070 class InputDispatcherThread : public Thread {
1072 explicit InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher);
1073 ~InputDispatcherThread();
1076 virtual bool threadLoop();
1078 sp<InputDispatcherInterface> mDispatcher;
1081 } // namespace android
1083 #endif // _UI_INPUT_DISPATCHER_H