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