blob: af33fbe82bceaf9834f1fcba0e07ab83bcb5eeff [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>
Michael Wrightd02c5b62014-02-10 15:10:22 -080027#include <utils/Looper.h>
28#include <utils/BitSet.h>
29#include <cutils/atomic.h>
30
31#include <stddef.h>
32#include <unistd.h>
33#include <limits.h>
Arthur Hungb92218b2018-08-14 12:00:21 +080034#include <unordered_map>
Michael Wrightd02c5b62014-02-10 15:10:22 -080035
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
Michael Wrightcdcd8f22016-03-22 16:52:13 -070092 /* This flag indicates that the MotionEvent falls within the area of the target
Michael Wrightd02c5b62014-02-10 15:10:22 -080093 * 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,
Michael Wrightcdcd8f22016-03-22 16:52:13 -0700142
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,
147
Michael Wrightd02c5b62014-02-10 15:10:22 -0800148 };
149
150 // The input channel to be targeted.
151 sp<InputChannel> inputChannel;
152
153 // Flags for the input target.
154 int32_t flags;
155
156 // The x and y offset to add to a MotionEvent as it is delivered.
157 // (ignored for KeyEvents)
158 float xOffset, yOffset;
159
160 // Scaling factor to apply to MotionEvent as it is delivered.
161 // (ignored for KeyEvents)
162 float scaleFactor;
163
164 // The subset of pointer ids to include in motion events dispatched to this input target
165 // if FLAG_SPLIT is set.
166 BitSet32 pointerIds;
167};
168
169
170/*
171 * Input dispatcher configuration.
172 *
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.
176 */
177struct InputDispatcherConfiguration {
178 // The key repeat initial timeout.
179 nsecs_t keyRepeatTimeout;
180
181 // The key repeat inter-key delay.
182 nsecs_t keyRepeatDelay;
183
184 InputDispatcherConfiguration() :
185 keyRepeatTimeout(500 * 1000000LL),
186 keyRepeatDelay(50 * 1000000LL) { }
187};
188
189
190/*
191 * Input dispatcher policy interface.
192 *
193 * The input reader policy is used by the input reader to interact with the Window Manager
194 * and other system components.
195 *
196 * The actual implementation is partially supported by callbacks into the DVM
197 * via JNI. This interface is also mocked in the unit tests.
198 */
199class InputDispatcherPolicyInterface : public virtual RefBase {
200protected:
201 InputDispatcherPolicyInterface() { }
202 virtual ~InputDispatcherPolicyInterface() { }
203
204public:
205 /* Notifies the system that a configuration change has occurred. */
206 virtual void notifyConfigurationChanged(nsecs_t when) = 0;
207
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,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800212 const std::string& reason) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800213
214 /* Notifies the system that an input channel is unrecoverably broken. */
215 virtual void notifyInputChannelBroken(const sp<InputWindowHandle>& inputWindowHandle) = 0;
216
217 /* Gets the input dispatcher configuration. */
218 virtual void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) = 0;
219
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220 /* 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.
224 */
225 virtual bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) = 0;
226
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.
230 *
231 * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
232 * should be dispatched to applications.
233 */
234 virtual void interceptKeyBeforeQueueing(const KeyEvent* keyEvent, uint32_t& policyFlags) = 0;
235
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.
239 *
240 * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
241 * should be dispatched to applications.
242 */
243 virtual void interceptMotionBeforeQueueing(nsecs_t when, uint32_t& policyFlags) = 0;
244
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;
248
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;
253
254 /* Notifies the policy about switch events.
255 */
256 virtual void notifySwitch(nsecs_t when,
257 uint32_t switchValues, uint32_t switchMask, uint32_t policyFlags) = 0;
258
259 /* Poke user activity for an event dispatched to a window. */
260 virtual void pokeUserActivity(nsecs_t eventTime, int32_t eventType) = 0;
261
262 /* Checks whether a given application pid/uid has permission to inject input events
263 * into other applications.
264 *
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!)
267 */
268 virtual bool checkInjectEventsPermissionNonReentrant(
269 int32_t injectorPid, int32_t injectorUid) = 0;
270};
271
272
273/* Notifies the system about input events generated by the input reader.
274 * The dispatcher is expected to be mostly asynchronous. */
275class InputDispatcherInterface : public virtual RefBase, public InputListenerInterface {
276protected:
277 InputDispatcherInterface() { }
278 virtual ~InputDispatcherInterface() { }
279
280public:
281 /* Dumps the state of the input dispatcher.
282 *
283 * This method may be called on any thread (usually by the input manager). */
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800284 virtual void dump(std::string& dump) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800285
286 /* Called by the heatbeat to ensures that the dispatcher has not deadlocked. */
287 virtual void monitor() = 0;
288
289 /* Runs a single iteration of the dispatch loop.
290 * Nominally processes one queued event, a timeout, or a response from an input consumer.
291 *
292 * This method should only be called on the input dispatcher thread.
293 */
294 virtual void dispatchOnce() = 0;
295
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.
300 *
301 * This method may be called on any thread (usually by the input manager).
302 */
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800303 virtual int32_t injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800304 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
305 uint32_t policyFlags) = 0;
306
307 /* Sets the list of input windows.
308 *
309 * This method may be called on any thread (usually by the input manager).
310 */
Arthur Hungb92218b2018-08-14 12:00:21 +0800311 virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles,
312 int32_t displayId) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800313
Tiger Huang721e26f2018-07-24 22:26:19 +0800314 /* Sets the focused application on the given display.
Michael Wrightd02c5b62014-02-10 15:10:22 -0800315 *
316 * This method may be called on any thread (usually by the input manager).
317 */
318 virtual void setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +0800319 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) = 0;
320
321 /* Sets the focused display.
322 *
323 * This method may be called on any thread (usually by the input manager).
324 */
325 virtual void setFocusedDisplay(int32_t displayId) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800326
327 /* Sets the input dispatching mode.
328 *
329 * This method may be called on any thread (usually by the input manager).
330 */
331 virtual void setInputDispatchMode(bool enabled, bool frozen) = 0;
332
333 /* Sets whether input event filtering is enabled.
334 * When enabled, incoming input events are sent to the policy's filterInputEvent
335 * method instead of being dispatched. The filter is expected to use
336 * injectInputEvent to inject the events it would like to have dispatched.
337 * It should include POLICY_FLAG_FILTERED in the policy flags during injection.
338 */
339 virtual void setInputFilterEnabled(bool enabled) = 0;
340
341 /* Transfers touch focus from the window associated with one channel to the
342 * window associated with the other channel.
343 *
344 * Returns true on success. False if the window did not actually have touch focus.
345 */
346 virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel,
347 const sp<InputChannel>& toChannel) = 0;
348
349 /* Registers or unregister input channels that may be used as targets for input events.
350 * If monitor is true, the channel will receive a copy of all input events.
351 *
352 * These methods may be called on any thread (usually by the input manager).
353 */
354 virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel,
355 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) = 0;
356 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel) = 0;
357};
358
359/* Dispatches events to input targets. Some functions of the input dispatcher, such as
360 * identifying input targets, are controlled by a separate policy object.
361 *
362 * IMPORTANT INVARIANT:
363 * Because the policy can potentially block or cause re-entrance into the input dispatcher,
364 * the input dispatcher never calls into the policy while holding its internal locks.
365 * The implementation is also carefully designed to recover from scenarios such as an
366 * input channel becoming unregistered while identifying input targets or processing timeouts.
367 *
368 * Methods marked 'Locked' must be called with the lock acquired.
369 *
370 * Methods marked 'LockedInterruptible' must be called with the lock acquired but
371 * may during the course of their execution release the lock, call into the policy, and
372 * then reacquire the lock. The caller is responsible for recovering gracefully.
373 *
374 * A 'LockedInterruptible' method may called a 'Locked' method, but NOT vice-versa.
375 */
376class InputDispatcher : public InputDispatcherInterface {
377protected:
378 virtual ~InputDispatcher();
379
380public:
381 explicit InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy);
382
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800383 virtual void dump(std::string& dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800384 virtual void monitor();
385
386 virtual void dispatchOnce();
387
388 virtual void notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args);
389 virtual void notifyKey(const NotifyKeyArgs* args);
390 virtual void notifyMotion(const NotifyMotionArgs* args);
391 virtual void notifySwitch(const NotifySwitchArgs* args);
392 virtual void notifyDeviceReset(const NotifyDeviceResetArgs* args);
393
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800394 virtual int32_t injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800395 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
396 uint32_t policyFlags);
397
Arthur Hungb92218b2018-08-14 12:00:21 +0800398 virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles,
399 int32_t displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +0800400 virtual void setFocusedApplication(int32_t displayId,
401 const sp<InputApplicationHandle>& inputApplicationHandle);
402 virtual void setFocusedDisplay(int32_t displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800403 virtual void setInputDispatchMode(bool enabled, bool frozen);
404 virtual void setInputFilterEnabled(bool enabled);
405
406 virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel,
407 const sp<InputChannel>& toChannel);
408
409 virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel,
410 const sp<InputWindowHandle>& inputWindowHandle, bool monitor);
411 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel);
412
413private:
414 template <typename T>
415 struct Link {
416 T* next;
417 T* prev;
418
419 protected:
Yi Kong9b14ac62018-07-17 13:48:38 -0700420 inline Link() : next(nullptr), prev(nullptr) { }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800421 };
422
423 struct InjectionState {
424 mutable int32_t refCount;
425
426 int32_t injectorPid;
427 int32_t injectorUid;
428 int32_t injectionResult; // initially INPUT_EVENT_INJECTION_PENDING
429 bool injectionIsAsync; // set to true if injection is not waiting for the result
430 int32_t pendingForegroundDispatches; // the number of foreground dispatches in progress
431
432 InjectionState(int32_t injectorPid, int32_t injectorUid);
433 void release();
434
435 private:
436 ~InjectionState();
437 };
438
439 struct EventEntry : Link<EventEntry> {
440 enum {
441 TYPE_CONFIGURATION_CHANGED,
442 TYPE_DEVICE_RESET,
443 TYPE_KEY,
444 TYPE_MOTION
445 };
446
447 mutable int32_t refCount;
448 int32_t type;
449 nsecs_t eventTime;
450 uint32_t policyFlags;
451 InjectionState* injectionState;
452
453 bool dispatchInProgress; // initially false, set to true while dispatching
454
Yi Kong9b14ac62018-07-17 13:48:38 -0700455 inline bool isInjected() const { return injectionState != nullptr; }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800456
457 void release();
458
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800459 virtual void appendDescription(std::string& msg) const = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800460
461 protected:
462 EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags);
463 virtual ~EventEntry();
464 void releaseInjectionState();
465 };
466
467 struct ConfigurationChangedEntry : EventEntry {
Chih-Hung Hsieh6d2ede12016-09-01 11:28:23 -0700468 explicit ConfigurationChangedEntry(nsecs_t eventTime);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800469 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800470
471 protected:
472 virtual ~ConfigurationChangedEntry();
473 };
474
475 struct DeviceResetEntry : EventEntry {
476 int32_t deviceId;
477
478 DeviceResetEntry(nsecs_t eventTime, int32_t deviceId);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800479 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800480
481 protected:
482 virtual ~DeviceResetEntry();
483 };
484
485 struct KeyEntry : EventEntry {
486 int32_t deviceId;
487 uint32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100488 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800489 int32_t action;
490 int32_t flags;
491 int32_t keyCode;
492 int32_t scanCode;
493 int32_t metaState;
494 int32_t repeatCount;
495 nsecs_t downTime;
496
497 bool syntheticRepeat; // set to true for synthetic key repeats
498
499 enum InterceptKeyResult {
500 INTERCEPT_KEY_RESULT_UNKNOWN,
501 INTERCEPT_KEY_RESULT_SKIP,
502 INTERCEPT_KEY_RESULT_CONTINUE,
503 INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER,
504 };
505 InterceptKeyResult interceptKeyResult; // set based on the interception result
506 nsecs_t interceptKeyWakeupTime; // used with INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER
507
508 KeyEntry(nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100509 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags,
510 int32_t action, int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800511 int32_t repeatCount, nsecs_t downTime);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800512 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800513 void recycle();
514
515 protected:
516 virtual ~KeyEntry();
517 };
518
519 struct MotionEntry : EventEntry {
520 nsecs_t eventTime;
521 int32_t deviceId;
522 uint32_t source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800523 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800524 int32_t action;
Michael Wright7b159c92015-05-14 14:48:03 +0100525 int32_t actionButton;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800526 int32_t flags;
527 int32_t metaState;
528 int32_t buttonState;
529 int32_t edgeFlags;
530 float xPrecision;
531 float yPrecision;
532 nsecs_t downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533 uint32_t pointerCount;
534 PointerProperties pointerProperties[MAX_POINTERS];
535 PointerCoords pointerCoords[MAX_POINTERS];
536
537 MotionEntry(nsecs_t eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800538 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +0100539 int32_t action, int32_t actionButton, int32_t flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800540 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800541 float xPrecision, float yPrecision, nsecs_t downTime, uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -0800542 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
543 float xOffset, float yOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800544 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800545
546 protected:
547 virtual ~MotionEntry();
548 };
549
550 // Tracks the progress of dispatching a particular event to a particular connection.
551 struct DispatchEntry : Link<DispatchEntry> {
552 const uint32_t seq; // unique sequence number, never 0
553
554 EventEntry* eventEntry; // the event to dispatch
555 int32_t targetFlags;
556 float xOffset;
557 float yOffset;
558 float scaleFactor;
559 nsecs_t deliveryTime; // time when the event was actually delivered
560
561 // Set to the resolved action and flags when the event is enqueued.
562 int32_t resolvedAction;
563 int32_t resolvedFlags;
564
565 DispatchEntry(EventEntry* eventEntry,
566 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor);
567 ~DispatchEntry();
568
569 inline bool hasForegroundTarget() const {
570 return targetFlags & InputTarget::FLAG_FOREGROUND;
571 }
572
573 inline bool isSplit() const {
574 return targetFlags & InputTarget::FLAG_SPLIT;
575 }
576
577 private:
578 static volatile int32_t sNextSeqAtomic;
579
580 static uint32_t nextSeq();
581 };
582
583 // A command entry captures state and behavior for an action to be performed in the
584 // dispatch loop after the initial processing has taken place. It is essentially
585 // a kind of continuation used to postpone sensitive policy interactions to a point
586 // in the dispatch loop where it is safe to release the lock (generally after finishing
587 // the critical parts of the dispatch cycle).
588 //
589 // The special thing about commands is that they can voluntarily release and reacquire
590 // the dispatcher lock at will. Initially when the command starts running, the
591 // dispatcher lock is held. However, if the command needs to call into the policy to
592 // do some work, it can release the lock, do the work, then reacquire the lock again
593 // before returning.
594 //
595 // This mechanism is a bit clunky but it helps to preserve the invariant that the dispatch
596 // never calls into the policy while holding its lock.
597 //
598 // Commands are implicitly 'LockedInterruptible'.
599 struct CommandEntry;
600 typedef void (InputDispatcher::*Command)(CommandEntry* commandEntry);
601
602 class Connection;
603 struct CommandEntry : Link<CommandEntry> {
Chih-Hung Hsieh6d2ede12016-09-01 11:28:23 -0700604 explicit CommandEntry(Command command);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800605 ~CommandEntry();
606
607 Command command;
608
609 // parameters for the command (usage varies by command)
610 sp<Connection> connection;
611 nsecs_t eventTime;
612 KeyEntry* keyEntry;
613 sp<InputApplicationHandle> inputApplicationHandle;
614 sp<InputWindowHandle> inputWindowHandle;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800615 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800616 int32_t userActivityEventType;
617 uint32_t seq;
618 bool handled;
619 };
620
621 // Generic queue implementation.
622 template <typename T>
623 struct Queue {
624 T* head;
625 T* tail;
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800626 uint32_t entryCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627
Yi Kong9b14ac62018-07-17 13:48:38 -0700628 inline Queue() : head(nullptr), tail(nullptr), entryCount(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800629 }
630
631 inline bool isEmpty() const {
632 return !head;
633 }
634
635 inline void enqueueAtTail(T* entry) {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800636 entryCount++;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800637 entry->prev = tail;
638 if (tail) {
639 tail->next = entry;
640 } else {
641 head = entry;
642 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700643 entry->next = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800644 tail = entry;
645 }
646
647 inline void enqueueAtHead(T* entry) {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800648 entryCount++;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800649 entry->next = head;
650 if (head) {
651 head->prev = entry;
652 } else {
653 tail = entry;
654 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700655 entry->prev = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800656 head = entry;
657 }
658
659 inline void dequeue(T* entry) {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800660 entryCount--;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800661 if (entry->prev) {
662 entry->prev->next = entry->next;
663 } else {
664 head = entry->next;
665 }
666 if (entry->next) {
667 entry->next->prev = entry->prev;
668 } else {
669 tail = entry->prev;
670 }
671 }
672
673 inline T* dequeueAtHead() {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800674 entryCount--;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800675 T* entry = head;
676 head = entry->next;
677 if (head) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700678 head->prev = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800679 } else {
Yi Kong9b14ac62018-07-17 13:48:38 -0700680 tail = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681 }
682 return entry;
683 }
684
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800685 uint32_t count() const {
686 return entryCount;
687 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800688 };
689
690 /* Specifies which events are to be canceled and why. */
691 struct CancelationOptions {
692 enum Mode {
693 CANCEL_ALL_EVENTS = 0,
694 CANCEL_POINTER_EVENTS = 1,
695 CANCEL_NON_POINTER_EVENTS = 2,
696 CANCEL_FALLBACK_EVENTS = 3,
Tiger Huang721e26f2018-07-24 22:26:19 +0800697
698 /* Cancel events where the display not specified. These events would go to the focused
699 * display. */
700 CANCEL_DISPLAY_UNSPECIFIED_EVENTS = 4,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800701 };
702
703 // The criterion to use to determine which events should be canceled.
704 Mode mode;
705
706 // Descriptive reason for the cancelation.
707 const char* reason;
708
709 // The specific keycode of the key event to cancel, or -1 to cancel any key event.
710 int32_t keyCode;
711
712 // The specific device id of events to cancel, or -1 to cancel events from any device.
713 int32_t deviceId;
714
715 CancelationOptions(Mode mode, const char* reason) :
716 mode(mode), reason(reason), keyCode(-1), deviceId(-1) { }
717 };
718
719 /* Tracks dispatched key and motion event state so that cancelation events can be
720 * synthesized when events are dropped. */
721 class InputState {
722 public:
723 InputState();
724 ~InputState();
725
726 // Returns true if there is no state to be canceled.
727 bool isNeutral() const;
728
729 // Returns true if the specified source is known to have received a hover enter
730 // motion event.
731 bool isHovering(int32_t deviceId, uint32_t source, int32_t displayId) const;
732
733 // Records tracking information for a key event that has just been published.
734 // Returns true if the event should be delivered, false if it is inconsistent
735 // and should be skipped.
736 bool trackKey(const KeyEntry* entry, int32_t action, int32_t flags);
737
738 // Records tracking information for a motion event that has just been published.
739 // Returns true if the event should be delivered, false if it is inconsistent
740 // and should be skipped.
741 bool trackMotion(const MotionEntry* entry, int32_t action, int32_t flags);
742
743 // Synthesizes cancelation events for the current state and resets the tracked state.
744 void synthesizeCancelationEvents(nsecs_t currentTime,
745 Vector<EventEntry*>& outEvents, const CancelationOptions& options);
746
747 // Clears the current state.
748 void clear();
749
750 // Copies pointer-related parts of the input state to another instance.
751 void copyPointerStateTo(InputState& other) const;
752
753 // Gets the fallback key associated with a keycode.
754 // Returns -1 if none.
755 // Returns AKEYCODE_UNKNOWN if we are only dispatching the unhandled key to the policy.
756 int32_t getFallbackKey(int32_t originalKeyCode);
757
758 // Sets the fallback key for a particular keycode.
759 void setFallbackKey(int32_t originalKeyCode, int32_t fallbackKeyCode);
760
761 // Removes the fallback key for a particular keycode.
762 void removeFallbackKey(int32_t originalKeyCode);
763
764 inline const KeyedVector<int32_t, int32_t>& getFallbackKeys() const {
765 return mFallbackKeys;
766 }
767
768 private:
769 struct KeyMemento {
770 int32_t deviceId;
771 uint32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100772 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800773 int32_t keyCode;
774 int32_t scanCode;
775 int32_t metaState;
776 int32_t flags;
777 nsecs_t downTime;
778 uint32_t policyFlags;
779 };
780
781 struct MotionMemento {
782 int32_t deviceId;
783 uint32_t source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800784 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800785 int32_t flags;
786 float xPrecision;
787 float yPrecision;
788 nsecs_t downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800789 uint32_t pointerCount;
790 PointerProperties pointerProperties[MAX_POINTERS];
791 PointerCoords pointerCoords[MAX_POINTERS];
792 bool hovering;
793 uint32_t policyFlags;
794
795 void setPointers(const MotionEntry* entry);
796 };
797
798 Vector<KeyMemento> mKeyMementos;
799 Vector<MotionMemento> mMotionMementos;
800 KeyedVector<int32_t, int32_t> mFallbackKeys;
801
802 ssize_t findKeyMemento(const KeyEntry* entry) const;
803 ssize_t findMotionMemento(const MotionEntry* entry, bool hovering) const;
804
805 void addKeyMemento(const KeyEntry* entry, int32_t flags);
806 void addMotionMemento(const MotionEntry* entry, int32_t flags, bool hovering);
807
808 static bool shouldCancelKey(const KeyMemento& memento,
809 const CancelationOptions& options);
810 static bool shouldCancelMotion(const MotionMemento& memento,
811 const CancelationOptions& options);
812 };
813
814 /* Manages the dispatch state associated with a single input channel. */
815 class Connection : public RefBase {
816 protected:
817 virtual ~Connection();
818
819 public:
820 enum Status {
821 // Everything is peachy.
822 STATUS_NORMAL,
823 // An unrecoverable communication error has occurred.
824 STATUS_BROKEN,
825 // The input channel has been unregistered.
826 STATUS_ZOMBIE
827 };
828
829 Status status;
830 sp<InputChannel> inputChannel; // never null
831 sp<InputWindowHandle> inputWindowHandle; // may be null
832 bool monitor;
833 InputPublisher inputPublisher;
834 InputState inputState;
835
836 // True if the socket is full and no further events can be published until
837 // the application consumes some of the input.
838 bool inputPublisherBlocked;
839
840 // Queue of events that need to be published to the connection.
841 Queue<DispatchEntry> outboundQueue;
842
843 // Queue of events that have been published to the connection but that have not
844 // yet received a "finished" response from the application.
845 Queue<DispatchEntry> waitQueue;
846
847 explicit Connection(const sp<InputChannel>& inputChannel,
848 const sp<InputWindowHandle>& inputWindowHandle, bool monitor);
849
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -0800850 inline const std::string getInputChannelName() const { return inputChannel->getName(); }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -0800852 const std::string getWindowName() const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800853 const char* getStatusLabel() const;
854
855 DispatchEntry* findWaitQueueEntry(uint32_t seq);
856 };
857
858 enum DropReason {
859 DROP_REASON_NOT_DROPPED = 0,
860 DROP_REASON_POLICY = 1,
861 DROP_REASON_APP_SWITCH = 2,
862 DROP_REASON_DISABLED = 3,
863 DROP_REASON_BLOCKED = 4,
864 DROP_REASON_STALE = 5,
865 };
866
867 sp<InputDispatcherPolicyInterface> mPolicy;
868 InputDispatcherConfiguration mConfig;
869
870 Mutex mLock;
871
872 Condition mDispatcherIsAliveCondition;
873
874 sp<Looper> mLooper;
875
876 EventEntry* mPendingEvent;
877 Queue<EventEntry> mInboundQueue;
878 Queue<EventEntry> mRecentQueue;
879 Queue<CommandEntry> mCommandQueue;
880
Michael Wright3a981722015-06-10 15:26:13 +0100881 DropReason mLastDropReason;
882
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883 void dispatchOnceInnerLocked(nsecs_t* nextWakeupTime);
884
885 // Enqueues an inbound event. Returns true if mLooper->wake() should be called.
886 bool enqueueInboundEventLocked(EventEntry* entry);
887
888 // Cleans up input state when dropping an inbound event.
889 void dropInboundEventLocked(EventEntry* entry, DropReason dropReason);
890
891 // Adds an event to a queue of recent events for debugging purposes.
892 void addRecentEventLocked(EventEntry* entry);
893
894 // App switch latency optimization.
895 bool mAppSwitchSawKeyDown;
896 nsecs_t mAppSwitchDueTime;
897
898 static bool isAppSwitchKeyCode(int32_t keyCode);
899 bool isAppSwitchKeyEventLocked(KeyEntry* keyEntry);
900 bool isAppSwitchPendingLocked();
901 void resetPendingAppSwitchLocked(bool handled);
902
903 // Stale event latency optimization.
904 static bool isStaleEventLocked(nsecs_t currentTime, EventEntry* entry);
905
906 // Blocked event latency optimization. Drops old events when the user intends
907 // to transfer focus to a new application.
908 EventEntry* mNextUnblockedEvent;
909
910 sp<InputWindowHandle> findTouchedWindowAtLocked(int32_t displayId, int32_t x, int32_t y);
911
912 // All registered connections mapped by channel file descriptor.
913 KeyedVector<int, sp<Connection> > mConnectionsByFd;
914
915 ssize_t getConnectionIndexLocked(const sp<InputChannel>& inputChannel);
916
917 // Input channels that will receive a copy of all input events.
918 Vector<sp<InputChannel> > mMonitoringChannels;
919
920 // Event injection and synchronization.
921 Condition mInjectionResultAvailableCondition;
922 bool hasInjectionPermission(int32_t injectorPid, int32_t injectorUid);
923 void setInjectionResultLocked(EventEntry* entry, int32_t injectionResult);
924
925 Condition mInjectionSyncFinishedCondition;
926 void incrementPendingForegroundDispatchesLocked(EventEntry* entry);
927 void decrementPendingForegroundDispatchesLocked(EventEntry* entry);
928
929 // Key repeat tracking.
930 struct KeyRepeatState {
931 KeyEntry* lastKeyEntry; // or null if no repeat
932 nsecs_t nextRepeatTime;
933 } mKeyRepeatState;
934
935 void resetKeyRepeatLocked();
936 KeyEntry* synthesizeKeyRepeatLocked(nsecs_t currentTime);
937
Michael Wright78f24442014-08-06 15:55:28 -0700938 // Key replacement tracking
939 struct KeyReplacement {
940 int32_t keyCode;
941 int32_t deviceId;
942 bool operator==(const KeyReplacement& rhs) const {
943 return keyCode == rhs.keyCode && deviceId == rhs.deviceId;
944 }
945 bool operator<(const KeyReplacement& rhs) const {
946 return keyCode != rhs.keyCode ? keyCode < rhs.keyCode : deviceId < rhs.deviceId;
947 }
948 };
949 // Maps the key code replaced, device id tuple to the key code it was replaced with
950 KeyedVector<KeyReplacement, int32_t> mReplacedKeys;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -0500951 // Process certain Meta + Key combinations
952 void accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
953 int32_t& keyCode, int32_t& metaState);
Michael Wright78f24442014-08-06 15:55:28 -0700954
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955 // Deferred command processing.
956 bool haveCommandsLocked() const;
957 bool runCommandsLockedInterruptible();
958 CommandEntry* postCommandLocked(Command command);
959
960 // Input filter processing.
961 bool shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args);
962 bool shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args);
963
964 // Inbound event processing.
965 void drainInboundQueueLocked();
966 void releasePendingEventLocked();
967 void releaseInboundEventLocked(EventEntry* entry);
968
969 // Dispatch state.
970 bool mDispatchEnabled;
971 bool mDispatchFrozen;
972 bool mInputFilterEnabled;
973
Arthur Hungb92218b2018-08-14 12:00:21 +0800974 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>> mWindowHandlesByDisplay;
975 // Get window handles by display, return an empty vector if not found.
976 Vector<sp<InputWindowHandle>> getWindowHandlesLocked(int32_t displayId) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977 sp<InputWindowHandle> getWindowHandleLocked(const sp<InputChannel>& inputChannel) const;
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +0000978 bool hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979
980 // Focus tracking for keys, trackball, etc.
Tiger Huang721e26f2018-07-24 22:26:19 +0800981 std::unordered_map<int32_t, sp<InputWindowHandle>> mFocusedWindowHandlesByDisplay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982
983 // Focus tracking for touch.
984 struct TouchedWindow {
985 sp<InputWindowHandle> windowHandle;
986 int32_t targetFlags;
987 BitSet32 pointerIds; // zero unless target flag FLAG_SPLIT is set
988 };
989 struct TouchState {
990 bool down;
991 bool split;
992 int32_t deviceId; // id of the device that is currently down, others are rejected
993 uint32_t source; // source of the device that is current down, others are rejected
994 int32_t displayId; // id to the display that currently has a touch, others are rejected
995 Vector<TouchedWindow> windows;
996
997 TouchState();
998 ~TouchState();
999 void reset();
1000 void copyFrom(const TouchState& other);
1001 void addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
1002 int32_t targetFlags, BitSet32 pointerIds);
1003 void removeWindow(const sp<InputWindowHandle>& windowHandle);
1004 void filterNonAsIsTouchWindows();
1005 sp<InputWindowHandle> getFirstForegroundWindowHandle() const;
1006 bool isSlippery() const;
1007 };
1008
Jeff Brownf086ddb2014-02-11 14:28:48 -08001009 KeyedVector<int32_t, TouchState> mTouchStatesByDisplay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 TouchState mTempTouchState;
1011
Tiger Huang721e26f2018-07-24 22:26:19 +08001012 // Focused applications.
1013 std::unordered_map<int32_t, sp<InputApplicationHandle>> mFocusedApplicationHandlesByDisplay;
1014
1015 // Top focused display.
1016 int32_t mFocusedDisplayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017
1018 // Dispatcher state at time of last ANR.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001019 std::string mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001020
1021 // Dispatch inbound events.
1022 bool dispatchConfigurationChangedLocked(
1023 nsecs_t currentTime, ConfigurationChangedEntry* entry);
1024 bool dispatchDeviceResetLocked(
1025 nsecs_t currentTime, DeviceResetEntry* entry);
1026 bool dispatchKeyLocked(
1027 nsecs_t currentTime, KeyEntry* entry,
1028 DropReason* dropReason, nsecs_t* nextWakeupTime);
1029 bool dispatchMotionLocked(
1030 nsecs_t currentTime, MotionEntry* entry,
1031 DropReason* dropReason, nsecs_t* nextWakeupTime);
1032 void dispatchEventLocked(nsecs_t currentTime, EventEntry* entry,
1033 const Vector<InputTarget>& inputTargets);
1034
1035 void logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry);
1036 void logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry);
1037
1038 // Keeping track of ANR timeouts.
1039 enum InputTargetWaitCause {
1040 INPUT_TARGET_WAIT_CAUSE_NONE,
1041 INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY,
1042 INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY,
1043 };
1044
1045 InputTargetWaitCause mInputTargetWaitCause;
1046 nsecs_t mInputTargetWaitStartTime;
1047 nsecs_t mInputTargetWaitTimeoutTime;
1048 bool mInputTargetWaitTimeoutExpired;
1049 sp<InputApplicationHandle> mInputTargetWaitApplicationHandle;
1050
1051 // Contains the last window which received a hover event.
1052 sp<InputWindowHandle> mLastHoverWindowHandle;
1053
1054 // Finding targets for input events.
1055 int32_t handleTargetsNotReadyLocked(nsecs_t currentTime, const EventEntry* entry,
1056 const sp<InputApplicationHandle>& applicationHandle,
1057 const sp<InputWindowHandle>& windowHandle,
1058 nsecs_t* nextWakeupTime, const char* reason);
1059 void resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1060 const sp<InputChannel>& inputChannel);
1061 nsecs_t getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime);
1062 void resetANRTimeoutsLocked();
1063
Tiger Huang721e26f2018-07-24 22:26:19 +08001064 int32_t getTargetDisplayId(const EventEntry* entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065 int32_t findFocusedWindowTargetsLocked(nsecs_t currentTime, const EventEntry* entry,
1066 Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime);
1067 int32_t findTouchedWindowTargetsLocked(nsecs_t currentTime, const MotionEntry* entry,
1068 Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1069 bool* outConflictingPointerActions);
1070
1071 void addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1072 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets);
1073 void addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets);
1074
1075 void pokeUserActivityLocked(const EventEntry* eventEntry);
1076 bool checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1077 const InjectionState* injectionState);
1078 bool isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1079 int32_t x, int32_t y) const;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001080 bool isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001081 std::string getApplicationWindowLabelLocked(const sp<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082 const sp<InputWindowHandle>& windowHandle);
1083
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001084 std::string checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001085 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1086 const char* targetType);
1087
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 // Manage the dispatch cycle for a single connection.
1089 // These methods are deliberately not Interruptible because doing all of the work
1090 // with the mutex held makes it easier to ensure that connection invariants are maintained.
1091 // If needed, the methods post commands to run later once the critical bits are done.
1092 void prepareDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1093 EventEntry* eventEntry, const InputTarget* inputTarget);
1094 void enqueueDispatchEntriesLocked(nsecs_t currentTime, const sp<Connection>& connection,
1095 EventEntry* eventEntry, const InputTarget* inputTarget);
1096 void enqueueDispatchEntryLocked(const sp<Connection>& connection,
1097 EventEntry* eventEntry, const InputTarget* inputTarget, int32_t dispatchMode);
1098 void startDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
1099 void finishDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1100 uint32_t seq, bool handled);
1101 void abortBrokenDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1102 bool notify);
1103 void drainDispatchQueueLocked(Queue<DispatchEntry>* queue);
1104 void releaseDispatchEntryLocked(DispatchEntry* dispatchEntry);
1105 static int handleReceiveCallback(int fd, int events, void* data);
1106
1107 void synthesizeCancelationEventsForAllConnectionsLocked(
1108 const CancelationOptions& options);
Michael Wrightfa13dcf2015-06-12 13:25:11 +01001109 void synthesizeCancelationEventsForMonitorsLocked(const CancelationOptions& options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001110 void synthesizeCancelationEventsForInputChannelLocked(const sp<InputChannel>& channel,
1111 const CancelationOptions& options);
1112 void synthesizeCancelationEventsForConnectionLocked(const sp<Connection>& connection,
1113 const CancelationOptions& options);
1114
1115 // Splitting motion events across windows.
1116 MotionEntry* splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds);
1117
1118 // Reset and drop everything the dispatcher is doing.
1119 void resetAndDropEverythingLocked(const char* reason);
1120
1121 // Dump state.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001122 void dumpDispatchStateLocked(std::string& dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123 void logDispatchStateLocked();
1124
1125 // Registration.
1126 void removeMonitorChannelLocked(const sp<InputChannel>& inputChannel);
1127 status_t unregisterInputChannelLocked(const sp<InputChannel>& inputChannel, bool notify);
1128
1129 // Add or remove a connection to the mActiveConnections vector.
1130 void activateConnectionLocked(Connection* connection);
1131 void deactivateConnectionLocked(Connection* connection);
1132
1133 // Interesting events that we might like to log or tell the framework about.
1134 void onDispatchCycleFinishedLocked(
1135 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled);
1136 void onDispatchCycleBrokenLocked(
1137 nsecs_t currentTime, const sp<Connection>& connection);
1138 void onANRLocked(
1139 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
1140 const sp<InputWindowHandle>& windowHandle,
1141 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason);
1142
1143 // Outbound policy interactions.
1144 void doNotifyConfigurationChangedInterruptible(CommandEntry* commandEntry);
1145 void doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry);
1146 void doNotifyANRLockedInterruptible(CommandEntry* commandEntry);
1147 void doInterceptKeyBeforeDispatchingLockedInterruptible(CommandEntry* commandEntry);
1148 void doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry);
1149 bool afterKeyEventLockedInterruptible(const sp<Connection>& connection,
1150 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled);
1151 bool afterMotionEventLockedInterruptible(const sp<Connection>& connection,
1152 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled);
1153 void doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry);
1154 void initializeKeyEvent(KeyEvent* event, const KeyEntry* entry);
1155
1156 // Statistics gathering.
1157 void updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
1158 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication);
1159 void traceInboundQueueLengthLocked();
1160 void traceOutboundQueueLengthLocked(const sp<Connection>& connection);
1161 void traceWaitQueueLengthLocked(const sp<Connection>& connection);
1162};
1163
1164/* Enqueues and dispatches input events, endlessly. */
1165class InputDispatcherThread : public Thread {
1166public:
1167 explicit InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher);
1168 ~InputDispatcherThread();
1169
1170private:
1171 virtual bool threadLoop();
1172
1173 sp<InputDispatcherInterface> mDispatcher;
1174};
1175
1176} // namespace android
1177
1178#endif // _UI_INPUT_DISPATCHER_H