blob: 41f7dee7d64c6a5299837437042e34dac26d4566 [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>
Robert Carr5c8a0262018-10-03 16:30:44 -070032#include <unordered_map>
Michael Wrightd02c5b62014-02-10 15:10:22 -080033
34#include <stddef.h>
35#include <unistd.h>
36#include <limits.h>
Arthur Hungb92218b2018-08-14 12:00:21 +080037#include <unordered_map>
Michael Wrightd02c5b62014-02-10 15:10:22 -080038
Michael Wrightd02c5b62014-02-10 15:10:22 -080039#include "InputListener.h"
Prabir Pradhanf93562f2018-11-29 12:13:37 -080040#include "InputReporter.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080041
42
43namespace android {
44
45/*
46 * Constants used to report the outcome of input event injection.
47 */
48enum {
49 /* (INTERNAL USE ONLY) Specifies that injection is pending and its outcome is unknown. */
50 INPUT_EVENT_INJECTION_PENDING = -1,
51
52 /* Injection succeeded. */
53 INPUT_EVENT_INJECTION_SUCCEEDED = 0,
54
55 /* Injection failed because the injector did not have permission to inject
56 * into the application with input focus. */
57 INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1,
58
59 /* Injection failed because there were no available input targets. */
60 INPUT_EVENT_INJECTION_FAILED = 2,
61
62 /* Injection failed due to a timeout. */
63 INPUT_EVENT_INJECTION_TIMED_OUT = 3
64};
65
66/*
67 * Constants used to determine the input event injection synchronization mode.
68 */
69enum {
70 /* Injection is asynchronous and is assumed always to be successful. */
71 INPUT_EVENT_INJECTION_SYNC_NONE = 0,
72
73 /* Waits for previous events to be dispatched so that the input dispatcher can determine
74 * whether input event injection willbe permitted based on the current input focus.
75 * Does not wait for the input event to finish processing. */
76 INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_RESULT = 1,
77
78 /* Waits for the input event to be completely processed. */
79 INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED = 2,
80};
81
82
83/*
84 * An input target specifies how an input event is to be dispatched to a particular window
85 * including the window's input channel, control flags, a timeout, and an X / Y offset to
86 * be added to input event coordinates to compensate for the absolute position of the
87 * window area.
88 */
89struct InputTarget {
90 enum {
91 /* This flag indicates that the event is being delivered to a foreground application. */
92 FLAG_FOREGROUND = 1 << 0,
93
Michael Wrightcdcd8f22016-03-22 16:52:13 -070094 /* This flag indicates that the MotionEvent falls within the area of the target
Michael Wrightd02c5b62014-02-10 15:10:22 -080095 * obscured by another visible window above it. The motion event should be
96 * delivered with flag AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED. */
97 FLAG_WINDOW_IS_OBSCURED = 1 << 1,
98
99 /* This flag indicates that a motion event is being split across multiple windows. */
100 FLAG_SPLIT = 1 << 2,
101
102 /* This flag indicates that the pointer coordinates dispatched to the application
103 * will be zeroed out to avoid revealing information to an application. This is
104 * used in conjunction with FLAG_DISPATCH_AS_OUTSIDE to prevent apps not sharing
105 * the same UID from watching all touches. */
106 FLAG_ZERO_COORDS = 1 << 3,
107
108 /* This flag indicates that the event should be sent as is.
109 * Should always be set unless the event is to be transmuted. */
110 FLAG_DISPATCH_AS_IS = 1 << 8,
111
112 /* This flag indicates that a MotionEvent with AMOTION_EVENT_ACTION_DOWN falls outside
113 * of the area of this target and so should instead be delivered as an
114 * AMOTION_EVENT_ACTION_OUTSIDE to this target. */
115 FLAG_DISPATCH_AS_OUTSIDE = 1 << 9,
116
117 /* This flag indicates that a hover sequence is starting in the given window.
118 * The event is transmuted into ACTION_HOVER_ENTER. */
119 FLAG_DISPATCH_AS_HOVER_ENTER = 1 << 10,
120
121 /* This flag indicates that a hover event happened outside of a window which handled
122 * previous hover events, signifying the end of the current hover sequence for that
123 * window.
124 * The event is transmuted into ACTION_HOVER_ENTER. */
125 FLAG_DISPATCH_AS_HOVER_EXIT = 1 << 11,
126
127 /* This flag indicates that the event should be canceled.
128 * It is used to transmute ACTION_MOVE into ACTION_CANCEL when a touch slips
129 * outside of a window. */
130 FLAG_DISPATCH_AS_SLIPPERY_EXIT = 1 << 12,
131
132 /* This flag indicates that the event should be dispatched as an initial down.
133 * It is used to transmute ACTION_MOVE into ACTION_DOWN when a touch slips
134 * into a new window. */
135 FLAG_DISPATCH_AS_SLIPPERY_ENTER = 1 << 13,
136
137 /* Mask for all dispatch modes. */
138 FLAG_DISPATCH_MASK = FLAG_DISPATCH_AS_IS
139 | FLAG_DISPATCH_AS_OUTSIDE
140 | FLAG_DISPATCH_AS_HOVER_ENTER
141 | FLAG_DISPATCH_AS_HOVER_EXIT
142 | FLAG_DISPATCH_AS_SLIPPERY_EXIT
143 | FLAG_DISPATCH_AS_SLIPPERY_ENTER,
Michael Wrightcdcd8f22016-03-22 16:52:13 -0700144
145 /* This flag indicates that the target of a MotionEvent is partly or wholly
146 * obscured by another visible window above it. The motion event should be
147 * delivered with flag AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED. */
148 FLAG_WINDOW_IS_PARTIALLY_OBSCURED = 1 << 14,
149
Michael Wrightd02c5b62014-02-10 15:10:22 -0800150 };
151
152 // The input channel to be targeted.
153 sp<InputChannel> inputChannel;
154
155 // Flags for the input target.
156 int32_t flags;
157
158 // The x and y offset to add to a MotionEvent as it is delivered.
159 // (ignored for KeyEvents)
160 float xOffset, yOffset;
161
162 // Scaling factor to apply to MotionEvent as it is delivered.
163 // (ignored for KeyEvents)
Robert Carre07e1032018-11-26 12:55:53 -0800164 float globalScaleFactor;
165 float windowXScale = 1.0f;
166 float windowYScale = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800167
168 // The subset of pointer ids to include in motion events dispatched to this input target
169 // if FLAG_SPLIT is set.
170 BitSet32 pointerIds;
171};
172
173
174/*
175 * Input dispatcher configuration.
176 *
177 * Specifies various options that modify the behavior of the input dispatcher.
178 * The values provided here are merely defaults. The actual values will come from ViewConfiguration
179 * and are passed into the dispatcher during initialization.
180 */
181struct InputDispatcherConfiguration {
182 // The key repeat initial timeout.
183 nsecs_t keyRepeatTimeout;
184
185 // The key repeat inter-key delay.
186 nsecs_t keyRepeatDelay;
187
188 InputDispatcherConfiguration() :
189 keyRepeatTimeout(500 * 1000000LL),
190 keyRepeatDelay(50 * 1000000LL) { }
191};
192
193
194/*
195 * Input dispatcher policy interface.
196 *
197 * The input reader policy is used by the input reader to interact with the Window Manager
198 * and other system components.
199 *
200 * The actual implementation is partially supported by callbacks into the DVM
201 * via JNI. This interface is also mocked in the unit tests.
202 */
203class InputDispatcherPolicyInterface : public virtual RefBase {
204protected:
205 InputDispatcherPolicyInterface() { }
206 virtual ~InputDispatcherPolicyInterface() { }
207
208public:
209 /* Notifies the system that a configuration change has occurred. */
210 virtual void notifyConfigurationChanged(nsecs_t when) = 0;
211
212 /* Notifies the system that an application is not responding.
213 * Returns a new timeout to continue waiting, or 0 to abort dispatch. */
214 virtual nsecs_t notifyANR(const sp<InputApplicationHandle>& inputApplicationHandle,
Robert Carr803535b2018-08-02 16:38:15 -0700215 const sp<IBinder>& token,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800216 const std::string& reason) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800217
218 /* Notifies the system that an input channel is unrecoverably broken. */
Robert Carr803535b2018-08-02 16:38:15 -0700219 virtual void notifyInputChannelBroken(const sp<IBinder>& token) = 0;
Robert Carrf759f162018-11-13 12:57:11 -0800220 virtual void notifyFocusChanged(const sp<IBinder>& token) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800221
222 /* Gets the input dispatcher configuration. */
223 virtual void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) = 0;
224
Michael Wrightd02c5b62014-02-10 15:10:22 -0800225 /* Filters an input event.
226 * Return true to dispatch the event unmodified, false to consume the event.
227 * A filter can also transform and inject events later by passing POLICY_FLAG_FILTERED
228 * to injectInputEvent.
229 */
230 virtual bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) = 0;
231
232 /* Intercepts a key event immediately before queueing it.
233 * The policy can use this method as an opportunity to perform power management functions
234 * and early event preprocessing such as updating policy flags.
235 *
236 * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
237 * should be dispatched to applications.
238 */
239 virtual void interceptKeyBeforeQueueing(const KeyEvent* keyEvent, uint32_t& policyFlags) = 0;
240
241 /* Intercepts a touch, trackball or other motion event before queueing it.
242 * The policy can use this method as an opportunity to perform power management functions
243 * and early event preprocessing such as updating policy flags.
244 *
245 * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
246 * should be dispatched to applications.
247 */
248 virtual void interceptMotionBeforeQueueing(nsecs_t when, uint32_t& policyFlags) = 0;
249
250 /* Allows the policy a chance to intercept a key before dispatching. */
Robert Carr803535b2018-08-02 16:38:15 -0700251 virtual nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>& token,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800252 const KeyEvent* keyEvent, uint32_t policyFlags) = 0;
253
254 /* Allows the policy a chance to perform default processing for an unhandled key.
255 * Returns an alternate keycode to redispatch as a fallback, or 0 to give up. */
Robert Carr803535b2018-08-02 16:38:15 -0700256 virtual bool dispatchUnhandledKey(const sp<IBinder>& token,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800257 const KeyEvent* keyEvent, uint32_t policyFlags, KeyEvent* outFallbackKeyEvent) = 0;
258
259 /* Notifies the policy about switch events.
260 */
261 virtual void notifySwitch(nsecs_t when,
262 uint32_t switchValues, uint32_t switchMask, uint32_t policyFlags) = 0;
263
264 /* Poke user activity for an event dispatched to a window. */
265 virtual void pokeUserActivity(nsecs_t eventTime, int32_t eventType) = 0;
266
267 /* Checks whether a given application pid/uid has permission to inject input events
268 * into other applications.
269 *
270 * This method is special in that its implementation promises to be non-reentrant and
271 * is safe to call while holding other locks. (Most other methods make no such guarantees!)
272 */
273 virtual bool checkInjectEventsPermissionNonReentrant(
274 int32_t injectorPid, int32_t injectorUid) = 0;
275};
276
277
278/* Notifies the system about input events generated by the input reader.
279 * The dispatcher is expected to be mostly asynchronous. */
280class InputDispatcherInterface : public virtual RefBase, public InputListenerInterface {
281protected:
282 InputDispatcherInterface() { }
283 virtual ~InputDispatcherInterface() { }
284
285public:
286 /* Dumps the state of the input dispatcher.
287 *
288 * This method may be called on any thread (usually by the input manager). */
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800289 virtual void dump(std::string& dump) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800290
291 /* Called by the heatbeat to ensures that the dispatcher has not deadlocked. */
292 virtual void monitor() = 0;
293
294 /* Runs a single iteration of the dispatch loop.
295 * Nominally processes one queued event, a timeout, or a response from an input consumer.
296 *
297 * This method should only be called on the input dispatcher thread.
298 */
299 virtual void dispatchOnce() = 0;
300
301 /* Injects an input event and optionally waits for sync.
302 * The synchronization mode determines whether the method blocks while waiting for
303 * input injection to proceed.
304 * Returns one of the INPUT_EVENT_INJECTION_XXX constants.
305 *
306 * This method may be called on any thread (usually by the input manager).
307 */
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800308 virtual int32_t injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800309 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
310 uint32_t policyFlags) = 0;
311
312 /* Sets the list of input windows.
313 *
314 * This method may be called on any thread (usually by the input manager).
315 */
Arthur Hungb92218b2018-08-14 12:00:21 +0800316 virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles,
317 int32_t displayId) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800318
Tiger Huang721e26f2018-07-24 22:26:19 +0800319 /* Sets the focused application on the given display.
Michael Wrightd02c5b62014-02-10 15:10:22 -0800320 *
321 * This method may be called on any thread (usually by the input manager).
322 */
323 virtual void setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +0800324 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) = 0;
325
326 /* Sets the focused display.
327 *
328 * This method may be called on any thread (usually by the input manager).
329 */
330 virtual void setFocusedDisplay(int32_t displayId) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800331
332 /* Sets the input dispatching mode.
333 *
334 * This method may be called on any thread (usually by the input manager).
335 */
336 virtual void setInputDispatchMode(bool enabled, bool frozen) = 0;
337
338 /* Sets whether input event filtering is enabled.
339 * When enabled, incoming input events are sent to the policy's filterInputEvent
340 * method instead of being dispatched. The filter is expected to use
341 * injectInputEvent to inject the events it would like to have dispatched.
342 * It should include POLICY_FLAG_FILTERED in the policy flags during injection.
343 */
344 virtual void setInputFilterEnabled(bool enabled) = 0;
345
chaviwfbe5d9c2018-12-26 12:23:37 -0800346 /* Transfers touch focus from one window to another window.
Michael Wrightd02c5b62014-02-10 15:10:22 -0800347 *
348 * Returns true on success. False if the window did not actually have touch focus.
349 */
chaviwfbe5d9c2018-12-26 12:23:37 -0800350 virtual bool transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) = 0;
351
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800352 /* Registers input channels that may be used as targets for input events.
353 * If inputWindowHandle is null, and displayId is not ADISPLAY_ID_NONE,
354 * the channel will receive a copy of all input events form the specific displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -0800355 *
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800356 * This method may be called on any thread (usually by the input manager).
Michael Wrightd02c5b62014-02-10 15:10:22 -0800357 */
Robert Carr803535b2018-08-02 16:38:15 -0700358 virtual status_t registerInputChannel(
359 const sp<InputChannel>& inputChannel, int32_t displayId) = 0;
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800360
361 /* Unregister input channels that will no longer receive input events.
362 *
363 * This method may be called on any thread (usually by the input manager).
364 */
Michael Wrightd02c5b62014-02-10 15:10:22 -0800365 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel) = 0;
366};
367
368/* Dispatches events to input targets. Some functions of the input dispatcher, such as
369 * identifying input targets, are controlled by a separate policy object.
370 *
371 * IMPORTANT INVARIANT:
372 * Because the policy can potentially block or cause re-entrance into the input dispatcher,
373 * the input dispatcher never calls into the policy while holding its internal locks.
374 * The implementation is also carefully designed to recover from scenarios such as an
375 * input channel becoming unregistered while identifying input targets or processing timeouts.
376 *
377 * Methods marked 'Locked' must be called with the lock acquired.
378 *
379 * Methods marked 'LockedInterruptible' must be called with the lock acquired but
380 * may during the course of their execution release the lock, call into the policy, and
381 * then reacquire the lock. The caller is responsible for recovering gracefully.
382 *
383 * A 'LockedInterruptible' method may called a 'Locked' method, but NOT vice-versa.
384 */
385class InputDispatcher : public InputDispatcherInterface {
386protected:
387 virtual ~InputDispatcher();
388
389public:
390 explicit InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy);
391
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800392 virtual void dump(std::string& dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800393 virtual void monitor();
394
395 virtual void dispatchOnce();
396
397 virtual void notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args);
398 virtual void notifyKey(const NotifyKeyArgs* args);
399 virtual void notifyMotion(const NotifyMotionArgs* args);
400 virtual void notifySwitch(const NotifySwitchArgs* args);
401 virtual void notifyDeviceReset(const NotifyDeviceResetArgs* args);
402
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800403 virtual int32_t injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800404 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
405 uint32_t policyFlags);
406
Arthur Hungb92218b2018-08-14 12:00:21 +0800407 virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles,
408 int32_t displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +0800409 virtual void setFocusedApplication(int32_t displayId,
410 const sp<InputApplicationHandle>& inputApplicationHandle);
411 virtual void setFocusedDisplay(int32_t displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800412 virtual void setInputDispatchMode(bool enabled, bool frozen);
413 virtual void setInputFilterEnabled(bool enabled);
414
chaviwfbe5d9c2018-12-26 12:23:37 -0800415 virtual bool transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800416
417 virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel,
Robert Carr803535b2018-08-02 16:38:15 -0700418 int32_t displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800419 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel);
420
421private:
422 template <typename T>
423 struct Link {
424 T* next;
425 T* prev;
426
427 protected:
Yi Kong9b14ac62018-07-17 13:48:38 -0700428 inline Link() : next(nullptr), prev(nullptr) { }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800429 };
430
431 struct InjectionState {
432 mutable int32_t refCount;
433
434 int32_t injectorPid;
435 int32_t injectorUid;
436 int32_t injectionResult; // initially INPUT_EVENT_INJECTION_PENDING
437 bool injectionIsAsync; // set to true if injection is not waiting for the result
438 int32_t pendingForegroundDispatches; // the number of foreground dispatches in progress
439
440 InjectionState(int32_t injectorPid, int32_t injectorUid);
441 void release();
442
443 private:
444 ~InjectionState();
445 };
446
447 struct EventEntry : Link<EventEntry> {
448 enum {
449 TYPE_CONFIGURATION_CHANGED,
450 TYPE_DEVICE_RESET,
451 TYPE_KEY,
452 TYPE_MOTION
453 };
454
Prabir Pradhan42611e02018-11-27 14:04:02 -0800455 uint32_t sequenceNum;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800456 mutable int32_t refCount;
457 int32_t type;
458 nsecs_t eventTime;
459 uint32_t policyFlags;
460 InjectionState* injectionState;
461
462 bool dispatchInProgress; // initially false, set to true while dispatching
463
Yi Kong9b14ac62018-07-17 13:48:38 -0700464 inline bool isInjected() const { return injectionState != nullptr; }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800465
466 void release();
467
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800468 virtual void appendDescription(std::string& msg) const = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800469
470 protected:
Prabir Pradhan42611e02018-11-27 14:04:02 -0800471 EventEntry(uint32_t sequenceNum, int32_t type, nsecs_t eventTime, uint32_t policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800472 virtual ~EventEntry();
473 void releaseInjectionState();
474 };
475
476 struct ConfigurationChangedEntry : EventEntry {
Prabir Pradhan42611e02018-11-27 14:04:02 -0800477 explicit ConfigurationChangedEntry(uint32_t sequenceNum, nsecs_t eventTime);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800478 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800479
480 protected:
481 virtual ~ConfigurationChangedEntry();
482 };
483
484 struct DeviceResetEntry : EventEntry {
485 int32_t deviceId;
486
Prabir Pradhan42611e02018-11-27 14:04:02 -0800487 DeviceResetEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800488 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800489
490 protected:
491 virtual ~DeviceResetEntry();
492 };
493
494 struct KeyEntry : EventEntry {
495 int32_t deviceId;
496 uint32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100497 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800498 int32_t action;
499 int32_t flags;
500 int32_t keyCode;
501 int32_t scanCode;
502 int32_t metaState;
503 int32_t repeatCount;
504 nsecs_t downTime;
505
506 bool syntheticRepeat; // set to true for synthetic key repeats
507
508 enum InterceptKeyResult {
509 INTERCEPT_KEY_RESULT_UNKNOWN,
510 INTERCEPT_KEY_RESULT_SKIP,
511 INTERCEPT_KEY_RESULT_CONTINUE,
512 INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER,
513 };
514 InterceptKeyResult interceptKeyResult; // set based on the interception result
515 nsecs_t interceptKeyWakeupTime; // used with INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER
516
Prabir Pradhan42611e02018-11-27 14:04:02 -0800517 KeyEntry(uint32_t sequenceNum, nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100518 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags,
519 int32_t action, int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800520 int32_t repeatCount, nsecs_t downTime);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800521 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800522 void recycle();
523
524 protected:
525 virtual ~KeyEntry();
526 };
527
528 struct MotionEntry : EventEntry {
529 nsecs_t eventTime;
530 int32_t deviceId;
531 uint32_t source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800532 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533 int32_t action;
Michael Wright7b159c92015-05-14 14:48:03 +0100534 int32_t actionButton;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800535 int32_t flags;
536 int32_t metaState;
537 int32_t buttonState;
538 int32_t edgeFlags;
539 float xPrecision;
540 float yPrecision;
541 nsecs_t downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800542 uint32_t pointerCount;
543 PointerProperties pointerProperties[MAX_POINTERS];
544 PointerCoords pointerCoords[MAX_POINTERS];
545
Prabir Pradhan42611e02018-11-27 14:04:02 -0800546 MotionEntry(uint32_t sequenceNum, nsecs_t eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800547 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +0100548 int32_t action, int32_t actionButton, int32_t flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800549 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800550 float xPrecision, float yPrecision, nsecs_t downTime, uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -0800551 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
552 float xOffset, float yOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800553 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800554
555 protected:
556 virtual ~MotionEntry();
557 };
558
559 // Tracks the progress of dispatching a particular event to a particular connection.
560 struct DispatchEntry : Link<DispatchEntry> {
561 const uint32_t seq; // unique sequence number, never 0
562
563 EventEntry* eventEntry; // the event to dispatch
564 int32_t targetFlags;
565 float xOffset;
566 float yOffset;
Robert Carre07e1032018-11-26 12:55:53 -0800567 float globalScaleFactor;
568 float windowXScale = 1.0f;
569 float windowYScale = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800570 nsecs_t deliveryTime; // time when the event was actually delivered
571
572 // Set to the resolved action and flags when the event is enqueued.
573 int32_t resolvedAction;
574 int32_t resolvedFlags;
575
576 DispatchEntry(EventEntry* eventEntry,
Robert Carre07e1032018-11-26 12:55:53 -0800577 int32_t targetFlags, float xOffset, float yOffset,
578 float globalScaleFactor, float windowXScale, float windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800579 ~DispatchEntry();
580
581 inline bool hasForegroundTarget() const {
582 return targetFlags & InputTarget::FLAG_FOREGROUND;
583 }
584
585 inline bool isSplit() const {
586 return targetFlags & InputTarget::FLAG_SPLIT;
587 }
588
589 private:
590 static volatile int32_t sNextSeqAtomic;
591
592 static uint32_t nextSeq();
593 };
594
595 // A command entry captures state and behavior for an action to be performed in the
596 // dispatch loop after the initial processing has taken place. It is essentially
597 // a kind of continuation used to postpone sensitive policy interactions to a point
598 // in the dispatch loop where it is safe to release the lock (generally after finishing
599 // the critical parts of the dispatch cycle).
600 //
601 // The special thing about commands is that they can voluntarily release and reacquire
602 // the dispatcher lock at will. Initially when the command starts running, the
603 // dispatcher lock is held. However, if the command needs to call into the policy to
604 // do some work, it can release the lock, do the work, then reacquire the lock again
605 // before returning.
606 //
607 // This mechanism is a bit clunky but it helps to preserve the invariant that the dispatch
608 // never calls into the policy while holding its lock.
609 //
610 // Commands are implicitly 'LockedInterruptible'.
611 struct CommandEntry;
612 typedef void (InputDispatcher::*Command)(CommandEntry* commandEntry);
613
614 class Connection;
615 struct CommandEntry : Link<CommandEntry> {
Chih-Hung Hsieh6d2ede12016-09-01 11:28:23 -0700616 explicit CommandEntry(Command command);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800617 ~CommandEntry();
618
619 Command command;
620
621 // parameters for the command (usage varies by command)
622 sp<Connection> connection;
623 nsecs_t eventTime;
624 KeyEntry* keyEntry;
625 sp<InputApplicationHandle> inputApplicationHandle;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800626 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627 int32_t userActivityEventType;
628 uint32_t seq;
629 bool handled;
Robert Carr803535b2018-08-02 16:38:15 -0700630 sp<InputChannel> inputChannel;
Robert Carrf759f162018-11-13 12:57:11 -0800631 sp<IBinder> token;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800632 };
633
634 // Generic queue implementation.
635 template <typename T>
636 struct Queue {
637 T* head;
638 T* tail;
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800639 uint32_t entryCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800640
Yi Kong9b14ac62018-07-17 13:48:38 -0700641 inline Queue() : head(nullptr), tail(nullptr), entryCount(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800642 }
643
644 inline bool isEmpty() const {
645 return !head;
646 }
647
648 inline void enqueueAtTail(T* entry) {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800649 entryCount++;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800650 entry->prev = tail;
651 if (tail) {
652 tail->next = entry;
653 } else {
654 head = entry;
655 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700656 entry->next = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800657 tail = entry;
658 }
659
660 inline void enqueueAtHead(T* entry) {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800661 entryCount++;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800662 entry->next = head;
663 if (head) {
664 head->prev = entry;
665 } else {
666 tail = entry;
667 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700668 entry->prev = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800669 head = entry;
670 }
671
672 inline void dequeue(T* entry) {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800673 entryCount--;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800674 if (entry->prev) {
675 entry->prev->next = entry->next;
676 } else {
677 head = entry->next;
678 }
679 if (entry->next) {
680 entry->next->prev = entry->prev;
681 } else {
682 tail = entry->prev;
683 }
684 }
685
686 inline T* dequeueAtHead() {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800687 entryCount--;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800688 T* entry = head;
689 head = entry->next;
690 if (head) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700691 head->prev = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692 } else {
Yi Kong9b14ac62018-07-17 13:48:38 -0700693 tail = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800694 }
695 return entry;
696 }
697
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800698 uint32_t count() const {
699 return entryCount;
700 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800701 };
702
703 /* Specifies which events are to be canceled and why. */
704 struct CancelationOptions {
705 enum Mode {
706 CANCEL_ALL_EVENTS = 0,
707 CANCEL_POINTER_EVENTS = 1,
708 CANCEL_NON_POINTER_EVENTS = 2,
709 CANCEL_FALLBACK_EVENTS = 3,
Tiger Huang721e26f2018-07-24 22:26:19 +0800710
711 /* Cancel events where the display not specified. These events would go to the focused
712 * display. */
713 CANCEL_DISPLAY_UNSPECIFIED_EVENTS = 4,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800714 };
715
716 // The criterion to use to determine which events should be canceled.
717 Mode mode;
718
719 // Descriptive reason for the cancelation.
720 const char* reason;
721
722 // The specific keycode of the key event to cancel, or -1 to cancel any key event.
723 int32_t keyCode;
724
725 // The specific device id of events to cancel, or -1 to cancel events from any device.
726 int32_t deviceId;
727
728 CancelationOptions(Mode mode, const char* reason) :
729 mode(mode), reason(reason), keyCode(-1), deviceId(-1) { }
730 };
731
732 /* Tracks dispatched key and motion event state so that cancelation events can be
733 * synthesized when events are dropped. */
734 class InputState {
735 public:
736 InputState();
737 ~InputState();
738
739 // Returns true if there is no state to be canceled.
740 bool isNeutral() const;
741
742 // Returns true if the specified source is known to have received a hover enter
743 // motion event.
744 bool isHovering(int32_t deviceId, uint32_t source, int32_t displayId) const;
745
746 // Records tracking information for a key event that has just been published.
747 // Returns true if the event should be delivered, false if it is inconsistent
748 // and should be skipped.
749 bool trackKey(const KeyEntry* entry, int32_t action, int32_t flags);
750
751 // Records tracking information for a motion event that has just been published.
752 // Returns true if the event should be delivered, false if it is inconsistent
753 // and should be skipped.
754 bool trackMotion(const MotionEntry* entry, int32_t action, int32_t flags);
755
756 // Synthesizes cancelation events for the current state and resets the tracked state.
757 void synthesizeCancelationEvents(nsecs_t currentTime,
758 Vector<EventEntry*>& outEvents, const CancelationOptions& options);
759
760 // Clears the current state.
761 void clear();
762
763 // Copies pointer-related parts of the input state to another instance.
764 void copyPointerStateTo(InputState& other) const;
765
766 // Gets the fallback key associated with a keycode.
767 // Returns -1 if none.
768 // Returns AKEYCODE_UNKNOWN if we are only dispatching the unhandled key to the policy.
769 int32_t getFallbackKey(int32_t originalKeyCode);
770
771 // Sets the fallback key for a particular keycode.
772 void setFallbackKey(int32_t originalKeyCode, int32_t fallbackKeyCode);
773
774 // Removes the fallback key for a particular keycode.
775 void removeFallbackKey(int32_t originalKeyCode);
776
777 inline const KeyedVector<int32_t, int32_t>& getFallbackKeys() const {
778 return mFallbackKeys;
779 }
780
781 private:
782 struct KeyMemento {
783 int32_t deviceId;
784 uint32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100785 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786 int32_t keyCode;
787 int32_t scanCode;
788 int32_t metaState;
789 int32_t flags;
790 nsecs_t downTime;
791 uint32_t policyFlags;
792 };
793
794 struct MotionMemento {
795 int32_t deviceId;
796 uint32_t source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800797 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800798 int32_t flags;
799 float xPrecision;
800 float yPrecision;
801 nsecs_t downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800802 uint32_t pointerCount;
803 PointerProperties pointerProperties[MAX_POINTERS];
804 PointerCoords pointerCoords[MAX_POINTERS];
805 bool hovering;
806 uint32_t policyFlags;
807
808 void setPointers(const MotionEntry* entry);
809 };
810
811 Vector<KeyMemento> mKeyMementos;
812 Vector<MotionMemento> mMotionMementos;
813 KeyedVector<int32_t, int32_t> mFallbackKeys;
814
815 ssize_t findKeyMemento(const KeyEntry* entry) const;
816 ssize_t findMotionMemento(const MotionEntry* entry, bool hovering) const;
817
818 void addKeyMemento(const KeyEntry* entry, int32_t flags);
819 void addMotionMemento(const MotionEntry* entry, int32_t flags, bool hovering);
820
821 static bool shouldCancelKey(const KeyMemento& memento,
822 const CancelationOptions& options);
823 static bool shouldCancelMotion(const MotionMemento& memento,
824 const CancelationOptions& options);
825 };
826
827 /* Manages the dispatch state associated with a single input channel. */
828 class Connection : public RefBase {
829 protected:
830 virtual ~Connection();
831
832 public:
833 enum Status {
834 // Everything is peachy.
835 STATUS_NORMAL,
836 // An unrecoverable communication error has occurred.
837 STATUS_BROKEN,
838 // The input channel has been unregistered.
839 STATUS_ZOMBIE
840 };
841
842 Status status;
843 sp<InputChannel> inputChannel; // never null
Michael Wrightd02c5b62014-02-10 15:10:22 -0800844 bool monitor;
845 InputPublisher inputPublisher;
846 InputState inputState;
847
848 // True if the socket is full and no further events can be published until
849 // the application consumes some of the input.
850 bool inputPublisherBlocked;
851
852 // Queue of events that need to be published to the connection.
853 Queue<DispatchEntry> outboundQueue;
854
855 // Queue of events that have been published to the connection but that have not
856 // yet received a "finished" response from the application.
857 Queue<DispatchEntry> waitQueue;
858
Robert Carr803535b2018-08-02 16:38:15 -0700859 explicit Connection(const sp<InputChannel>& inputChannel, bool monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -0800861 inline const std::string getInputChannelName() const { return inputChannel->getName(); }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -0800863 const std::string getWindowName() const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864 const char* getStatusLabel() const;
865
866 DispatchEntry* findWaitQueueEntry(uint32_t seq);
867 };
868
869 enum DropReason {
870 DROP_REASON_NOT_DROPPED = 0,
871 DROP_REASON_POLICY = 1,
872 DROP_REASON_APP_SWITCH = 2,
873 DROP_REASON_DISABLED = 3,
874 DROP_REASON_BLOCKED = 4,
875 DROP_REASON_STALE = 5,
876 };
877
878 sp<InputDispatcherPolicyInterface> mPolicy;
879 InputDispatcherConfiguration mConfig;
880
881 Mutex mLock;
882
883 Condition mDispatcherIsAliveCondition;
884
885 sp<Looper> mLooper;
886
887 EventEntry* mPendingEvent;
888 Queue<EventEntry> mInboundQueue;
889 Queue<EventEntry> mRecentQueue;
890 Queue<CommandEntry> mCommandQueue;
891
Michael Wright3a981722015-06-10 15:26:13 +0100892 DropReason mLastDropReason;
893
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 void dispatchOnceInnerLocked(nsecs_t* nextWakeupTime);
895
896 // Enqueues an inbound event. Returns true if mLooper->wake() should be called.
897 bool enqueueInboundEventLocked(EventEntry* entry);
898
899 // Cleans up input state when dropping an inbound event.
900 void dropInboundEventLocked(EventEntry* entry, DropReason dropReason);
901
902 // Adds an event to a queue of recent events for debugging purposes.
903 void addRecentEventLocked(EventEntry* entry);
904
905 // App switch latency optimization.
906 bool mAppSwitchSawKeyDown;
907 nsecs_t mAppSwitchDueTime;
908
909 static bool isAppSwitchKeyCode(int32_t keyCode);
910 bool isAppSwitchKeyEventLocked(KeyEntry* keyEntry);
911 bool isAppSwitchPendingLocked();
912 void resetPendingAppSwitchLocked(bool handled);
913
914 // Stale event latency optimization.
915 static bool isStaleEventLocked(nsecs_t currentTime, EventEntry* entry);
916
917 // Blocked event latency optimization. Drops old events when the user intends
918 // to transfer focus to a new application.
919 EventEntry* mNextUnblockedEvent;
920
921 sp<InputWindowHandle> findTouchedWindowAtLocked(int32_t displayId, int32_t x, int32_t y);
922
923 // All registered connections mapped by channel file descriptor.
924 KeyedVector<int, sp<Connection> > mConnectionsByFd;
925
Robert Carr5c8a0262018-10-03 16:30:44 -0700926 struct IBinderHash {
927 std::size_t operator()(const sp<IBinder>& b) const {
928 return std::hash<IBinder *>{}(b.get());
929 }
930 };
931 std::unordered_map<sp<IBinder>, sp<InputChannel>, IBinderHash> mInputChannelsByToken;
932
Michael Wrightd02c5b62014-02-10 15:10:22 -0800933 ssize_t getConnectionIndexLocked(const sp<InputChannel>& inputChannel);
934
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800935 // Input channels that will receive a copy of all input events sent to the provided display.
936 std::unordered_map<int32_t, Vector<sp<InputChannel>>> mMonitoringChannelsByDisplay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800937
938 // Event injection and synchronization.
939 Condition mInjectionResultAvailableCondition;
940 bool hasInjectionPermission(int32_t injectorPid, int32_t injectorUid);
941 void setInjectionResultLocked(EventEntry* entry, int32_t injectionResult);
942
943 Condition mInjectionSyncFinishedCondition;
944 void incrementPendingForegroundDispatchesLocked(EventEntry* entry);
945 void decrementPendingForegroundDispatchesLocked(EventEntry* entry);
946
947 // Key repeat tracking.
948 struct KeyRepeatState {
949 KeyEntry* lastKeyEntry; // or null if no repeat
950 nsecs_t nextRepeatTime;
951 } mKeyRepeatState;
952
953 void resetKeyRepeatLocked();
954 KeyEntry* synthesizeKeyRepeatLocked(nsecs_t currentTime);
955
Michael Wright78f24442014-08-06 15:55:28 -0700956 // Key replacement tracking
957 struct KeyReplacement {
958 int32_t keyCode;
959 int32_t deviceId;
960 bool operator==(const KeyReplacement& rhs) const {
961 return keyCode == rhs.keyCode && deviceId == rhs.deviceId;
962 }
963 bool operator<(const KeyReplacement& rhs) const {
964 return keyCode != rhs.keyCode ? keyCode < rhs.keyCode : deviceId < rhs.deviceId;
965 }
966 };
967 // Maps the key code replaced, device id tuple to the key code it was replaced with
968 KeyedVector<KeyReplacement, int32_t> mReplacedKeys;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -0500969 // Process certain Meta + Key combinations
970 void accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
971 int32_t& keyCode, int32_t& metaState);
Michael Wright78f24442014-08-06 15:55:28 -0700972
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973 // Deferred command processing.
974 bool haveCommandsLocked() const;
975 bool runCommandsLockedInterruptible();
976 CommandEntry* postCommandLocked(Command command);
977
978 // Input filter processing.
979 bool shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args);
980 bool shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args);
981
982 // Inbound event processing.
983 void drainInboundQueueLocked();
984 void releasePendingEventLocked();
985 void releaseInboundEventLocked(EventEntry* entry);
986
987 // Dispatch state.
988 bool mDispatchEnabled;
989 bool mDispatchFrozen;
990 bool mInputFilterEnabled;
991
Arthur Hungb92218b2018-08-14 12:00:21 +0800992 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>> mWindowHandlesByDisplay;
993 // Get window handles by display, return an empty vector if not found.
994 Vector<sp<InputWindowHandle>> getWindowHandlesLocked(int32_t displayId) const;
chaviwfbe5d9c2018-12-26 12:23:37 -0800995 sp<InputWindowHandle> getWindowHandleLocked(const sp<IBinder>& windowHandleToken) const;
Robert Carr5c8a0262018-10-03 16:30:44 -0700996 sp<InputChannel> getInputChannelLocked(const sp<IBinder>& windowToken) const;
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +0000997 bool hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998
999 // Focus tracking for keys, trackball, etc.
Tiger Huang721e26f2018-07-24 22:26:19 +08001000 std::unordered_map<int32_t, sp<InputWindowHandle>> mFocusedWindowHandlesByDisplay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001
1002 // Focus tracking for touch.
1003 struct TouchedWindow {
1004 sp<InputWindowHandle> windowHandle;
1005 int32_t targetFlags;
1006 BitSet32 pointerIds; // zero unless target flag FLAG_SPLIT is set
1007 };
1008 struct TouchState {
1009 bool down;
1010 bool split;
1011 int32_t deviceId; // id of the device that is currently down, others are rejected
1012 uint32_t source; // source of the device that is current down, others are rejected
1013 int32_t displayId; // id to the display that currently has a touch, others are rejected
1014 Vector<TouchedWindow> windows;
1015
1016 TouchState();
1017 ~TouchState();
1018 void reset();
1019 void copyFrom(const TouchState& other);
1020 void addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
1021 int32_t targetFlags, BitSet32 pointerIds);
1022 void removeWindow(const sp<InputWindowHandle>& windowHandle);
Robert Carr803535b2018-08-02 16:38:15 -07001023 void removeWindowByToken(const sp<IBinder>& token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 void filterNonAsIsTouchWindows();
1025 sp<InputWindowHandle> getFirstForegroundWindowHandle() const;
1026 bool isSlippery() const;
1027 };
1028
Jeff Brownf086ddb2014-02-11 14:28:48 -08001029 KeyedVector<int32_t, TouchState> mTouchStatesByDisplay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001030 TouchState mTempTouchState;
1031
Tiger Huang721e26f2018-07-24 22:26:19 +08001032 // Focused applications.
1033 std::unordered_map<int32_t, sp<InputApplicationHandle>> mFocusedApplicationHandlesByDisplay;
1034
1035 // Top focused display.
1036 int32_t mFocusedDisplayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001037
1038 // Dispatcher state at time of last ANR.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001039 std::string mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001040
1041 // Dispatch inbound events.
1042 bool dispatchConfigurationChangedLocked(
1043 nsecs_t currentTime, ConfigurationChangedEntry* entry);
1044 bool dispatchDeviceResetLocked(
1045 nsecs_t currentTime, DeviceResetEntry* entry);
1046 bool dispatchKeyLocked(
1047 nsecs_t currentTime, KeyEntry* entry,
1048 DropReason* dropReason, nsecs_t* nextWakeupTime);
1049 bool dispatchMotionLocked(
1050 nsecs_t currentTime, MotionEntry* entry,
1051 DropReason* dropReason, nsecs_t* nextWakeupTime);
1052 void dispatchEventLocked(nsecs_t currentTime, EventEntry* entry,
1053 const Vector<InputTarget>& inputTargets);
1054
1055 void logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry);
1056 void logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry);
1057
1058 // Keeping track of ANR timeouts.
1059 enum InputTargetWaitCause {
1060 INPUT_TARGET_WAIT_CAUSE_NONE,
1061 INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY,
1062 INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY,
1063 };
1064
1065 InputTargetWaitCause mInputTargetWaitCause;
1066 nsecs_t mInputTargetWaitStartTime;
1067 nsecs_t mInputTargetWaitTimeoutTime;
1068 bool mInputTargetWaitTimeoutExpired;
Robert Carr740167f2018-10-11 19:03:41 -07001069 sp<IBinder> mInputTargetWaitApplicationToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001070
1071 // Contains the last window which received a hover event.
1072 sp<InputWindowHandle> mLastHoverWindowHandle;
1073
1074 // Finding targets for input events.
1075 int32_t handleTargetsNotReadyLocked(nsecs_t currentTime, const EventEntry* entry,
1076 const sp<InputApplicationHandle>& applicationHandle,
1077 const sp<InputWindowHandle>& windowHandle,
1078 nsecs_t* nextWakeupTime, const char* reason);
Robert Carr803535b2018-08-02 16:38:15 -07001079
1080 void removeWindowByTokenLocked(const sp<IBinder>& token);
1081
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082 void resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1083 const sp<InputChannel>& inputChannel);
1084 nsecs_t getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime);
1085 void resetANRTimeoutsLocked();
1086
Tiger Huang721e26f2018-07-24 22:26:19 +08001087 int32_t getTargetDisplayId(const EventEntry* entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 int32_t findFocusedWindowTargetsLocked(nsecs_t currentTime, const EventEntry* entry,
1089 Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime);
1090 int32_t findTouchedWindowTargetsLocked(nsecs_t currentTime, const MotionEntry* entry,
1091 Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1092 bool* outConflictingPointerActions);
1093
1094 void addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1095 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001096 void addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets, int32_t displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001097
1098 void pokeUserActivityLocked(const EventEntry* eventEntry);
1099 bool checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1100 const InjectionState* injectionState);
1101 bool isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1102 int32_t x, int32_t y) const;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001103 bool isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001104 std::string getApplicationWindowLabelLocked(const sp<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001105 const sp<InputWindowHandle>& windowHandle);
1106
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001107 std::string checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001108 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1109 const char* targetType);
1110
Michael Wrightd02c5b62014-02-10 15:10:22 -08001111 // Manage the dispatch cycle for a single connection.
1112 // These methods are deliberately not Interruptible because doing all of the work
1113 // with the mutex held makes it easier to ensure that connection invariants are maintained.
1114 // If needed, the methods post commands to run later once the critical bits are done.
1115 void prepareDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1116 EventEntry* eventEntry, const InputTarget* inputTarget);
1117 void enqueueDispatchEntriesLocked(nsecs_t currentTime, const sp<Connection>& connection,
1118 EventEntry* eventEntry, const InputTarget* inputTarget);
1119 void enqueueDispatchEntryLocked(const sp<Connection>& connection,
1120 EventEntry* eventEntry, const InputTarget* inputTarget, int32_t dispatchMode);
1121 void startDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
1122 void finishDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1123 uint32_t seq, bool handled);
1124 void abortBrokenDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1125 bool notify);
1126 void drainDispatchQueueLocked(Queue<DispatchEntry>* queue);
1127 void releaseDispatchEntryLocked(DispatchEntry* dispatchEntry);
1128 static int handleReceiveCallback(int fd, int events, void* data);
1129
1130 void synthesizeCancelationEventsForAllConnectionsLocked(
1131 const CancelationOptions& options);
Michael Wrightfa13dcf2015-06-12 13:25:11 +01001132 void synthesizeCancelationEventsForMonitorsLocked(const CancelationOptions& options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133 void synthesizeCancelationEventsForInputChannelLocked(const sp<InputChannel>& channel,
1134 const CancelationOptions& options);
1135 void synthesizeCancelationEventsForConnectionLocked(const sp<Connection>& connection,
1136 const CancelationOptions& options);
1137
1138 // Splitting motion events across windows.
1139 MotionEntry* splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds);
1140
1141 // Reset and drop everything the dispatcher is doing.
1142 void resetAndDropEverythingLocked(const char* reason);
1143
1144 // Dump state.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001145 void dumpDispatchStateLocked(std::string& dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146 void logDispatchStateLocked();
1147
1148 // Registration.
1149 void removeMonitorChannelLocked(const sp<InputChannel>& inputChannel);
1150 status_t unregisterInputChannelLocked(const sp<InputChannel>& inputChannel, bool notify);
1151
1152 // Add or remove a connection to the mActiveConnections vector.
1153 void activateConnectionLocked(Connection* connection);
1154 void deactivateConnectionLocked(Connection* connection);
1155
1156 // Interesting events that we might like to log or tell the framework about.
1157 void onDispatchCycleFinishedLocked(
1158 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled);
1159 void onDispatchCycleBrokenLocked(
1160 nsecs_t currentTime, const sp<Connection>& connection);
Robert Carrf759f162018-11-13 12:57:11 -08001161 void onFocusChangedLocked(const sp<InputWindowHandle>& newFocus);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162 void onANRLocked(
1163 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
1164 const sp<InputWindowHandle>& windowHandle,
1165 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason);
1166
1167 // Outbound policy interactions.
1168 void doNotifyConfigurationChangedInterruptible(CommandEntry* commandEntry);
1169 void doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry);
Robert Carrf759f162018-11-13 12:57:11 -08001170 void doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171 void doNotifyANRLockedInterruptible(CommandEntry* commandEntry);
1172 void doInterceptKeyBeforeDispatchingLockedInterruptible(CommandEntry* commandEntry);
1173 void doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry);
1174 bool afterKeyEventLockedInterruptible(const sp<Connection>& connection,
1175 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled);
1176 bool afterMotionEventLockedInterruptible(const sp<Connection>& connection,
1177 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled);
1178 void doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry);
1179 void initializeKeyEvent(KeyEvent* event, const KeyEntry* entry);
1180
1181 // Statistics gathering.
1182 void updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
1183 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication);
1184 void traceInboundQueueLengthLocked();
1185 void traceOutboundQueueLengthLocked(const sp<Connection>& connection);
1186 void traceWaitQueueLengthLocked(const sp<Connection>& connection);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08001187
1188 sp<InputReporter> mReporter;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189};
1190
1191/* Enqueues and dispatches input events, endlessly. */
1192class InputDispatcherThread : public Thread {
1193public:
1194 explicit InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher);
1195 ~InputDispatcherThread();
1196
1197private:
1198 virtual bool threadLoop();
1199
1200 sp<InputDispatcherInterface> mDispatcher;
1201};
1202
1203} // namespace android
1204
1205#endif // _UI_INPUT_DISPATCHER_H