blob: 5efb2fa05ba7fb56176e05f1b9378ef342b098af [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>
Robert Carr3720ed02018-08-08 16:08:27 -070021#include <input/InputApplication.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080022#include <input/InputTransport.h>
Robert Carr3720ed02018-08-08 16:08:27 -070023#include <input/InputWindow.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080024#include <utils/KeyedVector.h>
25#include <utils/Vector.h>
26#include <utils/threads.h>
27#include <utils/Timers.h>
28#include <utils/RefBase.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080029#include <utils/Looper.h>
30#include <utils/BitSet.h>
31#include <cutils/atomic.h>
32
33#include <stddef.h>
34#include <unistd.h>
35#include <limits.h>
Arthur Hungb92218b2018-08-14 12:00:21 +080036#include <unordered_map>
Michael Wrightd02c5b62014-02-10 15:10:22 -080037
Michael Wrightd02c5b62014-02-10 15:10:22 -080038#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
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800349 /* Registers input channels that may be used as targets for input events.
350 * If inputWindowHandle is null, and displayId is not ADISPLAY_ID_NONE,
351 * the channel will receive a copy of all input events form the specific displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -0800352 *
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800353 * This method may be called on any thread (usually by the input manager).
Michael Wrightd02c5b62014-02-10 15:10:22 -0800354 */
355 virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel,
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800356 const sp<InputWindowHandle>& inputWindowHandle, int32_t displayId) = 0;
357
358 /* Unregister input channels that will no longer receive input events.
359 *
360 * This method may be called on any thread (usually by the input manager).
361 */
Michael Wrightd02c5b62014-02-10 15:10:22 -0800362 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel) = 0;
363};
364
365/* Dispatches events to input targets. Some functions of the input dispatcher, such as
366 * identifying input targets, are controlled by a separate policy object.
367 *
368 * IMPORTANT INVARIANT:
369 * Because the policy can potentially block or cause re-entrance into the input dispatcher,
370 * the input dispatcher never calls into the policy while holding its internal locks.
371 * The implementation is also carefully designed to recover from scenarios such as an
372 * input channel becoming unregistered while identifying input targets or processing timeouts.
373 *
374 * Methods marked 'Locked' must be called with the lock acquired.
375 *
376 * Methods marked 'LockedInterruptible' must be called with the lock acquired but
377 * may during the course of their execution release the lock, call into the policy, and
378 * then reacquire the lock. The caller is responsible for recovering gracefully.
379 *
380 * A 'LockedInterruptible' method may called a 'Locked' method, but NOT vice-versa.
381 */
382class InputDispatcher : public InputDispatcherInterface {
383protected:
384 virtual ~InputDispatcher();
385
386public:
387 explicit InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy);
388
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800389 virtual void dump(std::string& dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800390 virtual void monitor();
391
392 virtual void dispatchOnce();
393
394 virtual void notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args);
395 virtual void notifyKey(const NotifyKeyArgs* args);
396 virtual void notifyMotion(const NotifyMotionArgs* args);
397 virtual void notifySwitch(const NotifySwitchArgs* args);
398 virtual void notifyDeviceReset(const NotifyDeviceResetArgs* args);
399
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800400 virtual int32_t injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800401 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
402 uint32_t policyFlags);
403
Arthur Hungb92218b2018-08-14 12:00:21 +0800404 virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles,
405 int32_t displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +0800406 virtual void setFocusedApplication(int32_t displayId,
407 const sp<InputApplicationHandle>& inputApplicationHandle);
408 virtual void setFocusedDisplay(int32_t displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800409 virtual void setInputDispatchMode(bool enabled, bool frozen);
410 virtual void setInputFilterEnabled(bool enabled);
411
412 virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel,
413 const sp<InputChannel>& toChannel);
414
415 virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel,
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800416 const sp<InputWindowHandle>& inputWindowHandle, int32_t displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800417 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel);
418
419private:
420 template <typename T>
421 struct Link {
422 T* next;
423 T* prev;
424
425 protected:
Yi Kong9b14ac62018-07-17 13:48:38 -0700426 inline Link() : next(nullptr), prev(nullptr) { }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800427 };
428
429 struct InjectionState {
430 mutable int32_t refCount;
431
432 int32_t injectorPid;
433 int32_t injectorUid;
434 int32_t injectionResult; // initially INPUT_EVENT_INJECTION_PENDING
435 bool injectionIsAsync; // set to true if injection is not waiting for the result
436 int32_t pendingForegroundDispatches; // the number of foreground dispatches in progress
437
438 InjectionState(int32_t injectorPid, int32_t injectorUid);
439 void release();
440
441 private:
442 ~InjectionState();
443 };
444
445 struct EventEntry : Link<EventEntry> {
446 enum {
447 TYPE_CONFIGURATION_CHANGED,
448 TYPE_DEVICE_RESET,
449 TYPE_KEY,
450 TYPE_MOTION
451 };
452
453 mutable int32_t refCount;
454 int32_t type;
455 nsecs_t eventTime;
456 uint32_t policyFlags;
457 InjectionState* injectionState;
458
459 bool dispatchInProgress; // initially false, set to true while dispatching
460
Yi Kong9b14ac62018-07-17 13:48:38 -0700461 inline bool isInjected() const { return injectionState != nullptr; }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800462
463 void release();
464
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800465 virtual void appendDescription(std::string& msg) const = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800466
467 protected:
468 EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags);
469 virtual ~EventEntry();
470 void releaseInjectionState();
471 };
472
473 struct ConfigurationChangedEntry : EventEntry {
Chih-Hung Hsieh6d2ede12016-09-01 11:28:23 -0700474 explicit ConfigurationChangedEntry(nsecs_t eventTime);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800475 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800476
477 protected:
478 virtual ~ConfigurationChangedEntry();
479 };
480
481 struct DeviceResetEntry : EventEntry {
482 int32_t deviceId;
483
484 DeviceResetEntry(nsecs_t eventTime, int32_t deviceId);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800485 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800486
487 protected:
488 virtual ~DeviceResetEntry();
489 };
490
491 struct KeyEntry : EventEntry {
492 int32_t deviceId;
493 uint32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100494 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800495 int32_t action;
496 int32_t flags;
497 int32_t keyCode;
498 int32_t scanCode;
499 int32_t metaState;
500 int32_t repeatCount;
501 nsecs_t downTime;
502
503 bool syntheticRepeat; // set to true for synthetic key repeats
504
505 enum InterceptKeyResult {
506 INTERCEPT_KEY_RESULT_UNKNOWN,
507 INTERCEPT_KEY_RESULT_SKIP,
508 INTERCEPT_KEY_RESULT_CONTINUE,
509 INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER,
510 };
511 InterceptKeyResult interceptKeyResult; // set based on the interception result
512 nsecs_t interceptKeyWakeupTime; // used with INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER
513
514 KeyEntry(nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100515 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags,
516 int32_t action, int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800517 int32_t repeatCount, nsecs_t downTime);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800518 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800519 void recycle();
520
521 protected:
522 virtual ~KeyEntry();
523 };
524
525 struct MotionEntry : EventEntry {
526 nsecs_t eventTime;
527 int32_t deviceId;
528 uint32_t source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800529 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800530 int32_t action;
Michael Wright7b159c92015-05-14 14:48:03 +0100531 int32_t actionButton;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800532 int32_t flags;
533 int32_t metaState;
534 int32_t buttonState;
535 int32_t edgeFlags;
536 float xPrecision;
537 float yPrecision;
538 nsecs_t downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800539 uint32_t pointerCount;
540 PointerProperties pointerProperties[MAX_POINTERS];
541 PointerCoords pointerCoords[MAX_POINTERS];
542
543 MotionEntry(nsecs_t eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800544 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +0100545 int32_t action, int32_t actionButton, int32_t flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800546 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800547 float xPrecision, float yPrecision, nsecs_t downTime, uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -0800548 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
549 float xOffset, float yOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800550 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800551
552 protected:
553 virtual ~MotionEntry();
554 };
555
556 // Tracks the progress of dispatching a particular event to a particular connection.
557 struct DispatchEntry : Link<DispatchEntry> {
558 const uint32_t seq; // unique sequence number, never 0
559
560 EventEntry* eventEntry; // the event to dispatch
561 int32_t targetFlags;
562 float xOffset;
563 float yOffset;
564 float scaleFactor;
565 nsecs_t deliveryTime; // time when the event was actually delivered
566
567 // Set to the resolved action and flags when the event is enqueued.
568 int32_t resolvedAction;
569 int32_t resolvedFlags;
570
571 DispatchEntry(EventEntry* eventEntry,
572 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor);
573 ~DispatchEntry();
574
575 inline bool hasForegroundTarget() const {
576 return targetFlags & InputTarget::FLAG_FOREGROUND;
577 }
578
579 inline bool isSplit() const {
580 return targetFlags & InputTarget::FLAG_SPLIT;
581 }
582
583 private:
584 static volatile int32_t sNextSeqAtomic;
585
586 static uint32_t nextSeq();
587 };
588
589 // A command entry captures state and behavior for an action to be performed in the
590 // dispatch loop after the initial processing has taken place. It is essentially
591 // a kind of continuation used to postpone sensitive policy interactions to a point
592 // in the dispatch loop where it is safe to release the lock (generally after finishing
593 // the critical parts of the dispatch cycle).
594 //
595 // The special thing about commands is that they can voluntarily release and reacquire
596 // the dispatcher lock at will. Initially when the command starts running, the
597 // dispatcher lock is held. However, if the command needs to call into the policy to
598 // do some work, it can release the lock, do the work, then reacquire the lock again
599 // before returning.
600 //
601 // This mechanism is a bit clunky but it helps to preserve the invariant that the dispatch
602 // never calls into the policy while holding its lock.
603 //
604 // Commands are implicitly 'LockedInterruptible'.
605 struct CommandEntry;
606 typedef void (InputDispatcher::*Command)(CommandEntry* commandEntry);
607
608 class Connection;
609 struct CommandEntry : Link<CommandEntry> {
Chih-Hung Hsieh6d2ede12016-09-01 11:28:23 -0700610 explicit CommandEntry(Command command);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611 ~CommandEntry();
612
613 Command command;
614
615 // parameters for the command (usage varies by command)
616 sp<Connection> connection;
617 nsecs_t eventTime;
618 KeyEntry* keyEntry;
619 sp<InputApplicationHandle> inputApplicationHandle;
620 sp<InputWindowHandle> inputWindowHandle;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800621 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800622 int32_t userActivityEventType;
623 uint32_t seq;
624 bool handled;
625 };
626
627 // Generic queue implementation.
628 template <typename T>
629 struct Queue {
630 T* head;
631 T* tail;
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800632 uint32_t entryCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800633
Yi Kong9b14ac62018-07-17 13:48:38 -0700634 inline Queue() : head(nullptr), tail(nullptr), entryCount(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800635 }
636
637 inline bool isEmpty() const {
638 return !head;
639 }
640
641 inline void enqueueAtTail(T* entry) {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800642 entryCount++;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800643 entry->prev = tail;
644 if (tail) {
645 tail->next = entry;
646 } else {
647 head = entry;
648 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700649 entry->next = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800650 tail = entry;
651 }
652
653 inline void enqueueAtHead(T* entry) {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800654 entryCount++;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800655 entry->next = head;
656 if (head) {
657 head->prev = entry;
658 } else {
659 tail = entry;
660 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700661 entry->prev = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800662 head = entry;
663 }
664
665 inline void dequeue(T* entry) {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800666 entryCount--;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800667 if (entry->prev) {
668 entry->prev->next = entry->next;
669 } else {
670 head = entry->next;
671 }
672 if (entry->next) {
673 entry->next->prev = entry->prev;
674 } else {
675 tail = entry->prev;
676 }
677 }
678
679 inline T* dequeueAtHead() {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800680 entryCount--;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681 T* entry = head;
682 head = entry->next;
683 if (head) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700684 head->prev = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800685 } else {
Yi Kong9b14ac62018-07-17 13:48:38 -0700686 tail = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800687 }
688 return entry;
689 }
690
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800691 uint32_t count() const {
692 return entryCount;
693 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800694 };
695
696 /* Specifies which events are to be canceled and why. */
697 struct CancelationOptions {
698 enum Mode {
699 CANCEL_ALL_EVENTS = 0,
700 CANCEL_POINTER_EVENTS = 1,
701 CANCEL_NON_POINTER_EVENTS = 2,
702 CANCEL_FALLBACK_EVENTS = 3,
Tiger Huang721e26f2018-07-24 22:26:19 +0800703
704 /* Cancel events where the display not specified. These events would go to the focused
705 * display. */
706 CANCEL_DISPLAY_UNSPECIFIED_EVENTS = 4,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800707 };
708
709 // The criterion to use to determine which events should be canceled.
710 Mode mode;
711
712 // Descriptive reason for the cancelation.
713 const char* reason;
714
715 // The specific keycode of the key event to cancel, or -1 to cancel any key event.
716 int32_t keyCode;
717
718 // The specific device id of events to cancel, or -1 to cancel events from any device.
719 int32_t deviceId;
720
721 CancelationOptions(Mode mode, const char* reason) :
722 mode(mode), reason(reason), keyCode(-1), deviceId(-1) { }
723 };
724
725 /* Tracks dispatched key and motion event state so that cancelation events can be
726 * synthesized when events are dropped. */
727 class InputState {
728 public:
729 InputState();
730 ~InputState();
731
732 // Returns true if there is no state to be canceled.
733 bool isNeutral() const;
734
735 // Returns true if the specified source is known to have received a hover enter
736 // motion event.
737 bool isHovering(int32_t deviceId, uint32_t source, int32_t displayId) const;
738
739 // Records tracking information for a key event that has just been published.
740 // Returns true if the event should be delivered, false if it is inconsistent
741 // and should be skipped.
742 bool trackKey(const KeyEntry* entry, int32_t action, int32_t flags);
743
744 // Records tracking information for a motion event that has just been published.
745 // Returns true if the event should be delivered, false if it is inconsistent
746 // and should be skipped.
747 bool trackMotion(const MotionEntry* entry, int32_t action, int32_t flags);
748
749 // Synthesizes cancelation events for the current state and resets the tracked state.
750 void synthesizeCancelationEvents(nsecs_t currentTime,
751 Vector<EventEntry*>& outEvents, const CancelationOptions& options);
752
753 // Clears the current state.
754 void clear();
755
756 // Copies pointer-related parts of the input state to another instance.
757 void copyPointerStateTo(InputState& other) const;
758
759 // Gets the fallback key associated with a keycode.
760 // Returns -1 if none.
761 // Returns AKEYCODE_UNKNOWN if we are only dispatching the unhandled key to the policy.
762 int32_t getFallbackKey(int32_t originalKeyCode);
763
764 // Sets the fallback key for a particular keycode.
765 void setFallbackKey(int32_t originalKeyCode, int32_t fallbackKeyCode);
766
767 // Removes the fallback key for a particular keycode.
768 void removeFallbackKey(int32_t originalKeyCode);
769
770 inline const KeyedVector<int32_t, int32_t>& getFallbackKeys() const {
771 return mFallbackKeys;
772 }
773
774 private:
775 struct KeyMemento {
776 int32_t deviceId;
777 uint32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100778 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779 int32_t keyCode;
780 int32_t scanCode;
781 int32_t metaState;
782 int32_t flags;
783 nsecs_t downTime;
784 uint32_t policyFlags;
785 };
786
787 struct MotionMemento {
788 int32_t deviceId;
789 uint32_t source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800790 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800791 int32_t flags;
792 float xPrecision;
793 float yPrecision;
794 nsecs_t downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800795 uint32_t pointerCount;
796 PointerProperties pointerProperties[MAX_POINTERS];
797 PointerCoords pointerCoords[MAX_POINTERS];
798 bool hovering;
799 uint32_t policyFlags;
800
801 void setPointers(const MotionEntry* entry);
802 };
803
804 Vector<KeyMemento> mKeyMementos;
805 Vector<MotionMemento> mMotionMementos;
806 KeyedVector<int32_t, int32_t> mFallbackKeys;
807
808 ssize_t findKeyMemento(const KeyEntry* entry) const;
809 ssize_t findMotionMemento(const MotionEntry* entry, bool hovering) const;
810
811 void addKeyMemento(const KeyEntry* entry, int32_t flags);
812 void addMotionMemento(const MotionEntry* entry, int32_t flags, bool hovering);
813
814 static bool shouldCancelKey(const KeyMemento& memento,
815 const CancelationOptions& options);
816 static bool shouldCancelMotion(const MotionMemento& memento,
817 const CancelationOptions& options);
818 };
819
820 /* Manages the dispatch state associated with a single input channel. */
821 class Connection : public RefBase {
822 protected:
823 virtual ~Connection();
824
825 public:
826 enum Status {
827 // Everything is peachy.
828 STATUS_NORMAL,
829 // An unrecoverable communication error has occurred.
830 STATUS_BROKEN,
831 // The input channel has been unregistered.
832 STATUS_ZOMBIE
833 };
834
835 Status status;
836 sp<InputChannel> inputChannel; // never null
837 sp<InputWindowHandle> inputWindowHandle; // may be null
838 bool monitor;
839 InputPublisher inputPublisher;
840 InputState inputState;
841
842 // True if the socket is full and no further events can be published until
843 // the application consumes some of the input.
844 bool inputPublisherBlocked;
845
846 // Queue of events that need to be published to the connection.
847 Queue<DispatchEntry> outboundQueue;
848
849 // Queue of events that have been published to the connection but that have not
850 // yet received a "finished" response from the application.
851 Queue<DispatchEntry> waitQueue;
852
853 explicit Connection(const sp<InputChannel>& inputChannel,
854 const sp<InputWindowHandle>& inputWindowHandle, bool monitor);
855
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -0800856 inline const std::string getInputChannelName() const { return inputChannel->getName(); }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800857
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -0800858 const std::string getWindowName() const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800859 const char* getStatusLabel() const;
860
861 DispatchEntry* findWaitQueueEntry(uint32_t seq);
862 };
863
864 enum DropReason {
865 DROP_REASON_NOT_DROPPED = 0,
866 DROP_REASON_POLICY = 1,
867 DROP_REASON_APP_SWITCH = 2,
868 DROP_REASON_DISABLED = 3,
869 DROP_REASON_BLOCKED = 4,
870 DROP_REASON_STALE = 5,
871 };
872
873 sp<InputDispatcherPolicyInterface> mPolicy;
874 InputDispatcherConfiguration mConfig;
875
876 Mutex mLock;
877
878 Condition mDispatcherIsAliveCondition;
879
880 sp<Looper> mLooper;
881
882 EventEntry* mPendingEvent;
883 Queue<EventEntry> mInboundQueue;
884 Queue<EventEntry> mRecentQueue;
885 Queue<CommandEntry> mCommandQueue;
886
Michael Wright3a981722015-06-10 15:26:13 +0100887 DropReason mLastDropReason;
888
Michael Wrightd02c5b62014-02-10 15:10:22 -0800889 void dispatchOnceInnerLocked(nsecs_t* nextWakeupTime);
890
891 // Enqueues an inbound event. Returns true if mLooper->wake() should be called.
892 bool enqueueInboundEventLocked(EventEntry* entry);
893
894 // Cleans up input state when dropping an inbound event.
895 void dropInboundEventLocked(EventEntry* entry, DropReason dropReason);
896
897 // Adds an event to a queue of recent events for debugging purposes.
898 void addRecentEventLocked(EventEntry* entry);
899
900 // App switch latency optimization.
901 bool mAppSwitchSawKeyDown;
902 nsecs_t mAppSwitchDueTime;
903
904 static bool isAppSwitchKeyCode(int32_t keyCode);
905 bool isAppSwitchKeyEventLocked(KeyEntry* keyEntry);
906 bool isAppSwitchPendingLocked();
907 void resetPendingAppSwitchLocked(bool handled);
908
909 // Stale event latency optimization.
910 static bool isStaleEventLocked(nsecs_t currentTime, EventEntry* entry);
911
912 // Blocked event latency optimization. Drops old events when the user intends
913 // to transfer focus to a new application.
914 EventEntry* mNextUnblockedEvent;
915
916 sp<InputWindowHandle> findTouchedWindowAtLocked(int32_t displayId, int32_t x, int32_t y);
917
918 // All registered connections mapped by channel file descriptor.
919 KeyedVector<int, sp<Connection> > mConnectionsByFd;
920
921 ssize_t getConnectionIndexLocked(const sp<InputChannel>& inputChannel);
922
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800923 // Input channels that will receive a copy of all input events sent to the provided display.
924 std::unordered_map<int32_t, Vector<sp<InputChannel>>> mMonitoringChannelsByDisplay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925
926 // Event injection and synchronization.
927 Condition mInjectionResultAvailableCondition;
928 bool hasInjectionPermission(int32_t injectorPid, int32_t injectorUid);
929 void setInjectionResultLocked(EventEntry* entry, int32_t injectionResult);
930
931 Condition mInjectionSyncFinishedCondition;
932 void incrementPendingForegroundDispatchesLocked(EventEntry* entry);
933 void decrementPendingForegroundDispatchesLocked(EventEntry* entry);
934
935 // Key repeat tracking.
936 struct KeyRepeatState {
937 KeyEntry* lastKeyEntry; // or null if no repeat
938 nsecs_t nextRepeatTime;
939 } mKeyRepeatState;
940
941 void resetKeyRepeatLocked();
942 KeyEntry* synthesizeKeyRepeatLocked(nsecs_t currentTime);
943
Michael Wright78f24442014-08-06 15:55:28 -0700944 // Key replacement tracking
945 struct KeyReplacement {
946 int32_t keyCode;
947 int32_t deviceId;
948 bool operator==(const KeyReplacement& rhs) const {
949 return keyCode == rhs.keyCode && deviceId == rhs.deviceId;
950 }
951 bool operator<(const KeyReplacement& rhs) const {
952 return keyCode != rhs.keyCode ? keyCode < rhs.keyCode : deviceId < rhs.deviceId;
953 }
954 };
955 // Maps the key code replaced, device id tuple to the key code it was replaced with
956 KeyedVector<KeyReplacement, int32_t> mReplacedKeys;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -0500957 // Process certain Meta + Key combinations
958 void accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
959 int32_t& keyCode, int32_t& metaState);
Michael Wright78f24442014-08-06 15:55:28 -0700960
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961 // Deferred command processing.
962 bool haveCommandsLocked() const;
963 bool runCommandsLockedInterruptible();
964 CommandEntry* postCommandLocked(Command command);
965
966 // Input filter processing.
967 bool shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args);
968 bool shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args);
969
970 // Inbound event processing.
971 void drainInboundQueueLocked();
972 void releasePendingEventLocked();
973 void releaseInboundEventLocked(EventEntry* entry);
974
975 // Dispatch state.
976 bool mDispatchEnabled;
977 bool mDispatchFrozen;
978 bool mInputFilterEnabled;
979
Arthur Hungb92218b2018-08-14 12:00:21 +0800980 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>> mWindowHandlesByDisplay;
981 // Get window handles by display, return an empty vector if not found.
982 Vector<sp<InputWindowHandle>> getWindowHandlesLocked(int32_t displayId) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800983 sp<InputWindowHandle> getWindowHandleLocked(const sp<InputChannel>& inputChannel) const;
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +0000984 bool hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800985
986 // Focus tracking for keys, trackball, etc.
Tiger Huang721e26f2018-07-24 22:26:19 +0800987 std::unordered_map<int32_t, sp<InputWindowHandle>> mFocusedWindowHandlesByDisplay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800988
989 // Focus tracking for touch.
990 struct TouchedWindow {
991 sp<InputWindowHandle> windowHandle;
992 int32_t targetFlags;
993 BitSet32 pointerIds; // zero unless target flag FLAG_SPLIT is set
994 };
995 struct TouchState {
996 bool down;
997 bool split;
998 int32_t deviceId; // id of the device that is currently down, others are rejected
999 uint32_t source; // source of the device that is current down, others are rejected
1000 int32_t displayId; // id to the display that currently has a touch, others are rejected
1001 Vector<TouchedWindow> windows;
1002
1003 TouchState();
1004 ~TouchState();
1005 void reset();
1006 void copyFrom(const TouchState& other);
1007 void addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
1008 int32_t targetFlags, BitSet32 pointerIds);
1009 void removeWindow(const sp<InputWindowHandle>& windowHandle);
1010 void filterNonAsIsTouchWindows();
1011 sp<InputWindowHandle> getFirstForegroundWindowHandle() const;
1012 bool isSlippery() const;
1013 };
1014
Jeff Brownf086ddb2014-02-11 14:28:48 -08001015 KeyedVector<int32_t, TouchState> mTouchStatesByDisplay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016 TouchState mTempTouchState;
1017
Tiger Huang721e26f2018-07-24 22:26:19 +08001018 // Focused applications.
1019 std::unordered_map<int32_t, sp<InputApplicationHandle>> mFocusedApplicationHandlesByDisplay;
1020
1021 // Top focused display.
1022 int32_t mFocusedDisplayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023
1024 // Dispatcher state at time of last ANR.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001025 std::string mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026
1027 // Dispatch inbound events.
1028 bool dispatchConfigurationChangedLocked(
1029 nsecs_t currentTime, ConfigurationChangedEntry* entry);
1030 bool dispatchDeviceResetLocked(
1031 nsecs_t currentTime, DeviceResetEntry* entry);
1032 bool dispatchKeyLocked(
1033 nsecs_t currentTime, KeyEntry* entry,
1034 DropReason* dropReason, nsecs_t* nextWakeupTime);
1035 bool dispatchMotionLocked(
1036 nsecs_t currentTime, MotionEntry* entry,
1037 DropReason* dropReason, nsecs_t* nextWakeupTime);
1038 void dispatchEventLocked(nsecs_t currentTime, EventEntry* entry,
1039 const Vector<InputTarget>& inputTargets);
1040
1041 void logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry);
1042 void logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry);
1043
1044 // Keeping track of ANR timeouts.
1045 enum InputTargetWaitCause {
1046 INPUT_TARGET_WAIT_CAUSE_NONE,
1047 INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY,
1048 INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY,
1049 };
1050
1051 InputTargetWaitCause mInputTargetWaitCause;
1052 nsecs_t mInputTargetWaitStartTime;
1053 nsecs_t mInputTargetWaitTimeoutTime;
1054 bool mInputTargetWaitTimeoutExpired;
1055 sp<InputApplicationHandle> mInputTargetWaitApplicationHandle;
1056
1057 // Contains the last window which received a hover event.
1058 sp<InputWindowHandle> mLastHoverWindowHandle;
1059
1060 // Finding targets for input events.
1061 int32_t handleTargetsNotReadyLocked(nsecs_t currentTime, const EventEntry* entry,
1062 const sp<InputApplicationHandle>& applicationHandle,
1063 const sp<InputWindowHandle>& windowHandle,
1064 nsecs_t* nextWakeupTime, const char* reason);
1065 void resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1066 const sp<InputChannel>& inputChannel);
1067 nsecs_t getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime);
1068 void resetANRTimeoutsLocked();
1069
Tiger Huang721e26f2018-07-24 22:26:19 +08001070 int32_t getTargetDisplayId(const EventEntry* entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071 int32_t findFocusedWindowTargetsLocked(nsecs_t currentTime, const EventEntry* entry,
1072 Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime);
1073 int32_t findTouchedWindowTargetsLocked(nsecs_t currentTime, const MotionEntry* entry,
1074 Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1075 bool* outConflictingPointerActions);
1076
1077 void addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1078 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001079 void addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets, int32_t displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080
1081 void pokeUserActivityLocked(const EventEntry* eventEntry);
1082 bool checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1083 const InjectionState* injectionState);
1084 bool isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1085 int32_t x, int32_t y) const;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001086 bool isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001087 std::string getApplicationWindowLabelLocked(const sp<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 const sp<InputWindowHandle>& windowHandle);
1089
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001090 std::string checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001091 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1092 const char* targetType);
1093
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094 // Manage the dispatch cycle for a single connection.
1095 // These methods are deliberately not Interruptible because doing all of the work
1096 // with the mutex held makes it easier to ensure that connection invariants are maintained.
1097 // If needed, the methods post commands to run later once the critical bits are done.
1098 void prepareDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1099 EventEntry* eventEntry, const InputTarget* inputTarget);
1100 void enqueueDispatchEntriesLocked(nsecs_t currentTime, const sp<Connection>& connection,
1101 EventEntry* eventEntry, const InputTarget* inputTarget);
1102 void enqueueDispatchEntryLocked(const sp<Connection>& connection,
1103 EventEntry* eventEntry, const InputTarget* inputTarget, int32_t dispatchMode);
1104 void startDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
1105 void finishDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1106 uint32_t seq, bool handled);
1107 void abortBrokenDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1108 bool notify);
1109 void drainDispatchQueueLocked(Queue<DispatchEntry>* queue);
1110 void releaseDispatchEntryLocked(DispatchEntry* dispatchEntry);
1111 static int handleReceiveCallback(int fd, int events, void* data);
1112
1113 void synthesizeCancelationEventsForAllConnectionsLocked(
1114 const CancelationOptions& options);
Michael Wrightfa13dcf2015-06-12 13:25:11 +01001115 void synthesizeCancelationEventsForMonitorsLocked(const CancelationOptions& options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001116 void synthesizeCancelationEventsForInputChannelLocked(const sp<InputChannel>& channel,
1117 const CancelationOptions& options);
1118 void synthesizeCancelationEventsForConnectionLocked(const sp<Connection>& connection,
1119 const CancelationOptions& options);
1120
1121 // Splitting motion events across windows.
1122 MotionEntry* splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds);
1123
1124 // Reset and drop everything the dispatcher is doing.
1125 void resetAndDropEverythingLocked(const char* reason);
1126
1127 // Dump state.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001128 void dumpDispatchStateLocked(std::string& dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001129 void logDispatchStateLocked();
1130
1131 // Registration.
1132 void removeMonitorChannelLocked(const sp<InputChannel>& inputChannel);
1133 status_t unregisterInputChannelLocked(const sp<InputChannel>& inputChannel, bool notify);
1134
1135 // Add or remove a connection to the mActiveConnections vector.
1136 void activateConnectionLocked(Connection* connection);
1137 void deactivateConnectionLocked(Connection* connection);
1138
1139 // Interesting events that we might like to log or tell the framework about.
1140 void onDispatchCycleFinishedLocked(
1141 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled);
1142 void onDispatchCycleBrokenLocked(
1143 nsecs_t currentTime, const sp<Connection>& connection);
1144 void onANRLocked(
1145 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
1146 const sp<InputWindowHandle>& windowHandle,
1147 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason);
1148
1149 // Outbound policy interactions.
1150 void doNotifyConfigurationChangedInterruptible(CommandEntry* commandEntry);
1151 void doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry);
1152 void doNotifyANRLockedInterruptible(CommandEntry* commandEntry);
1153 void doInterceptKeyBeforeDispatchingLockedInterruptible(CommandEntry* commandEntry);
1154 void doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry);
1155 bool afterKeyEventLockedInterruptible(const sp<Connection>& connection,
1156 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled);
1157 bool afterMotionEventLockedInterruptible(const sp<Connection>& connection,
1158 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled);
1159 void doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry);
1160 void initializeKeyEvent(KeyEvent* event, const KeyEntry* entry);
1161
1162 // Statistics gathering.
1163 void updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
1164 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication);
1165 void traceInboundQueueLengthLocked();
1166 void traceOutboundQueueLengthLocked(const sp<Connection>& connection);
1167 void traceWaitQueueLengthLocked(const sp<Connection>& connection);
1168};
1169
1170/* Enqueues and dispatches input events, endlessly. */
1171class InputDispatcherThread : public Thread {
1172public:
1173 explicit InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher);
1174 ~InputDispatcherThread();
1175
1176private:
1177 virtual bool threadLoop();
1178
1179 sp<InputDispatcherInterface> mDispatcher;
1180};
1181
1182} // namespace android
1183
1184#endif // _UI_INPUT_DISPATCHER_H