blob: fdf75f68a60a0b45e061ff230a053c6326e36f98 [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>
21#include <input/InputTransport.h>
22#include <utils/KeyedVector.h>
23#include <utils/Vector.h>
24#include <utils/threads.h>
25#include <utils/Timers.h>
26#include <utils/RefBase.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080027#include <utils/Looper.h>
28#include <utils/BitSet.h>
29#include <cutils/atomic.h>
30
31#include <stddef.h>
32#include <unistd.h>
33#include <limits.h>
Arthur Hungb92218b2018-08-14 12:00:21 +080034#include <unordered_map>
Michael Wrightd02c5b62014-02-10 15:10:22 -080035
36#include "InputWindow.h"
37#include "InputApplication.h"
38#include "InputListener.h"
39
40
41namespace android {
42
43/*
44 * Constants used to report the outcome of input event injection.
45 */
46enum {
47 /* (INTERNAL USE ONLY) Specifies that injection is pending and its outcome is unknown. */
48 INPUT_EVENT_INJECTION_PENDING = -1,
49
50 /* Injection succeeded. */
51 INPUT_EVENT_INJECTION_SUCCEEDED = 0,
52
53 /* Injection failed because the injector did not have permission to inject
54 * into the application with input focus. */
55 INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1,
56
57 /* Injection failed because there were no available input targets. */
58 INPUT_EVENT_INJECTION_FAILED = 2,
59
60 /* Injection failed due to a timeout. */
61 INPUT_EVENT_INJECTION_TIMED_OUT = 3
62};
63
64/*
65 * Constants used to determine the input event injection synchronization mode.
66 */
67enum {
68 /* Injection is asynchronous and is assumed always to be successful. */
69 INPUT_EVENT_INJECTION_SYNC_NONE = 0,
70
71 /* Waits for previous events to be dispatched so that the input dispatcher can determine
72 * whether input event injection willbe permitted based on the current input focus.
73 * Does not wait for the input event to finish processing. */
74 INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_RESULT = 1,
75
76 /* Waits for the input event to be completely processed. */
77 INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED = 2,
78};
79
80
81/*
82 * An input target specifies how an input event is to be dispatched to a particular window
83 * including the window's input channel, control flags, a timeout, and an X / Y offset to
84 * be added to input event coordinates to compensate for the absolute position of the
85 * window area.
86 */
87struct InputTarget {
88 enum {
89 /* This flag indicates that the event is being delivered to a foreground application. */
90 FLAG_FOREGROUND = 1 << 0,
91
Michael Wrightcdcd8f22016-03-22 16:52:13 -070092 /* This flag indicates that the MotionEvent falls within the area of the target
Michael Wrightd02c5b62014-02-10 15:10:22 -080093 * obscured by another visible window above it. The motion event should be
94 * delivered with flag AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED. */
95 FLAG_WINDOW_IS_OBSCURED = 1 << 1,
96
97 /* This flag indicates that a motion event is being split across multiple windows. */
98 FLAG_SPLIT = 1 << 2,
99
100 /* This flag indicates that the pointer coordinates dispatched to the application
101 * will be zeroed out to avoid revealing information to an application. This is
102 * used in conjunction with FLAG_DISPATCH_AS_OUTSIDE to prevent apps not sharing
103 * the same UID from watching all touches. */
104 FLAG_ZERO_COORDS = 1 << 3,
105
106 /* This flag indicates that the event should be sent as is.
107 * Should always be set unless the event is to be transmuted. */
108 FLAG_DISPATCH_AS_IS = 1 << 8,
109
110 /* This flag indicates that a MotionEvent with AMOTION_EVENT_ACTION_DOWN falls outside
111 * of the area of this target and so should instead be delivered as an
112 * AMOTION_EVENT_ACTION_OUTSIDE to this target. */
113 FLAG_DISPATCH_AS_OUTSIDE = 1 << 9,
114
115 /* This flag indicates that a hover sequence is starting in the given window.
116 * The event is transmuted into ACTION_HOVER_ENTER. */
117 FLAG_DISPATCH_AS_HOVER_ENTER = 1 << 10,
118
119 /* This flag indicates that a hover event happened outside of a window which handled
120 * previous hover events, signifying the end of the current hover sequence for that
121 * window.
122 * The event is transmuted into ACTION_HOVER_ENTER. */
123 FLAG_DISPATCH_AS_HOVER_EXIT = 1 << 11,
124
125 /* This flag indicates that the event should be canceled.
126 * It is used to transmute ACTION_MOVE into ACTION_CANCEL when a touch slips
127 * outside of a window. */
128 FLAG_DISPATCH_AS_SLIPPERY_EXIT = 1 << 12,
129
130 /* This flag indicates that the event should be dispatched as an initial down.
131 * It is used to transmute ACTION_MOVE into ACTION_DOWN when a touch slips
132 * into a new window. */
133 FLAG_DISPATCH_AS_SLIPPERY_ENTER = 1 << 13,
134
135 /* Mask for all dispatch modes. */
136 FLAG_DISPATCH_MASK = FLAG_DISPATCH_AS_IS
137 | FLAG_DISPATCH_AS_OUTSIDE
138 | FLAG_DISPATCH_AS_HOVER_ENTER
139 | FLAG_DISPATCH_AS_HOVER_EXIT
140 | FLAG_DISPATCH_AS_SLIPPERY_EXIT
141 | FLAG_DISPATCH_AS_SLIPPERY_ENTER,
Michael Wrightcdcd8f22016-03-22 16:52:13 -0700142
143 /* This flag indicates that the target of a MotionEvent is partly or wholly
144 * obscured by another visible window above it. The motion event should be
145 * delivered with flag AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED. */
146 FLAG_WINDOW_IS_PARTIALLY_OBSCURED = 1 << 14,
147
Michael Wrightd02c5b62014-02-10 15:10:22 -0800148 };
149
150 // The input channel to be targeted.
151 sp<InputChannel> inputChannel;
152
153 // Flags for the input target.
154 int32_t flags;
155
156 // The x and y offset to add to a MotionEvent as it is delivered.
157 // (ignored for KeyEvents)
158 float xOffset, yOffset;
159
160 // Scaling factor to apply to MotionEvent as it is delivered.
161 // (ignored for KeyEvents)
162 float scaleFactor;
163
164 // The subset of pointer ids to include in motion events dispatched to this input target
165 // if FLAG_SPLIT is set.
166 BitSet32 pointerIds;
167};
168
169
170/*
171 * Input dispatcher configuration.
172 *
173 * Specifies various options that modify the behavior of the input dispatcher.
174 * The values provided here are merely defaults. The actual values will come from ViewConfiguration
175 * and are passed into the dispatcher during initialization.
176 */
177struct InputDispatcherConfiguration {
178 // The key repeat initial timeout.
179 nsecs_t keyRepeatTimeout;
180
181 // The key repeat inter-key delay.
182 nsecs_t keyRepeatDelay;
183
184 InputDispatcherConfiguration() :
185 keyRepeatTimeout(500 * 1000000LL),
186 keyRepeatDelay(50 * 1000000LL) { }
187};
188
189
190/*
191 * Input dispatcher policy interface.
192 *
193 * The input reader policy is used by the input reader to interact with the Window Manager
194 * and other system components.
195 *
196 * The actual implementation is partially supported by callbacks into the DVM
197 * via JNI. This interface is also mocked in the unit tests.
198 */
199class InputDispatcherPolicyInterface : public virtual RefBase {
200protected:
201 InputDispatcherPolicyInterface() { }
202 virtual ~InputDispatcherPolicyInterface() { }
203
204public:
205 /* Notifies the system that a configuration change has occurred. */
206 virtual void notifyConfigurationChanged(nsecs_t when) = 0;
207
208 /* Notifies the system that an application is not responding.
209 * Returns a new timeout to continue waiting, or 0 to abort dispatch. */
210 virtual nsecs_t notifyANR(const sp<InputApplicationHandle>& inputApplicationHandle,
211 const sp<InputWindowHandle>& inputWindowHandle,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800212 const std::string& reason) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800213
214 /* Notifies the system that an input channel is unrecoverably broken. */
215 virtual void notifyInputChannelBroken(const sp<InputWindowHandle>& inputWindowHandle) = 0;
216
217 /* Gets the input dispatcher configuration. */
218 virtual void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) = 0;
219
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220 /* Filters an input event.
221 * Return true to dispatch the event unmodified, false to consume the event.
222 * A filter can also transform and inject events later by passing POLICY_FLAG_FILTERED
223 * to injectInputEvent.
224 */
225 virtual bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) = 0;
226
227 /* Intercepts a key event immediately before queueing it.
228 * The policy can use this method as an opportunity to perform power management functions
229 * and early event preprocessing such as updating policy flags.
230 *
231 * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
232 * should be dispatched to applications.
233 */
234 virtual void interceptKeyBeforeQueueing(const KeyEvent* keyEvent, uint32_t& policyFlags) = 0;
235
236 /* Intercepts a touch, trackball or other motion event before queueing it.
237 * The policy can use this method as an opportunity to perform power management functions
238 * and early event preprocessing such as updating policy flags.
239 *
240 * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
241 * should be dispatched to applications.
242 */
243 virtual void interceptMotionBeforeQueueing(nsecs_t when, uint32_t& policyFlags) = 0;
244
245 /* Allows the policy a chance to intercept a key before dispatching. */
246 virtual nsecs_t interceptKeyBeforeDispatching(const sp<InputWindowHandle>& inputWindowHandle,
247 const KeyEvent* keyEvent, uint32_t policyFlags) = 0;
248
249 /* Allows the policy a chance to perform default processing for an unhandled key.
250 * Returns an alternate keycode to redispatch as a fallback, or 0 to give up. */
251 virtual bool dispatchUnhandledKey(const sp<InputWindowHandle>& inputWindowHandle,
252 const KeyEvent* keyEvent, uint32_t policyFlags, KeyEvent* outFallbackKeyEvent) = 0;
253
254 /* Notifies the policy about switch events.
255 */
256 virtual void notifySwitch(nsecs_t when,
257 uint32_t switchValues, uint32_t switchMask, uint32_t policyFlags) = 0;
258
259 /* Poke user activity for an event dispatched to a window. */
260 virtual void pokeUserActivity(nsecs_t eventTime, int32_t eventType) = 0;
261
262 /* Checks whether a given application pid/uid has permission to inject input events
263 * into other applications.
264 *
265 * This method is special in that its implementation promises to be non-reentrant and
266 * is safe to call while holding other locks. (Most other methods make no such guarantees!)
267 */
268 virtual bool checkInjectEventsPermissionNonReentrant(
269 int32_t injectorPid, int32_t injectorUid) = 0;
270};
271
272
273/* Notifies the system about input events generated by the input reader.
274 * The dispatcher is expected to be mostly asynchronous. */
275class InputDispatcherInterface : public virtual RefBase, public InputListenerInterface {
276protected:
277 InputDispatcherInterface() { }
278 virtual ~InputDispatcherInterface() { }
279
280public:
281 /* Dumps the state of the input dispatcher.
282 *
283 * This method may be called on any thread (usually by the input manager). */
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800284 virtual void dump(std::string& dump) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800285
286 /* Called by the heatbeat to ensures that the dispatcher has not deadlocked. */
287 virtual void monitor() = 0;
288
289 /* Runs a single iteration of the dispatch loop.
290 * Nominally processes one queued event, a timeout, or a response from an input consumer.
291 *
292 * This method should only be called on the input dispatcher thread.
293 */
294 virtual void dispatchOnce() = 0;
295
296 /* Injects an input event and optionally waits for sync.
297 * The synchronization mode determines whether the method blocks while waiting for
298 * input injection to proceed.
299 * Returns one of the INPUT_EVENT_INJECTION_XXX constants.
300 *
301 * This method may be called on any thread (usually by the input manager).
302 */
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800303 virtual int32_t injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800304 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
305 uint32_t policyFlags) = 0;
306
307 /* Sets the list of input windows.
308 *
309 * This method may be called on any thread (usually by the input manager).
310 */
Arthur Hungb92218b2018-08-14 12:00:21 +0800311 virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles,
312 int32_t displayId) = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800313
314 /* Sets the focused application.
315 *
316 * This method may be called on any thread (usually by the input manager).
317 */
318 virtual void setFocusedApplication(
319 const sp<InputApplicationHandle>& inputApplicationHandle) = 0;
320
321 /* Sets the input dispatching mode.
322 *
323 * This method may be called on any thread (usually by the input manager).
324 */
325 virtual void setInputDispatchMode(bool enabled, bool frozen) = 0;
326
327 /* Sets whether input event filtering is enabled.
328 * When enabled, incoming input events are sent to the policy's filterInputEvent
329 * method instead of being dispatched. The filter is expected to use
330 * injectInputEvent to inject the events it would like to have dispatched.
331 * It should include POLICY_FLAG_FILTERED in the policy flags during injection.
332 */
333 virtual void setInputFilterEnabled(bool enabled) = 0;
334
335 /* Transfers touch focus from the window associated with one channel to the
336 * window associated with the other channel.
337 *
338 * Returns true on success. False if the window did not actually have touch focus.
339 */
340 virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel,
341 const sp<InputChannel>& toChannel) = 0;
342
343 /* Registers or unregister input channels that may be used as targets for input events.
344 * If monitor is true, the channel will receive a copy of all input events.
345 *
346 * These methods may be called on any thread (usually by the input manager).
347 */
348 virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel,
349 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) = 0;
350 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel) = 0;
351};
352
353/* Dispatches events to input targets. Some functions of the input dispatcher, such as
354 * identifying input targets, are controlled by a separate policy object.
355 *
356 * IMPORTANT INVARIANT:
357 * Because the policy can potentially block or cause re-entrance into the input dispatcher,
358 * the input dispatcher never calls into the policy while holding its internal locks.
359 * The implementation is also carefully designed to recover from scenarios such as an
360 * input channel becoming unregistered while identifying input targets or processing timeouts.
361 *
362 * Methods marked 'Locked' must be called with the lock acquired.
363 *
364 * Methods marked 'LockedInterruptible' must be called with the lock acquired but
365 * may during the course of their execution release the lock, call into the policy, and
366 * then reacquire the lock. The caller is responsible for recovering gracefully.
367 *
368 * A 'LockedInterruptible' method may called a 'Locked' method, but NOT vice-versa.
369 */
370class InputDispatcher : public InputDispatcherInterface {
371protected:
372 virtual ~InputDispatcher();
373
374public:
375 explicit InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy);
376
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800377 virtual void dump(std::string& dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800378 virtual void monitor();
379
380 virtual void dispatchOnce();
381
382 virtual void notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args);
383 virtual void notifyKey(const NotifyKeyArgs* args);
384 virtual void notifyMotion(const NotifyMotionArgs* args);
385 virtual void notifySwitch(const NotifySwitchArgs* args);
386 virtual void notifyDeviceReset(const NotifyDeviceResetArgs* args);
387
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800388 virtual int32_t injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800389 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
390 uint32_t policyFlags);
391
Arthur Hungb92218b2018-08-14 12:00:21 +0800392 virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles,
393 int32_t displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800394 virtual void setFocusedApplication(const sp<InputApplicationHandle>& inputApplicationHandle);
395 virtual void setInputDispatchMode(bool enabled, bool frozen);
396 virtual void setInputFilterEnabled(bool enabled);
397
398 virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel,
399 const sp<InputChannel>& toChannel);
400
401 virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel,
402 const sp<InputWindowHandle>& inputWindowHandle, bool monitor);
403 virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel);
404
405private:
406 template <typename T>
407 struct Link {
408 T* next;
409 T* prev;
410
411 protected:
Yi Kong9b14ac62018-07-17 13:48:38 -0700412 inline Link() : next(nullptr), prev(nullptr) { }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800413 };
414
415 struct InjectionState {
416 mutable int32_t refCount;
417
418 int32_t injectorPid;
419 int32_t injectorUid;
420 int32_t injectionResult; // initially INPUT_EVENT_INJECTION_PENDING
421 bool injectionIsAsync; // set to true if injection is not waiting for the result
422 int32_t pendingForegroundDispatches; // the number of foreground dispatches in progress
423
424 InjectionState(int32_t injectorPid, int32_t injectorUid);
425 void release();
426
427 private:
428 ~InjectionState();
429 };
430
431 struct EventEntry : Link<EventEntry> {
432 enum {
433 TYPE_CONFIGURATION_CHANGED,
434 TYPE_DEVICE_RESET,
435 TYPE_KEY,
436 TYPE_MOTION
437 };
438
439 mutable int32_t refCount;
440 int32_t type;
441 nsecs_t eventTime;
442 uint32_t policyFlags;
443 InjectionState* injectionState;
444
445 bool dispatchInProgress; // initially false, set to true while dispatching
446
Yi Kong9b14ac62018-07-17 13:48:38 -0700447 inline bool isInjected() const { return injectionState != nullptr; }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800448
449 void release();
450
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800451 virtual void appendDescription(std::string& msg) const = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800452
453 protected:
454 EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags);
455 virtual ~EventEntry();
456 void releaseInjectionState();
457 };
458
459 struct ConfigurationChangedEntry : EventEntry {
Chih-Hung Hsieh6d2ede12016-09-01 11:28:23 -0700460 explicit ConfigurationChangedEntry(nsecs_t eventTime);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800461 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800462
463 protected:
464 virtual ~ConfigurationChangedEntry();
465 };
466
467 struct DeviceResetEntry : EventEntry {
468 int32_t deviceId;
469
470 DeviceResetEntry(nsecs_t eventTime, int32_t deviceId);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800471 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800472
473 protected:
474 virtual ~DeviceResetEntry();
475 };
476
477 struct KeyEntry : EventEntry {
478 int32_t deviceId;
479 uint32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100480 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800481 int32_t action;
482 int32_t flags;
483 int32_t keyCode;
484 int32_t scanCode;
485 int32_t metaState;
486 int32_t repeatCount;
487 nsecs_t downTime;
488
489 bool syntheticRepeat; // set to true for synthetic key repeats
490
491 enum InterceptKeyResult {
492 INTERCEPT_KEY_RESULT_UNKNOWN,
493 INTERCEPT_KEY_RESULT_SKIP,
494 INTERCEPT_KEY_RESULT_CONTINUE,
495 INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER,
496 };
497 InterceptKeyResult interceptKeyResult; // set based on the interception result
498 nsecs_t interceptKeyWakeupTime; // used with INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER
499
500 KeyEntry(nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100501 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags,
502 int32_t action, int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800503 int32_t repeatCount, nsecs_t downTime);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800504 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800505 void recycle();
506
507 protected:
508 virtual ~KeyEntry();
509 };
510
511 struct MotionEntry : EventEntry {
512 nsecs_t eventTime;
513 int32_t deviceId;
514 uint32_t source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800515 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800516 int32_t action;
Michael Wright7b159c92015-05-14 14:48:03 +0100517 int32_t actionButton;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800518 int32_t flags;
519 int32_t metaState;
520 int32_t buttonState;
521 int32_t edgeFlags;
522 float xPrecision;
523 float yPrecision;
524 nsecs_t downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800525 uint32_t pointerCount;
526 PointerProperties pointerProperties[MAX_POINTERS];
527 PointerCoords pointerCoords[MAX_POINTERS];
528
529 MotionEntry(nsecs_t eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800530 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +0100531 int32_t action, int32_t actionButton, int32_t flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800532 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800533 float xPrecision, float yPrecision, nsecs_t downTime, uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -0800534 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
535 float xOffset, float yOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800536 virtual void appendDescription(std::string& msg) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800537
538 protected:
539 virtual ~MotionEntry();
540 };
541
542 // Tracks the progress of dispatching a particular event to a particular connection.
543 struct DispatchEntry : Link<DispatchEntry> {
544 const uint32_t seq; // unique sequence number, never 0
545
546 EventEntry* eventEntry; // the event to dispatch
547 int32_t targetFlags;
548 float xOffset;
549 float yOffset;
550 float scaleFactor;
551 nsecs_t deliveryTime; // time when the event was actually delivered
552
553 // Set to the resolved action and flags when the event is enqueued.
554 int32_t resolvedAction;
555 int32_t resolvedFlags;
556
557 DispatchEntry(EventEntry* eventEntry,
558 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor);
559 ~DispatchEntry();
560
561 inline bool hasForegroundTarget() const {
562 return targetFlags & InputTarget::FLAG_FOREGROUND;
563 }
564
565 inline bool isSplit() const {
566 return targetFlags & InputTarget::FLAG_SPLIT;
567 }
568
569 private:
570 static volatile int32_t sNextSeqAtomic;
571
572 static uint32_t nextSeq();
573 };
574
575 // A command entry captures state and behavior for an action to be performed in the
576 // dispatch loop after the initial processing has taken place. It is essentially
577 // a kind of continuation used to postpone sensitive policy interactions to a point
578 // in the dispatch loop where it is safe to release the lock (generally after finishing
579 // the critical parts of the dispatch cycle).
580 //
581 // The special thing about commands is that they can voluntarily release and reacquire
582 // the dispatcher lock at will. Initially when the command starts running, the
583 // dispatcher lock is held. However, if the command needs to call into the policy to
584 // do some work, it can release the lock, do the work, then reacquire the lock again
585 // before returning.
586 //
587 // This mechanism is a bit clunky but it helps to preserve the invariant that the dispatch
588 // never calls into the policy while holding its lock.
589 //
590 // Commands are implicitly 'LockedInterruptible'.
591 struct CommandEntry;
592 typedef void (InputDispatcher::*Command)(CommandEntry* commandEntry);
593
594 class Connection;
595 struct CommandEntry : Link<CommandEntry> {
Chih-Hung Hsieh6d2ede12016-09-01 11:28:23 -0700596 explicit CommandEntry(Command command);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800597 ~CommandEntry();
598
599 Command command;
600
601 // parameters for the command (usage varies by command)
602 sp<Connection> connection;
603 nsecs_t eventTime;
604 KeyEntry* keyEntry;
605 sp<InputApplicationHandle> inputApplicationHandle;
606 sp<InputWindowHandle> inputWindowHandle;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800607 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800608 int32_t userActivityEventType;
609 uint32_t seq;
610 bool handled;
611 };
612
613 // Generic queue implementation.
614 template <typename T>
615 struct Queue {
616 T* head;
617 T* tail;
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800618 uint32_t entryCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800619
Yi Kong9b14ac62018-07-17 13:48:38 -0700620 inline Queue() : head(nullptr), tail(nullptr), entryCount(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800621 }
622
623 inline bool isEmpty() const {
624 return !head;
625 }
626
627 inline void enqueueAtTail(T* entry) {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800628 entryCount++;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800629 entry->prev = tail;
630 if (tail) {
631 tail->next = entry;
632 } else {
633 head = entry;
634 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700635 entry->next = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800636 tail = entry;
637 }
638
639 inline void enqueueAtHead(T* entry) {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800640 entryCount++;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800641 entry->next = head;
642 if (head) {
643 head->prev = entry;
644 } else {
645 tail = entry;
646 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700647 entry->prev = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800648 head = entry;
649 }
650
651 inline void dequeue(T* entry) {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800652 entryCount--;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800653 if (entry->prev) {
654 entry->prev->next = entry->next;
655 } else {
656 head = entry->next;
657 }
658 if (entry->next) {
659 entry->next->prev = entry->prev;
660 } else {
661 tail = entry->prev;
662 }
663 }
664
665 inline T* dequeueAtHead() {
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800666 entryCount--;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800667 T* entry = head;
668 head = entry->next;
669 if (head) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700670 head->prev = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800671 } else {
Yi Kong9b14ac62018-07-17 13:48:38 -0700672 tail = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800673 }
674 return entry;
675 }
676
Jon McCaffrey65dbe972014-11-18 12:07:08 -0800677 uint32_t count() const {
678 return entryCount;
679 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800680 };
681
682 /* Specifies which events are to be canceled and why. */
683 struct CancelationOptions {
684 enum Mode {
685 CANCEL_ALL_EVENTS = 0,
686 CANCEL_POINTER_EVENTS = 1,
687 CANCEL_NON_POINTER_EVENTS = 2,
688 CANCEL_FALLBACK_EVENTS = 3,
689 };
690
691 // The criterion to use to determine which events should be canceled.
692 Mode mode;
693
694 // Descriptive reason for the cancelation.
695 const char* reason;
696
697 // The specific keycode of the key event to cancel, or -1 to cancel any key event.
698 int32_t keyCode;
699
700 // The specific device id of events to cancel, or -1 to cancel events from any device.
701 int32_t deviceId;
702
703 CancelationOptions(Mode mode, const char* reason) :
704 mode(mode), reason(reason), keyCode(-1), deviceId(-1) { }
705 };
706
707 /* Tracks dispatched key and motion event state so that cancelation events can be
708 * synthesized when events are dropped. */
709 class InputState {
710 public:
711 InputState();
712 ~InputState();
713
714 // Returns true if there is no state to be canceled.
715 bool isNeutral() const;
716
717 // Returns true if the specified source is known to have received a hover enter
718 // motion event.
719 bool isHovering(int32_t deviceId, uint32_t source, int32_t displayId) const;
720
721 // Records tracking information for a key event that has just been published.
722 // Returns true if the event should be delivered, false if it is inconsistent
723 // and should be skipped.
724 bool trackKey(const KeyEntry* entry, int32_t action, int32_t flags);
725
726 // Records tracking information for a motion event that has just been published.
727 // Returns true if the event should be delivered, false if it is inconsistent
728 // and should be skipped.
729 bool trackMotion(const MotionEntry* entry, int32_t action, int32_t flags);
730
731 // Synthesizes cancelation events for the current state and resets the tracked state.
732 void synthesizeCancelationEvents(nsecs_t currentTime,
733 Vector<EventEntry*>& outEvents, const CancelationOptions& options);
734
735 // Clears the current state.
736 void clear();
737
738 // Copies pointer-related parts of the input state to another instance.
739 void copyPointerStateTo(InputState& other) const;
740
741 // Gets the fallback key associated with a keycode.
742 // Returns -1 if none.
743 // Returns AKEYCODE_UNKNOWN if we are only dispatching the unhandled key to the policy.
744 int32_t getFallbackKey(int32_t originalKeyCode);
745
746 // Sets the fallback key for a particular keycode.
747 void setFallbackKey(int32_t originalKeyCode, int32_t fallbackKeyCode);
748
749 // Removes the fallback key for a particular keycode.
750 void removeFallbackKey(int32_t originalKeyCode);
751
752 inline const KeyedVector<int32_t, int32_t>& getFallbackKeys() const {
753 return mFallbackKeys;
754 }
755
756 private:
757 struct KeyMemento {
758 int32_t deviceId;
759 uint32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100760 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800761 int32_t keyCode;
762 int32_t scanCode;
763 int32_t metaState;
764 int32_t flags;
765 nsecs_t downTime;
766 uint32_t policyFlags;
767 };
768
769 struct MotionMemento {
770 int32_t deviceId;
771 uint32_t source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800772 int32_t displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800773 int32_t flags;
774 float xPrecision;
775 float yPrecision;
776 nsecs_t downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800777 uint32_t pointerCount;
778 PointerProperties pointerProperties[MAX_POINTERS];
779 PointerCoords pointerCoords[MAX_POINTERS];
780 bool hovering;
781 uint32_t policyFlags;
782
783 void setPointers(const MotionEntry* entry);
784 };
785
786 Vector<KeyMemento> mKeyMementos;
787 Vector<MotionMemento> mMotionMementos;
788 KeyedVector<int32_t, int32_t> mFallbackKeys;
789
790 ssize_t findKeyMemento(const KeyEntry* entry) const;
791 ssize_t findMotionMemento(const MotionEntry* entry, bool hovering) const;
792
793 void addKeyMemento(const KeyEntry* entry, int32_t flags);
794 void addMotionMemento(const MotionEntry* entry, int32_t flags, bool hovering);
795
796 static bool shouldCancelKey(const KeyMemento& memento,
797 const CancelationOptions& options);
798 static bool shouldCancelMotion(const MotionMemento& memento,
799 const CancelationOptions& options);
800 };
801
802 /* Manages the dispatch state associated with a single input channel. */
803 class Connection : public RefBase {
804 protected:
805 virtual ~Connection();
806
807 public:
808 enum Status {
809 // Everything is peachy.
810 STATUS_NORMAL,
811 // An unrecoverable communication error has occurred.
812 STATUS_BROKEN,
813 // The input channel has been unregistered.
814 STATUS_ZOMBIE
815 };
816
817 Status status;
818 sp<InputChannel> inputChannel; // never null
819 sp<InputWindowHandle> inputWindowHandle; // may be null
820 bool monitor;
821 InputPublisher inputPublisher;
822 InputState inputState;
823
824 // True if the socket is full and no further events can be published until
825 // the application consumes some of the input.
826 bool inputPublisherBlocked;
827
828 // Queue of events that need to be published to the connection.
829 Queue<DispatchEntry> outboundQueue;
830
831 // Queue of events that have been published to the connection but that have not
832 // yet received a "finished" response from the application.
833 Queue<DispatchEntry> waitQueue;
834
835 explicit Connection(const sp<InputChannel>& inputChannel,
836 const sp<InputWindowHandle>& inputWindowHandle, bool monitor);
837
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -0800838 inline const std::string getInputChannelName() const { return inputChannel->getName(); }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -0800840 const std::string getWindowName() const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800841 const char* getStatusLabel() const;
842
843 DispatchEntry* findWaitQueueEntry(uint32_t seq);
844 };
845
846 enum DropReason {
847 DROP_REASON_NOT_DROPPED = 0,
848 DROP_REASON_POLICY = 1,
849 DROP_REASON_APP_SWITCH = 2,
850 DROP_REASON_DISABLED = 3,
851 DROP_REASON_BLOCKED = 4,
852 DROP_REASON_STALE = 5,
853 };
854
855 sp<InputDispatcherPolicyInterface> mPolicy;
856 InputDispatcherConfiguration mConfig;
857
858 Mutex mLock;
859
860 Condition mDispatcherIsAliveCondition;
861
862 sp<Looper> mLooper;
863
864 EventEntry* mPendingEvent;
865 Queue<EventEntry> mInboundQueue;
866 Queue<EventEntry> mRecentQueue;
867 Queue<CommandEntry> mCommandQueue;
868
Michael Wright3a981722015-06-10 15:26:13 +0100869 DropReason mLastDropReason;
870
Michael Wrightd02c5b62014-02-10 15:10:22 -0800871 void dispatchOnceInnerLocked(nsecs_t* nextWakeupTime);
872
873 // Enqueues an inbound event. Returns true if mLooper->wake() should be called.
874 bool enqueueInboundEventLocked(EventEntry* entry);
875
876 // Cleans up input state when dropping an inbound event.
877 void dropInboundEventLocked(EventEntry* entry, DropReason dropReason);
878
879 // Adds an event to a queue of recent events for debugging purposes.
880 void addRecentEventLocked(EventEntry* entry);
881
882 // App switch latency optimization.
883 bool mAppSwitchSawKeyDown;
884 nsecs_t mAppSwitchDueTime;
885
886 static bool isAppSwitchKeyCode(int32_t keyCode);
887 bool isAppSwitchKeyEventLocked(KeyEntry* keyEntry);
888 bool isAppSwitchPendingLocked();
889 void resetPendingAppSwitchLocked(bool handled);
890
891 // Stale event latency optimization.
892 static bool isStaleEventLocked(nsecs_t currentTime, EventEntry* entry);
893
894 // Blocked event latency optimization. Drops old events when the user intends
895 // to transfer focus to a new application.
896 EventEntry* mNextUnblockedEvent;
897
898 sp<InputWindowHandle> findTouchedWindowAtLocked(int32_t displayId, int32_t x, int32_t y);
899
900 // All registered connections mapped by channel file descriptor.
901 KeyedVector<int, sp<Connection> > mConnectionsByFd;
902
903 ssize_t getConnectionIndexLocked(const sp<InputChannel>& inputChannel);
904
905 // Input channels that will receive a copy of all input events.
906 Vector<sp<InputChannel> > mMonitoringChannels;
907
908 // Event injection and synchronization.
909 Condition mInjectionResultAvailableCondition;
910 bool hasInjectionPermission(int32_t injectorPid, int32_t injectorUid);
911 void setInjectionResultLocked(EventEntry* entry, int32_t injectionResult);
912
913 Condition mInjectionSyncFinishedCondition;
914 void incrementPendingForegroundDispatchesLocked(EventEntry* entry);
915 void decrementPendingForegroundDispatchesLocked(EventEntry* entry);
916
917 // Key repeat tracking.
918 struct KeyRepeatState {
919 KeyEntry* lastKeyEntry; // or null if no repeat
920 nsecs_t nextRepeatTime;
921 } mKeyRepeatState;
922
923 void resetKeyRepeatLocked();
924 KeyEntry* synthesizeKeyRepeatLocked(nsecs_t currentTime);
925
Michael Wright78f24442014-08-06 15:55:28 -0700926 // Key replacement tracking
927 struct KeyReplacement {
928 int32_t keyCode;
929 int32_t deviceId;
930 bool operator==(const KeyReplacement& rhs) const {
931 return keyCode == rhs.keyCode && deviceId == rhs.deviceId;
932 }
933 bool operator<(const KeyReplacement& rhs) const {
934 return keyCode != rhs.keyCode ? keyCode < rhs.keyCode : deviceId < rhs.deviceId;
935 }
936 };
937 // Maps the key code replaced, device id tuple to the key code it was replaced with
938 KeyedVector<KeyReplacement, int32_t> mReplacedKeys;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -0500939 // Process certain Meta + Key combinations
940 void accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
941 int32_t& keyCode, int32_t& metaState);
Michael Wright78f24442014-08-06 15:55:28 -0700942
Michael Wrightd02c5b62014-02-10 15:10:22 -0800943 // Deferred command processing.
944 bool haveCommandsLocked() const;
945 bool runCommandsLockedInterruptible();
946 CommandEntry* postCommandLocked(Command command);
947
948 // Input filter processing.
949 bool shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args);
950 bool shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args);
951
952 // Inbound event processing.
953 void drainInboundQueueLocked();
954 void releasePendingEventLocked();
955 void releaseInboundEventLocked(EventEntry* entry);
956
957 // Dispatch state.
958 bool mDispatchEnabled;
959 bool mDispatchFrozen;
960 bool mInputFilterEnabled;
961
Arthur Hungb92218b2018-08-14 12:00:21 +0800962 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>> mWindowHandlesByDisplay;
963 // Get window handles by display, return an empty vector if not found.
964 Vector<sp<InputWindowHandle>> getWindowHandlesLocked(int32_t displayId) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965 sp<InputWindowHandle> getWindowHandleLocked(const sp<InputChannel>& inputChannel) const;
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +0000966 bool hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967
968 // Focus tracking for keys, trackball, etc.
969 sp<InputWindowHandle> mFocusedWindowHandle;
970
971 // Focus tracking for touch.
972 struct TouchedWindow {
973 sp<InputWindowHandle> windowHandle;
974 int32_t targetFlags;
975 BitSet32 pointerIds; // zero unless target flag FLAG_SPLIT is set
976 };
977 struct TouchState {
978 bool down;
979 bool split;
980 int32_t deviceId; // id of the device that is currently down, others are rejected
981 uint32_t source; // source of the device that is current down, others are rejected
982 int32_t displayId; // id to the display that currently has a touch, others are rejected
983 Vector<TouchedWindow> windows;
984
985 TouchState();
986 ~TouchState();
987 void reset();
988 void copyFrom(const TouchState& other);
989 void addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
990 int32_t targetFlags, BitSet32 pointerIds);
991 void removeWindow(const sp<InputWindowHandle>& windowHandle);
992 void filterNonAsIsTouchWindows();
993 sp<InputWindowHandle> getFirstForegroundWindowHandle() const;
994 bool isSlippery() const;
995 };
996
Jeff Brownf086ddb2014-02-11 14:28:48 -0800997 KeyedVector<int32_t, TouchState> mTouchStatesByDisplay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998 TouchState mTempTouchState;
999
1000 // Focused application.
1001 sp<InputApplicationHandle> mFocusedApplicationHandle;
1002
1003 // Dispatcher state at time of last ANR.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001004 std::string mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001005
1006 // Dispatch inbound events.
1007 bool dispatchConfigurationChangedLocked(
1008 nsecs_t currentTime, ConfigurationChangedEntry* entry);
1009 bool dispatchDeviceResetLocked(
1010 nsecs_t currentTime, DeviceResetEntry* entry);
1011 bool dispatchKeyLocked(
1012 nsecs_t currentTime, KeyEntry* entry,
1013 DropReason* dropReason, nsecs_t* nextWakeupTime);
1014 bool dispatchMotionLocked(
1015 nsecs_t currentTime, MotionEntry* entry,
1016 DropReason* dropReason, nsecs_t* nextWakeupTime);
1017 void dispatchEventLocked(nsecs_t currentTime, EventEntry* entry,
1018 const Vector<InputTarget>& inputTargets);
1019
1020 void logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry);
1021 void logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry);
1022
1023 // Keeping track of ANR timeouts.
1024 enum InputTargetWaitCause {
1025 INPUT_TARGET_WAIT_CAUSE_NONE,
1026 INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY,
1027 INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY,
1028 };
1029
1030 InputTargetWaitCause mInputTargetWaitCause;
1031 nsecs_t mInputTargetWaitStartTime;
1032 nsecs_t mInputTargetWaitTimeoutTime;
1033 bool mInputTargetWaitTimeoutExpired;
1034 sp<InputApplicationHandle> mInputTargetWaitApplicationHandle;
1035
1036 // Contains the last window which received a hover event.
1037 sp<InputWindowHandle> mLastHoverWindowHandle;
1038
1039 // Finding targets for input events.
1040 int32_t handleTargetsNotReadyLocked(nsecs_t currentTime, const EventEntry* entry,
1041 const sp<InputApplicationHandle>& applicationHandle,
1042 const sp<InputWindowHandle>& windowHandle,
1043 nsecs_t* nextWakeupTime, const char* reason);
1044 void resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1045 const sp<InputChannel>& inputChannel);
1046 nsecs_t getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime);
1047 void resetANRTimeoutsLocked();
1048
1049 int32_t findFocusedWindowTargetsLocked(nsecs_t currentTime, const EventEntry* entry,
1050 Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime);
1051 int32_t findTouchedWindowTargetsLocked(nsecs_t currentTime, const MotionEntry* entry,
1052 Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1053 bool* outConflictingPointerActions);
1054
1055 void addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1056 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets);
1057 void addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets);
1058
1059 void pokeUserActivityLocked(const EventEntry* eventEntry);
1060 bool checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1061 const InjectionState* injectionState);
1062 bool isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1063 int32_t x, int32_t y) const;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001064 bool isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001065 std::string getApplicationWindowLabelLocked(const sp<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066 const sp<InputWindowHandle>& windowHandle);
1067
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001068 std::string checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001069 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1070 const char* targetType);
1071
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072 // Manage the dispatch cycle for a single connection.
1073 // These methods are deliberately not Interruptible because doing all of the work
1074 // with the mutex held makes it easier to ensure that connection invariants are maintained.
1075 // If needed, the methods post commands to run later once the critical bits are done.
1076 void prepareDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1077 EventEntry* eventEntry, const InputTarget* inputTarget);
1078 void enqueueDispatchEntriesLocked(nsecs_t currentTime, const sp<Connection>& connection,
1079 EventEntry* eventEntry, const InputTarget* inputTarget);
1080 void enqueueDispatchEntryLocked(const sp<Connection>& connection,
1081 EventEntry* eventEntry, const InputTarget* inputTarget, int32_t dispatchMode);
1082 void startDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
1083 void finishDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1084 uint32_t seq, bool handled);
1085 void abortBrokenDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
1086 bool notify);
1087 void drainDispatchQueueLocked(Queue<DispatchEntry>* queue);
1088 void releaseDispatchEntryLocked(DispatchEntry* dispatchEntry);
1089 static int handleReceiveCallback(int fd, int events, void* data);
1090
1091 void synthesizeCancelationEventsForAllConnectionsLocked(
1092 const CancelationOptions& options);
Michael Wrightfa13dcf2015-06-12 13:25:11 +01001093 void synthesizeCancelationEventsForMonitorsLocked(const CancelationOptions& options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094 void synthesizeCancelationEventsForInputChannelLocked(const sp<InputChannel>& channel,
1095 const CancelationOptions& options);
1096 void synthesizeCancelationEventsForConnectionLocked(const sp<Connection>& connection,
1097 const CancelationOptions& options);
1098
1099 // Splitting motion events across windows.
1100 MotionEntry* splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds);
1101
1102 // Reset and drop everything the dispatcher is doing.
1103 void resetAndDropEverythingLocked(const char* reason);
1104
1105 // Dump state.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001106 void dumpDispatchStateLocked(std::string& dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001107 void logDispatchStateLocked();
1108
1109 // Registration.
1110 void removeMonitorChannelLocked(const sp<InputChannel>& inputChannel);
1111 status_t unregisterInputChannelLocked(const sp<InputChannel>& inputChannel, bool notify);
1112
1113 // Add or remove a connection to the mActiveConnections vector.
1114 void activateConnectionLocked(Connection* connection);
1115 void deactivateConnectionLocked(Connection* connection);
1116
1117 // Interesting events that we might like to log or tell the framework about.
1118 void onDispatchCycleFinishedLocked(
1119 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled);
1120 void onDispatchCycleBrokenLocked(
1121 nsecs_t currentTime, const sp<Connection>& connection);
1122 void onANRLocked(
1123 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
1124 const sp<InputWindowHandle>& windowHandle,
1125 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason);
1126
1127 // Outbound policy interactions.
1128 void doNotifyConfigurationChangedInterruptible(CommandEntry* commandEntry);
1129 void doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry);
1130 void doNotifyANRLockedInterruptible(CommandEntry* commandEntry);
1131 void doInterceptKeyBeforeDispatchingLockedInterruptible(CommandEntry* commandEntry);
1132 void doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry);
1133 bool afterKeyEventLockedInterruptible(const sp<Connection>& connection,
1134 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled);
1135 bool afterMotionEventLockedInterruptible(const sp<Connection>& connection,
1136 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled);
1137 void doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry);
1138 void initializeKeyEvent(KeyEvent* event, const KeyEntry* entry);
1139
1140 // Statistics gathering.
1141 void updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
1142 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication);
1143 void traceInboundQueueLengthLocked();
1144 void traceOutboundQueueLengthLocked(const sp<Connection>& connection);
1145 void traceWaitQueueLengthLocked(const sp<Connection>& connection);
1146};
1147
1148/* Enqueues and dispatches input events, endlessly. */
1149class InputDispatcherThread : public Thread {
1150public:
1151 explicit InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher);
1152 ~InputDispatcherThread();
1153
1154private:
1155 virtual bool threadLoop();
1156
1157 sp<InputDispatcherInterface> mDispatcher;
1158};
1159
1160} // namespace android
1161
1162#endif // _UI_INPUT_DISPATCHER_H