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
20 #include <input/Input.h>
21 #include <input/InputTransport.h>
22 #include <utils/KeyedVector.h>
23 #include <utils/Vector.h>
24 #include <utils/threads.h>
25 #include <utils/Timers.h>
26 #include <utils/RefBase.h>
27 #include <utils/String8.h>
28 #include <utils/Looper.h>
29 #include <utils/BitSet.h>
30 #include <cutils/atomic.h>
36 #include "InputWindow.h"
37 #include "InputApplication.h"
38 #include "InputListener.h"
44 * Constants used to report the outcome of input event injection.
47 /* (INTERNAL USE ONLY) Specifies that injection is pending and its outcome is unknown. */
48 INPUT_EVENT_INJECTION_PENDING = -1,
50 /* Injection succeeded. */
51 INPUT_EVENT_INJECTION_SUCCEEDED = 0,
53 /* Injection failed because the injector did not have permission to inject
54 * into the application with input focus. */
55 INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1,
57 /* Injection failed because there were no available input targets. */
58 INPUT_EVENT_INJECTION_FAILED = 2,
60 /* Injection failed due to a timeout. */
61 INPUT_EVENT_INJECTION_TIMED_OUT = 3
65 * Constants used to determine the input event injection synchronization mode.
68 /* Injection is asynchronous and is assumed always to be successful. */
69 INPUT_EVENT_INJECTION_SYNC_NONE = 0,
71 /* Waits for previous events to be dispatched so that the input dispatcher can determine
72 * whether input event injection willbe permitted based on the current input focus.
73 * Does not wait for the input event to finish processing. */
74 INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_RESULT = 1,
76 /* Waits for the input event to be completely processed. */
77 INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED = 2,
82 * An input target specifies how an input event is to be dispatched to a particular window
83 * including the window's input channel, control flags, a timeout, and an X / Y offset to
84 * be added to input event coordinates to compensate for the absolute position of the
89 /* This flag indicates that the event is being delivered to a foreground application. */
90 FLAG_FOREGROUND = 1 << 0,
92 /* This flag indicates that the MotionEvent falls within the area of the target
93 * obscured by another visible window above it. The motion event should be
94 * delivered with flag AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED. */
95 FLAG_WINDOW_IS_OBSCURED = 1 << 1,
97 /* This flag indicates that a motion event is being split across multiple windows. */
100 /* This flag indicates that the pointer coordinates dispatched to the application
101 * will be zeroed out to avoid revealing information to an application. This is
102 * used in conjunction with FLAG_DISPATCH_AS_OUTSIDE to prevent apps not sharing
103 * the same UID from watching all touches. */
104 FLAG_ZERO_COORDS = 1 << 3,
106 /* This flag indicates that the event should be sent as is.
107 * Should always be set unless the event is to be transmuted. */
108 FLAG_DISPATCH_AS_IS = 1 << 8,
110 /* This flag indicates that a MotionEvent with AMOTION_EVENT_ACTION_DOWN falls outside
111 * of the area of this target and so should instead be delivered as an
112 * AMOTION_EVENT_ACTION_OUTSIDE to this target. */
113 FLAG_DISPATCH_AS_OUTSIDE = 1 << 9,
115 /* This flag indicates that a hover sequence is starting in the given window.
116 * The event is transmuted into ACTION_HOVER_ENTER. */
117 FLAG_DISPATCH_AS_HOVER_ENTER = 1 << 10,
119 /* This flag indicates that a hover event happened outside of a window which handled
120 * previous hover events, signifying the end of the current hover sequence for that
122 * The event is transmuted into ACTION_HOVER_ENTER. */
123 FLAG_DISPATCH_AS_HOVER_EXIT = 1 << 11,
125 /* This flag indicates that the event should be canceled.
126 * It is used to transmute ACTION_MOVE into ACTION_CANCEL when a touch slips
127 * outside of a window. */
128 FLAG_DISPATCH_AS_SLIPPERY_EXIT = 1 << 12,
130 /* This flag indicates that the event should be dispatched as an initial down.
131 * It is used to transmute ACTION_MOVE into ACTION_DOWN when a touch slips
132 * into a new window. */
133 FLAG_DISPATCH_AS_SLIPPERY_ENTER = 1 << 13,
135 /* Mask for all dispatch modes. */
136 FLAG_DISPATCH_MASK = FLAG_DISPATCH_AS_IS
137 | FLAG_DISPATCH_AS_OUTSIDE
138 | FLAG_DISPATCH_AS_HOVER_ENTER
139 | FLAG_DISPATCH_AS_HOVER_EXIT
140 | FLAG_DISPATCH_AS_SLIPPERY_EXIT
141 | FLAG_DISPATCH_AS_SLIPPERY_ENTER,
143 /* This flag indicates that the target of a MotionEvent is partly or wholly
144 * obscured by another visible window above it. The motion event should be
145 * delivered with flag AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED. */
146 FLAG_WINDOW_IS_PARTIALLY_OBSCURED = 1 << 14,
150 // The input channel to be targeted.
151 sp<InputChannel> inputChannel;
153 // Flags for the input target.
156 // The x and y offset to add to a MotionEvent as it is delivered.
157 // (ignored for KeyEvents)
158 float xOffset, yOffset;
160 // Scaling factor to apply to MotionEvent as it is delivered.
161 // (ignored for KeyEvents)
164 // The subset of pointer ids to include in motion events dispatched to this input target
165 // if FLAG_SPLIT is set.
171 * Input dispatcher configuration.
173 * Specifies various options that modify the behavior of the input dispatcher.
174 * The values provided here are merely defaults. The actual values will come from ViewConfiguration
175 * and are passed into the dispatcher during initialization.
177 struct InputDispatcherConfiguration {
178 // The key repeat initial timeout.
179 nsecs_t keyRepeatTimeout;
181 // The key repeat inter-key delay.
182 nsecs_t keyRepeatDelay;
184 InputDispatcherConfiguration() :
185 keyRepeatTimeout(500 * 1000000LL),
186 keyRepeatDelay(50 * 1000000LL) { }
191 * Input dispatcher policy interface.
193 * The input reader policy is used by the input reader to interact with the Window Manager
194 * and other system components.
196 * The actual implementation is partially supported by callbacks into the DVM
197 * via JNI. This interface is also mocked in the unit tests.
199 class InputDispatcherPolicyInterface : public virtual RefBase {
201 InputDispatcherPolicyInterface() { }
202 virtual ~InputDispatcherPolicyInterface() { }
205 /* Notifies the system that a configuration change has occurred. */
206 virtual void notifyConfigurationChanged(nsecs_t when) = 0;
208 /* Notifies the system that an application is not responding.
209 * Returns a new timeout to continue waiting, or 0 to abort dispatch. */
210 virtual nsecs_t notifyANR(const sp<InputApplicationHandle>& inputApplicationHandle,
211 const sp<InputWindowHandle>& inputWindowHandle,
212 const String8& reason) = 0;
214 /* Notifies the system that an input channel is unrecoverably broken. */
215 virtual void notifyInputChannelBroken(const sp<InputWindowHandle>& inputWindowHandle) = 0;
217 /* Gets the input dispatcher configuration. */
218 virtual void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) = 0;
220 /* Filters an input event.
221 * Return true to dispatch the event unmodified, false to consume the event.
222 * A filter can also transform and inject events later by passing POLICY_FLAG_FILTERED
223 * to injectInputEvent.
225 virtual bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) = 0;
227 /* Intercepts a key event immediately before queueing it.
228 * The policy can use this method as an opportunity to perform power management functions
229 * and early event preprocessing such as updating policy flags.
231 * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
232 * should be dispatched to applications.
234 virtual void interceptKeyBeforeQueueing(const KeyEvent* keyEvent, uint32_t& policyFlags) = 0;
236 /* Intercepts a touch, trackball or other motion event before queueing it.
237 * The policy can use this method as an opportunity to perform power management functions
238 * and early event preprocessing such as updating policy flags.
240 * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
241 * should be dispatched to applications.
243 virtual void interceptMotionBeforeQueueing(nsecs_t when, uint32_t& policyFlags) = 0;
245 /* Allows the policy a chance to intercept a key before dispatching. */
246 virtual nsecs_t interceptKeyBeforeDispatching(const sp<InputWindowHandle>& inputWindowHandle,
247 const KeyEvent* keyEvent, uint32_t policyFlags) = 0;
249 /* Allows the policy a chance to perform default processing for an unhandled key.
250 * Returns an alternate keycode to redispatch as a fallback, or 0 to give up. */
251 virtual bool dispatchUnhandledKey(const sp<InputWindowHandle>& inputWindowHandle,
252 const KeyEvent* keyEvent, uint32_t policyFlags, KeyEvent* outFallbackKeyEvent) = 0;
254 /* Notifies the policy about switch events.
256 virtual void notifySwitch(nsecs_t when,
257 uint32_t switchValues, uint32_t switchMask, uint32_t policyFlags) = 0;
259 /* Poke user activity for an event dispatched to a window. */
260 virtual void pokeUserActivity(nsecs_t eventTime, int32_t eventType) = 0;
262 /* Checks whether a given application pid/uid has permission to inject input events
263 * into other applications.
265 * This method is special in that its implementation promises to be non-reentrant and
266 * is safe to call while holding other locks. (Most other methods make no such guarantees!)
268 virtual bool checkInjectEventsPermissionNonReentrant(
269 int32_t injectorPid, int32_t injectorUid) = 0;
273 /* Notifies the system about input events generated by the input reader.
274 * The dispatcher is expected to be mostly asynchronous. */
275 class InputDispatcherInterface : public virtual RefBase, public InputListenerInterface {
277 InputDispatcherInterface() { }
278 virtual ~InputDispatcherInterface() { }
281 /* Dumps the state of the input dispatcher.
283 * This method may be called on any thread (usually by the input manager). */
284 virtual void dump(String8& dump) = 0;
286 /* Called by the heatbeat to ensures that the dispatcher has not deadlocked. */
287 virtual void monitor() = 0;
289 /* Runs a single iteration of the dispatch loop.
290 * Nominally processes one queued event, a timeout, or a response from an input consumer.
292 * This method should only be called on the input dispatcher thread.
294 virtual void dispatchOnce() = 0;
296 /* Injects an input event and optionally waits for sync.
297 * The synchronization mode determines whether the method blocks while waiting for
298 * input injection to proceed.
299 * Returns one of the INPUT_EVENT_INJECTION_XXX constants.
301 * This method may be called on any thread (usually by the input manager).
303 virtual int32_t injectInputEvent(const InputEvent* event, int32_t displayId,
304 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
305 uint32_t policyFlags) = 0;
307 /* Sets the list of input windows.
309 * This method may be called on any thread (usually by the input manager).
311 virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) = 0;
313 /* Sets the focused application.
315 * This method may be called on any thread (usually by the input manager).
317 virtual void setFocusedApplication(
318 const sp<InputApplicationHandle>& inputApplicationHandle) = 0;
320 /* Sets the input dispatching mode.
322 * This method may be called on any thread (usually by the input manager).
324 virtual void setInputDispatchMode(bool enabled, bool frozen) = 0;
326 /* Sets whether input event filtering is enabled.
327 * When enabled, incoming input events are sent to the policy's filterInputEvent
328 * method instead of being dispatched. The filter is expected to use
329 * injectInputEvent to inject the events it would like to have dispatched.
330 * It should include POLICY_FLAG_FILTERED in the policy flags during injection.
332 virtual void setInputFilterEnabled(bool enabled) = 0;
334 /* Transfers touch focus from the window associated with one channel to the
335 * window associated with the other channel.
337 * Returns true on success. False if the window did not actually have touch focus.
339 virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel,
340 const sp<InputChannel>& toChannel) = 0;
342 /* Registers or unregister input channels that may be used as targets for input events.
343 * If monitor is true, the channel will receive a copy of all input events.
345 * These methods may be called on any thread (usually by the input manager).
347 virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel,
348 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) = 0;
349 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel) = 0;
352 /* Dispatches events to input targets. Some functions of the input dispatcher, such as
353 * identifying input targets, are controlled by a separate policy object.
355 * IMPORTANT INVARIANT:
356 * Because the policy can potentially block or cause re-entrance into the input dispatcher,
357 * the input dispatcher never calls into the policy while holding its internal locks.
358 * The implementation is also carefully designed to recover from scenarios such as an
359 * input channel becoming unregistered while identifying input targets or processing timeouts.
361 * Methods marked 'Locked' must be called with the lock acquired.
363 * Methods marked 'LockedInterruptible' must be called with the lock acquired but
364 * may during the course of their execution release the lock, call into the policy, and
365 * then reacquire the lock. The caller is responsible for recovering gracefully.
367 * A 'LockedInterruptible' method may called a 'Locked' method, but NOT vice-versa.
369 class InputDispatcher : public InputDispatcherInterface {
371 virtual ~InputDispatcher();
374 explicit InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy);
376 virtual void dump(String8& dump);
377 virtual void monitor();
379 virtual void dispatchOnce();
381 virtual void notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args);
382 virtual void notifyKey(const NotifyKeyArgs* args);
383 virtual void notifyMotion(const NotifyMotionArgs* args);
384 virtual void notifySwitch(const NotifySwitchArgs* args);
385 virtual void notifyDeviceReset(const NotifyDeviceResetArgs* args);
387 virtual int32_t injectInputEvent(const InputEvent* event, int32_t displayId,
388 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
389 uint32_t policyFlags);
391 virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles);
392 virtual void setFocusedApplication(const sp<InputApplicationHandle>& inputApplicationHandle);
393 virtual void setInputDispatchMode(bool enabled, bool frozen);
394 virtual void setInputFilterEnabled(bool enabled);
396 virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel,
397 const sp<InputChannel>& toChannel);
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);
404 template <typename T>
410 inline Link() : next(NULL), prev(NULL) { }
413 struct InjectionState {
414 mutable int32_t refCount;
418 int32_t injectionResult; // initially INPUT_EVENT_INJECTION_PENDING
419 bool injectionIsAsync; // set to true if injection is not waiting for the result
420 int32_t pendingForegroundDispatches; // the number of foreground dispatches in progress
422 InjectionState(int32_t injectorPid, int32_t injectorUid);
429 struct EventEntry : Link<EventEntry> {
431 TYPE_CONFIGURATION_CHANGED,
437 mutable int32_t refCount;
440 uint32_t policyFlags;
441 InjectionState* injectionState;
443 bool dispatchInProgress; // initially false, set to true while dispatching
445 inline bool isInjected() const { return injectionState != NULL; }
449 virtual void appendDescription(String8& msg) const = 0;
452 EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags);
453 virtual ~EventEntry();
454 void releaseInjectionState();
457 struct ConfigurationChangedEntry : EventEntry {
458 ConfigurationChangedEntry(nsecs_t eventTime);
459 virtual void appendDescription(String8& msg) const;
462 virtual ~ConfigurationChangedEntry();
465 struct DeviceResetEntry : EventEntry {
468 DeviceResetEntry(nsecs_t eventTime, int32_t deviceId);
469 virtual void appendDescription(String8& msg) const;
472 virtual ~DeviceResetEntry();
475 struct KeyEntry : EventEntry {
486 bool syntheticRepeat; // set to true for synthetic key repeats
488 enum InterceptKeyResult {
489 INTERCEPT_KEY_RESULT_UNKNOWN,
490 INTERCEPT_KEY_RESULT_SKIP,
491 INTERCEPT_KEY_RESULT_CONTINUE,
492 INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER,
494 InterceptKeyResult interceptKeyResult; // set based on the interception result
495 nsecs_t interceptKeyWakeupTime; // used with INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER
497 KeyEntry(nsecs_t eventTime,
498 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
499 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
500 int32_t repeatCount, nsecs_t downTime);
501 virtual void appendDescription(String8& msg) const;
508 struct MotionEntry : EventEntry {
513 int32_t actionButton;
522 uint32_t pointerCount;
523 PointerProperties pointerProperties[MAX_POINTERS];
524 PointerCoords pointerCoords[MAX_POINTERS];
526 MotionEntry(nsecs_t eventTime,
527 int32_t deviceId, uint32_t source, uint32_t policyFlags,
528 int32_t action, int32_t actionButton, int32_t flags,
529 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
530 float xPrecision, float yPrecision, nsecs_t downTime,
531 int32_t displayId, uint32_t pointerCount,
532 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
533 float xOffset, float yOffset);
534 virtual void appendDescription(String8& msg) const;
537 virtual ~MotionEntry();
540 // Tracks the progress of dispatching a particular event to a particular connection.
541 struct DispatchEntry : Link<DispatchEntry> {
542 const uint32_t seq; // unique sequence number, never 0
544 EventEntry* eventEntry; // the event to dispatch
549 nsecs_t deliveryTime; // time when the event was actually delivered
551 // Set to the resolved action and flags when the event is enqueued.
552 int32_t resolvedAction;
553 int32_t resolvedFlags;
555 DispatchEntry(EventEntry* eventEntry,
556 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor);
559 inline bool hasForegroundTarget() const {
560 return targetFlags & InputTarget::FLAG_FOREGROUND;
563 inline bool isSplit() const {
564 return targetFlags & InputTarget::FLAG_SPLIT;
568 static volatile int32_t sNextSeqAtomic;
570 static uint32_t nextSeq();
573 // A command entry captures state and behavior for an action to be performed in the
574 // dispatch loop after the initial processing has taken place. It is essentially
575 // a kind of continuation used to postpone sensitive policy interactions to a point
576 // in the dispatch loop where it is safe to release the lock (generally after finishing
577 // the critical parts of the dispatch cycle).
579 // The special thing about commands is that they can voluntarily release and reacquire
580 // the dispatcher lock at will. Initially when the command starts running, the
581 // dispatcher lock is held. However, if the command needs to call into the policy to
582 // do some work, it can release the lock, do the work, then reacquire the lock again
585 // This mechanism is a bit clunky but it helps to preserve the invariant that the dispatch
586 // never calls into the policy while holding its lock.
588 // Commands are implicitly 'LockedInterruptible'.
590 typedef void (InputDispatcher::*Command)(CommandEntry* commandEntry);
593 struct CommandEntry : Link<CommandEntry> {
594 CommandEntry(Command command);
599 // parameters for the command (usage varies by command)
600 sp<Connection> connection;
603 sp<InputApplicationHandle> inputApplicationHandle;
604 sp<InputWindowHandle> inputWindowHandle;
606 int32_t userActivityEventType;
611 // Generic queue implementation.
612 template <typename T>
618 inline Queue() : head(NULL), tail(NULL), entryCount(0) {
621 inline bool isEmpty() const {
625 inline void enqueueAtTail(T* entry) {
637 inline void enqueueAtHead(T* entry) {
649 inline void dequeue(T* entry) {
652 entry->prev->next = entry->next;
657 entry->next->prev = entry->prev;
663 inline T* dequeueAtHead() {
675 uint32_t count() const {
680 /* Specifies which events are to be canceled and why. */
681 struct CancelationOptions {
683 CANCEL_ALL_EVENTS = 0,
684 CANCEL_POINTER_EVENTS = 1,
685 CANCEL_NON_POINTER_EVENTS = 2,
686 CANCEL_FALLBACK_EVENTS = 3,
689 // The criterion to use to determine which events should be canceled.
692 // Descriptive reason for the cancelation.
695 // The specific keycode of the key event to cancel, or -1 to cancel any key event.
698 // The specific device id of events to cancel, or -1 to cancel events from any device.
701 CancelationOptions(Mode mode, const char* reason) :
702 mode(mode), reason(reason), keyCode(-1), deviceId(-1) { }
705 /* Tracks dispatched key and motion event state so that cancelation events can be
706 * synthesized when events are dropped. */
712 // Returns true if there is no state to be canceled.
713 bool isNeutral() const;
715 // Returns true if the specified source is known to have received a hover enter
717 bool isHovering(int32_t deviceId, uint32_t source, int32_t displayId) const;
719 // Records tracking information for a key event that has just been published.
720 // Returns true if the event should be delivered, false if it is inconsistent
721 // and should be skipped.
722 bool trackKey(const KeyEntry* entry, int32_t action, int32_t flags);
724 // Records tracking information for a motion event that has just been published.
725 // Returns true if the event should be delivered, false if it is inconsistent
726 // and should be skipped.
727 bool trackMotion(const MotionEntry* entry, int32_t action, int32_t flags);
729 // Synthesizes cancelation events for the current state and resets the tracked state.
730 void synthesizeCancelationEvents(nsecs_t currentTime,
731 Vector<EventEntry*>& outEvents, const CancelationOptions& options);
733 // Clears the current state.
736 // Copies pointer-related parts of the input state to another instance.
737 void copyPointerStateTo(InputState& other) const;
739 // Gets the fallback key associated with a keycode.
740 // Returns -1 if none.
741 // Returns AKEYCODE_UNKNOWN if we are only dispatching the unhandled key to the policy.
742 int32_t getFallbackKey(int32_t originalKeyCode);
744 // Sets the fallback key for a particular keycode.
745 void setFallbackKey(int32_t originalKeyCode, int32_t fallbackKeyCode);
747 // Removes the fallback key for a particular keycode.
748 void removeFallbackKey(int32_t originalKeyCode);
750 inline const KeyedVector<int32_t, int32_t>& getFallbackKeys() const {
751 return mFallbackKeys;
763 uint32_t policyFlags;
766 struct MotionMemento {
774 uint32_t pointerCount;
775 PointerProperties pointerProperties[MAX_POINTERS];
776 PointerCoords pointerCoords[MAX_POINTERS];
778 uint32_t policyFlags;
780 void setPointers(const MotionEntry* entry);
783 Vector<KeyMemento> mKeyMementos;
784 Vector<MotionMemento> mMotionMementos;
785 KeyedVector<int32_t, int32_t> mFallbackKeys;
787 ssize_t findKeyMemento(const KeyEntry* entry) const;
788 ssize_t findMotionMemento(const MotionEntry* entry, bool hovering) const;
790 void addKeyMemento(const KeyEntry* entry, int32_t flags);
791 void addMotionMemento(const MotionEntry* entry, int32_t flags, bool hovering);
793 static bool shouldCancelKey(const KeyMemento& memento,
794 const CancelationOptions& options);
795 static bool shouldCancelMotion(const MotionMemento& memento,
796 const CancelationOptions& options);
799 /* Manages the dispatch state associated with a single input channel. */
800 class Connection : public RefBase {
802 virtual ~Connection();
806 // Everything is peachy.
808 // An unrecoverable communication error has occurred.
810 // The input channel has been unregistered.
815 sp<InputChannel> inputChannel; // never null
816 sp<InputWindowHandle> inputWindowHandle; // may be null
818 InputPublisher inputPublisher;
819 InputState inputState;
821 // True if the socket is full and no further events can be published until
822 // the application consumes some of the input.
823 bool inputPublisherBlocked;
825 // Queue of events that need to be published to the connection.
826 Queue<DispatchEntry> outboundQueue;
828 // Queue of events that have been published to the connection but that have not
829 // yet received a "finished" response from the application.
830 Queue<DispatchEntry> waitQueue;
832 explicit Connection(const sp<InputChannel>& inputChannel,
833 const sp<InputWindowHandle>& inputWindowHandle, bool monitor);
835 inline const char* getInputChannelName() const { return inputChannel->getName().string(); }
837 const char* getWindowName() const;
838 const char* getStatusLabel() const;
840 DispatchEntry* findWaitQueueEntry(uint32_t seq);
844 DROP_REASON_NOT_DROPPED = 0,
845 DROP_REASON_POLICY = 1,
846 DROP_REASON_APP_SWITCH = 2,
847 DROP_REASON_DISABLED = 3,
848 DROP_REASON_BLOCKED = 4,
849 DROP_REASON_STALE = 5,
852 sp<InputDispatcherPolicyInterface> mPolicy;
853 InputDispatcherConfiguration mConfig;
857 Condition mDispatcherIsAliveCondition;
861 EventEntry* mPendingEvent;
862 Queue<EventEntry> mInboundQueue;
863 Queue<EventEntry> mRecentQueue;
864 Queue<CommandEntry> mCommandQueue;
866 DropReason mLastDropReason;
868 void dispatchOnceInnerLocked(nsecs_t* nextWakeupTime);
870 // Enqueues an inbound event. Returns true if mLooper->wake() should be called.
871 bool enqueueInboundEventLocked(EventEntry* entry);
873 // Cleans up input state when dropping an inbound event.
874 void dropInboundEventLocked(EventEntry* entry, DropReason dropReason);
876 // Adds an event to a queue of recent events for debugging purposes.
877 void addRecentEventLocked(EventEntry* entry);
879 // App switch latency optimization.
880 bool mAppSwitchSawKeyDown;
881 nsecs_t mAppSwitchDueTime;
883 static bool isAppSwitchKeyCode(int32_t keyCode);
884 bool isAppSwitchKeyEventLocked(KeyEntry* keyEntry);
885 bool isAppSwitchPendingLocked();
886 void resetPendingAppSwitchLocked(bool handled);
888 // Stale event latency optimization.
889 static bool isStaleEventLocked(nsecs_t currentTime, EventEntry* entry);
891 // Blocked event latency optimization. Drops old events when the user intends
892 // to transfer focus to a new application.
893 EventEntry* mNextUnblockedEvent;
895 sp<InputWindowHandle> findTouchedWindowAtLocked(int32_t displayId, int32_t x, int32_t y);
897 // All registered connections mapped by channel file descriptor.
898 KeyedVector<int, sp<Connection> > mConnectionsByFd;
900 ssize_t getConnectionIndexLocked(const sp<InputChannel>& inputChannel);
902 // Input channels that will receive a copy of all input events.
903 Vector<sp<InputChannel> > mMonitoringChannels;
905 // Event injection and synchronization.
906 Condition mInjectionResultAvailableCondition;
907 bool hasInjectionPermission(int32_t injectorPid, int32_t injectorUid);
908 void setInjectionResultLocked(EventEntry* entry, int32_t injectionResult);
910 Condition mInjectionSyncFinishedCondition;
911 void incrementPendingForegroundDispatchesLocked(EventEntry* entry);
912 void decrementPendingForegroundDispatchesLocked(EventEntry* entry);
914 // Key repeat tracking.
915 struct KeyRepeatState {
916 KeyEntry* lastKeyEntry; // or null if no repeat
917 nsecs_t nextRepeatTime;
920 void resetKeyRepeatLocked();
921 KeyEntry* synthesizeKeyRepeatLocked(nsecs_t currentTime);
923 // Key replacement tracking
924 struct KeyReplacement {
927 bool operator==(const KeyReplacement& rhs) const {
928 return keyCode == rhs.keyCode && deviceId == rhs.deviceId;
930 bool operator<(const KeyReplacement& rhs) const {
931 return keyCode != rhs.keyCode ? keyCode < rhs.keyCode : deviceId < rhs.deviceId;
934 // Maps the key code replaced, device id tuple to the key code it was replaced with
935 KeyedVector<KeyReplacement, int32_t> mReplacedKeys;
937 // Deferred command processing.
938 bool haveCommandsLocked() const;
939 bool runCommandsLockedInterruptible();
940 CommandEntry* postCommandLocked(Command command);
942 // Input filter processing.
943 bool shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args);
944 bool shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args);
946 // Inbound event processing.
947 void drainInboundQueueLocked();
948 void releasePendingEventLocked();
949 void releaseInboundEventLocked(EventEntry* entry);
952 bool mDispatchEnabled;
953 bool mDispatchFrozen;
954 bool mInputFilterEnabled;
956 Vector<sp<InputWindowHandle> > mWindowHandles;
958 sp<InputWindowHandle> getWindowHandleLocked(const sp<InputChannel>& inputChannel) const;
959 bool hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const;
961 // Focus tracking for keys, trackball, etc.
962 sp<InputWindowHandle> mFocusedWindowHandle;
964 // Focus tracking for touch.
965 struct TouchedWindow {
966 sp<InputWindowHandle> windowHandle;
968 BitSet32 pointerIds; // zero unless target flag FLAG_SPLIT is set
973 int32_t deviceId; // id of the device that is currently down, others are rejected
974 uint32_t source; // source of the device that is current down, others are rejected
975 int32_t displayId; // id to the display that currently has a touch, others are rejected
976 Vector<TouchedWindow> windows;
981 void copyFrom(const TouchState& other);
982 void addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
983 int32_t targetFlags, BitSet32 pointerIds);
984 void removeWindow(const sp<InputWindowHandle>& windowHandle);
985 void filterNonAsIsTouchWindows();
986 sp<InputWindowHandle> getFirstForegroundWindowHandle() const;
987 bool isSlippery() const;
990 KeyedVector<int32_t, TouchState> mTouchStatesByDisplay;
991 TouchState mTempTouchState;
993 // Focused application.
994 sp<InputApplicationHandle> mFocusedApplicationHandle;
996 // Dispatcher state at time of last ANR.
997 String8 mLastANRState;
999 // Dispatch inbound events.
1000 bool dispatchConfigurationChangedLocked(
1001 nsecs_t currentTime, ConfigurationChangedEntry* entry);
1002 bool dispatchDeviceResetLocked(
1003 nsecs_t currentTime, DeviceResetEntry* entry);
1004 bool dispatchKeyLocked(
1005 nsecs_t currentTime, KeyEntry* entry,
1006 DropReason* dropReason, nsecs_t* nextWakeupTime);
1007 bool dispatchMotionLocked(
1008 nsecs_t currentTime, MotionEntry* entry,
1009 DropReason* dropReason, nsecs_t* nextWakeupTime);
1010 void dispatchEventLocked(nsecs_t currentTime, EventEntry* entry,
1011 const Vector<InputTarget>& inputTargets);
1013 void logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry);
1014 void logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry);
1016 // Keeping track of ANR timeouts.
1017 enum InputTargetWaitCause {
1018 INPUT_TARGET_WAIT_CAUSE_NONE,
1019 INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY,
1020 INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY,
1023 InputTargetWaitCause mInputTargetWaitCause;
1024 nsecs_t mInputTargetWaitStartTime;
1025 nsecs_t mInputTargetWaitTimeoutTime;
1026 bool mInputTargetWaitTimeoutExpired;
1027 sp<InputApplicationHandle> mInputTargetWaitApplicationHandle;
1029 // Contains the last window which received a hover event.
1030 sp<InputWindowHandle> mLastHoverWindowHandle;
1032 // Finding targets for input events.
1033 int32_t handleTargetsNotReadyLocked(nsecs_t currentTime, const EventEntry* entry,
1034 const sp<InputApplicationHandle>& applicationHandle,
1035 const sp<InputWindowHandle>& windowHandle,
1036 nsecs_t* nextWakeupTime, const char* reason);
1037 void resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1038 const sp<InputChannel>& inputChannel);
1039 nsecs_t getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime);
1040 void resetANRTimeoutsLocked();
1042 int32_t findFocusedWindowTargetsLocked(nsecs_t currentTime, const EventEntry* entry,
1043 Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime);
1044 int32_t findTouchedWindowTargetsLocked(nsecs_t currentTime, const MotionEntry* entry,
1045 Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1046 bool* outConflictingPointerActions);
1048 void addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1049 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets);
1050 void addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets);
1052 void pokeUserActivityLocked(const EventEntry* eventEntry);
1053 bool checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1054 const InjectionState* injectionState);
1055 bool isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1056 int32_t x, int32_t y) const;
1057 bool isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const;
1058 String8 getApplicationWindowLabelLocked(const sp<InputApplicationHandle>& applicationHandle,
1059 const sp<InputWindowHandle>& windowHandle);
1061 String8 checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
1062 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1063 const char* targetType);
1065 // Manage the dispatch cycle for a single connection.
1066 // These methods are deliberately not Interruptible because doing all of the work
1067 // with the mutex held makes it easier to ensure that connection invariants are maintained.
1068 // If needed, the methods post commands to run later once the critical bits are done.
1069 void prepareDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1070 EventEntry* eventEntry, const InputTarget* inputTarget);
1071 void enqueueDispatchEntriesLocked(nsecs_t currentTime, const sp<Connection>& connection,
1072 EventEntry* eventEntry, const InputTarget* inputTarget);
1073 void enqueueDispatchEntryLocked(const sp<Connection>& connection,
1074 EventEntry* eventEntry, const InputTarget* inputTarget, int32_t dispatchMode);
1075 void startDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
1076 void finishDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1077 uint32_t seq, bool handled);
1078 void abortBrokenDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1080 void drainDispatchQueueLocked(Queue<DispatchEntry>* queue);
1081 void releaseDispatchEntryLocked(DispatchEntry* dispatchEntry);
1082 static int handleReceiveCallback(int fd, int events, void* data);
1084 void synthesizeCancelationEventsForAllConnectionsLocked(
1085 const CancelationOptions& options);
1086 void synthesizeCancelationEventsForMonitorsLocked(const CancelationOptions& options);
1087 void synthesizeCancelationEventsForInputChannelLocked(const sp<InputChannel>& channel,
1088 const CancelationOptions& options);
1089 void synthesizeCancelationEventsForConnectionLocked(const sp<Connection>& connection,
1090 const CancelationOptions& options);
1092 // Splitting motion events across windows.
1093 MotionEntry* splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds);
1095 // Reset and drop everything the dispatcher is doing.
1096 void resetAndDropEverythingLocked(const char* reason);
1099 void dumpDispatchStateLocked(String8& dump);
1100 void logDispatchStateLocked();
1103 void removeMonitorChannelLocked(const sp<InputChannel>& inputChannel);
1104 status_t unregisterInputChannelLocked(const sp<InputChannel>& inputChannel, bool notify);
1106 // Add or remove a connection to the mActiveConnections vector.
1107 void activateConnectionLocked(Connection* connection);
1108 void deactivateConnectionLocked(Connection* connection);
1110 // Interesting events that we might like to log or tell the framework about.
1111 void onDispatchCycleFinishedLocked(
1112 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled);
1113 void onDispatchCycleBrokenLocked(
1114 nsecs_t currentTime, const sp<Connection>& connection);
1116 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
1117 const sp<InputWindowHandle>& windowHandle,
1118 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason);
1120 // Outbound policy interactions.
1121 void doNotifyConfigurationChangedInterruptible(CommandEntry* commandEntry);
1122 void doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry);
1123 void doNotifyANRLockedInterruptible(CommandEntry* commandEntry);
1124 void doInterceptKeyBeforeDispatchingLockedInterruptible(CommandEntry* commandEntry);
1125 void doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry);
1126 bool afterKeyEventLockedInterruptible(const sp<Connection>& connection,
1127 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled);
1128 bool afterMotionEventLockedInterruptible(const sp<Connection>& connection,
1129 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled);
1130 void doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry);
1131 void initializeKeyEvent(KeyEvent* event, const KeyEntry* entry);
1133 // Statistics gathering.
1134 void updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
1135 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication);
1136 void traceInboundQueueLengthLocked();
1137 void traceOutboundQueueLengthLocked(const sp<Connection>& connection);
1138 void traceWaitQueueLengthLocked(const sp<Connection>& connection);
1141 /* Enqueues and dispatches input events, endlessly. */
1142 class InputDispatcherThread : public Thread {
1144 explicit InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher);
1145 ~InputDispatcherThread();
1148 virtual bool threadLoop();
1150 sp<InputDispatcherInterface> mDispatcher;
1153 } // namespace android
1155 #endif // _UI_INPUT_DISPATCHER_H