blob: 11df5d91d901eca35624f17e4ae3a569a7a54098 [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;
Robert Carrf759f162018-11-13 12:57:11 -0800217 virtual void notifyFocusChanged(const sp<IBinder>& token) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218
219 /* Gets the input dispatcher configuration. */
220 virtual void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) = 0;
221
Michael Wrightd02c5b62014-02-10 15:10:22 -0800222 /* Filters an input event.
223 * Return true to dispatch the event unmodified, false to consume the event.
224 * A filter can also transform and inject events later by passing POLICY_FLAG_FILTERED
225 * to injectInputEvent.
226 */
227 virtual bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) = 0;
228
229 /* Intercepts a key event immediately before queueing it.
230 * The policy can use this method as an opportunity to perform power management functions
231 * and early event preprocessing such as updating policy flags.
232 *
233 * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
234 * should be dispatched to applications.
235 */
236 virtual void interceptKeyBeforeQueueing(const KeyEvent* keyEvent, uint32_t& policyFlags) = 0;
237
238 /* Intercepts a touch, trackball or other motion event before queueing it.
239 * The policy can use this method as an opportunity to perform power management functions
240 * and early event preprocessing such as updating policy flags.
241 *
242 * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
243 * should be dispatched to applications.
244 */
245 virtual void interceptMotionBeforeQueueing(nsecs_t when, uint32_t& policyFlags) = 0;
246
247 /* Allows the policy a chance to intercept a key before dispatching. */
Robert Carr803535b2018-08-02 16:38:15 -0700248 virtual nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>& token,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800249 const KeyEvent* keyEvent, uint32_t policyFlags) = 0;
250
251 /* Allows the policy a chance to perform default processing for an unhandled key.
252 * Returns an alternate keycode to redispatch as a fallback, or 0 to give up. */
Robert Carr803535b2018-08-02 16:38:15 -0700253 virtual bool dispatchUnhandledKey(const sp<IBinder>& token,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254 const KeyEvent* keyEvent, uint32_t policyFlags, KeyEvent* outFallbackKeyEvent) = 0;
255
256 /* Notifies the policy about switch events.
257 */
258 virtual void notifySwitch(nsecs_t when,
259 uint32_t switchValues, uint32_t switchMask, uint32_t policyFlags) = 0;
260
261 /* Poke user activity for an event dispatched to a window. */
262 virtual void pokeUserActivity(nsecs_t eventTime, int32_t eventType) = 0;
263
264 /* Checks whether a given application pid/uid has permission to inject input events
265 * into other applications.
266 *
267 * This method is special in that its implementation promises to be non-reentrant and
268 * is safe to call while holding other locks. (Most other methods make no such guarantees!)
269 */
270 virtual bool checkInjectEventsPermissionNonReentrant(
271 int32_t injectorPid, int32_t injectorUid) = 0;
272};
273
274
275/* Notifies the system about input events generated by the input reader.
276 * The dispatcher is expected to be mostly asynchronous. */
277class InputDispatcherInterface : public virtual RefBase, public InputListenerInterface {
278protected:
279 InputDispatcherInterface() { }
280 virtual ~InputDispatcherInterface() { }
281
282public:
283 /* Dumps the state of the input dispatcher.
284 *
285 * This method may be called on any thread (usually by the input manager). */
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800286 virtual void dump(std::string& dump) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800287
288 /* Called by the heatbeat to ensures that the dispatcher has not deadlocked. */
289 virtual void monitor() = 0;
290
291 /* Runs a single iteration of the dispatch loop.
292 * Nominally processes one queued event, a timeout, or a response from an input consumer.
293 *
294 * This method should only be called on the input dispatcher thread.
295 */
296 virtual void dispatchOnce() = 0;
297
298 /* Injects an input event and optionally waits for sync.
299 * The synchronization mode determines whether the method blocks while waiting for
300 * input injection to proceed.
301 * Returns one of the INPUT_EVENT_INJECTION_XXX constants.
302 *
303 * This method may be called on any thread (usually by the input manager).
304 */
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800305 virtual int32_t injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800306 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
307 uint32_t policyFlags) = 0;
308
309 /* Sets the list of input windows.
310 *
311 * This method may be called on any thread (usually by the input manager).
312 */
Arthur Hungb92218b2018-08-14 12:00:21 +0800313 virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles,
314 int32_t displayId) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800315
Tiger Huang721e26f2018-07-24 22:26:19 +0800316 /* Sets the focused application on the given display.
Michael Wrightd02c5b62014-02-10 15:10:22 -0800317 *
318 * This method may be called on any thread (usually by the input manager).
319 */
320 virtual void setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +0800321 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) = 0;
322
323 /* Sets the focused display.
324 *
325 * This method may be called on any thread (usually by the input manager).
326 */
327 virtual void setFocusedDisplay(int32_t displayId) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800328
329 /* Sets the input dispatching mode.
330 *
331 * This method may be called on any thread (usually by the input manager).
332 */
333 virtual void setInputDispatchMode(bool enabled, bool frozen) = 0;
334
335 /* Sets whether input event filtering is enabled.
336 * When enabled, incoming input events are sent to the policy's filterInputEvent
337 * method instead of being dispatched. The filter is expected to use
338 * injectInputEvent to inject the events it would like to have dispatched.
339 * It should include POLICY_FLAG_FILTERED in the policy flags during injection.
340 */
341 virtual void setInputFilterEnabled(bool enabled) = 0;
342
343 /* Transfers touch focus from the window associated with one channel to the
344 * window associated with the other channel.
345 *
346 * Returns true on success. False if the window did not actually have touch focus.
347 */
348 virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel,
349 const sp<InputChannel>& toChannel) = 0;
350
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800351 /* Registers input channels that may be used as targets for input events.
352 * If inputWindowHandle is null, and displayId is not ADISPLAY_ID_NONE,
353 * the channel will receive a copy of all input events form the specific displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -0800354 *
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800355 * This method may be called on any thread (usually by the input manager).
Michael Wrightd02c5b62014-02-10 15:10:22 -0800356 */
Robert Carr803535b2018-08-02 16:38:15 -0700357 virtual status_t registerInputChannel(
358 const sp<InputChannel>& inputChannel, int32_t displayId) = 0;
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800359
360 /* Unregister input channels that will no longer receive input events.
361 *
362 * This method may be called on any thread (usually by the input manager).
363 */
Michael Wrightd02c5b62014-02-10 15:10:22 -0800364 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel) = 0;
365};
366
367/* Dispatches events to input targets. Some functions of the input dispatcher, such as
368 * identifying input targets, are controlled by a separate policy object.
369 *
370 * IMPORTANT INVARIANT:
371 * Because the policy can potentially block or cause re-entrance into the input dispatcher,
372 * the input dispatcher never calls into the policy while holding its internal locks.
373 * The implementation is also carefully designed to recover from scenarios such as an
374 * input channel becoming unregistered while identifying input targets or processing timeouts.
375 *
376 * Methods marked 'Locked' must be called with the lock acquired.
377 *
378 * Methods marked 'LockedInterruptible' must be called with the lock acquired but
379 * may during the course of their execution release the lock, call into the policy, and
380 * then reacquire the lock. The caller is responsible for recovering gracefully.
381 *
382 * A 'LockedInterruptible' method may called a 'Locked' method, but NOT vice-versa.
383 */
384class InputDispatcher : public InputDispatcherInterface {
385protected:
386 virtual ~InputDispatcher();
387
388public:
389 explicit InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy);
390
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800391 virtual void dump(std::string& dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800392 virtual void monitor();
393
394 virtual void dispatchOnce();
395
396 virtual void notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args);
397 virtual void notifyKey(const NotifyKeyArgs* args);
398 virtual void notifyMotion(const NotifyMotionArgs* args);
399 virtual void notifySwitch(const NotifySwitchArgs* args);
400 virtual void notifyDeviceReset(const NotifyDeviceResetArgs* args);
401
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800402 virtual int32_t injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800403 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
404 uint32_t policyFlags);
405
Arthur Hungb92218b2018-08-14 12:00:21 +0800406 virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles,
407 int32_t displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +0800408 virtual void setFocusedApplication(int32_t displayId,
409 const sp<InputApplicationHandle>& inputApplicationHandle);
410 virtual void setFocusedDisplay(int32_t displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800411 virtual void setInputDispatchMode(bool enabled, bool frozen);
412 virtual void setInputFilterEnabled(bool enabled);
413
414 virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel,
415 const sp<InputChannel>& toChannel);
416
417 virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel,
Robert Carr803535b2018-08-02 16:38:15 -0700418 int32_t displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800419 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel);
420
421private:
422 template <typename T>
423 struct Link {
424 T* next;
425 T* prev;
426
427 protected:
Yi Kong9b14ac62018-07-17 13:48:38 -0700428 inline Link() : next(nullptr), prev(nullptr) { }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800429 };
430
431 struct InjectionState {
432 mutable int32_t refCount;
433
434 int32_t injectorPid;
435 int32_t injectorUid;
436 int32_t injectionResult; // initially INPUT_EVENT_INJECTION_PENDING
437 bool injectionIsAsync; // set to true if injection is not waiting for the result
438 int32_t pendingForegroundDispatches; // the number of foreground dispatches in progress
439
440 InjectionState(int32_t injectorPid, int32_t injectorUid);
441 void release();
442
443 private:
444 ~InjectionState();
445 };
446
447 struct EventEntry : Link<EventEntry> {
448 enum {
449 TYPE_CONFIGURATION_CHANGED,
450 TYPE_DEVICE_RESET,
451 TYPE_KEY,
452 TYPE_MOTION
453 };
454
455 mutable int32_t refCount;
456 int32_t type;
457 nsecs_t eventTime;
458 uint32_t policyFlags;
459 InjectionState* injectionState;
460
461 bool dispatchInProgress; // initially false, set to true while dispatching
462
Yi Kong9b14ac62018-07-17 13:48:38 -0700463 inline bool isInjected() const { return injectionState != nullptr; }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800464
465 void release();
466
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800467 virtual void appendDescription(std::string& msg) const = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800468
469 protected:
470 EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags);
471 virtual ~EventEntry();
472 void releaseInjectionState();
473 };
474
475 struct ConfigurationChangedEntry : EventEntry {
Chih-Hung Hsieh6d2ede12016-09-01 11:28:23 -0700476 explicit ConfigurationChangedEntry(nsecs_t eventTime);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800477 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800478
479 protected:
480 virtual ~ConfigurationChangedEntry();
481 };
482
483 struct DeviceResetEntry : EventEntry {
484 int32_t deviceId;
485
486 DeviceResetEntry(nsecs_t eventTime, int32_t deviceId);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800487 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800488
489 protected:
490 virtual ~DeviceResetEntry();
491 };
492
493 struct KeyEntry : EventEntry {
494 int32_t deviceId;
495 uint32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100496 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800497 int32_t action;
498 int32_t flags;
499 int32_t keyCode;
500 int32_t scanCode;
501 int32_t metaState;
502 int32_t repeatCount;
503 nsecs_t downTime;
504
505 bool syntheticRepeat; // set to true for synthetic key repeats
506
507 enum InterceptKeyResult {
508 INTERCEPT_KEY_RESULT_UNKNOWN,
509 INTERCEPT_KEY_RESULT_SKIP,
510 INTERCEPT_KEY_RESULT_CONTINUE,
511 INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER,
512 };
513 InterceptKeyResult interceptKeyResult; // set based on the interception result
514 nsecs_t interceptKeyWakeupTime; // used with INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER
515
516 KeyEntry(nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100517 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags,
518 int32_t action, int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800519 int32_t repeatCount, nsecs_t downTime);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800520 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800521 void recycle();
522
523 protected:
524 virtual ~KeyEntry();
525 };
526
527 struct MotionEntry : EventEntry {
528 nsecs_t eventTime;
529 int32_t deviceId;
530 uint32_t source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800531 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800532 int32_t action;
Michael Wright7b159c92015-05-14 14:48:03 +0100533 int32_t actionButton;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800534 int32_t flags;
535 int32_t metaState;
536 int32_t buttonState;
537 int32_t edgeFlags;
538 float xPrecision;
539 float yPrecision;
540 nsecs_t downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800541 uint32_t pointerCount;
542 PointerProperties pointerProperties[MAX_POINTERS];
543 PointerCoords pointerCoords[MAX_POINTERS];
544
545 MotionEntry(nsecs_t eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800546 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +0100547 int32_t action, int32_t actionButton, int32_t flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800548 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800549 float xPrecision, float yPrecision, nsecs_t downTime, uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -0800550 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
551 float xOffset, float yOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800552 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800553
554 protected:
555 virtual ~MotionEntry();
556 };
557
558 // Tracks the progress of dispatching a particular event to a particular connection.
559 struct DispatchEntry : Link<DispatchEntry> {
560 const uint32_t seq; // unique sequence number, never 0
561
562 EventEntry* eventEntry; // the event to dispatch
563 int32_t targetFlags;
564 float xOffset;
565 float yOffset;
566 float scaleFactor;
567 nsecs_t deliveryTime; // time when the event was actually delivered
568
569 // Set to the resolved action and flags when the event is enqueued.
570 int32_t resolvedAction;
571 int32_t resolvedFlags;
572
573 DispatchEntry(EventEntry* eventEntry,
574 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor);
575 ~DispatchEntry();
576
577 inline bool hasForegroundTarget() const {
578 return targetFlags & InputTarget::FLAG_FOREGROUND;
579 }
580
581 inline bool isSplit() const {
582 return targetFlags & InputTarget::FLAG_SPLIT;
583 }
584
585 private:
586 static volatile int32_t sNextSeqAtomic;
587
588 static uint32_t nextSeq();
589 };
590
591 // A command entry captures state and behavior for an action to be performed in the
592 // dispatch loop after the initial processing has taken place. It is essentially
593 // a kind of continuation used to postpone sensitive policy interactions to a point
594 // in the dispatch loop where it is safe to release the lock (generally after finishing
595 // the critical parts of the dispatch cycle).
596 //
597 // The special thing about commands is that they can voluntarily release and reacquire
598 // the dispatcher lock at will. Initially when the command starts running, the
599 // dispatcher lock is held. However, if the command needs to call into the policy to
600 // do some work, it can release the lock, do the work, then reacquire the lock again
601 // before returning.
602 //
603 // This mechanism is a bit clunky but it helps to preserve the invariant that the dispatch
604 // never calls into the policy while holding its lock.
605 //
606 // Commands are implicitly 'LockedInterruptible'.
607 struct CommandEntry;
608 typedef void (InputDispatcher::*Command)(CommandEntry* commandEntry);
609
610 class Connection;
611 struct CommandEntry : Link<CommandEntry> {
Chih-Hung Hsieh6d2ede12016-09-01 11:28:23 -0700612 explicit CommandEntry(Command command);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800613 ~CommandEntry();
614
615 Command command;
616
617 // parameters for the command (usage varies by command)
618 sp<Connection> connection;
619 nsecs_t eventTime;
620 KeyEntry* keyEntry;
621 sp<InputApplicationHandle> inputApplicationHandle;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800622 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800623 int32_t userActivityEventType;
624 uint32_t seq;
625 bool handled;
Robert Carr803535b2018-08-02 16:38:15 -0700626 sp<InputChannel> inputChannel;
Robert Carrf759f162018-11-13 12:57:11 -0800627 sp<IBinder> token;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800628 };
629
630 // Generic queue implementation.
631 template <typename T>
632 struct Queue {
633 T* head;
634 T* tail;
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800635 uint32_t entryCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800636
Yi Kong9b14ac62018-07-17 13:48:38 -0700637 inline Queue() : head(nullptr), tail(nullptr), entryCount(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800638 }
639
640 inline bool isEmpty() const {
641 return !head;
642 }
643
644 inline void enqueueAtTail(T* entry) {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800645 entryCount++;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800646 entry->prev = tail;
647 if (tail) {
648 tail->next = entry;
649 } else {
650 head = entry;
651 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700652 entry->next = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800653 tail = entry;
654 }
655
656 inline void enqueueAtHead(T* entry) {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800657 entryCount++;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800658 entry->next = head;
659 if (head) {
660 head->prev = entry;
661 } else {
662 tail = entry;
663 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700664 entry->prev = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800665 head = entry;
666 }
667
668 inline void dequeue(T* entry) {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800669 entryCount--;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800670 if (entry->prev) {
671 entry->prev->next = entry->next;
672 } else {
673 head = entry->next;
674 }
675 if (entry->next) {
676 entry->next->prev = entry->prev;
677 } else {
678 tail = entry->prev;
679 }
680 }
681
682 inline T* dequeueAtHead() {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800683 entryCount--;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800684 T* entry = head;
685 head = entry->next;
686 if (head) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700687 head->prev = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800688 } else {
Yi Kong9b14ac62018-07-17 13:48:38 -0700689 tail = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800690 }
691 return entry;
692 }
693
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800694 uint32_t count() const {
695 return entryCount;
696 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800697 };
698
699 /* Specifies which events are to be canceled and why. */
700 struct CancelationOptions {
701 enum Mode {
702 CANCEL_ALL_EVENTS = 0,
703 CANCEL_POINTER_EVENTS = 1,
704 CANCEL_NON_POINTER_EVENTS = 2,
705 CANCEL_FALLBACK_EVENTS = 3,
Tiger Huang721e26f2018-07-24 22:26:19 +0800706
707 /* Cancel events where the display not specified. These events would go to the focused
708 * display. */
709 CANCEL_DISPLAY_UNSPECIFIED_EVENTS = 4,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800710 };
711
712 // The criterion to use to determine which events should be canceled.
713 Mode mode;
714
715 // Descriptive reason for the cancelation.
716 const char* reason;
717
718 // The specific keycode of the key event to cancel, or -1 to cancel any key event.
719 int32_t keyCode;
720
721 // The specific device id of events to cancel, or -1 to cancel events from any device.
722 int32_t deviceId;
723
724 CancelationOptions(Mode mode, const char* reason) :
725 mode(mode), reason(reason), keyCode(-1), deviceId(-1) { }
726 };
727
728 /* Tracks dispatched key and motion event state so that cancelation events can be
729 * synthesized when events are dropped. */
730 class InputState {
731 public:
732 InputState();
733 ~InputState();
734
735 // Returns true if there is no state to be canceled.
736 bool isNeutral() const;
737
738 // Returns true if the specified source is known to have received a hover enter
739 // motion event.
740 bool isHovering(int32_t deviceId, uint32_t source, int32_t displayId) const;
741
742 // Records tracking information for a key event that has just been published.
743 // Returns true if the event should be delivered, false if it is inconsistent
744 // and should be skipped.
745 bool trackKey(const KeyEntry* entry, int32_t action, int32_t flags);
746
747 // Records tracking information for a motion event that has just been published.
748 // Returns true if the event should be delivered, false if it is inconsistent
749 // and should be skipped.
750 bool trackMotion(const MotionEntry* entry, int32_t action, int32_t flags);
751
752 // Synthesizes cancelation events for the current state and resets the tracked state.
753 void synthesizeCancelationEvents(nsecs_t currentTime,
754 Vector<EventEntry*>& outEvents, const CancelationOptions& options);
755
756 // Clears the current state.
757 void clear();
758
759 // Copies pointer-related parts of the input state to another instance.
760 void copyPointerStateTo(InputState& other) const;
761
762 // Gets the fallback key associated with a keycode.
763 // Returns -1 if none.
764 // Returns AKEYCODE_UNKNOWN if we are only dispatching the unhandled key to the policy.
765 int32_t getFallbackKey(int32_t originalKeyCode);
766
767 // Sets the fallback key for a particular keycode.
768 void setFallbackKey(int32_t originalKeyCode, int32_t fallbackKeyCode);
769
770 // Removes the fallback key for a particular keycode.
771 void removeFallbackKey(int32_t originalKeyCode);
772
773 inline const KeyedVector<int32_t, int32_t>& getFallbackKeys() const {
774 return mFallbackKeys;
775 }
776
777 private:
778 struct KeyMemento {
779 int32_t deviceId;
780 uint32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100781 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782 int32_t keyCode;
783 int32_t scanCode;
784 int32_t metaState;
785 int32_t flags;
786 nsecs_t downTime;
787 uint32_t policyFlags;
788 };
789
790 struct MotionMemento {
791 int32_t deviceId;
792 uint32_t source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800793 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800794 int32_t flags;
795 float xPrecision;
796 float yPrecision;
797 nsecs_t downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800798 uint32_t pointerCount;
799 PointerProperties pointerProperties[MAX_POINTERS];
800 PointerCoords pointerCoords[MAX_POINTERS];
801 bool hovering;
802 uint32_t policyFlags;
803
804 void setPointers(const MotionEntry* entry);
805 };
806
807 Vector<KeyMemento> mKeyMementos;
808 Vector<MotionMemento> mMotionMementos;
809 KeyedVector<int32_t, int32_t> mFallbackKeys;
810
811 ssize_t findKeyMemento(const KeyEntry* entry) const;
812 ssize_t findMotionMemento(const MotionEntry* entry, bool hovering) const;
813
814 void addKeyMemento(const KeyEntry* entry, int32_t flags);
815 void addMotionMemento(const MotionEntry* entry, int32_t flags, bool hovering);
816
817 static bool shouldCancelKey(const KeyMemento& memento,
818 const CancelationOptions& options);
819 static bool shouldCancelMotion(const MotionMemento& memento,
820 const CancelationOptions& options);
821 };
822
823 /* Manages the dispatch state associated with a single input channel. */
824 class Connection : public RefBase {
825 protected:
826 virtual ~Connection();
827
828 public:
829 enum Status {
830 // Everything is peachy.
831 STATUS_NORMAL,
832 // An unrecoverable communication error has occurred.
833 STATUS_BROKEN,
834 // The input channel has been unregistered.
835 STATUS_ZOMBIE
836 };
837
838 Status status;
839 sp<InputChannel> inputChannel; // never null
Michael Wrightd02c5b62014-02-10 15:10:22 -0800840 bool monitor;
841 InputPublisher inputPublisher;
842 InputState inputState;
843
844 // True if the socket is full and no further events can be published until
845 // the application consumes some of the input.
846 bool inputPublisherBlocked;
847
848 // Queue of events that need to be published to the connection.
849 Queue<DispatchEntry> outboundQueue;
850
851 // Queue of events that have been published to the connection but that have not
852 // yet received a "finished" response from the application.
853 Queue<DispatchEntry> waitQueue;
854
Robert Carr803535b2018-08-02 16:38:15 -0700855 explicit Connection(const sp<InputChannel>& inputChannel, bool monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800856
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -0800857 inline const std::string getInputChannelName() const { return inputChannel->getName(); }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800858
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -0800859 const std::string getWindowName() const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860 const char* getStatusLabel() const;
861
862 DispatchEntry* findWaitQueueEntry(uint32_t seq);
863 };
864
865 enum DropReason {
866 DROP_REASON_NOT_DROPPED = 0,
867 DROP_REASON_POLICY = 1,
868 DROP_REASON_APP_SWITCH = 2,
869 DROP_REASON_DISABLED = 3,
870 DROP_REASON_BLOCKED = 4,
871 DROP_REASON_STALE = 5,
872 };
873
874 sp<InputDispatcherPolicyInterface> mPolicy;
875 InputDispatcherConfiguration mConfig;
876
877 Mutex mLock;
878
879 Condition mDispatcherIsAliveCondition;
880
881 sp<Looper> mLooper;
882
883 EventEntry* mPendingEvent;
884 Queue<EventEntry> mInboundQueue;
885 Queue<EventEntry> mRecentQueue;
886 Queue<CommandEntry> mCommandQueue;
887
Michael Wright3a981722015-06-10 15:26:13 +0100888 DropReason mLastDropReason;
889
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890 void dispatchOnceInnerLocked(nsecs_t* nextWakeupTime);
891
892 // Enqueues an inbound event. Returns true if mLooper->wake() should be called.
893 bool enqueueInboundEventLocked(EventEntry* entry);
894
895 // Cleans up input state when dropping an inbound event.
896 void dropInboundEventLocked(EventEntry* entry, DropReason dropReason);
897
898 // Adds an event to a queue of recent events for debugging purposes.
899 void addRecentEventLocked(EventEntry* entry);
900
901 // App switch latency optimization.
902 bool mAppSwitchSawKeyDown;
903 nsecs_t mAppSwitchDueTime;
904
905 static bool isAppSwitchKeyCode(int32_t keyCode);
906 bool isAppSwitchKeyEventLocked(KeyEntry* keyEntry);
907 bool isAppSwitchPendingLocked();
908 void resetPendingAppSwitchLocked(bool handled);
909
910 // Stale event latency optimization.
911 static bool isStaleEventLocked(nsecs_t currentTime, EventEntry* entry);
912
913 // Blocked event latency optimization. Drops old events when the user intends
914 // to transfer focus to a new application.
915 EventEntry* mNextUnblockedEvent;
916
917 sp<InputWindowHandle> findTouchedWindowAtLocked(int32_t displayId, int32_t x, int32_t y);
918
919 // All registered connections mapped by channel file descriptor.
920 KeyedVector<int, sp<Connection> > mConnectionsByFd;
921
Robert Carr5c8a0262018-10-03 16:30:44 -0700922 struct IBinderHash {
923 std::size_t operator()(const sp<IBinder>& b) const {
924 return std::hash<IBinder *>{}(b.get());
925 }
926 };
927 std::unordered_map<sp<IBinder>, sp<InputChannel>, IBinderHash> mInputChannelsByToken;
928
Michael Wrightd02c5b62014-02-10 15:10:22 -0800929 ssize_t getConnectionIndexLocked(const sp<InputChannel>& inputChannel);
930
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800931 // Input channels that will receive a copy of all input events sent to the provided display.
932 std::unordered_map<int32_t, Vector<sp<InputChannel>>> mMonitoringChannelsByDisplay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800933
934 // Event injection and synchronization.
935 Condition mInjectionResultAvailableCondition;
936 bool hasInjectionPermission(int32_t injectorPid, int32_t injectorUid);
937 void setInjectionResultLocked(EventEntry* entry, int32_t injectionResult);
938
939 Condition mInjectionSyncFinishedCondition;
940 void incrementPendingForegroundDispatchesLocked(EventEntry* entry);
941 void decrementPendingForegroundDispatchesLocked(EventEntry* entry);
942
943 // Key repeat tracking.
944 struct KeyRepeatState {
945 KeyEntry* lastKeyEntry; // or null if no repeat
946 nsecs_t nextRepeatTime;
947 } mKeyRepeatState;
948
949 void resetKeyRepeatLocked();
950 KeyEntry* synthesizeKeyRepeatLocked(nsecs_t currentTime);
951
Michael Wright78f24442014-08-06 15:55:28 -0700952 // Key replacement tracking
953 struct KeyReplacement {
954 int32_t keyCode;
955 int32_t deviceId;
956 bool operator==(const KeyReplacement& rhs) const {
957 return keyCode == rhs.keyCode && deviceId == rhs.deviceId;
958 }
959 bool operator<(const KeyReplacement& rhs) const {
960 return keyCode != rhs.keyCode ? keyCode < rhs.keyCode : deviceId < rhs.deviceId;
961 }
962 };
963 // Maps the key code replaced, device id tuple to the key code it was replaced with
964 KeyedVector<KeyReplacement, int32_t> mReplacedKeys;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -0500965 // Process certain Meta + Key combinations
966 void accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
967 int32_t& keyCode, int32_t& metaState);
Michael Wright78f24442014-08-06 15:55:28 -0700968
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 // Deferred command processing.
970 bool haveCommandsLocked() const;
971 bool runCommandsLockedInterruptible();
972 CommandEntry* postCommandLocked(Command command);
973
974 // Input filter processing.
975 bool shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args);
976 bool shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args);
977
978 // Inbound event processing.
979 void drainInboundQueueLocked();
980 void releasePendingEventLocked();
981 void releaseInboundEventLocked(EventEntry* entry);
982
983 // Dispatch state.
984 bool mDispatchEnabled;
985 bool mDispatchFrozen;
986 bool mInputFilterEnabled;
987
Arthur Hungb92218b2018-08-14 12:00:21 +0800988 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>> mWindowHandlesByDisplay;
989 // Get window handles by display, return an empty vector if not found.
990 Vector<sp<InputWindowHandle>> getWindowHandlesLocked(int32_t displayId) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991 sp<InputWindowHandle> getWindowHandleLocked(const sp<InputChannel>& inputChannel) const;
Robert Carr5c8a0262018-10-03 16:30:44 -0700992 sp<InputChannel> getInputChannelLocked(const sp<IBinder>& windowToken) const;
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +0000993 bool hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994
995 // Focus tracking for keys, trackball, etc.
Tiger Huang721e26f2018-07-24 22:26:19 +0800996 std::unordered_map<int32_t, sp<InputWindowHandle>> mFocusedWindowHandlesByDisplay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800997
998 // Focus tracking for touch.
999 struct TouchedWindow {
1000 sp<InputWindowHandle> windowHandle;
1001 int32_t targetFlags;
1002 BitSet32 pointerIds; // zero unless target flag FLAG_SPLIT is set
1003 };
1004 struct TouchState {
1005 bool down;
1006 bool split;
1007 int32_t deviceId; // id of the device that is currently down, others are rejected
1008 uint32_t source; // source of the device that is current down, others are rejected
1009 int32_t displayId; // id to the display that currently has a touch, others are rejected
1010 Vector<TouchedWindow> windows;
1011
1012 TouchState();
1013 ~TouchState();
1014 void reset();
1015 void copyFrom(const TouchState& other);
1016 void addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
1017 int32_t targetFlags, BitSet32 pointerIds);
1018 void removeWindow(const sp<InputWindowHandle>& windowHandle);
Robert Carr803535b2018-08-02 16:38:15 -07001019 void removeWindowByToken(const sp<IBinder>& token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001020 void filterNonAsIsTouchWindows();
1021 sp<InputWindowHandle> getFirstForegroundWindowHandle() const;
1022 bool isSlippery() const;
1023 };
1024
Jeff Brownf086ddb2014-02-11 14:28:48 -08001025 KeyedVector<int32_t, TouchState> mTouchStatesByDisplay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 TouchState mTempTouchState;
1027
Tiger Huang721e26f2018-07-24 22:26:19 +08001028 // Focused applications.
1029 std::unordered_map<int32_t, sp<InputApplicationHandle>> mFocusedApplicationHandlesByDisplay;
1030
1031 // Top focused display.
1032 int32_t mFocusedDisplayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001033
1034 // Dispatcher state at time of last ANR.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001035 std::string mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001036
1037 // Dispatch inbound events.
1038 bool dispatchConfigurationChangedLocked(
1039 nsecs_t currentTime, ConfigurationChangedEntry* entry);
1040 bool dispatchDeviceResetLocked(
1041 nsecs_t currentTime, DeviceResetEntry* entry);
1042 bool dispatchKeyLocked(
1043 nsecs_t currentTime, KeyEntry* entry,
1044 DropReason* dropReason, nsecs_t* nextWakeupTime);
1045 bool dispatchMotionLocked(
1046 nsecs_t currentTime, MotionEntry* entry,
1047 DropReason* dropReason, nsecs_t* nextWakeupTime);
1048 void dispatchEventLocked(nsecs_t currentTime, EventEntry* entry,
1049 const Vector<InputTarget>& inputTargets);
1050
1051 void logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry);
1052 void logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry);
1053
1054 // Keeping track of ANR timeouts.
1055 enum InputTargetWaitCause {
1056 INPUT_TARGET_WAIT_CAUSE_NONE,
1057 INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY,
1058 INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY,
1059 };
1060
1061 InputTargetWaitCause mInputTargetWaitCause;
1062 nsecs_t mInputTargetWaitStartTime;
1063 nsecs_t mInputTargetWaitTimeoutTime;
1064 bool mInputTargetWaitTimeoutExpired;
Robert Carr740167f2018-10-11 19:03:41 -07001065 sp<IBinder> mInputTargetWaitApplicationToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066
1067 // Contains the last window which received a hover event.
1068 sp<InputWindowHandle> mLastHoverWindowHandle;
1069
1070 // Finding targets for input events.
1071 int32_t handleTargetsNotReadyLocked(nsecs_t currentTime, const EventEntry* entry,
1072 const sp<InputApplicationHandle>& applicationHandle,
1073 const sp<InputWindowHandle>& windowHandle,
1074 nsecs_t* nextWakeupTime, const char* reason);
Robert Carr803535b2018-08-02 16:38:15 -07001075
1076 void removeWindowByTokenLocked(const sp<IBinder>& token);
1077
Michael Wrightd02c5b62014-02-10 15:10:22 -08001078 void resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1079 const sp<InputChannel>& inputChannel);
1080 nsecs_t getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime);
1081 void resetANRTimeoutsLocked();
1082
Tiger Huang721e26f2018-07-24 22:26:19 +08001083 int32_t getTargetDisplayId(const EventEntry* entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001084 int32_t findFocusedWindowTargetsLocked(nsecs_t currentTime, const EventEntry* entry,
1085 Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime);
1086 int32_t findTouchedWindowTargetsLocked(nsecs_t currentTime, const MotionEntry* entry,
1087 Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1088 bool* outConflictingPointerActions);
1089
1090 void addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1091 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001092 void addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets, int32_t displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001093
1094 void pokeUserActivityLocked(const EventEntry* eventEntry);
1095 bool checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1096 const InjectionState* injectionState);
1097 bool isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1098 int32_t x, int32_t y) const;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001099 bool isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001100 std::string getApplicationWindowLabelLocked(const sp<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001101 const sp<InputWindowHandle>& windowHandle);
1102
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001103 std::string checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001104 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1105 const char* targetType);
1106
Michael Wrightd02c5b62014-02-10 15:10:22 -08001107 // Manage the dispatch cycle for a single connection.
1108 // These methods are deliberately not Interruptible because doing all of the work
1109 // with the mutex held makes it easier to ensure that connection invariants are maintained.
1110 // If needed, the methods post commands to run later once the critical bits are done.
1111 void prepareDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1112 EventEntry* eventEntry, const InputTarget* inputTarget);
1113 void enqueueDispatchEntriesLocked(nsecs_t currentTime, const sp<Connection>& connection,
1114 EventEntry* eventEntry, const InputTarget* inputTarget);
1115 void enqueueDispatchEntryLocked(const sp<Connection>& connection,
1116 EventEntry* eventEntry, const InputTarget* inputTarget, int32_t dispatchMode);
1117 void startDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
1118 void finishDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1119 uint32_t seq, bool handled);
1120 void abortBrokenDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1121 bool notify);
1122 void drainDispatchQueueLocked(Queue<DispatchEntry>* queue);
1123 void releaseDispatchEntryLocked(DispatchEntry* dispatchEntry);
1124 static int handleReceiveCallback(int fd, int events, void* data);
1125
1126 void synthesizeCancelationEventsForAllConnectionsLocked(
1127 const CancelationOptions& options);
Michael Wrightfa13dcf2015-06-12 13:25:11 +01001128 void synthesizeCancelationEventsForMonitorsLocked(const CancelationOptions& options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001129 void synthesizeCancelationEventsForInputChannelLocked(const sp<InputChannel>& channel,
1130 const CancelationOptions& options);
1131 void synthesizeCancelationEventsForConnectionLocked(const sp<Connection>& connection,
1132 const CancelationOptions& options);
1133
1134 // Splitting motion events across windows.
1135 MotionEntry* splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds);
1136
1137 // Reset and drop everything the dispatcher is doing.
1138 void resetAndDropEverythingLocked(const char* reason);
1139
1140 // Dump state.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001141 void dumpDispatchStateLocked(std::string& dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001142 void logDispatchStateLocked();
1143
1144 // Registration.
1145 void removeMonitorChannelLocked(const sp<InputChannel>& inputChannel);
1146 status_t unregisterInputChannelLocked(const sp<InputChannel>& inputChannel, bool notify);
1147
1148 // Add or remove a connection to the mActiveConnections vector.
1149 void activateConnectionLocked(Connection* connection);
1150 void deactivateConnectionLocked(Connection* connection);
1151
1152 // Interesting events that we might like to log or tell the framework about.
1153 void onDispatchCycleFinishedLocked(
1154 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled);
1155 void onDispatchCycleBrokenLocked(
1156 nsecs_t currentTime, const sp<Connection>& connection);
Robert Carrf759f162018-11-13 12:57:11 -08001157 void onFocusChangedLocked(const sp<InputWindowHandle>& newFocus);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001158 void onANRLocked(
1159 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
1160 const sp<InputWindowHandle>& windowHandle,
1161 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason);
1162
1163 // Outbound policy interactions.
1164 void doNotifyConfigurationChangedInterruptible(CommandEntry* commandEntry);
1165 void doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry);
Robert Carrf759f162018-11-13 12:57:11 -08001166 void doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167 void doNotifyANRLockedInterruptible(CommandEntry* commandEntry);
1168 void doInterceptKeyBeforeDispatchingLockedInterruptible(CommandEntry* commandEntry);
1169 void doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry);
1170 bool afterKeyEventLockedInterruptible(const sp<Connection>& connection,
1171 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled);
1172 bool afterMotionEventLockedInterruptible(const sp<Connection>& connection,
1173 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled);
1174 void doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry);
1175 void initializeKeyEvent(KeyEvent* event, const KeyEntry* entry);
1176
1177 // Statistics gathering.
1178 void updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
1179 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication);
1180 void traceInboundQueueLengthLocked();
1181 void traceOutboundQueueLengthLocked(const sp<Connection>& connection);
1182 void traceWaitQueueLengthLocked(const sp<Connection>& connection);
1183};
1184
1185/* Enqueues and dispatches input events, endlessly. */
1186class InputDispatcherThread : public Thread {
1187public:
1188 explicit InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher);
1189 ~InputDispatcherThread();
1190
1191private:
1192 virtual bool threadLoop();
1193
1194 sp<InputDispatcherInterface> mDispatcher;
1195};
1196
1197} // namespace android
1198
1199#endif // _UI_INPUT_DISPATCHER_H