blob: 29854b2d56e4ba59961723e8b1c9331c37aa4284 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
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 <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>
31
32#include <stddef.h>
33#include <unistd.h>
34#include <limits.h>
35
36#include "InputWindow.h"
37#include "InputApplication.h"
38#include "InputListener.h"
39
40
41namespace android {
42
43/*
44 * Constants used to report the outcome of input event injection.
45 */
46enum {
47 /* (INTERNAL USE ONLY) Specifies that injection is pending and its outcome is unknown. */
48 INPUT_EVENT_INJECTION_PENDING = -1,
49
50 /* Injection succeeded. */
51 INPUT_EVENT_INJECTION_SUCCEEDED = 0,
52
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,
56
57 /* Injection failed because there were no available input targets. */
58 INPUT_EVENT_INJECTION_FAILED = 2,
59
60 /* Injection failed due to a timeout. */
61 INPUT_EVENT_INJECTION_TIMED_OUT = 3
62};
63
64/*
65 * Constants used to determine the input event injection synchronization mode.
66 */
67enum {
68 /* Injection is asynchronous and is assumed always to be successful. */
69 INPUT_EVENT_INJECTION_SYNC_NONE = 0,
70
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,
75
76 /* Waits for the input event to be completely processed. */
77 INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED = 2,
78};
79
80
81/*
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
85 * window area.
86 */
87struct InputTarget {
88 enum {
89 /* This flag indicates that the event is being delivered to a foreground application. */
90 FLAG_FOREGROUND = 1 << 0,
91
92 /* This flag indicates that the target of a MotionEvent is partly or wholly
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,
96
97 /* This flag indicates that a motion event is being split across multiple windows. */
98 FLAG_SPLIT = 1 << 2,
99
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,
105
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,
109
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,
114
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,
118
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
121 * window.
122 * The event is transmuted into ACTION_HOVER_ENTER. */
123 FLAG_DISPATCH_AS_HOVER_EXIT = 1 << 11,
124
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,
129
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,
134
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,
142 };
143
144 // The input channel to be targeted.
145 sp<InputChannel> inputChannel;
146
147 // Flags for the input target.
148 int32_t flags;
149
150 // The x and y offset to add to a MotionEvent as it is delivered.
151 // (ignored for KeyEvents)
152 float xOffset, yOffset;
153
154 // Scaling factor to apply to MotionEvent as it is delivered.
155 // (ignored for KeyEvents)
156 float scaleFactor;
157
158 // The subset of pointer ids to include in motion events dispatched to this input target
159 // if FLAG_SPLIT is set.
160 BitSet32 pointerIds;
161};
162
163
164/*
165 * Input dispatcher configuration.
166 *
167 * Specifies various options that modify the behavior of the input dispatcher.
168 * The values provided here are merely defaults. The actual values will come from ViewConfiguration
169 * and are passed into the dispatcher during initialization.
170 */
171struct InputDispatcherConfiguration {
172 // The key repeat initial timeout.
173 nsecs_t keyRepeatTimeout;
174
175 // The key repeat inter-key delay.
176 nsecs_t keyRepeatDelay;
177
178 InputDispatcherConfiguration() :
179 keyRepeatTimeout(500 * 1000000LL),
180 keyRepeatDelay(50 * 1000000LL) { }
181};
182
183
184/*
185 * Input dispatcher policy interface.
186 *
187 * The input reader policy is used by the input reader to interact with the Window Manager
188 * and other system components.
189 *
190 * The actual implementation is partially supported by callbacks into the DVM
191 * via JNI. This interface is also mocked in the unit tests.
192 */
193class InputDispatcherPolicyInterface : public virtual RefBase {
194protected:
195 InputDispatcherPolicyInterface() { }
196 virtual ~InputDispatcherPolicyInterface() { }
197
198public:
199 /* Notifies the system that a configuration change has occurred. */
200 virtual void notifyConfigurationChanged(nsecs_t when) = 0;
201
202 /* Notifies the system that an application is not responding.
203 * Returns a new timeout to continue waiting, or 0 to abort dispatch. */
204 virtual nsecs_t notifyANR(const sp<InputApplicationHandle>& inputApplicationHandle,
205 const sp<InputWindowHandle>& inputWindowHandle,
206 const String8& reason) = 0;
207
208 /* Notifies the system that an input channel is unrecoverably broken. */
209 virtual void notifyInputChannelBroken(const sp<InputWindowHandle>& inputWindowHandle) = 0;
210
211 /* Gets the input dispatcher configuration. */
212 virtual void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) = 0;
213
214 /* Returns true if automatic key repeating is enabled. */
215 virtual bool isKeyRepeatEnabled() = 0;
216
217 /* Filters an input event.
218 * Return true to dispatch the event unmodified, false to consume the event.
219 * A filter can also transform and inject events later by passing POLICY_FLAG_FILTERED
220 * to injectInputEvent.
221 */
222 virtual bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) = 0;
223
224 /* Intercepts a key event immediately before queueing it.
225 * The policy can use this method as an opportunity to perform power management functions
226 * and early event preprocessing such as updating policy flags.
227 *
228 * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
229 * should be dispatched to applications.
230 */
231 virtual void interceptKeyBeforeQueueing(const KeyEvent* keyEvent, uint32_t& policyFlags) = 0;
232
233 /* Intercepts a touch, trackball or other motion event before queueing it.
234 * The policy can use this method as an opportunity to perform power management functions
235 * and early event preprocessing such as updating policy flags.
236 *
237 * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
238 * should be dispatched to applications.
239 */
240 virtual void interceptMotionBeforeQueueing(nsecs_t when, uint32_t& policyFlags) = 0;
241
242 /* Allows the policy a chance to intercept a key before dispatching. */
243 virtual nsecs_t interceptKeyBeforeDispatching(const sp<InputWindowHandle>& inputWindowHandle,
244 const KeyEvent* keyEvent, uint32_t policyFlags) = 0;
245
246 /* Allows the policy a chance to perform default processing for an unhandled key.
247 * Returns an alternate keycode to redispatch as a fallback, or 0 to give up. */
248 virtual bool dispatchUnhandledKey(const sp<InputWindowHandle>& inputWindowHandle,
249 const KeyEvent* keyEvent, uint32_t policyFlags, KeyEvent* outFallbackKeyEvent) = 0;
250
251 /* Notifies the policy about switch events.
252 */
253 virtual void notifySwitch(nsecs_t when,
254 uint32_t switchValues, uint32_t switchMask, uint32_t policyFlags) = 0;
255
256 /* Poke user activity for an event dispatched to a window. */
257 virtual void pokeUserActivity(nsecs_t eventTime, int32_t eventType) = 0;
258
259 /* Checks whether a given application pid/uid has permission to inject input events
260 * into other applications.
261 *
262 * This method is special in that its implementation promises to be non-reentrant and
263 * is safe to call while holding other locks. (Most other methods make no such guarantees!)
264 */
265 virtual bool checkInjectEventsPermissionNonReentrant(
266 int32_t injectorPid, int32_t injectorUid) = 0;
267};
268
269
270/* Notifies the system about input events generated by the input reader.
271 * The dispatcher is expected to be mostly asynchronous. */
272class InputDispatcherInterface : public virtual RefBase, public InputListenerInterface {
273protected:
274 InputDispatcherInterface() { }
275 virtual ~InputDispatcherInterface() { }
276
277public:
278 /* Dumps the state of the input dispatcher.
279 *
280 * This method may be called on any thread (usually by the input manager). */
281 virtual void dump(String8& dump) = 0;
282
283 /* Called by the heatbeat to ensures that the dispatcher has not deadlocked. */
284 virtual void monitor() = 0;
285
286 /* Runs a single iteration of the dispatch loop.
287 * Nominally processes one queued event, a timeout, or a response from an input consumer.
288 *
289 * This method should only be called on the input dispatcher thread.
290 */
291 virtual void dispatchOnce() = 0;
292
293 /* Injects an input event and optionally waits for sync.
294 * The synchronization mode determines whether the method blocks while waiting for
295 * input injection to proceed.
296 * Returns one of the INPUT_EVENT_INJECTION_XXX constants.
297 *
298 * This method may be called on any thread (usually by the input manager).
299 */
Jeff Brownf086ddb2014-02-11 14:28:48 -0800300 virtual int32_t injectInputEvent(const InputEvent* event, int32_t displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800301 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
302 uint32_t policyFlags) = 0;
303
304 /* Sets the list of input windows.
305 *
306 * This method may be called on any thread (usually by the input manager).
307 */
308 virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) = 0;
309
310 /* Sets the focused application.
311 *
312 * This method may be called on any thread (usually by the input manager).
313 */
314 virtual void setFocusedApplication(
315 const sp<InputApplicationHandle>& inputApplicationHandle) = 0;
316
317 /* Sets the input dispatching mode.
318 *
319 * This method may be called on any thread (usually by the input manager).
320 */
321 virtual void setInputDispatchMode(bool enabled, bool frozen) = 0;
322
323 /* Sets whether input event filtering is enabled.
324 * When enabled, incoming input events are sent to the policy's filterInputEvent
325 * method instead of being dispatched. The filter is expected to use
326 * injectInputEvent to inject the events it would like to have dispatched.
327 * It should include POLICY_FLAG_FILTERED in the policy flags during injection.
328 */
329 virtual void setInputFilterEnabled(bool enabled) = 0;
330
331 /* Transfers touch focus from the window associated with one channel to the
332 * window associated with the other channel.
333 *
334 * Returns true on success. False if the window did not actually have touch focus.
335 */
336 virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel,
337 const sp<InputChannel>& toChannel) = 0;
338
339 /* Registers or unregister input channels that may be used as targets for input events.
340 * If monitor is true, the channel will receive a copy of all input events.
341 *
342 * These methods may be called on any thread (usually by the input manager).
343 */
344 virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel,
345 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) = 0;
346 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel) = 0;
347};
348
349/* Dispatches events to input targets. Some functions of the input dispatcher, such as
350 * identifying input targets, are controlled by a separate policy object.
351 *
352 * IMPORTANT INVARIANT:
353 * Because the policy can potentially block or cause re-entrance into the input dispatcher,
354 * the input dispatcher never calls into the policy while holding its internal locks.
355 * The implementation is also carefully designed to recover from scenarios such as an
356 * input channel becoming unregistered while identifying input targets or processing timeouts.
357 *
358 * Methods marked 'Locked' must be called with the lock acquired.
359 *
360 * Methods marked 'LockedInterruptible' must be called with the lock acquired but
361 * may during the course of their execution release the lock, call into the policy, and
362 * then reacquire the lock. The caller is responsible for recovering gracefully.
363 *
364 * A 'LockedInterruptible' method may called a 'Locked' method, but NOT vice-versa.
365 */
366class InputDispatcher : public InputDispatcherInterface {
367protected:
368 virtual ~InputDispatcher();
369
370public:
371 explicit InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy);
372
373 virtual void dump(String8& dump);
374 virtual void monitor();
375
376 virtual void dispatchOnce();
377
378 virtual void notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args);
379 virtual void notifyKey(const NotifyKeyArgs* args);
380 virtual void notifyMotion(const NotifyMotionArgs* args);
381 virtual void notifySwitch(const NotifySwitchArgs* args);
382 virtual void notifyDeviceReset(const NotifyDeviceResetArgs* args);
383
Jeff Brownf086ddb2014-02-11 14:28:48 -0800384 virtual int32_t injectInputEvent(const InputEvent* event, int32_t displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800385 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
386 uint32_t policyFlags);
387
388 virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles);
389 virtual void setFocusedApplication(const sp<InputApplicationHandle>& inputApplicationHandle);
390 virtual void setInputDispatchMode(bool enabled, bool frozen);
391 virtual void setInputFilterEnabled(bool enabled);
392
393 virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel,
394 const sp<InputChannel>& toChannel);
395
396 virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel,
397 const sp<InputWindowHandle>& inputWindowHandle, bool monitor);
398 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel);
399
400private:
401 template <typename T>
402 struct Link {
403 T* next;
404 T* prev;
405
406 protected:
407 inline Link() : next(NULL), prev(NULL) { }
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 InjectionState(int32_t injectorPid, int32_t injectorUid);
420 void release();
421
422 private:
423 ~InjectionState();
424 };
425
426 struct EventEntry : Link<EventEntry> {
427 enum {
428 TYPE_CONFIGURATION_CHANGED,
429 TYPE_DEVICE_RESET,
430 TYPE_KEY,
431 TYPE_MOTION
432 };
433
434 mutable int32_t refCount;
435 int32_t type;
436 nsecs_t eventTime;
437 uint32_t policyFlags;
438 InjectionState* injectionState;
439
440 bool dispatchInProgress; // initially false, set to true while dispatching
441
442 inline bool isInjected() const { return injectionState != NULL; }
443
444 void release();
445
446 virtual void appendDescription(String8& msg) const = 0;
447
448 protected:
449 EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags);
450 virtual ~EventEntry();
451 void releaseInjectionState();
452 };
453
454 struct ConfigurationChangedEntry : EventEntry {
455 ConfigurationChangedEntry(nsecs_t eventTime);
456 virtual void appendDescription(String8& msg) const;
457
458 protected:
459 virtual ~ConfigurationChangedEntry();
460 };
461
462 struct DeviceResetEntry : EventEntry {
463 int32_t deviceId;
464
465 DeviceResetEntry(nsecs_t eventTime, int32_t deviceId);
466 virtual void appendDescription(String8& msg) const;
467
468 protected:
469 virtual ~DeviceResetEntry();
470 };
471
472 struct KeyEntry : EventEntry {
473 int32_t deviceId;
474 uint32_t source;
475 int32_t action;
476 int32_t flags;
477 int32_t keyCode;
478 int32_t scanCode;
479 int32_t metaState;
480 int32_t repeatCount;
481 nsecs_t downTime;
482
483 bool syntheticRepeat; // set to true for synthetic key repeats
484
485 enum InterceptKeyResult {
486 INTERCEPT_KEY_RESULT_UNKNOWN,
487 INTERCEPT_KEY_RESULT_SKIP,
488 INTERCEPT_KEY_RESULT_CONTINUE,
489 INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER,
490 };
491 InterceptKeyResult interceptKeyResult; // set based on the interception result
492 nsecs_t interceptKeyWakeupTime; // used with INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER
493
494 KeyEntry(nsecs_t eventTime,
495 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
496 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
497 int32_t repeatCount, nsecs_t downTime);
498 virtual void appendDescription(String8& msg) const;
499 void recycle();
500
501 protected:
502 virtual ~KeyEntry();
503 };
504
505 struct MotionEntry : EventEntry {
506 nsecs_t eventTime;
507 int32_t deviceId;
508 uint32_t source;
509 int32_t action;
510 int32_t flags;
511 int32_t metaState;
512 int32_t buttonState;
513 int32_t edgeFlags;
514 float xPrecision;
515 float yPrecision;
516 nsecs_t downTime;
517 int32_t displayId;
518 uint32_t pointerCount;
519 PointerProperties pointerProperties[MAX_POINTERS];
520 PointerCoords pointerCoords[MAX_POINTERS];
521
522 MotionEntry(nsecs_t eventTime,
523 int32_t deviceId, uint32_t source, uint32_t policyFlags,
524 int32_t action, int32_t flags,
525 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
526 float xPrecision, float yPrecision,
527 nsecs_t downTime, int32_t displayId, uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -0800528 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
529 float xOffset, float yOffset);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800530 virtual void appendDescription(String8& msg) const;
531
532 protected:
533 virtual ~MotionEntry();
534 };
535
536 // Tracks the progress of dispatching a particular event to a particular connection.
537 struct DispatchEntry : Link<DispatchEntry> {
538 const uint32_t seq; // unique sequence number, never 0
539
540 EventEntry* eventEntry; // the event to dispatch
541 int32_t targetFlags;
542 float xOffset;
543 float yOffset;
544 float scaleFactor;
545 nsecs_t deliveryTime; // time when the event was actually delivered
546
547 // Set to the resolved action and flags when the event is enqueued.
548 int32_t resolvedAction;
549 int32_t resolvedFlags;
550
551 DispatchEntry(EventEntry* eventEntry,
552 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor);
553 ~DispatchEntry();
554
555 inline bool hasForegroundTarget() const {
556 return targetFlags & InputTarget::FLAG_FOREGROUND;
557 }
558
559 inline bool isSplit() const {
560 return targetFlags & InputTarget::FLAG_SPLIT;
561 }
562
563 private:
564 static volatile int32_t sNextSeqAtomic;
565
566 static uint32_t nextSeq();
567 };
568
569 // A command entry captures state and behavior for an action to be performed in the
570 // dispatch loop after the initial processing has taken place. It is essentially
571 // a kind of continuation used to postpone sensitive policy interactions to a point
572 // in the dispatch loop where it is safe to release the lock (generally after finishing
573 // the critical parts of the dispatch cycle).
574 //
575 // The special thing about commands is that they can voluntarily release and reacquire
576 // the dispatcher lock at will. Initially when the command starts running, the
577 // dispatcher lock is held. However, if the command needs to call into the policy to
578 // do some work, it can release the lock, do the work, then reacquire the lock again
579 // before returning.
580 //
581 // This mechanism is a bit clunky but it helps to preserve the invariant that the dispatch
582 // never calls into the policy while holding its lock.
583 //
584 // Commands are implicitly 'LockedInterruptible'.
585 struct CommandEntry;
586 typedef void (InputDispatcher::*Command)(CommandEntry* commandEntry);
587
588 class Connection;
589 struct CommandEntry : Link<CommandEntry> {
590 CommandEntry(Command command);
591 ~CommandEntry();
592
593 Command command;
594
595 // parameters for the command (usage varies by command)
596 sp<Connection> connection;
597 nsecs_t eventTime;
598 KeyEntry* keyEntry;
599 sp<InputApplicationHandle> inputApplicationHandle;
600 sp<InputWindowHandle> inputWindowHandle;
601 String8 reason;
602 int32_t userActivityEventType;
603 uint32_t seq;
604 bool handled;
605 };
606
607 // Generic queue implementation.
608 template <typename T>
609 struct Queue {
610 T* head;
611 T* tail;
612
613 inline Queue() : head(NULL), tail(NULL) {
614 }
615
616 inline bool isEmpty() const {
617 return !head;
618 }
619
620 inline void enqueueAtTail(T* entry) {
621 entry->prev = tail;
622 if (tail) {
623 tail->next = entry;
624 } else {
625 head = entry;
626 }
627 entry->next = NULL;
628 tail = entry;
629 }
630
631 inline void enqueueAtHead(T* entry) {
632 entry->next = head;
633 if (head) {
634 head->prev = entry;
635 } else {
636 tail = entry;
637 }
638 entry->prev = NULL;
639 head = entry;
640 }
641
642 inline void dequeue(T* entry) {
643 if (entry->prev) {
644 entry->prev->next = entry->next;
645 } else {
646 head = entry->next;
647 }
648 if (entry->next) {
649 entry->next->prev = entry->prev;
650 } else {
651 tail = entry->prev;
652 }
653 }
654
655 inline T* dequeueAtHead() {
656 T* entry = head;
657 head = entry->next;
658 if (head) {
659 head->prev = NULL;
660 } else {
661 tail = NULL;
662 }
663 return entry;
664 }
665
666 uint32_t count() const;
667 };
668
669 /* Specifies which events are to be canceled and why. */
670 struct CancelationOptions {
671 enum Mode {
672 CANCEL_ALL_EVENTS = 0,
673 CANCEL_POINTER_EVENTS = 1,
674 CANCEL_NON_POINTER_EVENTS = 2,
675 CANCEL_FALLBACK_EVENTS = 3,
676 };
677
678 // The criterion to use to determine which events should be canceled.
679 Mode mode;
680
681 // Descriptive reason for the cancelation.
682 const char* reason;
683
684 // The specific keycode of the key event to cancel, or -1 to cancel any key event.
685 int32_t keyCode;
686
687 // The specific device id of events to cancel, or -1 to cancel events from any device.
688 int32_t deviceId;
689
690 CancelationOptions(Mode mode, const char* reason) :
691 mode(mode), reason(reason), keyCode(-1), deviceId(-1) { }
692 };
693
694 /* Tracks dispatched key and motion event state so that cancelation events can be
695 * synthesized when events are dropped. */
696 class InputState {
697 public:
698 InputState();
699 ~InputState();
700
701 // Returns true if there is no state to be canceled.
702 bool isNeutral() const;
703
704 // Returns true if the specified source is known to have received a hover enter
705 // motion event.
706 bool isHovering(int32_t deviceId, uint32_t source, int32_t displayId) const;
707
708 // Records tracking information for a key event that has just been published.
709 // Returns true if the event should be delivered, false if it is inconsistent
710 // and should be skipped.
711 bool trackKey(const KeyEntry* entry, int32_t action, int32_t flags);
712
713 // Records tracking information for a motion event that has just been published.
714 // Returns true if the event should be delivered, false if it is inconsistent
715 // and should be skipped.
716 bool trackMotion(const MotionEntry* entry, int32_t action, int32_t flags);
717
718 // Synthesizes cancelation events for the current state and resets the tracked state.
719 void synthesizeCancelationEvents(nsecs_t currentTime,
720 Vector<EventEntry*>& outEvents, const CancelationOptions& options);
721
722 // Clears the current state.
723 void clear();
724
725 // Copies pointer-related parts of the input state to another instance.
726 void copyPointerStateTo(InputState& other) const;
727
728 // Gets the fallback key associated with a keycode.
729 // Returns -1 if none.
730 // Returns AKEYCODE_UNKNOWN if we are only dispatching the unhandled key to the policy.
731 int32_t getFallbackKey(int32_t originalKeyCode);
732
733 // Sets the fallback key for a particular keycode.
734 void setFallbackKey(int32_t originalKeyCode, int32_t fallbackKeyCode);
735
736 // Removes the fallback key for a particular keycode.
737 void removeFallbackKey(int32_t originalKeyCode);
738
739 inline const KeyedVector<int32_t, int32_t>& getFallbackKeys() const {
740 return mFallbackKeys;
741 }
742
743 private:
744 struct KeyMemento {
745 int32_t deviceId;
746 uint32_t source;
747 int32_t keyCode;
748 int32_t scanCode;
749 int32_t metaState;
750 int32_t flags;
751 nsecs_t downTime;
752 uint32_t policyFlags;
753 };
754
755 struct MotionMemento {
756 int32_t deviceId;
757 uint32_t source;
758 int32_t flags;
759 float xPrecision;
760 float yPrecision;
761 nsecs_t downTime;
762 int32_t displayId;
763 uint32_t pointerCount;
764 PointerProperties pointerProperties[MAX_POINTERS];
765 PointerCoords pointerCoords[MAX_POINTERS];
766 bool hovering;
767 uint32_t policyFlags;
768
769 void setPointers(const MotionEntry* entry);
770 };
771
772 Vector<KeyMemento> mKeyMementos;
773 Vector<MotionMemento> mMotionMementos;
774 KeyedVector<int32_t, int32_t> mFallbackKeys;
775
776 ssize_t findKeyMemento(const KeyEntry* entry) const;
777 ssize_t findMotionMemento(const MotionEntry* entry, bool hovering) const;
778
779 void addKeyMemento(const KeyEntry* entry, int32_t flags);
780 void addMotionMemento(const MotionEntry* entry, int32_t flags, bool hovering);
781
782 static bool shouldCancelKey(const KeyMemento& memento,
783 const CancelationOptions& options);
784 static bool shouldCancelMotion(const MotionMemento& memento,
785 const CancelationOptions& options);
786 };
787
788 /* Manages the dispatch state associated with a single input channel. */
789 class Connection : public RefBase {
790 protected:
791 virtual ~Connection();
792
793 public:
794 enum Status {
795 // Everything is peachy.
796 STATUS_NORMAL,
797 // An unrecoverable communication error has occurred.
798 STATUS_BROKEN,
799 // The input channel has been unregistered.
800 STATUS_ZOMBIE
801 };
802
803 Status status;
804 sp<InputChannel> inputChannel; // never null
805 sp<InputWindowHandle> inputWindowHandle; // may be null
806 bool monitor;
807 InputPublisher inputPublisher;
808 InputState inputState;
809
810 // True if the socket is full and no further events can be published until
811 // the application consumes some of the input.
812 bool inputPublisherBlocked;
813
814 // Queue of events that need to be published to the connection.
815 Queue<DispatchEntry> outboundQueue;
816
817 // Queue of events that have been published to the connection but that have not
818 // yet received a "finished" response from the application.
819 Queue<DispatchEntry> waitQueue;
820
821 explicit Connection(const sp<InputChannel>& inputChannel,
822 const sp<InputWindowHandle>& inputWindowHandle, bool monitor);
823
824 inline const char* getInputChannelName() const { return inputChannel->getName().string(); }
825
826 const char* getWindowName() const;
827 const char* getStatusLabel() const;
828
829 DispatchEntry* findWaitQueueEntry(uint32_t seq);
830 };
831
832 enum DropReason {
833 DROP_REASON_NOT_DROPPED = 0,
834 DROP_REASON_POLICY = 1,
835 DROP_REASON_APP_SWITCH = 2,
836 DROP_REASON_DISABLED = 3,
837 DROP_REASON_BLOCKED = 4,
838 DROP_REASON_STALE = 5,
839 };
840
841 sp<InputDispatcherPolicyInterface> mPolicy;
842 InputDispatcherConfiguration mConfig;
843
844 Mutex mLock;
845
846 Condition mDispatcherIsAliveCondition;
847
848 sp<Looper> mLooper;
849
850 EventEntry* mPendingEvent;
851 Queue<EventEntry> mInboundQueue;
852 Queue<EventEntry> mRecentQueue;
853 Queue<CommandEntry> mCommandQueue;
854
855 void dispatchOnceInnerLocked(nsecs_t* nextWakeupTime);
856
857 // Enqueues an inbound event. Returns true if mLooper->wake() should be called.
858 bool enqueueInboundEventLocked(EventEntry* entry);
859
860 // Cleans up input state when dropping an inbound event.
861 void dropInboundEventLocked(EventEntry* entry, DropReason dropReason);
862
863 // Adds an event to a queue of recent events for debugging purposes.
864 void addRecentEventLocked(EventEntry* entry);
865
866 // App switch latency optimization.
867 bool mAppSwitchSawKeyDown;
868 nsecs_t mAppSwitchDueTime;
869
870 static bool isAppSwitchKeyCode(int32_t keyCode);
871 bool isAppSwitchKeyEventLocked(KeyEntry* keyEntry);
872 bool isAppSwitchPendingLocked();
873 void resetPendingAppSwitchLocked(bool handled);
874
875 // Stale event latency optimization.
876 static bool isStaleEventLocked(nsecs_t currentTime, EventEntry* entry);
877
878 // Blocked event latency optimization. Drops old events when the user intends
879 // to transfer focus to a new application.
880 EventEntry* mNextUnblockedEvent;
881
882 sp<InputWindowHandle> findTouchedWindowAtLocked(int32_t displayId, int32_t x, int32_t y);
883
884 // All registered connections mapped by channel file descriptor.
885 KeyedVector<int, sp<Connection> > mConnectionsByFd;
886
887 ssize_t getConnectionIndexLocked(const sp<InputChannel>& inputChannel);
888
889 // Input channels that will receive a copy of all input events.
890 Vector<sp<InputChannel> > mMonitoringChannels;
891
892 // Event injection and synchronization.
893 Condition mInjectionResultAvailableCondition;
894 bool hasInjectionPermission(int32_t injectorPid, int32_t injectorUid);
895 void setInjectionResultLocked(EventEntry* entry, int32_t injectionResult);
896
897 Condition mInjectionSyncFinishedCondition;
898 void incrementPendingForegroundDispatchesLocked(EventEntry* entry);
899 void decrementPendingForegroundDispatchesLocked(EventEntry* entry);
900
901 // Key repeat tracking.
902 struct KeyRepeatState {
903 KeyEntry* lastKeyEntry; // or null if no repeat
904 nsecs_t nextRepeatTime;
905 } mKeyRepeatState;
906
907 void resetKeyRepeatLocked();
908 KeyEntry* synthesizeKeyRepeatLocked(nsecs_t currentTime);
909
910 // Deferred command processing.
911 bool haveCommandsLocked() const;
912 bool runCommandsLockedInterruptible();
913 CommandEntry* postCommandLocked(Command command);
914
915 // Input filter processing.
916 bool shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args);
917 bool shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args);
918
919 // Inbound event processing.
920 void drainInboundQueueLocked();
921 void releasePendingEventLocked();
922 void releaseInboundEventLocked(EventEntry* entry);
923
924 // Dispatch state.
925 bool mDispatchEnabled;
926 bool mDispatchFrozen;
927 bool mInputFilterEnabled;
928
929 Vector<sp<InputWindowHandle> > mWindowHandles;
930
931 sp<InputWindowHandle> getWindowHandleLocked(const sp<InputChannel>& inputChannel) const;
932 bool hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const;
933
934 // Focus tracking for keys, trackball, etc.
935 sp<InputWindowHandle> mFocusedWindowHandle;
936
937 // Focus tracking for touch.
938 struct TouchedWindow {
939 sp<InputWindowHandle> windowHandle;
940 int32_t targetFlags;
941 BitSet32 pointerIds; // zero unless target flag FLAG_SPLIT is set
942 };
943 struct TouchState {
944 bool down;
945 bool split;
946 int32_t deviceId; // id of the device that is currently down, others are rejected
947 uint32_t source; // source of the device that is current down, others are rejected
948 int32_t displayId; // id to the display that currently has a touch, others are rejected
949 Vector<TouchedWindow> windows;
950
951 TouchState();
952 ~TouchState();
953 void reset();
954 void copyFrom(const TouchState& other);
955 void addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
956 int32_t targetFlags, BitSet32 pointerIds);
957 void removeWindow(const sp<InputWindowHandle>& windowHandle);
958 void filterNonAsIsTouchWindows();
959 sp<InputWindowHandle> getFirstForegroundWindowHandle() const;
960 bool isSlippery() const;
961 };
962
Jeff Brownf086ddb2014-02-11 14:28:48 -0800963 KeyedVector<int32_t, TouchState> mTouchStatesByDisplay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964 TouchState mTempTouchState;
965
966 // Focused application.
967 sp<InputApplicationHandle> mFocusedApplicationHandle;
968
969 // Dispatcher state at time of last ANR.
970 String8 mLastANRState;
971
972 // Dispatch inbound events.
973 bool dispatchConfigurationChangedLocked(
974 nsecs_t currentTime, ConfigurationChangedEntry* entry);
975 bool dispatchDeviceResetLocked(
976 nsecs_t currentTime, DeviceResetEntry* entry);
977 bool dispatchKeyLocked(
978 nsecs_t currentTime, KeyEntry* entry,
979 DropReason* dropReason, nsecs_t* nextWakeupTime);
980 bool dispatchMotionLocked(
981 nsecs_t currentTime, MotionEntry* entry,
982 DropReason* dropReason, nsecs_t* nextWakeupTime);
983 void dispatchEventLocked(nsecs_t currentTime, EventEntry* entry,
984 const Vector<InputTarget>& inputTargets);
985
986 void logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry);
987 void logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry);
988
989 // Keeping track of ANR timeouts.
990 enum InputTargetWaitCause {
991 INPUT_TARGET_WAIT_CAUSE_NONE,
992 INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY,
993 INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY,
994 };
995
996 InputTargetWaitCause mInputTargetWaitCause;
997 nsecs_t mInputTargetWaitStartTime;
998 nsecs_t mInputTargetWaitTimeoutTime;
999 bool mInputTargetWaitTimeoutExpired;
1000 sp<InputApplicationHandle> mInputTargetWaitApplicationHandle;
1001
1002 // Contains the last window which received a hover event.
1003 sp<InputWindowHandle> mLastHoverWindowHandle;
1004
1005 // Finding targets for input events.
1006 int32_t handleTargetsNotReadyLocked(nsecs_t currentTime, const EventEntry* entry,
1007 const sp<InputApplicationHandle>& applicationHandle,
1008 const sp<InputWindowHandle>& windowHandle,
1009 nsecs_t* nextWakeupTime, const char* reason);
1010 void resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1011 const sp<InputChannel>& inputChannel);
1012 nsecs_t getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime);
1013 void resetANRTimeoutsLocked();
1014
1015 int32_t findFocusedWindowTargetsLocked(nsecs_t currentTime, const EventEntry* entry,
1016 Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime);
1017 int32_t findTouchedWindowTargetsLocked(nsecs_t currentTime, const MotionEntry* entry,
1018 Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1019 bool* outConflictingPointerActions);
1020
1021 void addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1022 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets);
1023 void addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets);
1024
1025 void pokeUserActivityLocked(const EventEntry* eventEntry);
1026 bool checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1027 const InjectionState* injectionState);
1028 bool isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1029 int32_t x, int32_t y) const;
1030 bool isWindowReadyForMoreInputLocked(nsecs_t currentTime,
1031 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry);
1032 String8 getApplicationWindowLabelLocked(const sp<InputApplicationHandle>& applicationHandle,
1033 const sp<InputWindowHandle>& windowHandle);
1034
1035 // Manage the dispatch cycle for a single connection.
1036 // These methods are deliberately not Interruptible because doing all of the work
1037 // with the mutex held makes it easier to ensure that connection invariants are maintained.
1038 // If needed, the methods post commands to run later once the critical bits are done.
1039 void prepareDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1040 EventEntry* eventEntry, const InputTarget* inputTarget);
1041 void enqueueDispatchEntriesLocked(nsecs_t currentTime, const sp<Connection>& connection,
1042 EventEntry* eventEntry, const InputTarget* inputTarget);
1043 void enqueueDispatchEntryLocked(const sp<Connection>& connection,
1044 EventEntry* eventEntry, const InputTarget* inputTarget, int32_t dispatchMode);
1045 void startDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
1046 void finishDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1047 uint32_t seq, bool handled);
1048 void abortBrokenDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1049 bool notify);
1050 void drainDispatchQueueLocked(Queue<DispatchEntry>* queue);
1051 void releaseDispatchEntryLocked(DispatchEntry* dispatchEntry);
1052 static int handleReceiveCallback(int fd, int events, void* data);
1053
1054 void synthesizeCancelationEventsForAllConnectionsLocked(
1055 const CancelationOptions& options);
1056 void synthesizeCancelationEventsForInputChannelLocked(const sp<InputChannel>& channel,
1057 const CancelationOptions& options);
1058 void synthesizeCancelationEventsForConnectionLocked(const sp<Connection>& connection,
1059 const CancelationOptions& options);
1060
1061 // Splitting motion events across windows.
1062 MotionEntry* splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds);
1063
1064 // Reset and drop everything the dispatcher is doing.
1065 void resetAndDropEverythingLocked(const char* reason);
1066
1067 // Dump state.
1068 void dumpDispatchStateLocked(String8& dump);
1069 void logDispatchStateLocked();
1070
1071 // Registration.
1072 void removeMonitorChannelLocked(const sp<InputChannel>& inputChannel);
1073 status_t unregisterInputChannelLocked(const sp<InputChannel>& inputChannel, bool notify);
1074
1075 // Add or remove a connection to the mActiveConnections vector.
1076 void activateConnectionLocked(Connection* connection);
1077 void deactivateConnectionLocked(Connection* connection);
1078
1079 // Interesting events that we might like to log or tell the framework about.
1080 void onDispatchCycleFinishedLocked(
1081 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled);
1082 void onDispatchCycleBrokenLocked(
1083 nsecs_t currentTime, const sp<Connection>& connection);
1084 void onANRLocked(
1085 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
1086 const sp<InputWindowHandle>& windowHandle,
1087 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason);
1088
1089 // Outbound policy interactions.
1090 void doNotifyConfigurationChangedInterruptible(CommandEntry* commandEntry);
1091 void doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry);
1092 void doNotifyANRLockedInterruptible(CommandEntry* commandEntry);
1093 void doInterceptKeyBeforeDispatchingLockedInterruptible(CommandEntry* commandEntry);
1094 void doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry);
1095 bool afterKeyEventLockedInterruptible(const sp<Connection>& connection,
1096 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled);
1097 bool afterMotionEventLockedInterruptible(const sp<Connection>& connection,
1098 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled);
1099 void doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry);
1100 void initializeKeyEvent(KeyEvent* event, const KeyEntry* entry);
1101
1102 // Statistics gathering.
1103 void updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
1104 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication);
1105 void traceInboundQueueLengthLocked();
1106 void traceOutboundQueueLengthLocked(const sp<Connection>& connection);
1107 void traceWaitQueueLengthLocked(const sp<Connection>& connection);
1108};
1109
1110/* Enqueues and dispatches input events, endlessly. */
1111class InputDispatcherThread : public Thread {
1112public:
1113 explicit InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher);
1114 ~InputDispatcherThread();
1115
1116private:
1117 virtual bool threadLoop();
1118
1119 sp<InputDispatcherInterface> mDispatcher;
1120};
1121
1122} // namespace android
1123
1124#endif // _UI_INPUT_DISPATCHER_H