blob: 05b5dadc66166953eeb2af9774c67ff6573ddb81 [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)
Robert Carre07e1032018-11-26 12:55:53 -0800163 float globalScaleFactor;
164 float windowXScale = 1.0f;
165 float windowYScale = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800166
167 // The subset of pointer ids to include in motion events dispatched to this input target
168 // if FLAG_SPLIT is set.
169 BitSet32 pointerIds;
170};
171
172
173/*
174 * Input dispatcher configuration.
175 *
176 * Specifies various options that modify the behavior of the input dispatcher.
177 * The values provided here are merely defaults. The actual values will come from ViewConfiguration
178 * and are passed into the dispatcher during initialization.
179 */
180struct InputDispatcherConfiguration {
181 // The key repeat initial timeout.
182 nsecs_t keyRepeatTimeout;
183
184 // The key repeat inter-key delay.
185 nsecs_t keyRepeatDelay;
186
187 InputDispatcherConfiguration() :
188 keyRepeatTimeout(500 * 1000000LL),
189 keyRepeatDelay(50 * 1000000LL) { }
190};
191
192
193/*
194 * Input dispatcher policy interface.
195 *
196 * The input reader policy is used by the input reader to interact with the Window Manager
197 * and other system components.
198 *
199 * The actual implementation is partially supported by callbacks into the DVM
200 * via JNI. This interface is also mocked in the unit tests.
201 */
202class InputDispatcherPolicyInterface : public virtual RefBase {
203protected:
204 InputDispatcherPolicyInterface() { }
205 virtual ~InputDispatcherPolicyInterface() { }
206
207public:
208 /* Notifies the system that a configuration change has occurred. */
209 virtual void notifyConfigurationChanged(nsecs_t when) = 0;
210
211 /* Notifies the system that an application is not responding.
212 * Returns a new timeout to continue waiting, or 0 to abort dispatch. */
213 virtual nsecs_t notifyANR(const sp<InputApplicationHandle>& inputApplicationHandle,
Robert Carr803535b2018-08-02 16:38:15 -0700214 const sp<IBinder>& token,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800215 const std::string& reason) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216
217 /* Notifies the system that an input channel is unrecoverably broken. */
Robert Carr803535b2018-08-02 16:38:15 -0700218 virtual void notifyInputChannelBroken(const sp<IBinder>& token) = 0;
Robert Carrf759f162018-11-13 12:57:11 -0800219 virtual void notifyFocusChanged(const sp<IBinder>& token) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220
221 /* Gets the input dispatcher configuration. */
222 virtual void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) = 0;
223
Michael Wrightd02c5b62014-02-10 15:10:22 -0800224 /* Filters an input event.
225 * Return true to dispatch the event unmodified, false to consume the event.
226 * A filter can also transform and inject events later by passing POLICY_FLAG_FILTERED
227 * to injectInputEvent.
228 */
229 virtual bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) = 0;
230
231 /* Intercepts a key event immediately before queueing it.
232 * The policy can use this method as an opportunity to perform power management functions
233 * and early event preprocessing such as updating policy flags.
234 *
235 * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
236 * should be dispatched to applications.
237 */
238 virtual void interceptKeyBeforeQueueing(const KeyEvent* keyEvent, uint32_t& policyFlags) = 0;
239
240 /* Intercepts a touch, trackball or other motion event before queueing it.
241 * The policy can use this method as an opportunity to perform power management functions
242 * and early event preprocessing such as updating policy flags.
243 *
244 * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
245 * should be dispatched to applications.
246 */
247 virtual void interceptMotionBeforeQueueing(nsecs_t when, uint32_t& policyFlags) = 0;
248
249 /* Allows the policy a chance to intercept a key before dispatching. */
Robert Carr803535b2018-08-02 16:38:15 -0700250 virtual nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>& token,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800251 const KeyEvent* keyEvent, uint32_t policyFlags) = 0;
252
253 /* Allows the policy a chance to perform default processing for an unhandled key.
254 * Returns an alternate keycode to redispatch as a fallback, or 0 to give up. */
Robert Carr803535b2018-08-02 16:38:15 -0700255 virtual bool dispatchUnhandledKey(const sp<IBinder>& token,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800256 const KeyEvent* keyEvent, uint32_t policyFlags, KeyEvent* outFallbackKeyEvent) = 0;
257
258 /* Notifies the policy about switch events.
259 */
260 virtual void notifySwitch(nsecs_t when,
261 uint32_t switchValues, uint32_t switchMask, uint32_t policyFlags) = 0;
262
263 /* Poke user activity for an event dispatched to a window. */
264 virtual void pokeUserActivity(nsecs_t eventTime, int32_t eventType) = 0;
265
266 /* Checks whether a given application pid/uid has permission to inject input events
267 * into other applications.
268 *
269 * This method is special in that its implementation promises to be non-reentrant and
270 * is safe to call while holding other locks. (Most other methods make no such guarantees!)
271 */
272 virtual bool checkInjectEventsPermissionNonReentrant(
273 int32_t injectorPid, int32_t injectorUid) = 0;
274};
275
276
277/* Notifies the system about input events generated by the input reader.
278 * The dispatcher is expected to be mostly asynchronous. */
279class InputDispatcherInterface : public virtual RefBase, public InputListenerInterface {
280protected:
281 InputDispatcherInterface() { }
282 virtual ~InputDispatcherInterface() { }
283
284public:
285 /* Dumps the state of the input dispatcher.
286 *
287 * This method may be called on any thread (usually by the input manager). */
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800288 virtual void dump(std::string& dump) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800289
290 /* Called by the heatbeat to ensures that the dispatcher has not deadlocked. */
291 virtual void monitor() = 0;
292
293 /* Runs a single iteration of the dispatch loop.
294 * Nominally processes one queued event, a timeout, or a response from an input consumer.
295 *
296 * This method should only be called on the input dispatcher thread.
297 */
298 virtual void dispatchOnce() = 0;
299
300 /* Injects an input event and optionally waits for sync.
301 * The synchronization mode determines whether the method blocks while waiting for
302 * input injection to proceed.
303 * Returns one of the INPUT_EVENT_INJECTION_XXX constants.
304 *
305 * This method may be called on any thread (usually by the input manager).
306 */
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800307 virtual int32_t injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800308 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
309 uint32_t policyFlags) = 0;
310
311 /* Sets the list of input windows.
312 *
313 * This method may be called on any thread (usually by the input manager).
314 */
Arthur Hungb92218b2018-08-14 12:00:21 +0800315 virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles,
316 int32_t displayId) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800317
Tiger Huang721e26f2018-07-24 22:26:19 +0800318 /* Sets the focused application on the given display.
Michael Wrightd02c5b62014-02-10 15:10:22 -0800319 *
320 * This method may be called on any thread (usually by the input manager).
321 */
322 virtual void setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +0800323 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) = 0;
324
325 /* Sets the focused display.
326 *
327 * This method may be called on any thread (usually by the input manager).
328 */
329 virtual void setFocusedDisplay(int32_t displayId) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800330
331 /* Sets the input dispatching mode.
332 *
333 * This method may be called on any thread (usually by the input manager).
334 */
335 virtual void setInputDispatchMode(bool enabled, bool frozen) = 0;
336
337 /* Sets whether input event filtering is enabled.
338 * When enabled, incoming input events are sent to the policy's filterInputEvent
339 * method instead of being dispatched. The filter is expected to use
340 * injectInputEvent to inject the events it would like to have dispatched.
341 * It should include POLICY_FLAG_FILTERED in the policy flags during injection.
342 */
343 virtual void setInputFilterEnabled(bool enabled) = 0;
344
345 /* Transfers touch focus from the window associated with one channel to the
346 * window associated with the other channel.
347 *
348 * Returns true on success. False if the window did not actually have touch focus.
349 */
350 virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel,
351 const sp<InputChannel>& toChannel) = 0;
352
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800353 /* Registers input channels that may be used as targets for input events.
354 * If inputWindowHandle is null, and displayId is not ADISPLAY_ID_NONE,
355 * the channel will receive a copy of all input events form the specific displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -0800356 *
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800357 * This method may be called on any thread (usually by the input manager).
Michael Wrightd02c5b62014-02-10 15:10:22 -0800358 */
Robert Carr803535b2018-08-02 16:38:15 -0700359 virtual status_t registerInputChannel(
360 const sp<InputChannel>& inputChannel, int32_t displayId) = 0;
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800361
362 /* Unregister input channels that will no longer receive input events.
363 *
364 * This method may be called on any thread (usually by the input manager).
365 */
Michael Wrightd02c5b62014-02-10 15:10:22 -0800366 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel) = 0;
367};
368
369/* Dispatches events to input targets. Some functions of the input dispatcher, such as
370 * identifying input targets, are controlled by a separate policy object.
371 *
372 * IMPORTANT INVARIANT:
373 * Because the policy can potentially block or cause re-entrance into the input dispatcher,
374 * the input dispatcher never calls into the policy while holding its internal locks.
375 * The implementation is also carefully designed to recover from scenarios such as an
376 * input channel becoming unregistered while identifying input targets or processing timeouts.
377 *
378 * Methods marked 'Locked' must be called with the lock acquired.
379 *
380 * Methods marked 'LockedInterruptible' must be called with the lock acquired but
381 * may during the course of their execution release the lock, call into the policy, and
382 * then reacquire the lock. The caller is responsible for recovering gracefully.
383 *
384 * A 'LockedInterruptible' method may called a 'Locked' method, but NOT vice-versa.
385 */
386class InputDispatcher : public InputDispatcherInterface {
387protected:
388 virtual ~InputDispatcher();
389
390public:
391 explicit InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy);
392
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800393 virtual void dump(std::string& dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800394 virtual void monitor();
395
396 virtual void dispatchOnce();
397
398 virtual void notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args);
399 virtual void notifyKey(const NotifyKeyArgs* args);
400 virtual void notifyMotion(const NotifyMotionArgs* args);
401 virtual void notifySwitch(const NotifySwitchArgs* args);
402 virtual void notifyDeviceReset(const NotifyDeviceResetArgs* args);
403
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800404 virtual int32_t injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800405 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
406 uint32_t policyFlags);
407
Arthur Hungb92218b2018-08-14 12:00:21 +0800408 virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles,
409 int32_t displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +0800410 virtual void setFocusedApplication(int32_t displayId,
411 const sp<InputApplicationHandle>& inputApplicationHandle);
412 virtual void setFocusedDisplay(int32_t displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800413 virtual void setInputDispatchMode(bool enabled, bool frozen);
414 virtual void setInputFilterEnabled(bool enabled);
415
416 virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel,
417 const sp<InputChannel>& toChannel);
418
419 virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel,
Robert Carr803535b2018-08-02 16:38:15 -0700420 int32_t displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800421 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel);
422
423private:
424 template <typename T>
425 struct Link {
426 T* next;
427 T* prev;
428
429 protected:
Yi Kong9b14ac62018-07-17 13:48:38 -0700430 inline Link() : next(nullptr), prev(nullptr) { }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800431 };
432
433 struct InjectionState {
434 mutable int32_t refCount;
435
436 int32_t injectorPid;
437 int32_t injectorUid;
438 int32_t injectionResult; // initially INPUT_EVENT_INJECTION_PENDING
439 bool injectionIsAsync; // set to true if injection is not waiting for the result
440 int32_t pendingForegroundDispatches; // the number of foreground dispatches in progress
441
442 InjectionState(int32_t injectorPid, int32_t injectorUid);
443 void release();
444
445 private:
446 ~InjectionState();
447 };
448
449 struct EventEntry : Link<EventEntry> {
450 enum {
451 TYPE_CONFIGURATION_CHANGED,
452 TYPE_DEVICE_RESET,
453 TYPE_KEY,
454 TYPE_MOTION
455 };
456
Prabir Pradhan42611e02018-11-27 14:04:02 -0800457 uint32_t sequenceNum;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800458 mutable int32_t refCount;
459 int32_t type;
460 nsecs_t eventTime;
461 uint32_t policyFlags;
462 InjectionState* injectionState;
463
464 bool dispatchInProgress; // initially false, set to true while dispatching
465
Yi Kong9b14ac62018-07-17 13:48:38 -0700466 inline bool isInjected() const { return injectionState != nullptr; }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800467
468 void release();
469
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800470 virtual void appendDescription(std::string& msg) const = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800471
472 protected:
Prabir Pradhan42611e02018-11-27 14:04:02 -0800473 EventEntry(uint32_t sequenceNum, int32_t type, nsecs_t eventTime, uint32_t policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800474 virtual ~EventEntry();
475 void releaseInjectionState();
476 };
477
478 struct ConfigurationChangedEntry : EventEntry {
Prabir Pradhan42611e02018-11-27 14:04:02 -0800479 explicit ConfigurationChangedEntry(uint32_t sequenceNum, nsecs_t eventTime);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800480 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800481
482 protected:
483 virtual ~ConfigurationChangedEntry();
484 };
485
486 struct DeviceResetEntry : EventEntry {
487 int32_t deviceId;
488
Prabir Pradhan42611e02018-11-27 14:04:02 -0800489 DeviceResetEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800490 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800491
492 protected:
493 virtual ~DeviceResetEntry();
494 };
495
496 struct KeyEntry : EventEntry {
497 int32_t deviceId;
498 uint32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100499 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800500 int32_t action;
501 int32_t flags;
502 int32_t keyCode;
503 int32_t scanCode;
504 int32_t metaState;
505 int32_t repeatCount;
506 nsecs_t downTime;
507
508 bool syntheticRepeat; // set to true for synthetic key repeats
509
510 enum InterceptKeyResult {
511 INTERCEPT_KEY_RESULT_UNKNOWN,
512 INTERCEPT_KEY_RESULT_SKIP,
513 INTERCEPT_KEY_RESULT_CONTINUE,
514 INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER,
515 };
516 InterceptKeyResult interceptKeyResult; // set based on the interception result
517 nsecs_t interceptKeyWakeupTime; // used with INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER
518
Prabir Pradhan42611e02018-11-27 14:04:02 -0800519 KeyEntry(uint32_t sequenceNum, nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100520 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags,
521 int32_t action, int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800522 int32_t repeatCount, nsecs_t downTime);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800523 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800524 void recycle();
525
526 protected:
527 virtual ~KeyEntry();
528 };
529
530 struct MotionEntry : EventEntry {
531 nsecs_t eventTime;
532 int32_t deviceId;
533 uint32_t source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800534 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800535 int32_t action;
Michael Wright7b159c92015-05-14 14:48:03 +0100536 int32_t actionButton;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800537 int32_t flags;
538 int32_t metaState;
539 int32_t buttonState;
540 int32_t edgeFlags;
541 float xPrecision;
542 float yPrecision;
543 nsecs_t downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800544 uint32_t pointerCount;
545 PointerProperties pointerProperties[MAX_POINTERS];
546 PointerCoords pointerCoords[MAX_POINTERS];
547
Prabir Pradhan42611e02018-11-27 14:04:02 -0800548 MotionEntry(uint32_t sequenceNum, nsecs_t eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800549 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +0100550 int32_t action, int32_t actionButton, int32_t flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800551 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800552 float xPrecision, float yPrecision, nsecs_t downTime, uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -0800553 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
554 float xOffset, float yOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800555 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800556
557 protected:
558 virtual ~MotionEntry();
559 };
560
561 // Tracks the progress of dispatching a particular event to a particular connection.
562 struct DispatchEntry : Link<DispatchEntry> {
563 const uint32_t seq; // unique sequence number, never 0
564
565 EventEntry* eventEntry; // the event to dispatch
566 int32_t targetFlags;
567 float xOffset;
568 float yOffset;
Robert Carre07e1032018-11-26 12:55:53 -0800569 float globalScaleFactor;
570 float windowXScale = 1.0f;
571 float windowYScale = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800572 nsecs_t deliveryTime; // time when the event was actually delivered
573
574 // Set to the resolved action and flags when the event is enqueued.
575 int32_t resolvedAction;
576 int32_t resolvedFlags;
577
578 DispatchEntry(EventEntry* eventEntry,
Robert Carre07e1032018-11-26 12:55:53 -0800579 int32_t targetFlags, float xOffset, float yOffset,
580 float globalScaleFactor, float windowXScale, float windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800581 ~DispatchEntry();
582
583 inline bool hasForegroundTarget() const {
584 return targetFlags & InputTarget::FLAG_FOREGROUND;
585 }
586
587 inline bool isSplit() const {
588 return targetFlags & InputTarget::FLAG_SPLIT;
589 }
590
591 private:
592 static volatile int32_t sNextSeqAtomic;
593
594 static uint32_t nextSeq();
595 };
596
597 // A command entry captures state and behavior for an action to be performed in the
598 // dispatch loop after the initial processing has taken place. It is essentially
599 // a kind of continuation used to postpone sensitive policy interactions to a point
600 // in the dispatch loop where it is safe to release the lock (generally after finishing
601 // the critical parts of the dispatch cycle).
602 //
603 // The special thing about commands is that they can voluntarily release and reacquire
604 // the dispatcher lock at will. Initially when the command starts running, the
605 // dispatcher lock is held. However, if the command needs to call into the policy to
606 // do some work, it can release the lock, do the work, then reacquire the lock again
607 // before returning.
608 //
609 // This mechanism is a bit clunky but it helps to preserve the invariant that the dispatch
610 // never calls into the policy while holding its lock.
611 //
612 // Commands are implicitly 'LockedInterruptible'.
613 struct CommandEntry;
614 typedef void (InputDispatcher::*Command)(CommandEntry* commandEntry);
615
616 class Connection;
617 struct CommandEntry : Link<CommandEntry> {
Chih-Hung Hsieh6d2ede12016-09-01 11:28:23 -0700618 explicit CommandEntry(Command command);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800619 ~CommandEntry();
620
621 Command command;
622
623 // parameters for the command (usage varies by command)
624 sp<Connection> connection;
625 nsecs_t eventTime;
626 KeyEntry* keyEntry;
627 sp<InputApplicationHandle> inputApplicationHandle;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800628 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800629 int32_t userActivityEventType;
630 uint32_t seq;
631 bool handled;
Robert Carr803535b2018-08-02 16:38:15 -0700632 sp<InputChannel> inputChannel;
Robert Carrf759f162018-11-13 12:57:11 -0800633 sp<IBinder> token;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800634 };
635
636 // Generic queue implementation.
637 template <typename T>
638 struct Queue {
639 T* head;
640 T* tail;
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800641 uint32_t entryCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800642
Yi Kong9b14ac62018-07-17 13:48:38 -0700643 inline Queue() : head(nullptr), tail(nullptr), entryCount(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800644 }
645
646 inline bool isEmpty() const {
647 return !head;
648 }
649
650 inline void enqueueAtTail(T* entry) {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800651 entryCount++;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800652 entry->prev = tail;
653 if (tail) {
654 tail->next = entry;
655 } else {
656 head = entry;
657 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700658 entry->next = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800659 tail = entry;
660 }
661
662 inline void enqueueAtHead(T* entry) {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800663 entryCount++;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800664 entry->next = head;
665 if (head) {
666 head->prev = entry;
667 } else {
668 tail = entry;
669 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700670 entry->prev = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800671 head = entry;
672 }
673
674 inline void dequeue(T* entry) {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800675 entryCount--;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800676 if (entry->prev) {
677 entry->prev->next = entry->next;
678 } else {
679 head = entry->next;
680 }
681 if (entry->next) {
682 entry->next->prev = entry->prev;
683 } else {
684 tail = entry->prev;
685 }
686 }
687
688 inline T* dequeueAtHead() {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800689 entryCount--;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800690 T* entry = head;
691 head = entry->next;
692 if (head) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700693 head->prev = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800694 } else {
Yi Kong9b14ac62018-07-17 13:48:38 -0700695 tail = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800696 }
697 return entry;
698 }
699
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800700 uint32_t count() const {
701 return entryCount;
702 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800703 };
704
705 /* Specifies which events are to be canceled and why. */
706 struct CancelationOptions {
707 enum Mode {
708 CANCEL_ALL_EVENTS = 0,
709 CANCEL_POINTER_EVENTS = 1,
710 CANCEL_NON_POINTER_EVENTS = 2,
711 CANCEL_FALLBACK_EVENTS = 3,
Tiger Huang721e26f2018-07-24 22:26:19 +0800712
713 /* Cancel events where the display not specified. These events would go to the focused
714 * display. */
715 CANCEL_DISPLAY_UNSPECIFIED_EVENTS = 4,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716 };
717
718 // The criterion to use to determine which events should be canceled.
719 Mode mode;
720
721 // Descriptive reason for the cancelation.
722 const char* reason;
723
724 // The specific keycode of the key event to cancel, or -1 to cancel any key event.
725 int32_t keyCode;
726
727 // The specific device id of events to cancel, or -1 to cancel events from any device.
728 int32_t deviceId;
729
730 CancelationOptions(Mode mode, const char* reason) :
731 mode(mode), reason(reason), keyCode(-1), deviceId(-1) { }
732 };
733
734 /* Tracks dispatched key and motion event state so that cancelation events can be
735 * synthesized when events are dropped. */
736 class InputState {
737 public:
738 InputState();
739 ~InputState();
740
741 // Returns true if there is no state to be canceled.
742 bool isNeutral() const;
743
744 // Returns true if the specified source is known to have received a hover enter
745 // motion event.
746 bool isHovering(int32_t deviceId, uint32_t source, int32_t displayId) const;
747
748 // Records tracking information for a key event that has just been published.
749 // Returns true if the event should be delivered, false if it is inconsistent
750 // and should be skipped.
751 bool trackKey(const KeyEntry* entry, int32_t action, int32_t flags);
752
753 // Records tracking information for a motion event that has just been published.
754 // Returns true if the event should be delivered, false if it is inconsistent
755 // and should be skipped.
756 bool trackMotion(const MotionEntry* entry, int32_t action, int32_t flags);
757
758 // Synthesizes cancelation events for the current state and resets the tracked state.
759 void synthesizeCancelationEvents(nsecs_t currentTime,
760 Vector<EventEntry*>& outEvents, const CancelationOptions& options);
761
762 // Clears the current state.
763 void clear();
764
765 // Copies pointer-related parts of the input state to another instance.
766 void copyPointerStateTo(InputState& other) const;
767
768 // Gets the fallback key associated with a keycode.
769 // Returns -1 if none.
770 // Returns AKEYCODE_UNKNOWN if we are only dispatching the unhandled key to the policy.
771 int32_t getFallbackKey(int32_t originalKeyCode);
772
773 // Sets the fallback key for a particular keycode.
774 void setFallbackKey(int32_t originalKeyCode, int32_t fallbackKeyCode);
775
776 // Removes the fallback key for a particular keycode.
777 void removeFallbackKey(int32_t originalKeyCode);
778
779 inline const KeyedVector<int32_t, int32_t>& getFallbackKeys() const {
780 return mFallbackKeys;
781 }
782
783 private:
784 struct KeyMemento {
785 int32_t deviceId;
786 uint32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100787 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 int32_t keyCode;
789 int32_t scanCode;
790 int32_t metaState;
791 int32_t flags;
792 nsecs_t downTime;
793 uint32_t policyFlags;
794 };
795
796 struct MotionMemento {
797 int32_t deviceId;
798 uint32_t source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800799 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800800 int32_t flags;
801 float xPrecision;
802 float yPrecision;
803 nsecs_t downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800804 uint32_t pointerCount;
805 PointerProperties pointerProperties[MAX_POINTERS];
806 PointerCoords pointerCoords[MAX_POINTERS];
807 bool hovering;
808 uint32_t policyFlags;
809
810 void setPointers(const MotionEntry* entry);
811 };
812
813 Vector<KeyMemento> mKeyMementos;
814 Vector<MotionMemento> mMotionMementos;
815 KeyedVector<int32_t, int32_t> mFallbackKeys;
816
817 ssize_t findKeyMemento(const KeyEntry* entry) const;
818 ssize_t findMotionMemento(const MotionEntry* entry, bool hovering) const;
819
820 void addKeyMemento(const KeyEntry* entry, int32_t flags);
821 void addMotionMemento(const MotionEntry* entry, int32_t flags, bool hovering);
822
823 static bool shouldCancelKey(const KeyMemento& memento,
824 const CancelationOptions& options);
825 static bool shouldCancelMotion(const MotionMemento& memento,
826 const CancelationOptions& options);
827 };
828
829 /* Manages the dispatch state associated with a single input channel. */
830 class Connection : public RefBase {
831 protected:
832 virtual ~Connection();
833
834 public:
835 enum Status {
836 // Everything is peachy.
837 STATUS_NORMAL,
838 // An unrecoverable communication error has occurred.
839 STATUS_BROKEN,
840 // The input channel has been unregistered.
841 STATUS_ZOMBIE
842 };
843
844 Status status;
845 sp<InputChannel> inputChannel; // never null
Michael Wrightd02c5b62014-02-10 15:10:22 -0800846 bool monitor;
847 InputPublisher inputPublisher;
848 InputState inputState;
849
850 // True if the socket is full and no further events can be published until
851 // the application consumes some of the input.
852 bool inputPublisherBlocked;
853
854 // Queue of events that need to be published to the connection.
855 Queue<DispatchEntry> outboundQueue;
856
857 // Queue of events that have been published to the connection but that have not
858 // yet received a "finished" response from the application.
859 Queue<DispatchEntry> waitQueue;
860
Robert Carr803535b2018-08-02 16:38:15 -0700861 explicit Connection(const sp<InputChannel>& inputChannel, bool monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -0800863 inline const std::string getInputChannelName() const { return inputChannel->getName(); }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -0800865 const std::string getWindowName() const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800866 const char* getStatusLabel() const;
867
868 DispatchEntry* findWaitQueueEntry(uint32_t seq);
869 };
870
871 enum DropReason {
872 DROP_REASON_NOT_DROPPED = 0,
873 DROP_REASON_POLICY = 1,
874 DROP_REASON_APP_SWITCH = 2,
875 DROP_REASON_DISABLED = 3,
876 DROP_REASON_BLOCKED = 4,
877 DROP_REASON_STALE = 5,
878 };
879
880 sp<InputDispatcherPolicyInterface> mPolicy;
881 InputDispatcherConfiguration mConfig;
882
883 Mutex mLock;
884
885 Condition mDispatcherIsAliveCondition;
886
887 sp<Looper> mLooper;
888
889 EventEntry* mPendingEvent;
890 Queue<EventEntry> mInboundQueue;
891 Queue<EventEntry> mRecentQueue;
892 Queue<CommandEntry> mCommandQueue;
893
Michael Wright3a981722015-06-10 15:26:13 +0100894 DropReason mLastDropReason;
895
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 void dispatchOnceInnerLocked(nsecs_t* nextWakeupTime);
897
898 // Enqueues an inbound event. Returns true if mLooper->wake() should be called.
899 bool enqueueInboundEventLocked(EventEntry* entry);
900
901 // Cleans up input state when dropping an inbound event.
902 void dropInboundEventLocked(EventEntry* entry, DropReason dropReason);
903
904 // Adds an event to a queue of recent events for debugging purposes.
905 void addRecentEventLocked(EventEntry* entry);
906
907 // App switch latency optimization.
908 bool mAppSwitchSawKeyDown;
909 nsecs_t mAppSwitchDueTime;
910
911 static bool isAppSwitchKeyCode(int32_t keyCode);
912 bool isAppSwitchKeyEventLocked(KeyEntry* keyEntry);
913 bool isAppSwitchPendingLocked();
914 void resetPendingAppSwitchLocked(bool handled);
915
916 // Stale event latency optimization.
917 static bool isStaleEventLocked(nsecs_t currentTime, EventEntry* entry);
918
919 // Blocked event latency optimization. Drops old events when the user intends
920 // to transfer focus to a new application.
921 EventEntry* mNextUnblockedEvent;
922
923 sp<InputWindowHandle> findTouchedWindowAtLocked(int32_t displayId, int32_t x, int32_t y);
924
925 // All registered connections mapped by channel file descriptor.
926 KeyedVector<int, sp<Connection> > mConnectionsByFd;
927
Robert Carr5c8a0262018-10-03 16:30:44 -0700928 struct IBinderHash {
929 std::size_t operator()(const sp<IBinder>& b) const {
930 return std::hash<IBinder *>{}(b.get());
931 }
932 };
933 std::unordered_map<sp<IBinder>, sp<InputChannel>, IBinderHash> mInputChannelsByToken;
934
Michael Wrightd02c5b62014-02-10 15:10:22 -0800935 ssize_t getConnectionIndexLocked(const sp<InputChannel>& inputChannel);
936
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800937 // Input channels that will receive a copy of all input events sent to the provided display.
938 std::unordered_map<int32_t, Vector<sp<InputChannel>>> mMonitoringChannelsByDisplay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800939
940 // Event injection and synchronization.
941 Condition mInjectionResultAvailableCondition;
942 bool hasInjectionPermission(int32_t injectorPid, int32_t injectorUid);
943 void setInjectionResultLocked(EventEntry* entry, int32_t injectionResult);
944
945 Condition mInjectionSyncFinishedCondition;
946 void incrementPendingForegroundDispatchesLocked(EventEntry* entry);
947 void decrementPendingForegroundDispatchesLocked(EventEntry* entry);
948
949 // Key repeat tracking.
950 struct KeyRepeatState {
951 KeyEntry* lastKeyEntry; // or null if no repeat
952 nsecs_t nextRepeatTime;
953 } mKeyRepeatState;
954
955 void resetKeyRepeatLocked();
956 KeyEntry* synthesizeKeyRepeatLocked(nsecs_t currentTime);
957
Michael Wright78f24442014-08-06 15:55:28 -0700958 // Key replacement tracking
959 struct KeyReplacement {
960 int32_t keyCode;
961 int32_t deviceId;
962 bool operator==(const KeyReplacement& rhs) const {
963 return keyCode == rhs.keyCode && deviceId == rhs.deviceId;
964 }
965 bool operator<(const KeyReplacement& rhs) const {
966 return keyCode != rhs.keyCode ? keyCode < rhs.keyCode : deviceId < rhs.deviceId;
967 }
968 };
969 // Maps the key code replaced, device id tuple to the key code it was replaced with
970 KeyedVector<KeyReplacement, int32_t> mReplacedKeys;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -0500971 // Process certain Meta + Key combinations
972 void accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
973 int32_t& keyCode, int32_t& metaState);
Michael Wright78f24442014-08-06 15:55:28 -0700974
Michael Wrightd02c5b62014-02-10 15:10:22 -0800975 // Deferred command processing.
976 bool haveCommandsLocked() const;
977 bool runCommandsLockedInterruptible();
978 CommandEntry* postCommandLocked(Command command);
979
980 // Input filter processing.
981 bool shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args);
982 bool shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args);
983
984 // Inbound event processing.
985 void drainInboundQueueLocked();
986 void releasePendingEventLocked();
987 void releaseInboundEventLocked(EventEntry* entry);
988
989 // Dispatch state.
990 bool mDispatchEnabled;
991 bool mDispatchFrozen;
992 bool mInputFilterEnabled;
993
Arthur Hungb92218b2018-08-14 12:00:21 +0800994 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>> mWindowHandlesByDisplay;
995 // Get window handles by display, return an empty vector if not found.
996 Vector<sp<InputWindowHandle>> getWindowHandlesLocked(int32_t displayId) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800997 sp<InputWindowHandle> getWindowHandleLocked(const sp<InputChannel>& inputChannel) const;
Robert Carr5c8a0262018-10-03 16:30:44 -0700998 sp<InputChannel> getInputChannelLocked(const sp<IBinder>& windowToken) const;
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +0000999 bool hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001000
1001 // Focus tracking for keys, trackball, etc.
Tiger Huang721e26f2018-07-24 22:26:19 +08001002 std::unordered_map<int32_t, sp<InputWindowHandle>> mFocusedWindowHandlesByDisplay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003
1004 // Focus tracking for touch.
1005 struct TouchedWindow {
1006 sp<InputWindowHandle> windowHandle;
1007 int32_t targetFlags;
1008 BitSet32 pointerIds; // zero unless target flag FLAG_SPLIT is set
1009 };
1010 struct TouchState {
1011 bool down;
1012 bool split;
1013 int32_t deviceId; // id of the device that is currently down, others are rejected
1014 uint32_t source; // source of the device that is current down, others are rejected
1015 int32_t displayId; // id to the display that currently has a touch, others are rejected
1016 Vector<TouchedWindow> windows;
1017
1018 TouchState();
1019 ~TouchState();
1020 void reset();
1021 void copyFrom(const TouchState& other);
1022 void addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
1023 int32_t targetFlags, BitSet32 pointerIds);
1024 void removeWindow(const sp<InputWindowHandle>& windowHandle);
Robert Carr803535b2018-08-02 16:38:15 -07001025 void removeWindowByToken(const sp<IBinder>& token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 void filterNonAsIsTouchWindows();
1027 sp<InputWindowHandle> getFirstForegroundWindowHandle() const;
1028 bool isSlippery() const;
1029 };
1030
Jeff Brownf086ddb2014-02-11 14:28:48 -08001031 KeyedVector<int32_t, TouchState> mTouchStatesByDisplay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032 TouchState mTempTouchState;
1033
Tiger Huang721e26f2018-07-24 22:26:19 +08001034 // Focused applications.
1035 std::unordered_map<int32_t, sp<InputApplicationHandle>> mFocusedApplicationHandlesByDisplay;
1036
1037 // Top focused display.
1038 int32_t mFocusedDisplayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039
1040 // Dispatcher state at time of last ANR.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001041 std::string mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042
1043 // Dispatch inbound events.
1044 bool dispatchConfigurationChangedLocked(
1045 nsecs_t currentTime, ConfigurationChangedEntry* entry);
1046 bool dispatchDeviceResetLocked(
1047 nsecs_t currentTime, DeviceResetEntry* entry);
1048 bool dispatchKeyLocked(
1049 nsecs_t currentTime, KeyEntry* entry,
1050 DropReason* dropReason, nsecs_t* nextWakeupTime);
1051 bool dispatchMotionLocked(
1052 nsecs_t currentTime, MotionEntry* entry,
1053 DropReason* dropReason, nsecs_t* nextWakeupTime);
1054 void dispatchEventLocked(nsecs_t currentTime, EventEntry* entry,
1055 const Vector<InputTarget>& inputTargets);
1056
1057 void logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry);
1058 void logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry);
1059
1060 // Keeping track of ANR timeouts.
1061 enum InputTargetWaitCause {
1062 INPUT_TARGET_WAIT_CAUSE_NONE,
1063 INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY,
1064 INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY,
1065 };
1066
1067 InputTargetWaitCause mInputTargetWaitCause;
1068 nsecs_t mInputTargetWaitStartTime;
1069 nsecs_t mInputTargetWaitTimeoutTime;
1070 bool mInputTargetWaitTimeoutExpired;
Robert Carr740167f2018-10-11 19:03:41 -07001071 sp<IBinder> mInputTargetWaitApplicationToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072
1073 // Contains the last window which received a hover event.
1074 sp<InputWindowHandle> mLastHoverWindowHandle;
1075
1076 // Finding targets for input events.
1077 int32_t handleTargetsNotReadyLocked(nsecs_t currentTime, const EventEntry* entry,
1078 const sp<InputApplicationHandle>& applicationHandle,
1079 const sp<InputWindowHandle>& windowHandle,
1080 nsecs_t* nextWakeupTime, const char* reason);
Robert Carr803535b2018-08-02 16:38:15 -07001081
1082 void removeWindowByTokenLocked(const sp<IBinder>& token);
1083
Michael Wrightd02c5b62014-02-10 15:10:22 -08001084 void resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1085 const sp<InputChannel>& inputChannel);
1086 nsecs_t getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime);
1087 void resetANRTimeoutsLocked();
1088
Tiger Huang721e26f2018-07-24 22:26:19 +08001089 int32_t getTargetDisplayId(const EventEntry* entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090 int32_t findFocusedWindowTargetsLocked(nsecs_t currentTime, const EventEntry* entry,
1091 Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime);
1092 int32_t findTouchedWindowTargetsLocked(nsecs_t currentTime, const MotionEntry* entry,
1093 Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1094 bool* outConflictingPointerActions);
1095
1096 void addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1097 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001098 void addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets, int32_t displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001099
1100 void pokeUserActivityLocked(const EventEntry* eventEntry);
1101 bool checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1102 const InjectionState* injectionState);
1103 bool isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1104 int32_t x, int32_t y) const;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001105 bool isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001106 std::string getApplicationWindowLabelLocked(const sp<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001107 const sp<InputWindowHandle>& windowHandle);
1108
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001109 std::string checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001110 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1111 const char* targetType);
1112
Michael Wrightd02c5b62014-02-10 15:10:22 -08001113 // Manage the dispatch cycle for a single connection.
1114 // These methods are deliberately not Interruptible because doing all of the work
1115 // with the mutex held makes it easier to ensure that connection invariants are maintained.
1116 // If needed, the methods post commands to run later once the critical bits are done.
1117 void prepareDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1118 EventEntry* eventEntry, const InputTarget* inputTarget);
1119 void enqueueDispatchEntriesLocked(nsecs_t currentTime, const sp<Connection>& connection,
1120 EventEntry* eventEntry, const InputTarget* inputTarget);
1121 void enqueueDispatchEntryLocked(const sp<Connection>& connection,
1122 EventEntry* eventEntry, const InputTarget* inputTarget, int32_t dispatchMode);
1123 void startDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
1124 void finishDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1125 uint32_t seq, bool handled);
1126 void abortBrokenDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1127 bool notify);
1128 void drainDispatchQueueLocked(Queue<DispatchEntry>* queue);
1129 void releaseDispatchEntryLocked(DispatchEntry* dispatchEntry);
1130 static int handleReceiveCallback(int fd, int events, void* data);
1131
1132 void synthesizeCancelationEventsForAllConnectionsLocked(
1133 const CancelationOptions& options);
Michael Wrightfa13dcf2015-06-12 13:25:11 +01001134 void synthesizeCancelationEventsForMonitorsLocked(const CancelationOptions& options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001135 void synthesizeCancelationEventsForInputChannelLocked(const sp<InputChannel>& channel,
1136 const CancelationOptions& options);
1137 void synthesizeCancelationEventsForConnectionLocked(const sp<Connection>& connection,
1138 const CancelationOptions& options);
1139
1140 // Splitting motion events across windows.
1141 MotionEntry* splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds);
1142
1143 // Reset and drop everything the dispatcher is doing.
1144 void resetAndDropEverythingLocked(const char* reason);
1145
1146 // Dump state.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001147 void dumpDispatchStateLocked(std::string& dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148 void logDispatchStateLocked();
1149
1150 // Registration.
1151 void removeMonitorChannelLocked(const sp<InputChannel>& inputChannel);
1152 status_t unregisterInputChannelLocked(const sp<InputChannel>& inputChannel, bool notify);
1153
1154 // Add or remove a connection to the mActiveConnections vector.
1155 void activateConnectionLocked(Connection* connection);
1156 void deactivateConnectionLocked(Connection* connection);
1157
1158 // Interesting events that we might like to log or tell the framework about.
1159 void onDispatchCycleFinishedLocked(
1160 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled);
1161 void onDispatchCycleBrokenLocked(
1162 nsecs_t currentTime, const sp<Connection>& connection);
Robert Carrf759f162018-11-13 12:57:11 -08001163 void onFocusChangedLocked(const sp<InputWindowHandle>& newFocus);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164 void onANRLocked(
1165 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
1166 const sp<InputWindowHandle>& windowHandle,
1167 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason);
1168
1169 // Outbound policy interactions.
1170 void doNotifyConfigurationChangedInterruptible(CommandEntry* commandEntry);
1171 void doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry);
Robert Carrf759f162018-11-13 12:57:11 -08001172 void doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173 void doNotifyANRLockedInterruptible(CommandEntry* commandEntry);
1174 void doInterceptKeyBeforeDispatchingLockedInterruptible(CommandEntry* commandEntry);
1175 void doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry);
1176 bool afterKeyEventLockedInterruptible(const sp<Connection>& connection,
1177 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled);
1178 bool afterMotionEventLockedInterruptible(const sp<Connection>& connection,
1179 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled);
1180 void doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry);
1181 void initializeKeyEvent(KeyEvent* event, const KeyEntry* entry);
1182
1183 // Statistics gathering.
1184 void updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
1185 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication);
1186 void traceInboundQueueLengthLocked();
1187 void traceOutboundQueueLengthLocked(const sp<Connection>& connection);
1188 void traceWaitQueueLengthLocked(const sp<Connection>& connection);
1189};
1190
1191/* Enqueues and dispatches input events, endlessly. */
1192class InputDispatcherThread : public Thread {
1193public:
1194 explicit InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher);
1195 ~InputDispatcherThread();
1196
1197private:
1198 virtual bool threadLoop();
1199
1200 sp<InputDispatcherInterface> mDispatcher;
1201};
1202
1203} // namespace android
1204
1205#endif // _UI_INPUT_DISPATCHER_H