blob: 5016082958a298629a31ce770c9082050799f177 [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,
Robert Carr803535b2018-08-02 16:38:15 -0700211 const sp<IBinder>& token,
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. */
Robert Carr803535b2018-08-02 16:38:15 -0700215 virtual void notifyInputChannelBroken(const sp<IBinder>& token) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216
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. */
Robert Carr803535b2018-08-02 16:38:15 -0700246 virtual nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>& token,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800247 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. */
Robert Carr803535b2018-08-02 16:38:15 -0700251 virtual bool dispatchUnhandledKey(const sp<IBinder>& token,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800252 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 */
Robert Carr803535b2018-08-02 16:38:15 -0700355 virtual status_t registerInputChannel(
356 const sp<InputChannel>& inputChannel, int32_t displayId) = 0;
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800357
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,
Robert Carr803535b2018-08-02 16:38:15 -0700416 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;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800620 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800621 int32_t userActivityEventType;
622 uint32_t seq;
623 bool handled;
Robert Carr803535b2018-08-02 16:38:15 -0700624 sp<InputChannel> inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800625 };
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
Michael Wrightd02c5b62014-02-10 15:10:22 -0800837 bool monitor;
838 InputPublisher inputPublisher;
839 InputState inputState;
840
841 // True if the socket is full and no further events can be published until
842 // the application consumes some of the input.
843 bool inputPublisherBlocked;
844
845 // Queue of events that need to be published to the connection.
846 Queue<DispatchEntry> outboundQueue;
847
848 // Queue of events that have been published to the connection but that have not
849 // yet received a "finished" response from the application.
850 Queue<DispatchEntry> waitQueue;
851
Robert Carr803535b2018-08-02 16:38:15 -0700852 explicit Connection(const sp<InputChannel>& inputChannel, bool monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800853
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -0800854 inline const std::string getInputChannelName() const { return inputChannel->getName(); }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800855
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -0800856 const std::string getWindowName() const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800857 const char* getStatusLabel() const;
858
859 DispatchEntry* findWaitQueueEntry(uint32_t seq);
860 };
861
862 enum DropReason {
863 DROP_REASON_NOT_DROPPED = 0,
864 DROP_REASON_POLICY = 1,
865 DROP_REASON_APP_SWITCH = 2,
866 DROP_REASON_DISABLED = 3,
867 DROP_REASON_BLOCKED = 4,
868 DROP_REASON_STALE = 5,
869 };
870
871 sp<InputDispatcherPolicyInterface> mPolicy;
872 InputDispatcherConfiguration mConfig;
873
874 Mutex mLock;
875
876 Condition mDispatcherIsAliveCondition;
877
878 sp<Looper> mLooper;
879
880 EventEntry* mPendingEvent;
881 Queue<EventEntry> mInboundQueue;
882 Queue<EventEntry> mRecentQueue;
883 Queue<CommandEntry> mCommandQueue;
884
Michael Wright3a981722015-06-10 15:26:13 +0100885 DropReason mLastDropReason;
886
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887 void dispatchOnceInnerLocked(nsecs_t* nextWakeupTime);
888
889 // Enqueues an inbound event. Returns true if mLooper->wake() should be called.
890 bool enqueueInboundEventLocked(EventEntry* entry);
891
892 // Cleans up input state when dropping an inbound event.
893 void dropInboundEventLocked(EventEntry* entry, DropReason dropReason);
894
895 // Adds an event to a queue of recent events for debugging purposes.
896 void addRecentEventLocked(EventEntry* entry);
897
898 // App switch latency optimization.
899 bool mAppSwitchSawKeyDown;
900 nsecs_t mAppSwitchDueTime;
901
902 static bool isAppSwitchKeyCode(int32_t keyCode);
903 bool isAppSwitchKeyEventLocked(KeyEntry* keyEntry);
904 bool isAppSwitchPendingLocked();
905 void resetPendingAppSwitchLocked(bool handled);
906
907 // Stale event latency optimization.
908 static bool isStaleEventLocked(nsecs_t currentTime, EventEntry* entry);
909
910 // Blocked event latency optimization. Drops old events when the user intends
911 // to transfer focus to a new application.
912 EventEntry* mNextUnblockedEvent;
913
914 sp<InputWindowHandle> findTouchedWindowAtLocked(int32_t displayId, int32_t x, int32_t y);
915
916 // All registered connections mapped by channel file descriptor.
917 KeyedVector<int, sp<Connection> > mConnectionsByFd;
918
919 ssize_t getConnectionIndexLocked(const sp<InputChannel>& inputChannel);
920
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800921 // Input channels that will receive a copy of all input events sent to the provided display.
922 std::unordered_map<int32_t, Vector<sp<InputChannel>>> mMonitoringChannelsByDisplay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923
924 // Event injection and synchronization.
925 Condition mInjectionResultAvailableCondition;
926 bool hasInjectionPermission(int32_t injectorPid, int32_t injectorUid);
927 void setInjectionResultLocked(EventEntry* entry, int32_t injectionResult);
928
929 Condition mInjectionSyncFinishedCondition;
930 void incrementPendingForegroundDispatchesLocked(EventEntry* entry);
931 void decrementPendingForegroundDispatchesLocked(EventEntry* entry);
932
933 // Key repeat tracking.
934 struct KeyRepeatState {
935 KeyEntry* lastKeyEntry; // or null if no repeat
936 nsecs_t nextRepeatTime;
937 } mKeyRepeatState;
938
939 void resetKeyRepeatLocked();
940 KeyEntry* synthesizeKeyRepeatLocked(nsecs_t currentTime);
941
Michael Wright78f24442014-08-06 15:55:28 -0700942 // Key replacement tracking
943 struct KeyReplacement {
944 int32_t keyCode;
945 int32_t deviceId;
946 bool operator==(const KeyReplacement& rhs) const {
947 return keyCode == rhs.keyCode && deviceId == rhs.deviceId;
948 }
949 bool operator<(const KeyReplacement& rhs) const {
950 return keyCode != rhs.keyCode ? keyCode < rhs.keyCode : deviceId < rhs.deviceId;
951 }
952 };
953 // Maps the key code replaced, device id tuple to the key code it was replaced with
954 KeyedVector<KeyReplacement, int32_t> mReplacedKeys;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -0500955 // Process certain Meta + Key combinations
956 void accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
957 int32_t& keyCode, int32_t& metaState);
Michael Wright78f24442014-08-06 15:55:28 -0700958
Michael Wrightd02c5b62014-02-10 15:10:22 -0800959 // Deferred command processing.
960 bool haveCommandsLocked() const;
961 bool runCommandsLockedInterruptible();
962 CommandEntry* postCommandLocked(Command command);
963
964 // Input filter processing.
965 bool shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args);
966 bool shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args);
967
968 // Inbound event processing.
969 void drainInboundQueueLocked();
970 void releasePendingEventLocked();
971 void releaseInboundEventLocked(EventEntry* entry);
972
973 // Dispatch state.
974 bool mDispatchEnabled;
975 bool mDispatchFrozen;
976 bool mInputFilterEnabled;
977
Arthur Hungb92218b2018-08-14 12:00:21 +0800978 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>> mWindowHandlesByDisplay;
979 // Get window handles by display, return an empty vector if not found.
980 Vector<sp<InputWindowHandle>> getWindowHandlesLocked(int32_t displayId) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981 sp<InputWindowHandle> getWindowHandleLocked(const sp<InputChannel>& inputChannel) const;
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +0000982 bool hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800983
984 // Focus tracking for keys, trackball, etc.
Tiger Huang721e26f2018-07-24 22:26:19 +0800985 std::unordered_map<int32_t, sp<InputWindowHandle>> mFocusedWindowHandlesByDisplay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800986
987 // Focus tracking for touch.
988 struct TouchedWindow {
989 sp<InputWindowHandle> windowHandle;
990 int32_t targetFlags;
991 BitSet32 pointerIds; // zero unless target flag FLAG_SPLIT is set
992 };
993 struct TouchState {
994 bool down;
995 bool split;
996 int32_t deviceId; // id of the device that is currently down, others are rejected
997 uint32_t source; // source of the device that is current down, others are rejected
998 int32_t displayId; // id to the display that currently has a touch, others are rejected
999 Vector<TouchedWindow> windows;
1000
1001 TouchState();
1002 ~TouchState();
1003 void reset();
1004 void copyFrom(const TouchState& other);
1005 void addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
1006 int32_t targetFlags, BitSet32 pointerIds);
1007 void removeWindow(const sp<InputWindowHandle>& windowHandle);
Robert Carr803535b2018-08-02 16:38:15 -07001008 void removeWindowByToken(const sp<IBinder>& token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001009 void filterNonAsIsTouchWindows();
1010 sp<InputWindowHandle> getFirstForegroundWindowHandle() const;
1011 bool isSlippery() const;
1012 };
1013
Jeff Brownf086ddb2014-02-11 14:28:48 -08001014 KeyedVector<int32_t, TouchState> mTouchStatesByDisplay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015 TouchState mTempTouchState;
1016
Tiger Huang721e26f2018-07-24 22:26:19 +08001017 // Focused applications.
1018 std::unordered_map<int32_t, sp<InputApplicationHandle>> mFocusedApplicationHandlesByDisplay;
1019
1020 // Top focused display.
1021 int32_t mFocusedDisplayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001022
1023 // Dispatcher state at time of last ANR.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001024 std::string mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001025
1026 // Dispatch inbound events.
1027 bool dispatchConfigurationChangedLocked(
1028 nsecs_t currentTime, ConfigurationChangedEntry* entry);
1029 bool dispatchDeviceResetLocked(
1030 nsecs_t currentTime, DeviceResetEntry* entry);
1031 bool dispatchKeyLocked(
1032 nsecs_t currentTime, KeyEntry* entry,
1033 DropReason* dropReason, nsecs_t* nextWakeupTime);
1034 bool dispatchMotionLocked(
1035 nsecs_t currentTime, MotionEntry* entry,
1036 DropReason* dropReason, nsecs_t* nextWakeupTime);
1037 void dispatchEventLocked(nsecs_t currentTime, EventEntry* entry,
1038 const Vector<InputTarget>& inputTargets);
1039
1040 void logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry);
1041 void logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry);
1042
1043 // Keeping track of ANR timeouts.
1044 enum InputTargetWaitCause {
1045 INPUT_TARGET_WAIT_CAUSE_NONE,
1046 INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY,
1047 INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY,
1048 };
1049
1050 InputTargetWaitCause mInputTargetWaitCause;
1051 nsecs_t mInputTargetWaitStartTime;
1052 nsecs_t mInputTargetWaitTimeoutTime;
1053 bool mInputTargetWaitTimeoutExpired;
1054 sp<InputApplicationHandle> mInputTargetWaitApplicationHandle;
1055
1056 // Contains the last window which received a hover event.
1057 sp<InputWindowHandle> mLastHoverWindowHandle;
1058
1059 // Finding targets for input events.
1060 int32_t handleTargetsNotReadyLocked(nsecs_t currentTime, const EventEntry* entry,
1061 const sp<InputApplicationHandle>& applicationHandle,
1062 const sp<InputWindowHandle>& windowHandle,
1063 nsecs_t* nextWakeupTime, const char* reason);
Robert Carr803535b2018-08-02 16:38:15 -07001064
1065 void removeWindowByTokenLocked(const sp<IBinder>& token);
1066
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067 void resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1068 const sp<InputChannel>& inputChannel);
1069 nsecs_t getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime);
1070 void resetANRTimeoutsLocked();
1071
Tiger Huang721e26f2018-07-24 22:26:19 +08001072 int32_t getTargetDisplayId(const EventEntry* entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073 int32_t findFocusedWindowTargetsLocked(nsecs_t currentTime, const EventEntry* entry,
1074 Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime);
1075 int32_t findTouchedWindowTargetsLocked(nsecs_t currentTime, const MotionEntry* entry,
1076 Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1077 bool* outConflictingPointerActions);
1078
1079 void addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1080 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001081 void addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets, int32_t displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082
1083 void pokeUserActivityLocked(const EventEntry* eventEntry);
1084 bool checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1085 const InjectionState* injectionState);
1086 bool isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1087 int32_t x, int32_t y) const;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001088 bool isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001089 std::string getApplicationWindowLabelLocked(const sp<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090 const sp<InputWindowHandle>& windowHandle);
1091
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001092 std::string checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001093 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1094 const char* targetType);
1095
Michael Wrightd02c5b62014-02-10 15:10:22 -08001096 // Manage the dispatch cycle for a single connection.
1097 // These methods are deliberately not Interruptible because doing all of the work
1098 // with the mutex held makes it easier to ensure that connection invariants are maintained.
1099 // If needed, the methods post commands to run later once the critical bits are done.
1100 void prepareDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1101 EventEntry* eventEntry, const InputTarget* inputTarget);
1102 void enqueueDispatchEntriesLocked(nsecs_t currentTime, const sp<Connection>& connection,
1103 EventEntry* eventEntry, const InputTarget* inputTarget);
1104 void enqueueDispatchEntryLocked(const sp<Connection>& connection,
1105 EventEntry* eventEntry, const InputTarget* inputTarget, int32_t dispatchMode);
1106 void startDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
1107 void finishDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1108 uint32_t seq, bool handled);
1109 void abortBrokenDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1110 bool notify);
1111 void drainDispatchQueueLocked(Queue<DispatchEntry>* queue);
1112 void releaseDispatchEntryLocked(DispatchEntry* dispatchEntry);
1113 static int handleReceiveCallback(int fd, int events, void* data);
1114
1115 void synthesizeCancelationEventsForAllConnectionsLocked(
1116 const CancelationOptions& options);
Michael Wrightfa13dcf2015-06-12 13:25:11 +01001117 void synthesizeCancelationEventsForMonitorsLocked(const CancelationOptions& options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118 void synthesizeCancelationEventsForInputChannelLocked(const sp<InputChannel>& channel,
1119 const CancelationOptions& options);
1120 void synthesizeCancelationEventsForConnectionLocked(const sp<Connection>& connection,
1121 const CancelationOptions& options);
1122
1123 // Splitting motion events across windows.
1124 MotionEntry* splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds);
1125
1126 // Reset and drop everything the dispatcher is doing.
1127 void resetAndDropEverythingLocked(const char* reason);
1128
1129 // Dump state.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001130 void dumpDispatchStateLocked(std::string& dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131 void logDispatchStateLocked();
1132
1133 // Registration.
1134 void removeMonitorChannelLocked(const sp<InputChannel>& inputChannel);
1135 status_t unregisterInputChannelLocked(const sp<InputChannel>& inputChannel, bool notify);
1136
1137 // Add or remove a connection to the mActiveConnections vector.
1138 void activateConnectionLocked(Connection* connection);
1139 void deactivateConnectionLocked(Connection* connection);
1140
1141 // Interesting events that we might like to log or tell the framework about.
1142 void onDispatchCycleFinishedLocked(
1143 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled);
1144 void onDispatchCycleBrokenLocked(
1145 nsecs_t currentTime, const sp<Connection>& connection);
1146 void onANRLocked(
1147 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
1148 const sp<InputWindowHandle>& windowHandle,
1149 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason);
1150
1151 // Outbound policy interactions.
1152 void doNotifyConfigurationChangedInterruptible(CommandEntry* commandEntry);
1153 void doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry);
1154 void doNotifyANRLockedInterruptible(CommandEntry* commandEntry);
1155 void doInterceptKeyBeforeDispatchingLockedInterruptible(CommandEntry* commandEntry);
1156 void doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry);
1157 bool afterKeyEventLockedInterruptible(const sp<Connection>& connection,
1158 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled);
1159 bool afterMotionEventLockedInterruptible(const sp<Connection>& connection,
1160 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled);
1161 void doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry);
1162 void initializeKeyEvent(KeyEvent* event, const KeyEntry* entry);
1163
1164 // Statistics gathering.
1165 void updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
1166 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication);
1167 void traceInboundQueueLengthLocked();
1168 void traceOutboundQueueLengthLocked(const sp<Connection>& connection);
1169 void traceWaitQueueLengthLocked(const sp<Connection>& connection);
1170};
1171
1172/* Enqueues and dispatches input events, endlessly. */
1173class InputDispatcherThread : public Thread {
1174public:
1175 explicit InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher);
1176 ~InputDispatcherThread();
1177
1178private:
1179 virtual bool threadLoop();
1180
1181 sp<InputDispatcherInterface> mDispatcher;
1182};
1183
1184} // namespace android
1185
1186#endif // _UI_INPUT_DISPATCHER_H