blob: ecfeb6cac95f48bef3f58d290bf99f63f5bb0e63 [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 Pradhan79a4f0c2019-01-09 11:24:01 -080040#include "InputReporterInterface.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;
chaviw0c06c6e2019-01-09 13:27:07 -0800220 virtual void notifyFocusChanged(const sp<IBinder>& oldToken, const sp<IBinder>& newToken) = 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 */
Charles Chen3611f1f2019-01-29 17:26:18 +0800248 virtual void interceptMotionBeforeQueueing(const int32_t displayId, nsecs_t when,
249 uint32_t& policyFlags) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800250
251 /* Allows the policy a chance to intercept a key before dispatching. */
Robert Carr803535b2018-08-02 16:38:15 -0700252 virtual nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>& token,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800253 const KeyEvent* keyEvent, uint32_t policyFlags) = 0;
254
255 /* Allows the policy a chance to perform default processing for an unhandled key.
256 * Returns an alternate keycode to redispatch as a fallback, or 0 to give up. */
Robert Carr803535b2018-08-02 16:38:15 -0700257 virtual bool dispatchUnhandledKey(const sp<IBinder>& token,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800258 const KeyEvent* keyEvent, uint32_t policyFlags, KeyEvent* outFallbackKeyEvent) = 0;
259
260 /* Notifies the policy about switch events.
261 */
262 virtual void notifySwitch(nsecs_t when,
263 uint32_t switchValues, uint32_t switchMask, uint32_t policyFlags) = 0;
264
265 /* Poke user activity for an event dispatched to a window. */
266 virtual void pokeUserActivity(nsecs_t eventTime, int32_t eventType) = 0;
267
268 /* Checks whether a given application pid/uid has permission to inject input events
269 * into other applications.
270 *
271 * This method is special in that its implementation promises to be non-reentrant and
272 * is safe to call while holding other locks. (Most other methods make no such guarantees!)
273 */
274 virtual bool checkInjectEventsPermissionNonReentrant(
275 int32_t injectorPid, int32_t injectorUid) = 0;
276};
277
278
279/* Notifies the system about input events generated by the input reader.
280 * The dispatcher is expected to be mostly asynchronous. */
281class InputDispatcherInterface : public virtual RefBase, public InputListenerInterface {
282protected:
283 InputDispatcherInterface() { }
284 virtual ~InputDispatcherInterface() { }
285
286public:
287 /* Dumps the state of the input dispatcher.
288 *
289 * This method may be called on any thread (usually by the input manager). */
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800290 virtual void dump(std::string& dump) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800291
292 /* Called by the heatbeat to ensures that the dispatcher has not deadlocked. */
293 virtual void monitor() = 0;
294
295 /* Runs a single iteration of the dispatch loop.
296 * Nominally processes one queued event, a timeout, or a response from an input consumer.
297 *
298 * This method should only be called on the input dispatcher thread.
299 */
300 virtual void dispatchOnce() = 0;
301
302 /* Injects an input event and optionally waits for sync.
303 * The synchronization mode determines whether the method blocks while waiting for
304 * input injection to proceed.
305 * Returns one of the INPUT_EVENT_INJECTION_XXX constants.
306 *
307 * This method may be called on any thread (usually by the input manager).
308 */
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800309 virtual int32_t injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800310 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
311 uint32_t policyFlags) = 0;
312
313 /* Sets the list of input windows.
314 *
315 * This method may be called on any thread (usually by the input manager).
316 */
Arthur Hungb92218b2018-08-14 12:00:21 +0800317 virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles,
318 int32_t displayId) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800319
Tiger Huang721e26f2018-07-24 22:26:19 +0800320 /* Sets the focused application on the given display.
Michael Wrightd02c5b62014-02-10 15:10:22 -0800321 *
322 * This method may be called on any thread (usually by the input manager).
323 */
324 virtual void setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +0800325 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) = 0;
326
327 /* Sets the focused display.
328 *
329 * This method may be called on any thread (usually by the input manager).
330 */
331 virtual void setFocusedDisplay(int32_t displayId) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800332
333 /* Sets the input dispatching mode.
334 *
335 * This method may be called on any thread (usually by the input manager).
336 */
337 virtual void setInputDispatchMode(bool enabled, bool frozen) = 0;
338
339 /* Sets whether input event filtering is enabled.
340 * When enabled, incoming input events are sent to the policy's filterInputEvent
341 * method instead of being dispatched. The filter is expected to use
342 * injectInputEvent to inject the events it would like to have dispatched.
343 * It should include POLICY_FLAG_FILTERED in the policy flags during injection.
344 */
345 virtual void setInputFilterEnabled(bool enabled) = 0;
346
chaviwfbe5d9c2018-12-26 12:23:37 -0800347 /* Transfers touch focus from one window to another window.
Michael Wrightd02c5b62014-02-10 15:10:22 -0800348 *
349 * Returns true on success. False if the window did not actually have touch focus.
350 */
chaviwfbe5d9c2018-12-26 12:23:37 -0800351 virtual bool transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) = 0;
352
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800353 /* Registers input channels that may be used as targets for input events.
354 * If inputWindowHandle is null, and displayId is not ADISPLAY_ID_NONE,
355 * the channel will receive a copy of all input events form the specific displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -0800356 *
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800357 * This method may be called on any thread (usually by the input manager).
Michael Wrightd02c5b62014-02-10 15:10:22 -0800358 */
Robert Carr803535b2018-08-02 16:38:15 -0700359 virtual status_t registerInputChannel(
360 const sp<InputChannel>& inputChannel, int32_t displayId) = 0;
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800361
362 /* Unregister input channels that will no longer receive input events.
363 *
364 * This method may be called on any thread (usually by the input manager).
365 */
Michael Wrightd02c5b62014-02-10 15:10:22 -0800366 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel) = 0;
367};
368
369/* Dispatches events to input targets. Some functions of the input dispatcher, such as
370 * identifying input targets, are controlled by a separate policy object.
371 *
372 * IMPORTANT INVARIANT:
373 * Because the policy can potentially block or cause re-entrance into the input dispatcher,
374 * the input dispatcher never calls into the policy while holding its internal locks.
375 * The implementation is also carefully designed to recover from scenarios such as an
376 * input channel becoming unregistered while identifying input targets or processing timeouts.
377 *
378 * Methods marked 'Locked' must be called with the lock acquired.
379 *
380 * Methods marked 'LockedInterruptible' must be called with the lock acquired but
381 * may during the course of their execution release the lock, call into the policy, and
382 * then reacquire the lock. The caller is responsible for recovering gracefully.
383 *
384 * A 'LockedInterruptible' method may called a 'Locked' method, but NOT vice-versa.
385 */
386class InputDispatcher : public InputDispatcherInterface {
387protected:
388 virtual ~InputDispatcher();
389
390public:
391 explicit InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy);
392
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800393 virtual void dump(std::string& dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800394 virtual void monitor();
395
396 virtual void dispatchOnce();
397
398 virtual void notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args);
399 virtual void notifyKey(const NotifyKeyArgs* args);
400 virtual void notifyMotion(const NotifyMotionArgs* args);
401 virtual void notifySwitch(const NotifySwitchArgs* args);
402 virtual void notifyDeviceReset(const NotifyDeviceResetArgs* args);
403
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800404 virtual int32_t injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800405 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
406 uint32_t policyFlags);
407
Arthur Hungb92218b2018-08-14 12:00:21 +0800408 virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles,
409 int32_t displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +0800410 virtual void setFocusedApplication(int32_t displayId,
411 const sp<InputApplicationHandle>& inputApplicationHandle);
412 virtual void setFocusedDisplay(int32_t displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800413 virtual void setInputDispatchMode(bool enabled, bool frozen);
414 virtual void setInputFilterEnabled(bool enabled);
415
chaviwfbe5d9c2018-12-26 12:23:37 -0800416 virtual bool transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800417
418 virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel,
Robert Carr803535b2018-08-02 16:38:15 -0700419 int32_t displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800420 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel);
421
422private:
423 template <typename T>
424 struct Link {
425 T* next;
426 T* prev;
427
428 protected:
Yi Kong9b14ac62018-07-17 13:48:38 -0700429 inline Link() : next(nullptr), prev(nullptr) { }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800430 };
431
432 struct InjectionState {
433 mutable int32_t refCount;
434
435 int32_t injectorPid;
436 int32_t injectorUid;
437 int32_t injectionResult; // initially INPUT_EVENT_INJECTION_PENDING
438 bool injectionIsAsync; // set to true if injection is not waiting for the result
439 int32_t pendingForegroundDispatches; // the number of foreground dispatches in progress
440
441 InjectionState(int32_t injectorPid, int32_t injectorUid);
442 void release();
443
444 private:
445 ~InjectionState();
446 };
447
448 struct EventEntry : Link<EventEntry> {
449 enum {
450 TYPE_CONFIGURATION_CHANGED,
451 TYPE_DEVICE_RESET,
452 TYPE_KEY,
453 TYPE_MOTION
454 };
455
Prabir Pradhan42611e02018-11-27 14:04:02 -0800456 uint32_t sequenceNum;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800457 mutable int32_t refCount;
458 int32_t type;
459 nsecs_t eventTime;
460 uint32_t policyFlags;
461 InjectionState* injectionState;
462
463 bool dispatchInProgress; // initially false, set to true while dispatching
464
Yi Kong9b14ac62018-07-17 13:48:38 -0700465 inline bool isInjected() const { return injectionState != nullptr; }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800466
467 void release();
468
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800469 virtual void appendDescription(std::string& msg) const = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800470
471 protected:
Prabir Pradhan42611e02018-11-27 14:04:02 -0800472 EventEntry(uint32_t sequenceNum, int32_t type, nsecs_t eventTime, uint32_t policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800473 virtual ~EventEntry();
474 void releaseInjectionState();
475 };
476
477 struct ConfigurationChangedEntry : EventEntry {
Prabir Pradhan42611e02018-11-27 14:04:02 -0800478 explicit ConfigurationChangedEntry(uint32_t sequenceNum, nsecs_t eventTime);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800479 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800480
481 protected:
482 virtual ~ConfigurationChangedEntry();
483 };
484
485 struct DeviceResetEntry : EventEntry {
486 int32_t deviceId;
487
Prabir Pradhan42611e02018-11-27 14:04:02 -0800488 DeviceResetEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800489 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800490
491 protected:
492 virtual ~DeviceResetEntry();
493 };
494
495 struct KeyEntry : EventEntry {
496 int32_t deviceId;
497 uint32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100498 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800499 int32_t action;
500 int32_t flags;
501 int32_t keyCode;
502 int32_t scanCode;
503 int32_t metaState;
504 int32_t repeatCount;
505 nsecs_t downTime;
506
507 bool syntheticRepeat; // set to true for synthetic key repeats
508
509 enum InterceptKeyResult {
510 INTERCEPT_KEY_RESULT_UNKNOWN,
511 INTERCEPT_KEY_RESULT_SKIP,
512 INTERCEPT_KEY_RESULT_CONTINUE,
513 INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER,
514 };
515 InterceptKeyResult interceptKeyResult; // set based on the interception result
516 nsecs_t interceptKeyWakeupTime; // used with INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER
517
Prabir Pradhan42611e02018-11-27 14:04:02 -0800518 KeyEntry(uint32_t sequenceNum, nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100519 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags,
520 int32_t action, int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800521 int32_t repeatCount, nsecs_t downTime);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800522 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800523 void recycle();
524
525 protected:
526 virtual ~KeyEntry();
527 };
528
529 struct MotionEntry : EventEntry {
530 nsecs_t eventTime;
531 int32_t deviceId;
532 uint32_t source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800533 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800534 int32_t action;
Michael Wright7b159c92015-05-14 14:48:03 +0100535 int32_t actionButton;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800536 int32_t flags;
537 int32_t metaState;
538 int32_t buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800539 MotionClassification classification;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800540 int32_t edgeFlags;
541 float xPrecision;
542 float yPrecision;
543 nsecs_t downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800544 uint32_t pointerCount;
545 PointerProperties pointerProperties[MAX_POINTERS];
546 PointerCoords pointerCoords[MAX_POINTERS];
547
Prabir Pradhan42611e02018-11-27 14:04:02 -0800548 MotionEntry(uint32_t sequenceNum, nsecs_t eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800549 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +0100550 int32_t action, int32_t actionButton, int32_t flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800551 int32_t metaState, int32_t buttonState, MotionClassification classification,
552 int32_t edgeFlags, float xPrecision, float yPrecision,
553 nsecs_t downTime, uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -0800554 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
555 float xOffset, float yOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800556 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800557
558 protected:
559 virtual ~MotionEntry();
560 };
561
562 // Tracks the progress of dispatching a particular event to a particular connection.
563 struct DispatchEntry : Link<DispatchEntry> {
564 const uint32_t seq; // unique sequence number, never 0
565
566 EventEntry* eventEntry; // the event to dispatch
567 int32_t targetFlags;
568 float xOffset;
569 float yOffset;
Robert Carre07e1032018-11-26 12:55:53 -0800570 float globalScaleFactor;
571 float windowXScale = 1.0f;
572 float windowYScale = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800573 nsecs_t deliveryTime; // time when the event was actually delivered
574
575 // Set to the resolved action and flags when the event is enqueued.
576 int32_t resolvedAction;
577 int32_t resolvedFlags;
578
579 DispatchEntry(EventEntry* eventEntry,
Robert Carre07e1032018-11-26 12:55:53 -0800580 int32_t targetFlags, float xOffset, float yOffset,
581 float globalScaleFactor, float windowXScale, float windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800582 ~DispatchEntry();
583
584 inline bool hasForegroundTarget() const {
585 return targetFlags & InputTarget::FLAG_FOREGROUND;
586 }
587
588 inline bool isSplit() const {
589 return targetFlags & InputTarget::FLAG_SPLIT;
590 }
591
592 private:
593 static volatile int32_t sNextSeqAtomic;
594
595 static uint32_t nextSeq();
596 };
597
598 // A command entry captures state and behavior for an action to be performed in the
599 // dispatch loop after the initial processing has taken place. It is essentially
600 // a kind of continuation used to postpone sensitive policy interactions to a point
601 // in the dispatch loop where it is safe to release the lock (generally after finishing
602 // the critical parts of the dispatch cycle).
603 //
604 // The special thing about commands is that they can voluntarily release and reacquire
605 // the dispatcher lock at will. Initially when the command starts running, the
606 // dispatcher lock is held. However, if the command needs to call into the policy to
607 // do some work, it can release the lock, do the work, then reacquire the lock again
608 // before returning.
609 //
610 // This mechanism is a bit clunky but it helps to preserve the invariant that the dispatch
611 // never calls into the policy while holding its lock.
612 //
613 // Commands are implicitly 'LockedInterruptible'.
614 struct CommandEntry;
615 typedef void (InputDispatcher::*Command)(CommandEntry* commandEntry);
616
617 class Connection;
618 struct CommandEntry : Link<CommandEntry> {
Chih-Hung Hsieh6d2ede12016-09-01 11:28:23 -0700619 explicit CommandEntry(Command command);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800620 ~CommandEntry();
621
622 Command command;
623
624 // parameters for the command (usage varies by command)
625 sp<Connection> connection;
626 nsecs_t eventTime;
627 KeyEntry* keyEntry;
628 sp<InputApplicationHandle> inputApplicationHandle;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800629 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800630 int32_t userActivityEventType;
631 uint32_t seq;
632 bool handled;
Robert Carr803535b2018-08-02 16:38:15 -0700633 sp<InputChannel> inputChannel;
chaviw0c06c6e2019-01-09 13:27:07 -0800634 sp<IBinder> oldToken;
635 sp<IBinder> newToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800636 };
637
638 // Generic queue implementation.
639 template <typename T>
640 struct Queue {
641 T* head;
642 T* tail;
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800643 uint32_t entryCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800644
Yi Kong9b14ac62018-07-17 13:48:38 -0700645 inline Queue() : head(nullptr), tail(nullptr), entryCount(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800646 }
647
648 inline bool isEmpty() const {
649 return !head;
650 }
651
652 inline void enqueueAtTail(T* entry) {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800653 entryCount++;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800654 entry->prev = tail;
655 if (tail) {
656 tail->next = entry;
657 } else {
658 head = entry;
659 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700660 entry->next = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800661 tail = entry;
662 }
663
664 inline void enqueueAtHead(T* entry) {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800665 entryCount++;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800666 entry->next = head;
667 if (head) {
668 head->prev = entry;
669 } else {
670 tail = entry;
671 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700672 entry->prev = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800673 head = entry;
674 }
675
676 inline void dequeue(T* entry) {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800677 entryCount--;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800678 if (entry->prev) {
679 entry->prev->next = entry->next;
680 } else {
681 head = entry->next;
682 }
683 if (entry->next) {
684 entry->next->prev = entry->prev;
685 } else {
686 tail = entry->prev;
687 }
688 }
689
690 inline T* dequeueAtHead() {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800691 entryCount--;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692 T* entry = head;
693 head = entry->next;
694 if (head) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700695 head->prev = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800696 } else {
Yi Kong9b14ac62018-07-17 13:48:38 -0700697 tail = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 }
699 return entry;
700 }
701
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800702 uint32_t count() const {
703 return entryCount;
704 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800705 };
706
707 /* Specifies which events are to be canceled and why. */
708 struct CancelationOptions {
709 enum Mode {
710 CANCEL_ALL_EVENTS = 0,
711 CANCEL_POINTER_EVENTS = 1,
712 CANCEL_NON_POINTER_EVENTS = 2,
713 CANCEL_FALLBACK_EVENTS = 3,
Tiger Huang721e26f2018-07-24 22:26:19 +0800714
715 /* Cancel events where the display not specified. These events would go to the focused
716 * display. */
717 CANCEL_DISPLAY_UNSPECIFIED_EVENTS = 4,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718 };
719
720 // The criterion to use to determine which events should be canceled.
721 Mode mode;
722
723 // Descriptive reason for the cancelation.
724 const char* reason;
725
726 // The specific keycode of the key event to cancel, or -1 to cancel any key event.
727 int32_t keyCode;
728
729 // The specific device id of events to cancel, or -1 to cancel events from any device.
730 int32_t deviceId;
731
732 CancelationOptions(Mode mode, const char* reason) :
733 mode(mode), reason(reason), keyCode(-1), deviceId(-1) { }
734 };
735
736 /* Tracks dispatched key and motion event state so that cancelation events can be
737 * synthesized when events are dropped. */
738 class InputState {
739 public:
740 InputState();
741 ~InputState();
742
743 // Returns true if there is no state to be canceled.
744 bool isNeutral() const;
745
746 // Returns true if the specified source is known to have received a hover enter
747 // motion event.
748 bool isHovering(int32_t deviceId, uint32_t source, int32_t displayId) const;
749
750 // Records tracking information for a key event that has just been published.
751 // Returns true if the event should be delivered, false if it is inconsistent
752 // and should be skipped.
753 bool trackKey(const KeyEntry* entry, int32_t action, int32_t flags);
754
755 // Records tracking information for a motion event that has just been published.
756 // Returns true if the event should be delivered, false if it is inconsistent
757 // and should be skipped.
758 bool trackMotion(const MotionEntry* entry, int32_t action, int32_t flags);
759
760 // Synthesizes cancelation events for the current state and resets the tracked state.
761 void synthesizeCancelationEvents(nsecs_t currentTime,
762 Vector<EventEntry*>& outEvents, const CancelationOptions& options);
763
764 // Clears the current state.
765 void clear();
766
767 // Copies pointer-related parts of the input state to another instance.
768 void copyPointerStateTo(InputState& other) const;
769
770 // Gets the fallback key associated with a keycode.
771 // Returns -1 if none.
772 // Returns AKEYCODE_UNKNOWN if we are only dispatching the unhandled key to the policy.
773 int32_t getFallbackKey(int32_t originalKeyCode);
774
775 // Sets the fallback key for a particular keycode.
776 void setFallbackKey(int32_t originalKeyCode, int32_t fallbackKeyCode);
777
778 // Removes the fallback key for a particular keycode.
779 void removeFallbackKey(int32_t originalKeyCode);
780
781 inline const KeyedVector<int32_t, int32_t>& getFallbackKeys() const {
782 return mFallbackKeys;
783 }
784
785 private:
786 struct KeyMemento {
787 int32_t deviceId;
788 uint32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100789 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800790 int32_t keyCode;
791 int32_t scanCode;
792 int32_t metaState;
793 int32_t flags;
794 nsecs_t downTime;
795 uint32_t policyFlags;
796 };
797
798 struct MotionMemento {
799 int32_t deviceId;
800 uint32_t source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800801 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800802 int32_t flags;
803 float xPrecision;
804 float yPrecision;
805 nsecs_t downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806 uint32_t pointerCount;
807 PointerProperties pointerProperties[MAX_POINTERS];
808 PointerCoords pointerCoords[MAX_POINTERS];
809 bool hovering;
810 uint32_t policyFlags;
811
812 void setPointers(const MotionEntry* entry);
813 };
814
815 Vector<KeyMemento> mKeyMementos;
816 Vector<MotionMemento> mMotionMementos;
817 KeyedVector<int32_t, int32_t> mFallbackKeys;
818
819 ssize_t findKeyMemento(const KeyEntry* entry) const;
820 ssize_t findMotionMemento(const MotionEntry* entry, bool hovering) const;
821
822 void addKeyMemento(const KeyEntry* entry, int32_t flags);
823 void addMotionMemento(const MotionEntry* entry, int32_t flags, bool hovering);
824
825 static bool shouldCancelKey(const KeyMemento& memento,
826 const CancelationOptions& options);
827 static bool shouldCancelMotion(const MotionMemento& memento,
828 const CancelationOptions& options);
829 };
830
831 /* Manages the dispatch state associated with a single input channel. */
832 class Connection : public RefBase {
833 protected:
834 virtual ~Connection();
835
836 public:
837 enum Status {
838 // Everything is peachy.
839 STATUS_NORMAL,
840 // An unrecoverable communication error has occurred.
841 STATUS_BROKEN,
842 // The input channel has been unregistered.
843 STATUS_ZOMBIE
844 };
845
846 Status status;
847 sp<InputChannel> inputChannel; // never null
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848 bool monitor;
849 InputPublisher inputPublisher;
850 InputState inputState;
851
852 // True if the socket is full and no further events can be published until
853 // the application consumes some of the input.
854 bool inputPublisherBlocked;
855
856 // Queue of events that need to be published to the connection.
857 Queue<DispatchEntry> outboundQueue;
858
859 // Queue of events that have been published to the connection but that have not
860 // yet received a "finished" response from the application.
861 Queue<DispatchEntry> waitQueue;
862
Robert Carr803535b2018-08-02 16:38:15 -0700863 explicit Connection(const sp<InputChannel>& inputChannel, bool monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -0800865 inline const std::string getInputChannelName() const { return inputChannel->getName(); }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800866
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -0800867 const std::string getWindowName() const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800868 const char* getStatusLabel() const;
869
870 DispatchEntry* findWaitQueueEntry(uint32_t seq);
871 };
872
873 enum DropReason {
874 DROP_REASON_NOT_DROPPED = 0,
875 DROP_REASON_POLICY = 1,
876 DROP_REASON_APP_SWITCH = 2,
877 DROP_REASON_DISABLED = 3,
878 DROP_REASON_BLOCKED = 4,
879 DROP_REASON_STALE = 5,
880 };
881
882 sp<InputDispatcherPolicyInterface> mPolicy;
883 InputDispatcherConfiguration mConfig;
884
885 Mutex mLock;
886
887 Condition mDispatcherIsAliveCondition;
888
889 sp<Looper> mLooper;
890
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800891 EventEntry* mPendingEvent GUARDED_BY(mLock);
892 Queue<EventEntry> mInboundQueue GUARDED_BY(mLock);
893 Queue<EventEntry> mRecentQueue GUARDED_BY(mLock);
894 Queue<CommandEntry> mCommandQueue GUARDED_BY(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800896 DropReason mLastDropReason GUARDED_BY(mLock);
Michael Wright3a981722015-06-10 15:26:13 +0100897
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800898 void dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899
900 // Enqueues an inbound event. Returns true if mLooper->wake() should be called.
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800901 bool enqueueInboundEventLocked(EventEntry* entry) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902
903 // Cleans up input state when dropping an inbound event.
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800904 void dropInboundEventLocked(EventEntry* entry, DropReason dropReason) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905
906 // Adds an event to a queue of recent events for debugging purposes.
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800907 void addRecentEventLocked(EventEntry* entry) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908
909 // App switch latency optimization.
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800910 bool mAppSwitchSawKeyDown GUARDED_BY(mLock);
911 nsecs_t mAppSwitchDueTime GUARDED_BY(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800913 bool isAppSwitchKeyEvent(KeyEntry* keyEntry);
914 bool isAppSwitchPendingLocked() REQUIRES(mLock);
915 void resetPendingAppSwitchLocked(bool handled) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800916
917 // Stale event latency optimization.
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800918 static bool isStaleEvent(nsecs_t currentTime, EventEntry* entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800919
920 // Blocked event latency optimization. Drops old events when the user intends
921 // to transfer focus to a new application.
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800922 EventEntry* mNextUnblockedEvent GUARDED_BY(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800924 sp<InputWindowHandle> findTouchedWindowAtLocked(int32_t displayId, int32_t x, int32_t y,
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800925 bool addOutsideTargets = false, bool addPortalWindows = false) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926
927 // All registered connections mapped by channel file descriptor.
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800928 KeyedVector<int, sp<Connection> > mConnectionsByFd GUARDED_BY(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800929
Robert Carr5c8a0262018-10-03 16:30:44 -0700930 struct IBinderHash {
931 std::size_t operator()(const sp<IBinder>& b) const {
932 return std::hash<IBinder *>{}(b.get());
933 }
934 };
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800935 std::unordered_map<sp<IBinder>, sp<InputChannel>, IBinderHash> mInputChannelsByToken
936 GUARDED_BY(mLock);
Robert Carr5c8a0262018-10-03 16:30:44 -0700937
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800938 ssize_t getConnectionIndexLocked(const sp<InputChannel>& inputChannel) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800939
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800940 // Input channels that will receive a copy of all input events sent to the provided display.
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800941 std::unordered_map<int32_t, Vector<sp<InputChannel>>> mMonitoringChannelsByDisplay
942 GUARDED_BY(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800943
944 // Event injection and synchronization.
945 Condition mInjectionResultAvailableCondition;
946 bool hasInjectionPermission(int32_t injectorPid, int32_t injectorUid);
947 void setInjectionResultLocked(EventEntry* entry, int32_t injectionResult);
948
949 Condition mInjectionSyncFinishedCondition;
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800950 void incrementPendingForegroundDispatches(EventEntry* entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951 void decrementPendingForegroundDispatchesLocked(EventEntry* entry);
952
953 // Key repeat tracking.
954 struct KeyRepeatState {
955 KeyEntry* lastKeyEntry; // or null if no repeat
956 nsecs_t nextRepeatTime;
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800957 } mKeyRepeatState GUARDED_BY(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800958
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800959 void resetKeyRepeatLocked() REQUIRES(mLock);
960 KeyEntry* synthesizeKeyRepeatLocked(nsecs_t currentTime) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961
Michael Wright78f24442014-08-06 15:55:28 -0700962 // Key replacement tracking
963 struct KeyReplacement {
964 int32_t keyCode;
965 int32_t deviceId;
966 bool operator==(const KeyReplacement& rhs) const {
967 return keyCode == rhs.keyCode && deviceId == rhs.deviceId;
968 }
969 bool operator<(const KeyReplacement& rhs) const {
970 return keyCode != rhs.keyCode ? keyCode < rhs.keyCode : deviceId < rhs.deviceId;
971 }
972 };
973 // Maps the key code replaced, device id tuple to the key code it was replaced with
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800974 KeyedVector<KeyReplacement, int32_t> mReplacedKeys GUARDED_BY(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -0500975 // Process certain Meta + Key combinations
976 void accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
977 int32_t& keyCode, int32_t& metaState);
Michael Wright78f24442014-08-06 15:55:28 -0700978
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979 // Deferred command processing.
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800980 bool haveCommandsLocked() const REQUIRES(mLock);
981 bool runCommandsLockedInterruptible() REQUIRES(mLock);
982 CommandEntry* postCommandLocked(Command command) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800983
984 // Input filter processing.
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800985 bool shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) REQUIRES(mLock);
986 bool shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800987
988 // Inbound event processing.
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800989 void drainInboundQueueLocked() REQUIRES(mLock);
990 void releasePendingEventLocked() REQUIRES(mLock);
991 void releaseInboundEventLocked(EventEntry* entry) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992
993 // Dispatch state.
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800994 bool mDispatchEnabled GUARDED_BY(mLock);
995 bool mDispatchFrozen GUARDED_BY(mLock);
996 bool mInputFilterEnabled GUARDED_BY(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800997
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800998 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>> mWindowHandlesByDisplay
999 GUARDED_BY(mLock);
Arthur Hungb92218b2018-08-14 12:00:21 +08001000 // Get window handles by display, return an empty vector if not found.
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001001 Vector<sp<InputWindowHandle>> getWindowHandlesLocked(int32_t displayId) const REQUIRES(mLock);
1002 sp<InputWindowHandle> getWindowHandleLocked(const sp<IBinder>& windowHandleToken) const
1003 REQUIRES(mLock);
1004 sp<InputChannel> getInputChannelLocked(const sp<IBinder>& windowToken) const REQUIRES(mLock);
1005 bool hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006
1007 // Focus tracking for keys, trackball, etc.
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001008 std::unordered_map<int32_t, sp<InputWindowHandle>> mFocusedWindowHandlesByDisplay
1009 GUARDED_BY(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010
1011 // Focus tracking for touch.
1012 struct TouchedWindow {
1013 sp<InputWindowHandle> windowHandle;
1014 int32_t targetFlags;
1015 BitSet32 pointerIds; // zero unless target flag FLAG_SPLIT is set
1016 };
1017 struct TouchState {
1018 bool down;
1019 bool split;
1020 int32_t deviceId; // id of the device that is currently down, others are rejected
1021 uint32_t source; // source of the device that is current down, others are rejected
1022 int32_t displayId; // id to the display that currently has a touch, others are rejected
1023 Vector<TouchedWindow> windows;
1024
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001025 // This collects the portal windows that the touch has gone through. Each portal window
1026 // targets a display (embedded display for most cases). With this info, we can add the
1027 // monitoring channels of the displays touched.
1028 Vector<sp<InputWindowHandle>> portalWindows;
1029
Michael Wrightd02c5b62014-02-10 15:10:22 -08001030 TouchState();
1031 ~TouchState();
1032 void reset();
1033 void copyFrom(const TouchState& other);
1034 void addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
1035 int32_t targetFlags, BitSet32 pointerIds);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001036 void addPortalWindow(const sp<InputWindowHandle>& windowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001037 void removeWindow(const sp<InputWindowHandle>& windowHandle);
Robert Carr803535b2018-08-02 16:38:15 -07001038 void removeWindowByToken(const sp<IBinder>& token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 void filterNonAsIsTouchWindows();
1040 sp<InputWindowHandle> getFirstForegroundWindowHandle() const;
1041 bool isSlippery() const;
1042 };
1043
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001044 KeyedVector<int32_t, TouchState> mTouchStatesByDisplay GUARDED_BY(mLock);
1045 TouchState mTempTouchState GUARDED_BY(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001046
Tiger Huang721e26f2018-07-24 22:26:19 +08001047 // Focused applications.
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001048 std::unordered_map<int32_t, sp<InputApplicationHandle>> mFocusedApplicationHandlesByDisplay
1049 GUARDED_BY(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08001050
1051 // Top focused display.
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001052 int32_t mFocusedDisplayId GUARDED_BY(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053
1054 // Dispatcher state at time of last ANR.
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001055 std::string mLastANRState GUARDED_BY(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056
1057 // Dispatch inbound events.
1058 bool dispatchConfigurationChangedLocked(
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001059 nsecs_t currentTime, ConfigurationChangedEntry* entry) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001060 bool dispatchDeviceResetLocked(
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001061 nsecs_t currentTime, DeviceResetEntry* entry) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062 bool dispatchKeyLocked(
1063 nsecs_t currentTime, KeyEntry* entry,
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001064 DropReason* dropReason, nsecs_t* nextWakeupTime) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065 bool dispatchMotionLocked(
1066 nsecs_t currentTime, MotionEntry* entry,
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001067 DropReason* dropReason, nsecs_t* nextWakeupTime) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001068 void dispatchEventLocked(nsecs_t currentTime, EventEntry* entry,
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001069 const Vector<InputTarget>& inputTargets) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001070
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001071 void logOutboundKeyDetails(const char* prefix, const KeyEntry* entry);
1072 void logOutboundMotionDetails(const char* prefix, const MotionEntry* entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073
1074 // Keeping track of ANR timeouts.
1075 enum InputTargetWaitCause {
1076 INPUT_TARGET_WAIT_CAUSE_NONE,
1077 INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY,
1078 INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY,
1079 };
1080
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001081 InputTargetWaitCause mInputTargetWaitCause GUARDED_BY(mLock);
1082 nsecs_t mInputTargetWaitStartTime GUARDED_BY(mLock);
1083 nsecs_t mInputTargetWaitTimeoutTime GUARDED_BY(mLock);
1084 bool mInputTargetWaitTimeoutExpired GUARDED_BY(mLock);
1085 sp<IBinder> mInputTargetWaitApplicationToken GUARDED_BY(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001086
1087 // Contains the last window which received a hover event.
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001088 sp<InputWindowHandle> mLastHoverWindowHandle GUARDED_BY(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001089
1090 // Finding targets for input events.
1091 int32_t handleTargetsNotReadyLocked(nsecs_t currentTime, const EventEntry* entry,
1092 const sp<InputApplicationHandle>& applicationHandle,
1093 const sp<InputWindowHandle>& windowHandle,
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001094 nsecs_t* nextWakeupTime, const char* reason) REQUIRES(mLock);
Robert Carr803535b2018-08-02 16:38:15 -07001095
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001096 void removeWindowByTokenLocked(const sp<IBinder>& token) REQUIRES(mLock);
Robert Carr803535b2018-08-02 16:38:15 -07001097
Michael Wrightd02c5b62014-02-10 15:10:22 -08001098 void resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001099 const sp<InputChannel>& inputChannel) REQUIRES(mLock);
1100 nsecs_t getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime) REQUIRES(mLock);
1101 void resetANRTimeoutsLocked() REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001102
Tiger Huang721e26f2018-07-24 22:26:19 +08001103 int32_t getTargetDisplayId(const EventEntry* entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001104 int32_t findFocusedWindowTargetsLocked(nsecs_t currentTime, const EventEntry* entry,
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001105 Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106 int32_t findTouchedWindowTargetsLocked(nsecs_t currentTime, const MotionEntry* entry,
1107 Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001108 bool* outConflictingPointerActions) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001109
1110 void addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001111 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets)
1112 REQUIRES(mLock);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001113 void addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets, int32_t displayId,
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001114 float xOffset = 0, float yOffset = 0) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001115
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001116 void pokeUserActivityLocked(const EventEntry* eventEntry) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001117 bool checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1118 const InjectionState* injectionState);
1119 bool isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001120 int32_t x, int32_t y) const REQUIRES(mLock);
1121 bool isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const REQUIRES(mLock);
1122 std::string getApplicationWindowLabel(const sp<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123 const sp<InputWindowHandle>& windowHandle);
1124
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001125 std::string checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001126 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001127 const char* targetType) REQUIRES(mLock);
Jeff Brownffb49772014-10-10 19:01:34 -07001128
Michael Wrightd02c5b62014-02-10 15:10:22 -08001129 // Manage the dispatch cycle for a single connection.
1130 // These methods are deliberately not Interruptible because doing all of the work
1131 // with the mutex held makes it easier to ensure that connection invariants are maintained.
1132 // If needed, the methods post commands to run later once the critical bits are done.
1133 void prepareDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001134 EventEntry* eventEntry, const InputTarget* inputTarget) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001135 void enqueueDispatchEntriesLocked(nsecs_t currentTime, const sp<Connection>& connection,
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001136 EventEntry* eventEntry, const InputTarget* inputTarget) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001137 void enqueueDispatchEntryLocked(const sp<Connection>& connection,
1138 EventEntry* eventEntry, const InputTarget* inputTarget, int32_t dispatchMode);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001139 void startDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection)
1140 REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141 void finishDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001142 uint32_t seq, bool handled) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001143 void abortBrokenDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001144 bool notify) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001145 void drainDispatchQueueLocked(Queue<DispatchEntry>* queue);
1146 void releaseDispatchEntryLocked(DispatchEntry* dispatchEntry);
1147 static int handleReceiveCallback(int fd, int events, void* data);
1148
1149 void synthesizeCancelationEventsForAllConnectionsLocked(
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001150 const CancelationOptions& options) REQUIRES(mLock);
1151 void synthesizeCancelationEventsForMonitorsLocked(
1152 const CancelationOptions& options) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001153 void synthesizeCancelationEventsForInputChannelLocked(const sp<InputChannel>& channel,
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001154 const CancelationOptions& options) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155 void synthesizeCancelationEventsForConnectionLocked(const sp<Connection>& connection,
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001156 const CancelationOptions& options) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001157
1158 // Splitting motion events across windows.
1159 MotionEntry* splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds);
1160
1161 // Reset and drop everything the dispatcher is doing.
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001162 void resetAndDropEverythingLocked(const char* reason) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163
1164 // Dump state.
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001165 void dumpDispatchStateLocked(std::string& dump) REQUIRES(mLock);
1166 void logDispatchStateLocked() REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167
1168 // Registration.
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001169 void removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) REQUIRES(mLock);
1170 status_t unregisterInputChannelLocked(const sp<InputChannel>& inputChannel, bool notify)
1171 REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001172
1173 // Interesting events that we might like to log or tell the framework about.
1174 void onDispatchCycleFinishedLocked(
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001175 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled)
1176 REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177 void onDispatchCycleBrokenLocked(
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001178 nsecs_t currentTime, const sp<Connection>& connection) REQUIRES(mLock);
chaviw0c06c6e2019-01-09 13:27:07 -08001179 void onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001180 const sp<InputWindowHandle>& newFocus) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 void onANRLocked(
1182 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
1183 const sp<InputWindowHandle>& windowHandle,
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001184 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001185
1186 // Outbound policy interactions.
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001187 void doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry)
1188 REQUIRES(mLock);
1189 void doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) REQUIRES(mLock);
1190 void doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) REQUIRES(mLock);
1191 void doNotifyANRLockedInterruptible(CommandEntry* commandEntry) REQUIRES(mLock);
1192 void doInterceptKeyBeforeDispatchingLockedInterruptible(CommandEntry* commandEntry)
1193 REQUIRES(mLock);
1194 void doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001195 bool afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001196 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 bool afterMotionEventLockedInterruptible(const sp<Connection>& connection,
1198 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001199 void doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) REQUIRES(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 void initializeKeyEvent(KeyEvent* event, const KeyEntry* entry);
1201
1202 // Statistics gathering.
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001203 void updateDispatchStatistics(nsecs_t currentTime, const EventEntry* entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001205 void traceInboundQueueLengthLocked() REQUIRES(mLock);
1206 void traceOutboundQueueLength(const sp<Connection>& connection);
1207 void traceWaitQueueLength(const sp<Connection>& connection);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08001208
Prabir Pradhan79a4f0c2019-01-09 11:24:01 -08001209 sp<InputReporterInterface> mReporter;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001210};
1211
1212/* Enqueues and dispatches input events, endlessly. */
1213class InputDispatcherThread : public Thread {
1214public:
1215 explicit InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher);
1216 ~InputDispatcherThread();
1217
1218private:
1219 virtual bool threadLoop();
1220
1221 sp<InputDispatcherInterface> mDispatcher;
1222};
1223
1224} // namespace android
1225
1226#endif // _UI_INPUT_DISPATCHER_H