blob: 9ecabdbf086050ce97a5a13b7815edfece6c2c92 [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"
40
41
42namespace android {
43
44/*
45 * Constants used to report the outcome of input event injection.
46 */
47enum {
48 /* (INTERNAL USE ONLY) Specifies that injection is pending and its outcome is unknown. */
49 INPUT_EVENT_INJECTION_PENDING = -1,
50
51 /* Injection succeeded. */
52 INPUT_EVENT_INJECTION_SUCCEEDED = 0,
53
54 /* Injection failed because the injector did not have permission to inject
55 * into the application with input focus. */
56 INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1,
57
58 /* Injection failed because there were no available input targets. */
59 INPUT_EVENT_INJECTION_FAILED = 2,
60
61 /* Injection failed due to a timeout. */
62 INPUT_EVENT_INJECTION_TIMED_OUT = 3
63};
64
65/*
66 * Constants used to determine the input event injection synchronization mode.
67 */
68enum {
69 /* Injection is asynchronous and is assumed always to be successful. */
70 INPUT_EVENT_INJECTION_SYNC_NONE = 0,
71
72 /* Waits for previous events to be dispatched so that the input dispatcher can determine
73 * whether input event injection willbe permitted based on the current input focus.
74 * Does not wait for the input event to finish processing. */
75 INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_RESULT = 1,
76
77 /* Waits for the input event to be completely processed. */
78 INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED = 2,
79};
80
81
82/*
83 * An input target specifies how an input event is to be dispatched to a particular window
84 * including the window's input channel, control flags, a timeout, and an X / Y offset to
85 * be added to input event coordinates to compensate for the absolute position of the
86 * window area.
87 */
88struct InputTarget {
89 enum {
90 /* This flag indicates that the event is being delivered to a foreground application. */
91 FLAG_FOREGROUND = 1 << 0,
92
Michael Wrightcdcd8f22016-03-22 16:52:13 -070093 /* This flag indicates that the MotionEvent falls within the area of the target
Michael Wrightd02c5b62014-02-10 15:10:22 -080094 * obscured by another visible window above it. The motion event should be
95 * delivered with flag AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED. */
96 FLAG_WINDOW_IS_OBSCURED = 1 << 1,
97
98 /* This flag indicates that a motion event is being split across multiple windows. */
99 FLAG_SPLIT = 1 << 2,
100
101 /* This flag indicates that the pointer coordinates dispatched to the application
102 * will be zeroed out to avoid revealing information to an application. This is
103 * used in conjunction with FLAG_DISPATCH_AS_OUTSIDE to prevent apps not sharing
104 * the same UID from watching all touches. */
105 FLAG_ZERO_COORDS = 1 << 3,
106
107 /* This flag indicates that the event should be sent as is.
108 * Should always be set unless the event is to be transmuted. */
109 FLAG_DISPATCH_AS_IS = 1 << 8,
110
111 /* This flag indicates that a MotionEvent with AMOTION_EVENT_ACTION_DOWN falls outside
112 * of the area of this target and so should instead be delivered as an
113 * AMOTION_EVENT_ACTION_OUTSIDE to this target. */
114 FLAG_DISPATCH_AS_OUTSIDE = 1 << 9,
115
116 /* This flag indicates that a hover sequence is starting in the given window.
117 * The event is transmuted into ACTION_HOVER_ENTER. */
118 FLAG_DISPATCH_AS_HOVER_ENTER = 1 << 10,
119
120 /* This flag indicates that a hover event happened outside of a window which handled
121 * previous hover events, signifying the end of the current hover sequence for that
122 * window.
123 * The event is transmuted into ACTION_HOVER_ENTER. */
124 FLAG_DISPATCH_AS_HOVER_EXIT = 1 << 11,
125
126 /* This flag indicates that the event should be canceled.
127 * It is used to transmute ACTION_MOVE into ACTION_CANCEL when a touch slips
128 * outside of a window. */
129 FLAG_DISPATCH_AS_SLIPPERY_EXIT = 1 << 12,
130
131 /* This flag indicates that the event should be dispatched as an initial down.
132 * It is used to transmute ACTION_MOVE into ACTION_DOWN when a touch slips
133 * into a new window. */
134 FLAG_DISPATCH_AS_SLIPPERY_ENTER = 1 << 13,
135
136 /* Mask for all dispatch modes. */
137 FLAG_DISPATCH_MASK = FLAG_DISPATCH_AS_IS
138 | FLAG_DISPATCH_AS_OUTSIDE
139 | FLAG_DISPATCH_AS_HOVER_ENTER
140 | FLAG_DISPATCH_AS_HOVER_EXIT
141 | FLAG_DISPATCH_AS_SLIPPERY_EXIT
142 | FLAG_DISPATCH_AS_SLIPPERY_ENTER,
Michael Wrightcdcd8f22016-03-22 16:52:13 -0700143
144 /* This flag indicates that the target of a MotionEvent is partly or wholly
145 * obscured by another visible window above it. The motion event should be
146 * delivered with flag AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED. */
147 FLAG_WINDOW_IS_PARTIALLY_OBSCURED = 1 << 14,
148
Michael Wrightd02c5b62014-02-10 15:10:22 -0800149 };
150
151 // The input channel to be targeted.
152 sp<InputChannel> inputChannel;
153
154 // Flags for the input target.
155 int32_t flags;
156
157 // The x and y offset to add to a MotionEvent as it is delivered.
158 // (ignored for KeyEvents)
159 float xOffset, yOffset;
160
161 // Scaling factor to apply to MotionEvent as it is delivered.
162 // (ignored for KeyEvents)
163 float scaleFactor;
164
165 // The subset of pointer ids to include in motion events dispatched to this input target
166 // if FLAG_SPLIT is set.
167 BitSet32 pointerIds;
168};
169
170
171/*
172 * Input dispatcher configuration.
173 *
174 * Specifies various options that modify the behavior of the input dispatcher.
175 * The values provided here are merely defaults. The actual values will come from ViewConfiguration
176 * and are passed into the dispatcher during initialization.
177 */
178struct InputDispatcherConfiguration {
179 // The key repeat initial timeout.
180 nsecs_t keyRepeatTimeout;
181
182 // The key repeat inter-key delay.
183 nsecs_t keyRepeatDelay;
184
185 InputDispatcherConfiguration() :
186 keyRepeatTimeout(500 * 1000000LL),
187 keyRepeatDelay(50 * 1000000LL) { }
188};
189
190
191/*
192 * Input dispatcher policy interface.
193 *
194 * The input reader policy is used by the input reader to interact with the Window Manager
195 * and other system components.
196 *
197 * The actual implementation is partially supported by callbacks into the DVM
198 * via JNI. This interface is also mocked in the unit tests.
199 */
200class InputDispatcherPolicyInterface : public virtual RefBase {
201protected:
202 InputDispatcherPolicyInterface() { }
203 virtual ~InputDispatcherPolicyInterface() { }
204
205public:
206 /* Notifies the system that a configuration change has occurred. */
207 virtual void notifyConfigurationChanged(nsecs_t when) = 0;
208
209 /* Notifies the system that an application is not responding.
210 * Returns a new timeout to continue waiting, or 0 to abort dispatch. */
211 virtual nsecs_t notifyANR(const sp<InputApplicationHandle>& inputApplicationHandle,
Robert Carr803535b2018-08-02 16:38:15 -0700212 const sp<IBinder>& token,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800213 const std::string& reason) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800214
215 /* Notifies the system that an input channel is unrecoverably broken. */
Robert Carr803535b2018-08-02 16:38:15 -0700216 virtual void notifyInputChannelBroken(const sp<IBinder>& token) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800217
218 /* Gets the input dispatcher configuration. */
219 virtual void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) = 0;
220
Michael Wrightd02c5b62014-02-10 15:10:22 -0800221 /* Filters an input event.
222 * Return true to dispatch the event unmodified, false to consume the event.
223 * A filter can also transform and inject events later by passing POLICY_FLAG_FILTERED
224 * to injectInputEvent.
225 */
226 virtual bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) = 0;
227
228 /* Intercepts a key event immediately before queueing it.
229 * The policy can use this method as an opportunity to perform power management functions
230 * and early event preprocessing such as updating policy flags.
231 *
232 * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
233 * should be dispatched to applications.
234 */
235 virtual void interceptKeyBeforeQueueing(const KeyEvent* keyEvent, uint32_t& policyFlags) = 0;
236
237 /* Intercepts a touch, trackball or other motion event before queueing it.
238 * The policy can use this method as an opportunity to perform power management functions
239 * and early event preprocessing such as updating policy flags.
240 *
241 * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
242 * should be dispatched to applications.
243 */
244 virtual void interceptMotionBeforeQueueing(nsecs_t when, uint32_t& policyFlags) = 0;
245
246 /* Allows the policy a chance to intercept a key before dispatching. */
Robert Carr803535b2018-08-02 16:38:15 -0700247 virtual nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>& token,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800248 const KeyEvent* keyEvent, uint32_t policyFlags) = 0;
249
250 /* Allows the policy a chance to perform default processing for an unhandled key.
251 * Returns an alternate keycode to redispatch as a fallback, or 0 to give up. */
Robert Carr803535b2018-08-02 16:38:15 -0700252 virtual bool dispatchUnhandledKey(const sp<IBinder>& token,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800253 const KeyEvent* keyEvent, uint32_t policyFlags, KeyEvent* outFallbackKeyEvent) = 0;
254
255 /* Notifies the policy about switch events.
256 */
257 virtual void notifySwitch(nsecs_t when,
258 uint32_t switchValues, uint32_t switchMask, uint32_t policyFlags) = 0;
259
260 /* Poke user activity for an event dispatched to a window. */
261 virtual void pokeUserActivity(nsecs_t eventTime, int32_t eventType) = 0;
262
263 /* Checks whether a given application pid/uid has permission to inject input events
264 * into other applications.
265 *
266 * This method is special in that its implementation promises to be non-reentrant and
267 * is safe to call while holding other locks. (Most other methods make no such guarantees!)
268 */
269 virtual bool checkInjectEventsPermissionNonReentrant(
270 int32_t injectorPid, int32_t injectorUid) = 0;
271};
272
273
274/* Notifies the system about input events generated by the input reader.
275 * The dispatcher is expected to be mostly asynchronous. */
276class InputDispatcherInterface : public virtual RefBase, public InputListenerInterface {
277protected:
278 InputDispatcherInterface() { }
279 virtual ~InputDispatcherInterface() { }
280
281public:
282 /* Dumps the state of the input dispatcher.
283 *
284 * This method may be called on any thread (usually by the input manager). */
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800285 virtual void dump(std::string& dump) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800286
287 /* Called by the heatbeat to ensures that the dispatcher has not deadlocked. */
288 virtual void monitor() = 0;
289
290 /* Runs a single iteration of the dispatch loop.
291 * Nominally processes one queued event, a timeout, or a response from an input consumer.
292 *
293 * This method should only be called on the input dispatcher thread.
294 */
295 virtual void dispatchOnce() = 0;
296
297 /* Injects an input event and optionally waits for sync.
298 * The synchronization mode determines whether the method blocks while waiting for
299 * input injection to proceed.
300 * Returns one of the INPUT_EVENT_INJECTION_XXX constants.
301 *
302 * This method may be called on any thread (usually by the input manager).
303 */
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800304 virtual int32_t injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800305 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
306 uint32_t policyFlags) = 0;
307
308 /* Sets the list of input windows.
309 *
310 * This method may be called on any thread (usually by the input manager).
311 */
Arthur Hungb92218b2018-08-14 12:00:21 +0800312 virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles,
313 int32_t displayId) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800314
Tiger Huang721e26f2018-07-24 22:26:19 +0800315 /* Sets the focused application on the given display.
Michael Wrightd02c5b62014-02-10 15:10:22 -0800316 *
317 * This method may be called on any thread (usually by the input manager).
318 */
319 virtual void setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +0800320 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) = 0;
321
322 /* Sets the focused display.
323 *
324 * This method may be called on any thread (usually by the input manager).
325 */
326 virtual void setFocusedDisplay(int32_t displayId) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800327
328 /* Sets the input dispatching mode.
329 *
330 * This method may be called on any thread (usually by the input manager).
331 */
332 virtual void setInputDispatchMode(bool enabled, bool frozen) = 0;
333
334 /* Sets whether input event filtering is enabled.
335 * When enabled, incoming input events are sent to the policy's filterInputEvent
336 * method instead of being dispatched. The filter is expected to use
337 * injectInputEvent to inject the events it would like to have dispatched.
338 * It should include POLICY_FLAG_FILTERED in the policy flags during injection.
339 */
340 virtual void setInputFilterEnabled(bool enabled) = 0;
341
342 /* Transfers touch focus from the window associated with one channel to the
343 * window associated with the other channel.
344 *
345 * Returns true on success. False if the window did not actually have touch focus.
346 */
347 virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel,
348 const sp<InputChannel>& toChannel) = 0;
349
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800350 /* Registers input channels that may be used as targets for input events.
351 * If inputWindowHandle is null, and displayId is not ADISPLAY_ID_NONE,
352 * the channel will receive a copy of all input events form the specific displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -0800353 *
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800354 * This method may be called on any thread (usually by the input manager).
Michael Wrightd02c5b62014-02-10 15:10:22 -0800355 */
Robert Carr803535b2018-08-02 16:38:15 -0700356 virtual status_t registerInputChannel(
357 const sp<InputChannel>& inputChannel, int32_t displayId) = 0;
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800358
359 /* Unregister input channels that will no longer receive input events.
360 *
361 * This method may be called on any thread (usually by the input manager).
362 */
Michael Wrightd02c5b62014-02-10 15:10:22 -0800363 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel) = 0;
364};
365
366/* Dispatches events to input targets. Some functions of the input dispatcher, such as
367 * identifying input targets, are controlled by a separate policy object.
368 *
369 * IMPORTANT INVARIANT:
370 * Because the policy can potentially block or cause re-entrance into the input dispatcher,
371 * the input dispatcher never calls into the policy while holding its internal locks.
372 * The implementation is also carefully designed to recover from scenarios such as an
373 * input channel becoming unregistered while identifying input targets or processing timeouts.
374 *
375 * Methods marked 'Locked' must be called with the lock acquired.
376 *
377 * Methods marked 'LockedInterruptible' must be called with the lock acquired but
378 * may during the course of their execution release the lock, call into the policy, and
379 * then reacquire the lock. The caller is responsible for recovering gracefully.
380 *
381 * A 'LockedInterruptible' method may called a 'Locked' method, but NOT vice-versa.
382 */
383class InputDispatcher : public InputDispatcherInterface {
384protected:
385 virtual ~InputDispatcher();
386
387public:
388 explicit InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy);
389
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800390 virtual void dump(std::string& dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800391 virtual void monitor();
392
393 virtual void dispatchOnce();
394
395 virtual void notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args);
396 virtual void notifyKey(const NotifyKeyArgs* args);
397 virtual void notifyMotion(const NotifyMotionArgs* args);
398 virtual void notifySwitch(const NotifySwitchArgs* args);
399 virtual void notifyDeviceReset(const NotifyDeviceResetArgs* args);
400
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800401 virtual int32_t injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800402 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
403 uint32_t policyFlags);
404
Arthur Hungb92218b2018-08-14 12:00:21 +0800405 virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles,
406 int32_t displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +0800407 virtual void setFocusedApplication(int32_t displayId,
408 const sp<InputApplicationHandle>& inputApplicationHandle);
409 virtual void setFocusedDisplay(int32_t displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800410 virtual void setInputDispatchMode(bool enabled, bool frozen);
411 virtual void setInputFilterEnabled(bool enabled);
412
413 virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel,
414 const sp<InputChannel>& toChannel);
415
416 virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel,
Robert Carr803535b2018-08-02 16:38:15 -0700417 int32_t displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800418 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel);
419
420private:
421 template <typename T>
422 struct Link {
423 T* next;
424 T* prev;
425
426 protected:
Yi Kong9b14ac62018-07-17 13:48:38 -0700427 inline Link() : next(nullptr), prev(nullptr) { }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800428 };
429
430 struct InjectionState {
431 mutable int32_t refCount;
432
433 int32_t injectorPid;
434 int32_t injectorUid;
435 int32_t injectionResult; // initially INPUT_EVENT_INJECTION_PENDING
436 bool injectionIsAsync; // set to true if injection is not waiting for the result
437 int32_t pendingForegroundDispatches; // the number of foreground dispatches in progress
438
439 InjectionState(int32_t injectorPid, int32_t injectorUid);
440 void release();
441
442 private:
443 ~InjectionState();
444 };
445
446 struct EventEntry : Link<EventEntry> {
447 enum {
448 TYPE_CONFIGURATION_CHANGED,
449 TYPE_DEVICE_RESET,
450 TYPE_KEY,
451 TYPE_MOTION
452 };
453
454 mutable int32_t refCount;
455 int32_t type;
456 nsecs_t eventTime;
457 uint32_t policyFlags;
458 InjectionState* injectionState;
459
460 bool dispatchInProgress; // initially false, set to true while dispatching
461
Yi Kong9b14ac62018-07-17 13:48:38 -0700462 inline bool isInjected() const { return injectionState != nullptr; }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800463
464 void release();
465
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800466 virtual void appendDescription(std::string& msg) const = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800467
468 protected:
469 EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags);
470 virtual ~EventEntry();
471 void releaseInjectionState();
472 };
473
474 struct ConfigurationChangedEntry : EventEntry {
Chih-Hung Hsieh6d2ede12016-09-01 11:28:23 -0700475 explicit ConfigurationChangedEntry(nsecs_t eventTime);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800476 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800477
478 protected:
479 virtual ~ConfigurationChangedEntry();
480 };
481
482 struct DeviceResetEntry : EventEntry {
483 int32_t deviceId;
484
485 DeviceResetEntry(nsecs_t eventTime, int32_t deviceId);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800486 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800487
488 protected:
489 virtual ~DeviceResetEntry();
490 };
491
492 struct KeyEntry : EventEntry {
493 int32_t deviceId;
494 uint32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100495 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800496 int32_t action;
497 int32_t flags;
498 int32_t keyCode;
499 int32_t scanCode;
500 int32_t metaState;
501 int32_t repeatCount;
502 nsecs_t downTime;
503
504 bool syntheticRepeat; // set to true for synthetic key repeats
505
506 enum InterceptKeyResult {
507 INTERCEPT_KEY_RESULT_UNKNOWN,
508 INTERCEPT_KEY_RESULT_SKIP,
509 INTERCEPT_KEY_RESULT_CONTINUE,
510 INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER,
511 };
512 InterceptKeyResult interceptKeyResult; // set based on the interception result
513 nsecs_t interceptKeyWakeupTime; // used with INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER
514
515 KeyEntry(nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100516 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags,
517 int32_t action, int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800518 int32_t repeatCount, nsecs_t downTime);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800519 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800520 void recycle();
521
522 protected:
523 virtual ~KeyEntry();
524 };
525
526 struct MotionEntry : EventEntry {
527 nsecs_t eventTime;
528 int32_t deviceId;
529 uint32_t source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800530 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800531 int32_t action;
Michael Wright7b159c92015-05-14 14:48:03 +0100532 int32_t actionButton;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533 int32_t flags;
534 int32_t metaState;
535 int32_t buttonState;
536 int32_t edgeFlags;
537 float xPrecision;
538 float yPrecision;
539 nsecs_t downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800540 uint32_t pointerCount;
541 PointerProperties pointerProperties[MAX_POINTERS];
542 PointerCoords pointerCoords[MAX_POINTERS];
543
544 MotionEntry(nsecs_t eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800545 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +0100546 int32_t action, int32_t actionButton, int32_t flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800547 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800548 float xPrecision, float yPrecision, nsecs_t downTime, uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -0800549 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
550 float xOffset, float yOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800551 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552
553 protected:
554 virtual ~MotionEntry();
555 };
556
557 // Tracks the progress of dispatching a particular event to a particular connection.
558 struct DispatchEntry : Link<DispatchEntry> {
559 const uint32_t seq; // unique sequence number, never 0
560
561 EventEntry* eventEntry; // the event to dispatch
562 int32_t targetFlags;
563 float xOffset;
564 float yOffset;
565 float scaleFactor;
566 nsecs_t deliveryTime; // time when the event was actually delivered
567
568 // Set to the resolved action and flags when the event is enqueued.
569 int32_t resolvedAction;
570 int32_t resolvedFlags;
571
572 DispatchEntry(EventEntry* eventEntry,
573 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor);
574 ~DispatchEntry();
575
576 inline bool hasForegroundTarget() const {
577 return targetFlags & InputTarget::FLAG_FOREGROUND;
578 }
579
580 inline bool isSplit() const {
581 return targetFlags & InputTarget::FLAG_SPLIT;
582 }
583
584 private:
585 static volatile int32_t sNextSeqAtomic;
586
587 static uint32_t nextSeq();
588 };
589
590 // A command entry captures state and behavior for an action to be performed in the
591 // dispatch loop after the initial processing has taken place. It is essentially
592 // a kind of continuation used to postpone sensitive policy interactions to a point
593 // in the dispatch loop where it is safe to release the lock (generally after finishing
594 // the critical parts of the dispatch cycle).
595 //
596 // The special thing about commands is that they can voluntarily release and reacquire
597 // the dispatcher lock at will. Initially when the command starts running, the
598 // dispatcher lock is held. However, if the command needs to call into the policy to
599 // do some work, it can release the lock, do the work, then reacquire the lock again
600 // before returning.
601 //
602 // This mechanism is a bit clunky but it helps to preserve the invariant that the dispatch
603 // never calls into the policy while holding its lock.
604 //
605 // Commands are implicitly 'LockedInterruptible'.
606 struct CommandEntry;
607 typedef void (InputDispatcher::*Command)(CommandEntry* commandEntry);
608
609 class Connection;
610 struct CommandEntry : Link<CommandEntry> {
Chih-Hung Hsieh6d2ede12016-09-01 11:28:23 -0700611 explicit CommandEntry(Command command);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800612 ~CommandEntry();
613
614 Command command;
615
616 // parameters for the command (usage varies by command)
617 sp<Connection> connection;
618 nsecs_t eventTime;
619 KeyEntry* keyEntry;
620 sp<InputApplicationHandle> inputApplicationHandle;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800621 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800622 int32_t userActivityEventType;
623 uint32_t seq;
624 bool handled;
Robert Carr803535b2018-08-02 16:38:15 -0700625 sp<InputChannel> inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626 };
627
628 // Generic queue implementation.
629 template <typename T>
630 struct Queue {
631 T* head;
632 T* tail;
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800633 uint32_t entryCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800634
Yi Kong9b14ac62018-07-17 13:48:38 -0700635 inline Queue() : head(nullptr), tail(nullptr), entryCount(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800636 }
637
638 inline bool isEmpty() const {
639 return !head;
640 }
641
642 inline void enqueueAtTail(T* entry) {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800643 entryCount++;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800644 entry->prev = tail;
645 if (tail) {
646 tail->next = entry;
647 } else {
648 head = entry;
649 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700650 entry->next = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800651 tail = entry;
652 }
653
654 inline void enqueueAtHead(T* entry) {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800655 entryCount++;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800656 entry->next = head;
657 if (head) {
658 head->prev = entry;
659 } else {
660 tail = entry;
661 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700662 entry->prev = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800663 head = entry;
664 }
665
666 inline void dequeue(T* entry) {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800667 entryCount--;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800668 if (entry->prev) {
669 entry->prev->next = entry->next;
670 } else {
671 head = entry->next;
672 }
673 if (entry->next) {
674 entry->next->prev = entry->prev;
675 } else {
676 tail = entry->prev;
677 }
678 }
679
680 inline T* dequeueAtHead() {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800681 entryCount--;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800682 T* entry = head;
683 head = entry->next;
684 if (head) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700685 head->prev = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800686 } else {
Yi Kong9b14ac62018-07-17 13:48:38 -0700687 tail = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800688 }
689 return entry;
690 }
691
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800692 uint32_t count() const {
693 return entryCount;
694 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800695 };
696
697 /* Specifies which events are to be canceled and why. */
698 struct CancelationOptions {
699 enum Mode {
700 CANCEL_ALL_EVENTS = 0,
701 CANCEL_POINTER_EVENTS = 1,
702 CANCEL_NON_POINTER_EVENTS = 2,
703 CANCEL_FALLBACK_EVENTS = 3,
Tiger Huang721e26f2018-07-24 22:26:19 +0800704
705 /* Cancel events where the display not specified. These events would go to the focused
706 * display. */
707 CANCEL_DISPLAY_UNSPECIFIED_EVENTS = 4,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800708 };
709
710 // The criterion to use to determine which events should be canceled.
711 Mode mode;
712
713 // Descriptive reason for the cancelation.
714 const char* reason;
715
716 // The specific keycode of the key event to cancel, or -1 to cancel any key event.
717 int32_t keyCode;
718
719 // The specific device id of events to cancel, or -1 to cancel events from any device.
720 int32_t deviceId;
721
722 CancelationOptions(Mode mode, const char* reason) :
723 mode(mode), reason(reason), keyCode(-1), deviceId(-1) { }
724 };
725
726 /* Tracks dispatched key and motion event state so that cancelation events can be
727 * synthesized when events are dropped. */
728 class InputState {
729 public:
730 InputState();
731 ~InputState();
732
733 // Returns true if there is no state to be canceled.
734 bool isNeutral() const;
735
736 // Returns true if the specified source is known to have received a hover enter
737 // motion event.
738 bool isHovering(int32_t deviceId, uint32_t source, int32_t displayId) const;
739
740 // Records tracking information for a key event that has just been published.
741 // Returns true if the event should be delivered, false if it is inconsistent
742 // and should be skipped.
743 bool trackKey(const KeyEntry* entry, int32_t action, int32_t flags);
744
745 // Records tracking information for a motion event that has just been published.
746 // Returns true if the event should be delivered, false if it is inconsistent
747 // and should be skipped.
748 bool trackMotion(const MotionEntry* entry, int32_t action, int32_t flags);
749
750 // Synthesizes cancelation events for the current state and resets the tracked state.
751 void synthesizeCancelationEvents(nsecs_t currentTime,
752 Vector<EventEntry*>& outEvents, const CancelationOptions& options);
753
754 // Clears the current state.
755 void clear();
756
757 // Copies pointer-related parts of the input state to another instance.
758 void copyPointerStateTo(InputState& other) const;
759
760 // Gets the fallback key associated with a keycode.
761 // Returns -1 if none.
762 // Returns AKEYCODE_UNKNOWN if we are only dispatching the unhandled key to the policy.
763 int32_t getFallbackKey(int32_t originalKeyCode);
764
765 // Sets the fallback key for a particular keycode.
766 void setFallbackKey(int32_t originalKeyCode, int32_t fallbackKeyCode);
767
768 // Removes the fallback key for a particular keycode.
769 void removeFallbackKey(int32_t originalKeyCode);
770
771 inline const KeyedVector<int32_t, int32_t>& getFallbackKeys() const {
772 return mFallbackKeys;
773 }
774
775 private:
776 struct KeyMemento {
777 int32_t deviceId;
778 uint32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100779 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780 int32_t keyCode;
781 int32_t scanCode;
782 int32_t metaState;
783 int32_t flags;
784 nsecs_t downTime;
785 uint32_t policyFlags;
786 };
787
788 struct MotionMemento {
789 int32_t deviceId;
790 uint32_t source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800791 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792 int32_t flags;
793 float xPrecision;
794 float yPrecision;
795 nsecs_t downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800796 uint32_t pointerCount;
797 PointerProperties pointerProperties[MAX_POINTERS];
798 PointerCoords pointerCoords[MAX_POINTERS];
799 bool hovering;
800 uint32_t policyFlags;
801
802 void setPointers(const MotionEntry* entry);
803 };
804
805 Vector<KeyMemento> mKeyMementos;
806 Vector<MotionMemento> mMotionMementos;
807 KeyedVector<int32_t, int32_t> mFallbackKeys;
808
809 ssize_t findKeyMemento(const KeyEntry* entry) const;
810 ssize_t findMotionMemento(const MotionEntry* entry, bool hovering) const;
811
812 void addKeyMemento(const KeyEntry* entry, int32_t flags);
813 void addMotionMemento(const MotionEntry* entry, int32_t flags, bool hovering);
814
815 static bool shouldCancelKey(const KeyMemento& memento,
816 const CancelationOptions& options);
817 static bool shouldCancelMotion(const MotionMemento& memento,
818 const CancelationOptions& options);
819 };
820
821 /* Manages the dispatch state associated with a single input channel. */
822 class Connection : public RefBase {
823 protected:
824 virtual ~Connection();
825
826 public:
827 enum Status {
828 // Everything is peachy.
829 STATUS_NORMAL,
830 // An unrecoverable communication error has occurred.
831 STATUS_BROKEN,
832 // The input channel has been unregistered.
833 STATUS_ZOMBIE
834 };
835
836 Status status;
837 sp<InputChannel> inputChannel; // never null
Michael Wrightd02c5b62014-02-10 15:10:22 -0800838 bool monitor;
839 InputPublisher inputPublisher;
840 InputState inputState;
841
842 // True if the socket is full and no further events can be published until
843 // the application consumes some of the input.
844 bool inputPublisherBlocked;
845
846 // Queue of events that need to be published to the connection.
847 Queue<DispatchEntry> outboundQueue;
848
849 // Queue of events that have been published to the connection but that have not
850 // yet received a "finished" response from the application.
851 Queue<DispatchEntry> waitQueue;
852
Robert Carr803535b2018-08-02 16:38:15 -0700853 explicit Connection(const sp<InputChannel>& inputChannel, bool monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800854
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -0800855 inline const std::string getInputChannelName() const { return inputChannel->getName(); }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800856
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -0800857 const std::string getWindowName() const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800858 const char* getStatusLabel() const;
859
860 DispatchEntry* findWaitQueueEntry(uint32_t seq);
861 };
862
863 enum DropReason {
864 DROP_REASON_NOT_DROPPED = 0,
865 DROP_REASON_POLICY = 1,
866 DROP_REASON_APP_SWITCH = 2,
867 DROP_REASON_DISABLED = 3,
868 DROP_REASON_BLOCKED = 4,
869 DROP_REASON_STALE = 5,
870 };
871
872 sp<InputDispatcherPolicyInterface> mPolicy;
873 InputDispatcherConfiguration mConfig;
874
875 Mutex mLock;
876
877 Condition mDispatcherIsAliveCondition;
878
879 sp<Looper> mLooper;
880
881 EventEntry* mPendingEvent;
882 Queue<EventEntry> mInboundQueue;
883 Queue<EventEntry> mRecentQueue;
884 Queue<CommandEntry> mCommandQueue;
885
Michael Wright3a981722015-06-10 15:26:13 +0100886 DropReason mLastDropReason;
887
Michael Wrightd02c5b62014-02-10 15:10:22 -0800888 void dispatchOnceInnerLocked(nsecs_t* nextWakeupTime);
889
890 // Enqueues an inbound event. Returns true if mLooper->wake() should be called.
891 bool enqueueInboundEventLocked(EventEntry* entry);
892
893 // Cleans up input state when dropping an inbound event.
894 void dropInboundEventLocked(EventEntry* entry, DropReason dropReason);
895
896 // Adds an event to a queue of recent events for debugging purposes.
897 void addRecentEventLocked(EventEntry* entry);
898
899 // App switch latency optimization.
900 bool mAppSwitchSawKeyDown;
901 nsecs_t mAppSwitchDueTime;
902
903 static bool isAppSwitchKeyCode(int32_t keyCode);
904 bool isAppSwitchKeyEventLocked(KeyEntry* keyEntry);
905 bool isAppSwitchPendingLocked();
906 void resetPendingAppSwitchLocked(bool handled);
907
908 // Stale event latency optimization.
909 static bool isStaleEventLocked(nsecs_t currentTime, EventEntry* entry);
910
911 // Blocked event latency optimization. Drops old events when the user intends
912 // to transfer focus to a new application.
913 EventEntry* mNextUnblockedEvent;
914
915 sp<InputWindowHandle> findTouchedWindowAtLocked(int32_t displayId, int32_t x, int32_t y);
916
917 // All registered connections mapped by channel file descriptor.
918 KeyedVector<int, sp<Connection> > mConnectionsByFd;
919
Robert Carr5c8a0262018-10-03 16:30:44 -0700920 struct IBinderHash {
921 std::size_t operator()(const sp<IBinder>& b) const {
922 return std::hash<IBinder *>{}(b.get());
923 }
924 };
925 std::unordered_map<sp<IBinder>, sp<InputChannel>, IBinderHash> mInputChannelsByToken;
926
Michael Wrightd02c5b62014-02-10 15:10:22 -0800927 ssize_t getConnectionIndexLocked(const sp<InputChannel>& inputChannel);
928
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800929 // Input channels that will receive a copy of all input events sent to the provided display.
930 std::unordered_map<int32_t, Vector<sp<InputChannel>>> mMonitoringChannelsByDisplay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931
932 // Event injection and synchronization.
933 Condition mInjectionResultAvailableCondition;
934 bool hasInjectionPermission(int32_t injectorPid, int32_t injectorUid);
935 void setInjectionResultLocked(EventEntry* entry, int32_t injectionResult);
936
937 Condition mInjectionSyncFinishedCondition;
938 void incrementPendingForegroundDispatchesLocked(EventEntry* entry);
939 void decrementPendingForegroundDispatchesLocked(EventEntry* entry);
940
941 // Key repeat tracking.
942 struct KeyRepeatState {
943 KeyEntry* lastKeyEntry; // or null if no repeat
944 nsecs_t nextRepeatTime;
945 } mKeyRepeatState;
946
947 void resetKeyRepeatLocked();
948 KeyEntry* synthesizeKeyRepeatLocked(nsecs_t currentTime);
949
Michael Wright78f24442014-08-06 15:55:28 -0700950 // Key replacement tracking
951 struct KeyReplacement {
952 int32_t keyCode;
953 int32_t deviceId;
954 bool operator==(const KeyReplacement& rhs) const {
955 return keyCode == rhs.keyCode && deviceId == rhs.deviceId;
956 }
957 bool operator<(const KeyReplacement& rhs) const {
958 return keyCode != rhs.keyCode ? keyCode < rhs.keyCode : deviceId < rhs.deviceId;
959 }
960 };
961 // Maps the key code replaced, device id tuple to the key code it was replaced with
962 KeyedVector<KeyReplacement, int32_t> mReplacedKeys;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -0500963 // Process certain Meta + Key combinations
964 void accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
965 int32_t& keyCode, int32_t& metaState);
Michael Wright78f24442014-08-06 15:55:28 -0700966
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967 // Deferred command processing.
968 bool haveCommandsLocked() const;
969 bool runCommandsLockedInterruptible();
970 CommandEntry* postCommandLocked(Command command);
971
972 // Input filter processing.
973 bool shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args);
974 bool shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args);
975
976 // Inbound event processing.
977 void drainInboundQueueLocked();
978 void releasePendingEventLocked();
979 void releaseInboundEventLocked(EventEntry* entry);
980
981 // Dispatch state.
982 bool mDispatchEnabled;
983 bool mDispatchFrozen;
984 bool mInputFilterEnabled;
985
Arthur Hungb92218b2018-08-14 12:00:21 +0800986 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>> mWindowHandlesByDisplay;
987 // Get window handles by display, return an empty vector if not found.
988 Vector<sp<InputWindowHandle>> getWindowHandlesLocked(int32_t displayId) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989 sp<InputWindowHandle> getWindowHandleLocked(const sp<InputChannel>& inputChannel) const;
Robert Carr5c8a0262018-10-03 16:30:44 -0700990 sp<InputChannel> getInputChannelLocked(const sp<IBinder>& windowToken) const;
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +0000991 bool hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992
993 // Focus tracking for keys, trackball, etc.
Tiger Huang721e26f2018-07-24 22:26:19 +0800994 std::unordered_map<int32_t, sp<InputWindowHandle>> mFocusedWindowHandlesByDisplay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800995
996 // Focus tracking for touch.
997 struct TouchedWindow {
998 sp<InputWindowHandle> windowHandle;
999 int32_t targetFlags;
1000 BitSet32 pointerIds; // zero unless target flag FLAG_SPLIT is set
1001 };
1002 struct TouchState {
1003 bool down;
1004 bool split;
1005 int32_t deviceId; // id of the device that is currently down, others are rejected
1006 uint32_t source; // source of the device that is current down, others are rejected
1007 int32_t displayId; // id to the display that currently has a touch, others are rejected
1008 Vector<TouchedWindow> windows;
1009
1010 TouchState();
1011 ~TouchState();
1012 void reset();
1013 void copyFrom(const TouchState& other);
1014 void addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
1015 int32_t targetFlags, BitSet32 pointerIds);
1016 void removeWindow(const sp<InputWindowHandle>& windowHandle);
Robert Carr803535b2018-08-02 16:38:15 -07001017 void removeWindowByToken(const sp<IBinder>& token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018 void filterNonAsIsTouchWindows();
1019 sp<InputWindowHandle> getFirstForegroundWindowHandle() const;
1020 bool isSlippery() const;
1021 };
1022
Jeff Brownf086ddb2014-02-11 14:28:48 -08001023 KeyedVector<int32_t, TouchState> mTouchStatesByDisplay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 TouchState mTempTouchState;
1025
Tiger Huang721e26f2018-07-24 22:26:19 +08001026 // Focused applications.
1027 std::unordered_map<int32_t, sp<InputApplicationHandle>> mFocusedApplicationHandlesByDisplay;
1028
1029 // Top focused display.
1030 int32_t mFocusedDisplayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001031
1032 // Dispatcher state at time of last ANR.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001033 std::string mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001034
1035 // Dispatch inbound events.
1036 bool dispatchConfigurationChangedLocked(
1037 nsecs_t currentTime, ConfigurationChangedEntry* entry);
1038 bool dispatchDeviceResetLocked(
1039 nsecs_t currentTime, DeviceResetEntry* entry);
1040 bool dispatchKeyLocked(
1041 nsecs_t currentTime, KeyEntry* entry,
1042 DropReason* dropReason, nsecs_t* nextWakeupTime);
1043 bool dispatchMotionLocked(
1044 nsecs_t currentTime, MotionEntry* entry,
1045 DropReason* dropReason, nsecs_t* nextWakeupTime);
1046 void dispatchEventLocked(nsecs_t currentTime, EventEntry* entry,
1047 const Vector<InputTarget>& inputTargets);
1048
1049 void logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry);
1050 void logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry);
1051
1052 // Keeping track of ANR timeouts.
1053 enum InputTargetWaitCause {
1054 INPUT_TARGET_WAIT_CAUSE_NONE,
1055 INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY,
1056 INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY,
1057 };
1058
1059 InputTargetWaitCause mInputTargetWaitCause;
1060 nsecs_t mInputTargetWaitStartTime;
1061 nsecs_t mInputTargetWaitTimeoutTime;
1062 bool mInputTargetWaitTimeoutExpired;
Robert Carr740167f2018-10-11 19:03:41 -07001063 sp<IBinder> mInputTargetWaitApplicationToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064
1065 // Contains the last window which received a hover event.
1066 sp<InputWindowHandle> mLastHoverWindowHandle;
1067
1068 // Finding targets for input events.
1069 int32_t handleTargetsNotReadyLocked(nsecs_t currentTime, const EventEntry* entry,
1070 const sp<InputApplicationHandle>& applicationHandle,
1071 const sp<InputWindowHandle>& windowHandle,
1072 nsecs_t* nextWakeupTime, const char* reason);
Robert Carr803535b2018-08-02 16:38:15 -07001073
1074 void removeWindowByTokenLocked(const sp<IBinder>& token);
1075
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076 void resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1077 const sp<InputChannel>& inputChannel);
1078 nsecs_t getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime);
1079 void resetANRTimeoutsLocked();
1080
Tiger Huang721e26f2018-07-24 22:26:19 +08001081 int32_t getTargetDisplayId(const EventEntry* entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082 int32_t findFocusedWindowTargetsLocked(nsecs_t currentTime, const EventEntry* entry,
1083 Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime);
1084 int32_t findTouchedWindowTargetsLocked(nsecs_t currentTime, const MotionEntry* entry,
1085 Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1086 bool* outConflictingPointerActions);
1087
1088 void addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1089 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001090 void addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets, int32_t displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001091
1092 void pokeUserActivityLocked(const EventEntry* eventEntry);
1093 bool checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1094 const InjectionState* injectionState);
1095 bool isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1096 int32_t x, int32_t y) const;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001097 bool isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001098 std::string getApplicationWindowLabelLocked(const sp<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001099 const sp<InputWindowHandle>& windowHandle);
1100
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001101 std::string checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001102 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1103 const char* targetType);
1104
Michael Wrightd02c5b62014-02-10 15:10:22 -08001105 // Manage the dispatch cycle for a single connection.
1106 // These methods are deliberately not Interruptible because doing all of the work
1107 // with the mutex held makes it easier to ensure that connection invariants are maintained.
1108 // If needed, the methods post commands to run later once the critical bits are done.
1109 void prepareDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1110 EventEntry* eventEntry, const InputTarget* inputTarget);
1111 void enqueueDispatchEntriesLocked(nsecs_t currentTime, const sp<Connection>& connection,
1112 EventEntry* eventEntry, const InputTarget* inputTarget);
1113 void enqueueDispatchEntryLocked(const sp<Connection>& connection,
1114 EventEntry* eventEntry, const InputTarget* inputTarget, int32_t dispatchMode);
1115 void startDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
1116 void finishDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1117 uint32_t seq, bool handled);
1118 void abortBrokenDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1119 bool notify);
1120 void drainDispatchQueueLocked(Queue<DispatchEntry>* queue);
1121 void releaseDispatchEntryLocked(DispatchEntry* dispatchEntry);
1122 static int handleReceiveCallback(int fd, int events, void* data);
1123
1124 void synthesizeCancelationEventsForAllConnectionsLocked(
1125 const CancelationOptions& options);
Michael Wrightfa13dcf2015-06-12 13:25:11 +01001126 void synthesizeCancelationEventsForMonitorsLocked(const CancelationOptions& options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001127 void synthesizeCancelationEventsForInputChannelLocked(const sp<InputChannel>& channel,
1128 const CancelationOptions& options);
1129 void synthesizeCancelationEventsForConnectionLocked(const sp<Connection>& connection,
1130 const CancelationOptions& options);
1131
1132 // Splitting motion events across windows.
1133 MotionEntry* splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds);
1134
1135 // Reset and drop everything the dispatcher is doing.
1136 void resetAndDropEverythingLocked(const char* reason);
1137
1138 // Dump state.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001139 void dumpDispatchStateLocked(std::string& dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001140 void logDispatchStateLocked();
1141
1142 // Registration.
1143 void removeMonitorChannelLocked(const sp<InputChannel>& inputChannel);
1144 status_t unregisterInputChannelLocked(const sp<InputChannel>& inputChannel, bool notify);
1145
1146 // Add or remove a connection to the mActiveConnections vector.
1147 void activateConnectionLocked(Connection* connection);
1148 void deactivateConnectionLocked(Connection* connection);
1149
1150 // Interesting events that we might like to log or tell the framework about.
1151 void onDispatchCycleFinishedLocked(
1152 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled);
1153 void onDispatchCycleBrokenLocked(
1154 nsecs_t currentTime, const sp<Connection>& connection);
1155 void onANRLocked(
1156 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
1157 const sp<InputWindowHandle>& windowHandle,
1158 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason);
1159
1160 // Outbound policy interactions.
1161 void doNotifyConfigurationChangedInterruptible(CommandEntry* commandEntry);
1162 void doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry);
1163 void doNotifyANRLockedInterruptible(CommandEntry* commandEntry);
1164 void doInterceptKeyBeforeDispatchingLockedInterruptible(CommandEntry* commandEntry);
1165 void doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry);
1166 bool afterKeyEventLockedInterruptible(const sp<Connection>& connection,
1167 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled);
1168 bool afterMotionEventLockedInterruptible(const sp<Connection>& connection,
1169 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled);
1170 void doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry);
1171 void initializeKeyEvent(KeyEvent* event, const KeyEntry* entry);
1172
1173 // Statistics gathering.
1174 void updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
1175 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication);
1176 void traceInboundQueueLengthLocked();
1177 void traceOutboundQueueLengthLocked(const sp<Connection>& connection);
1178 void traceWaitQueueLengthLocked(const sp<Connection>& connection);
1179};
1180
1181/* Enqueues and dispatches input events, endlessly. */
1182class InputDispatcherThread : public Thread {
1183public:
1184 explicit InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher);
1185 ~InputDispatcherThread();
1186
1187private:
1188 virtual bool threadLoop();
1189
1190 sp<InputDispatcherInterface> mDispatcher;
1191};
1192
1193} // namespace android
1194
1195#endif // _UI_INPUT_DISPATCHER_H