blob: 8e3c811a6794f7fcd5de4256641dc55576c1d0bd [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#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
Michael Wright3dd60e22019-03-27 22:06:44 +000020#define LOG_NDEBUG 0
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
31// Log debug messages about registrations.
32#define DEBUG_REGISTRATION 0
33
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
38#define DEBUG_FOCUS 0
39
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
43// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
46#include "InputDispatcher.h"
47
Michael Wrightd02c5b62014-02-10 15:10:22 -080048#include <errno.h>
Siarhei Vishniakou443ad902019-03-06 17:25:41 -080049#include <inttypes.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#include <limits.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070051#include <stddef.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#include <time.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070053#include <unistd.h>
Garfield Tane4fc0102019-09-11 13:16:25 -070054#include <sstream>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070055
Michael Wright2b3c3302018-03-02 17:19:13 +000056#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080057#include <android-base/stringprintf.h>
Robert Carr4e670e52018-08-15 13:26:12 -070058#include <binder/Binder.h>
Garfield Tane4fc0102019-09-11 13:16:25 -070059#include <log/log.h>
60#include <powermanager/PowerManager.h>
61#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080062
63#define INDENT " "
64#define INDENT2 " "
65#define INDENT3 " "
66#define INDENT4 " "
67
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080068using android::base::StringPrintf;
69
Michael Wrightd02c5b62014-02-10 15:10:22 -080070namespace android {
71
72// Default input dispatching timeout if there is no focused application or paused window
73// from which to determine an appropriate dispatching timeout.
Michael Wright2b3c3302018-03-02 17:19:13 +000074constexpr nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080075
76// Amount of time to allow for all pending events to be processed when an app switch
77// key is on the way. This is used to preempt input dispatch and drop input events
78// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000079constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080080
81// Amount of time to allow for an event to be dispatched (measured since its eventTime)
82// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000083constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080084
85// Amount of time to allow touch events to be streamed out to a connection before requiring
86// that the first event be finished. This value extends the ANR timeout by the specified
87// amount. For example, if streaming is allowed to get ahead by one second relative to the
88// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
Michael Wright2b3c3302018-03-02 17:19:13 +000089constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080090
91// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000092constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
93
94// Log a warning when an interception call takes longer than this to process.
95constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080096
97// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +000098constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
99
Prabir Pradhan42611e02018-11-27 14:04:02 -0800100// Sequence number for synthesized or injected events.
101constexpr uint32_t SYNTHESIZED_EVENT_SEQUENCE_NUM = 0;
102
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103static inline nsecs_t now() {
104 return systemTime(SYSTEM_TIME_MONOTONIC);
105}
106
107static inline const char* toString(bool value) {
108 return value ? "true" : "false";
109}
110
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -0800111static std::string motionActionToString(int32_t action) {
112 // Convert MotionEvent action to string
Garfield Tane4fc0102019-09-11 13:16:25 -0700113 switch (action & AMOTION_EVENT_ACTION_MASK) {
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -0800114 case AMOTION_EVENT_ACTION_DOWN:
115 return "DOWN";
116 case AMOTION_EVENT_ACTION_MOVE:
117 return "MOVE";
118 case AMOTION_EVENT_ACTION_UP:
119 return "UP";
120 case AMOTION_EVENT_ACTION_POINTER_DOWN:
121 return "POINTER_DOWN";
122 case AMOTION_EVENT_ACTION_POINTER_UP:
123 return "POINTER_UP";
124 }
125 return StringPrintf("%" PRId32, action);
126}
127
128static std::string keyActionToString(int32_t action) {
129 // Convert KeyEvent action to string
Michael Wright3dd60e22019-03-27 22:06:44 +0000130 switch (action) {
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -0800131 case AKEY_EVENT_ACTION_DOWN:
132 return "DOWN";
133 case AKEY_EVENT_ACTION_UP:
134 return "UP";
135 case AKEY_EVENT_ACTION_MULTIPLE:
136 return "MULTIPLE";
137 }
138 return StringPrintf("%" PRId32, action);
139}
140
Michael Wright3dd60e22019-03-27 22:06:44 +0000141static std::string dispatchModeToString(int32_t dispatchMode) {
142 switch (dispatchMode) {
143 case InputTarget::FLAG_DISPATCH_AS_IS:
144 return "DISPATCH_AS_IS";
145 case InputTarget::FLAG_DISPATCH_AS_OUTSIDE:
146 return "DISPATCH_AS_OUTSIDE";
147 case InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER:
148 return "DISPATCH_AS_HOVER_ENTER";
149 case InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT:
150 return "DISPATCH_AS_HOVER_EXIT";
151 case InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT:
152 return "DISPATCH_AS_SLIPPERY_EXIT";
153 case InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER:
154 return "DISPATCH_AS_SLIPPERY_ENTER";
155 }
156 return StringPrintf("%" PRId32, dispatchMode);
157}
158
Michael Wrightd02c5b62014-02-10 15:10:22 -0800159static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700160 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
161 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800162}
163
164static bool isValidKeyAction(int32_t action) {
165 switch (action) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700166 case AKEY_EVENT_ACTION_DOWN:
167 case AKEY_EVENT_ACTION_UP:
168 return true;
169 default:
170 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800171 }
172}
173
174static bool validateKeyEvent(int32_t action) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700175 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800176 ALOGE("Key event has invalid action code 0x%x", action);
177 return false;
178 }
179 return true;
180}
181
Michael Wright7b159c92015-05-14 14:48:03 +0100182static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800183 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700184 case AMOTION_EVENT_ACTION_DOWN:
185 case AMOTION_EVENT_ACTION_UP:
186 case AMOTION_EVENT_ACTION_CANCEL:
187 case AMOTION_EVENT_ACTION_MOVE:
188 case AMOTION_EVENT_ACTION_OUTSIDE:
189 case AMOTION_EVENT_ACTION_HOVER_ENTER:
190 case AMOTION_EVENT_ACTION_HOVER_MOVE:
191 case AMOTION_EVENT_ACTION_HOVER_EXIT:
192 case AMOTION_EVENT_ACTION_SCROLL:
193 return true;
194 case AMOTION_EVENT_ACTION_POINTER_DOWN:
195 case AMOTION_EVENT_ACTION_POINTER_UP: {
196 int32_t index = getMotionEventActionPointerIndex(action);
197 return index >= 0 && index < pointerCount;
198 }
199 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
200 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
201 return actionButton != 0;
202 default:
203 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800204 }
205}
206
Michael Wright7b159c92015-05-14 14:48:03 +0100207static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tane4fc0102019-09-11 13:16:25 -0700208 const PointerProperties* pointerProperties) {
209 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800210 ALOGE("Motion event has invalid action code 0x%x", action);
211 return false;
212 }
213 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000214 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tane4fc0102019-09-11 13:16:25 -0700215 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 return false;
217 }
218 BitSet32 pointerIdBits;
219 for (size_t i = 0; i < pointerCount; i++) {
220 int32_t id = pointerProperties[i].id;
221 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700222 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
223 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800224 return false;
225 }
226 if (pointerIdBits.hasBit(id)) {
227 ALOGE("Motion event has duplicate pointer id %d", id);
228 return false;
229 }
230 pointerIdBits.markBit(id);
231 }
232 return true;
233}
234
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800235static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800236 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800237 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800238 return;
239 }
240
241 bool first = true;
242 Region::const_iterator cur = region.begin();
243 Region::const_iterator const tail = region.end();
244 while (cur != tail) {
245 if (first) {
246 first = false;
247 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800248 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800249 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800250 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800251 cur++;
252 }
253}
254
Garfield Tane4fc0102019-09-11 13:16:25 -0700255template <typename T, typename U>
Tiger Huang721e26f2018-07-24 22:26:19 +0800256static T getValueByKey(std::unordered_map<U, T>& map, U key) {
257 typename std::unordered_map<U, T>::const_iterator it = map.find(key);
258 return it != map.end() ? it->second : T{};
259}
260
Michael Wrightd02c5b62014-02-10 15:10:22 -0800261// --- InputDispatcher ---
262
Garfield Tane4fc0102019-09-11 13:16:25 -0700263InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
264 : mPolicy(policy),
265 mPendingEvent(nullptr),
266 mLastDropReason(DROP_REASON_NOT_DROPPED),
267 mAppSwitchSawKeyDown(false),
268 mAppSwitchDueTime(LONG_LONG_MAX),
269 mNextUnblockedEvent(nullptr),
270 mDispatchEnabled(false),
271 mDispatchFrozen(false),
272 mInputFilterEnabled(false),
273 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
274 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800275 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800276 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800277
Yi Kong9b14ac62018-07-17 13:48:38 -0700278 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800279
280 policy->getDispatcherConfiguration(&mConfig);
281}
282
283InputDispatcher::~InputDispatcher() {
284 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800285 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800286
287 resetKeyRepeatLocked();
288 releasePendingEventLocked();
289 drainInboundQueueLocked();
290 }
291
292 while (mConnectionsByFd.size() != 0) {
293 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
294 }
295}
296
297void InputDispatcher::dispatchOnce() {
298 nsecs_t nextWakeupTime = LONG_LONG_MAX;
299 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800300 std::scoped_lock _l(mLock);
301 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800302
303 // Run a dispatch loop if there are no pending commands.
304 // The dispatch loop might enqueue commands to run afterwards.
305 if (!haveCommandsLocked()) {
306 dispatchOnceInnerLocked(&nextWakeupTime);
307 }
308
309 // Run all pending commands if there are any.
310 // If any commands were run then force the next poll to wake up immediately.
311 if (runCommandsLockedInterruptible()) {
312 nextWakeupTime = LONG_LONG_MIN;
313 }
314 } // release lock
315
316 // Wait for callback or timeout or wake. (make sure we round up, not down)
317 nsecs_t currentTime = now();
318 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
319 mLooper->pollOnce(timeoutMillis);
320}
321
322void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
323 nsecs_t currentTime = now();
324
Jeff Browndc5992e2014-04-11 01:27:26 -0700325 // Reset the key repeat timer whenever normal dispatch is suspended while the
326 // device is in a non-interactive state. This is to ensure that we abort a key
327 // repeat if the device is just coming out of sleep.
328 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800329 resetKeyRepeatLocked();
330 }
331
332 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
333 if (mDispatchFrozen) {
334#if DEBUG_FOCUS
335 ALOGD("Dispatch frozen. Waiting some more.");
336#endif
337 return;
338 }
339
340 // Optimize latency of app switches.
341 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
342 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
343 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
344 if (mAppSwitchDueTime < *nextWakeupTime) {
345 *nextWakeupTime = mAppSwitchDueTime;
346 }
347
348 // Ready to start a new event.
349 // If we don't already have a pending event, go grab one.
Garfield Tane4fc0102019-09-11 13:16:25 -0700350 if (!mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800351 if (mInboundQueue.isEmpty()) {
352 if (isAppSwitchDue) {
353 // The inbound queue is empty so the app switch key we were waiting
354 // for will never arrive. Stop waiting for it.
355 resetPendingAppSwitchLocked(false);
356 isAppSwitchDue = false;
357 }
358
359 // Synthesize a key repeat if appropriate.
360 if (mKeyRepeatState.lastKeyEntry) {
361 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
362 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
363 } else {
364 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
365 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
366 }
367 }
368 }
369
370 // Nothing to do if there is no pending event.
371 if (!mPendingEvent) {
372 return;
373 }
374 } else {
375 // Inbound queue has at least one entry.
376 mPendingEvent = mInboundQueue.dequeueAtHead();
377 traceInboundQueueLengthLocked();
378 }
379
380 // Poke user activity for this event.
381 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
382 pokeUserActivityLocked(mPendingEvent);
383 }
384
385 // Get ready to dispatch the event.
386 resetANRTimeoutsLocked();
387 }
388
389 // Now we have an event to dispatch.
390 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700391 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800392 bool done = false;
393 DropReason dropReason = DROP_REASON_NOT_DROPPED;
394 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
395 dropReason = DROP_REASON_POLICY;
396 } else if (!mDispatchEnabled) {
397 dropReason = DROP_REASON_DISABLED;
398 }
399
400 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700401 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800402 }
403
404 switch (mPendingEvent->type) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700405 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
406 ConfigurationChangedEntry* typedEntry =
407 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
408 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
409 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
410 break;
411 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800412
Garfield Tane4fc0102019-09-11 13:16:25 -0700413 case EventEntry::TYPE_DEVICE_RESET: {
414 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
415 done = dispatchDeviceResetLocked(currentTime, typedEntry);
416 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
417 break;
418 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800419
Garfield Tane4fc0102019-09-11 13:16:25 -0700420 case EventEntry::TYPE_KEY: {
421 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
422 if (isAppSwitchDue) {
423 if (isAppSwitchKeyEvent(typedEntry)) {
424 resetPendingAppSwitchLocked(true);
425 isAppSwitchDue = false;
426 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
427 dropReason = DROP_REASON_APP_SWITCH;
428 }
429 }
430 if (dropReason == DROP_REASON_NOT_DROPPED && isStaleEvent(currentTime, typedEntry)) {
431 dropReason = DROP_REASON_STALE;
432 }
433 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
434 dropReason = DROP_REASON_BLOCKED;
435 }
436 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
437 break;
438 }
439
440 case EventEntry::TYPE_MOTION: {
441 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
442 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800443 dropReason = DROP_REASON_APP_SWITCH;
444 }
Garfield Tane4fc0102019-09-11 13:16:25 -0700445 if (dropReason == DROP_REASON_NOT_DROPPED && isStaleEvent(currentTime, typedEntry)) {
446 dropReason = DROP_REASON_STALE;
447 }
448 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
449 dropReason = DROP_REASON_BLOCKED;
450 }
451 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
452 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800453 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800454
Garfield Tane4fc0102019-09-11 13:16:25 -0700455 default:
456 ALOG_ASSERT(false);
457 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800458 }
459
460 if (done) {
461 if (dropReason != DROP_REASON_NOT_DROPPED) {
462 dropInboundEventLocked(mPendingEvent, dropReason);
463 }
Michael Wright3a981722015-06-10 15:26:13 +0100464 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800465
466 releasePendingEventLocked();
Garfield Tane4fc0102019-09-11 13:16:25 -0700467 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800468 }
469}
470
471bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
472 bool needWake = mInboundQueue.isEmpty();
473 mInboundQueue.enqueueAtTail(entry);
474 traceInboundQueueLengthLocked();
475
476 switch (entry->type) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700477 case EventEntry::TYPE_KEY: {
478 // Optimize app switch latency.
479 // If the application takes too long to catch up then we drop all events preceding
480 // the app switch key.
481 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
482 if (isAppSwitchKeyEvent(keyEntry)) {
483 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
484 mAppSwitchSawKeyDown = true;
485 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
486 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800487#if DEBUG_APP_SWITCH
Garfield Tane4fc0102019-09-11 13:16:25 -0700488 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800489#endif
Garfield Tane4fc0102019-09-11 13:16:25 -0700490 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
491 mAppSwitchSawKeyDown = false;
492 needWake = true;
493 }
494 }
495 }
496 break;
497 }
498
499 case EventEntry::TYPE_MOTION: {
500 // Optimize case where the current application is unresponsive and the user
501 // decides to touch a window in a different application.
502 // If the application takes too long to catch up then we drop all events preceding
503 // the touch into the other window.
504 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
505 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN &&
506 (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
507 mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY &&
508 mInputTargetWaitApplicationToken != nullptr) {
509 int32_t displayId = motionEntry->displayId;
510 int32_t x =
511 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
512 int32_t y =
513 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
514 sp<InputWindowHandle> touchedWindowHandle =
515 findTouchedWindowAtLocked(displayId, x, y);
516 if (touchedWindowHandle != nullptr &&
517 touchedWindowHandle->getApplicationToken() !=
518 mInputTargetWaitApplicationToken) {
519 // User touched a different application than the one we are waiting on.
520 // Flag the event, and start pruning the input queue.
521 mNextUnblockedEvent = motionEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800522 needWake = true;
523 }
524 }
Garfield Tane4fc0102019-09-11 13:16:25 -0700525 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800526 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800527 }
528
529 return needWake;
530}
531
532void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
533 entry->refCount += 1;
534 mRecentQueue.enqueueAtTail(entry);
535 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
536 mRecentQueue.dequeueAtHead()->release();
537 }
538}
539
Garfield Tane4fc0102019-09-11 13:16:25 -0700540sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
541 int32_t y, bool addOutsideTargets,
542 bool addPortalWindows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800544 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
545 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800546 const InputWindowInfo* windowInfo = windowHandle->getInfo();
547 if (windowInfo->displayId == displayId) {
548 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800549
550 if (windowInfo->visible) {
551 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700552 bool isTouchModal = (flags &
553 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
554 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800555 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800556 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tane4fc0102019-09-11 13:16:25 -0700557 if (portalToDisplayId != ADISPLAY_ID_NONE &&
558 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800559 if (addPortalWindows) {
560 // For the monitoring channels of the display.
561 mTempTouchState.addPortalWindow(windowHandle);
562 }
Garfield Tane4fc0102019-09-11 13:16:25 -0700563 return findTouchedWindowAtLocked(portalToDisplayId, x, y,
564 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800565 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800566 // Found window.
567 return windowHandle;
568 }
569 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800570
571 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700572 mTempTouchState.addOrUpdateWindow(windowHandle,
573 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
574 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800575 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800576 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800577 }
578 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700579 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800580}
581
Michael Wright3dd60e22019-03-27 22:06:44 +0000582std::vector<InputDispatcher::TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
583 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) {
584 std::vector<TouchedMonitor> touchedMonitors;
585
586 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
587 addGestureMonitors(monitors, touchedMonitors);
588 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
589 const InputWindowInfo* windowInfo = portalWindow->getInfo();
590 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tane4fc0102019-09-11 13:16:25 -0700591 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
592 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000593 }
594 return touchedMonitors;
595}
596
597void InputDispatcher::addGestureMonitors(const std::vector<Monitor>& monitors,
Garfield Tane4fc0102019-09-11 13:16:25 -0700598 std::vector<TouchedMonitor>& outTouchedMonitors,
599 float xOffset, float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000600 if (monitors.empty()) {
601 return;
602 }
603 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
604 for (const Monitor& monitor : monitors) {
605 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
606 }
607}
608
Michael Wrightd02c5b62014-02-10 15:10:22 -0800609void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
610 const char* reason;
611 switch (dropReason) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700612 case DROP_REASON_POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800613#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tane4fc0102019-09-11 13:16:25 -0700614 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800615#endif
Garfield Tane4fc0102019-09-11 13:16:25 -0700616 reason = "inbound event was dropped because the policy consumed it";
617 break;
618 case DROP_REASON_DISABLED:
619 if (mLastDropReason != DROP_REASON_DISABLED) {
620 ALOGI("Dropped event because input dispatch is disabled.");
621 }
622 reason = "inbound event was dropped because input dispatch is disabled";
623 break;
624 case DROP_REASON_APP_SWITCH:
625 ALOGI("Dropped event because of pending overdue app switch.");
626 reason = "inbound event was dropped because of pending overdue app switch";
627 break;
628 case DROP_REASON_BLOCKED:
629 ALOGI("Dropped event because the current application is not responding and the user "
630 "has started interacting with a different application.");
631 reason = "inbound event was dropped because the current application is not responding "
632 "and the user has started interacting with a different application";
633 break;
634 case DROP_REASON_STALE:
635 ALOGI("Dropped event because it is stale.");
636 reason = "inbound event was dropped because it is stale";
637 break;
638 default:
639 ALOG_ASSERT(false);
640 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800641 }
642
643 switch (entry->type) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700644 case EventEntry::TYPE_KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800645 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
646 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tane4fc0102019-09-11 13:16:25 -0700647 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800648 }
Garfield Tane4fc0102019-09-11 13:16:25 -0700649 case EventEntry::TYPE_MOTION: {
650 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
651 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
652 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
653 synthesizeCancelationEventsForAllConnectionsLocked(options);
654 } else {
655 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
656 synthesizeCancelationEventsForAllConnectionsLocked(options);
657 }
658 break;
659 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800660 }
661}
662
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800663static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700664 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
665 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800666}
667
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800668bool InputDispatcher::isAppSwitchKeyEvent(KeyEntry* keyEntry) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700669 return !(keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry->keyCode) &&
670 (keyEntry->policyFlags & POLICY_FLAG_TRUSTED) &&
671 (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800672}
673
674bool InputDispatcher::isAppSwitchPendingLocked() {
675 return mAppSwitchDueTime != LONG_LONG_MAX;
676}
677
678void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
679 mAppSwitchDueTime = LONG_LONG_MAX;
680
681#if DEBUG_APP_SWITCH
682 if (handled) {
683 ALOGD("App switch has arrived.");
684 } else {
685 ALOGD("App switch was abandoned.");
686 }
687#endif
688}
689
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800690bool InputDispatcher::isStaleEvent(nsecs_t currentTime, EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800691 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
692}
693
694bool InputDispatcher::haveCommandsLocked() const {
695 return !mCommandQueue.isEmpty();
696}
697
698bool InputDispatcher::runCommandsLockedInterruptible() {
699 if (mCommandQueue.isEmpty()) {
700 return false;
701 }
702
703 do {
704 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
705
706 Command command = commandEntry->command;
707 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
708
709 commandEntry->connection.clear();
710 delete commandEntry;
Garfield Tane4fc0102019-09-11 13:16:25 -0700711 } while (!mCommandQueue.isEmpty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712 return true;
713}
714
715InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
716 CommandEntry* commandEntry = new CommandEntry(command);
717 mCommandQueue.enqueueAtTail(commandEntry);
718 return commandEntry;
719}
720
721void InputDispatcher::drainInboundQueueLocked() {
Garfield Tane4fc0102019-09-11 13:16:25 -0700722 while (!mInboundQueue.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800723 EventEntry* entry = mInboundQueue.dequeueAtHead();
724 releaseInboundEventLocked(entry);
725 }
726 traceInboundQueueLengthLocked();
727}
728
729void InputDispatcher::releasePendingEventLocked() {
730 if (mPendingEvent) {
731 resetANRTimeoutsLocked();
732 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700733 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800734 }
735}
736
737void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
738 InjectionState* injectionState = entry->injectionState;
739 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
740#if DEBUG_DISPATCH_CYCLE
741 ALOGD("Injected inbound event was dropped.");
742#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800743 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744 }
745 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700746 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747 }
748 addRecentEventLocked(entry);
749 entry->release();
750}
751
752void InputDispatcher::resetKeyRepeatLocked() {
753 if (mKeyRepeatState.lastKeyEntry) {
754 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700755 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756 }
757}
758
759InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
760 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
761
762 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700763 uint32_t policyFlags = entry->policyFlags &
764 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800765 if (entry->refCount == 1) {
766 entry->recycle();
767 entry->eventTime = currentTime;
768 entry->policyFlags = policyFlags;
769 entry->repeatCount += 1;
770 } else {
Garfield Tane4fc0102019-09-11 13:16:25 -0700771 KeyEntry* newEntry =
772 new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime, entry->deviceId,
773 entry->source, entry->displayId, policyFlags, entry->action,
774 entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
775 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776
777 mKeyRepeatState.lastKeyEntry = newEntry;
778 entry->release();
779
780 entry = newEntry;
781 }
782 entry->syntheticRepeat = true;
783
784 // Increment reference count since we keep a reference to the event in
785 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
786 entry->refCount += 1;
787
788 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
789 return entry;
790}
791
Garfield Tane4fc0102019-09-11 13:16:25 -0700792bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
793 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800794#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700795 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800796#endif
797
798 // Reset key repeating in case a keyboard device was added or removed or something.
799 resetKeyRepeatLocked();
800
801 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Garfield Tane4fc0102019-09-11 13:16:25 -0700802 CommandEntry* commandEntry =
803 postCommandLocked(&InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800804 commandEntry->eventTime = entry->eventTime;
805 return true;
806}
807
Garfield Tane4fc0102019-09-11 13:16:25 -0700808bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800809#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700810 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tane4fc0102019-09-11 13:16:25 -0700811 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800812#endif
813
Garfield Tane4fc0102019-09-11 13:16:25 -0700814 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800815 options.deviceId = entry->deviceId;
816 synthesizeCancelationEventsForAllConnectionsLocked(options);
817 return true;
818}
819
820bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tane4fc0102019-09-11 13:16:25 -0700821 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822 // Preprocessing.
Garfield Tane4fc0102019-09-11 13:16:25 -0700823 if (!entry->dispatchInProgress) {
824 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
825 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
826 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
827 if (mKeyRepeatState.lastKeyEntry &&
828 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800829 // We have seen two identical key downs in a row which indicates that the device
830 // driver is automatically generating key repeats itself. We take note of the
831 // repeat here, but we disable our own next key repeat timer since it is clear that
832 // we will not need to synthesize key repeats ourselves.
833 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
834 resetKeyRepeatLocked();
835 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
836 } else {
837 // Not a repeat. Save key down state in case we do see a repeat later.
838 resetKeyRepeatLocked();
839 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
840 }
841 mKeyRepeatState.lastKeyEntry = entry;
842 entry->refCount += 1;
Garfield Tane4fc0102019-09-11 13:16:25 -0700843 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800844 resetKeyRepeatLocked();
845 }
846
847 if (entry->repeatCount == 1) {
848 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
849 } else {
850 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
851 }
852
853 entry->dispatchInProgress = true;
854
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800855 logOutboundKeyDetails("dispatchKey - ", entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800856 }
857
858 // Handle case where the policy asked us to try again later last time.
859 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
860 if (currentTime < entry->interceptKeyWakeupTime) {
861 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
862 *nextWakeupTime = entry->interceptKeyWakeupTime;
863 }
864 return false; // wait until next wakeup
865 }
866 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
867 entry->interceptKeyWakeupTime = 0;
868 }
869
870 // Give the policy a chance to intercept the key.
871 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
872 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
873 CommandEntry* commandEntry = postCommandLocked(
Garfield Tane4fc0102019-09-11 13:16:25 -0700874 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800875 sp<InputWindowHandle> focusedWindowHandle =
876 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(entry));
877 if (focusedWindowHandle != nullptr) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700878 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800879 }
880 commandEntry->keyEntry = entry;
881 entry->refCount += 1;
882 return false; // wait for the command to run
883 } else {
884 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
885 }
886 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
887 if (*dropReason == DROP_REASON_NOT_DROPPED) {
888 *dropReason = DROP_REASON_POLICY;
889 }
890 }
891
892 // Clean up if dropping the event.
893 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700894 setInjectionResult(entry,
895 *dropReason == DROP_REASON_POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
896 : INPUT_EVENT_INJECTION_FAILED);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800897 mReporter->reportDroppedKey(entry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898 return true;
899 }
900
901 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800902 std::vector<InputTarget> inputTargets;
Garfield Tane4fc0102019-09-11 13:16:25 -0700903 int32_t injectionResult =
904 findFocusedWindowTargetsLocked(currentTime, entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
906 return false;
907 }
908
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800909 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800910 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
911 return true;
912 }
913
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800914 // Add monitor channels from event's or focused display.
Michael Wright3dd60e22019-03-27 22:06:44 +0000915 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800916
917 // Dispatch the key.
918 dispatchEventLocked(currentTime, entry, inputTargets);
919 return true;
920}
921
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800922void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100924 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tane4fc0102019-09-11 13:16:25 -0700925 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
926 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
927 prefix, entry->eventTime, entry->deviceId, entry->source, entry->displayId,
928 entry->policyFlags, entry->action, entry->flags, entry->keyCode, entry->scanCode,
929 entry->metaState, entry->repeatCount, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930#endif
931}
932
Garfield Tane4fc0102019-09-11 13:16:25 -0700933bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
934 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000935 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800936 // Preprocessing.
Garfield Tane4fc0102019-09-11 13:16:25 -0700937 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938 entry->dispatchInProgress = true;
939
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800940 logOutboundMotionDetails("dispatchMotion - ", entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800941 }
942
943 // Clean up if dropping the event.
944 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700945 setInjectionResult(entry,
946 *dropReason == DROP_REASON_POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
947 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800948 return true;
949 }
950
951 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
952
953 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800954 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955
956 bool conflictingPointerActions = false;
957 int32_t injectionResult;
958 if (isPointerEvent) {
959 // Pointer event. (eg. touchscreen)
Garfield Tane4fc0102019-09-11 13:16:25 -0700960 injectionResult =
961 findTouchedWindowTargetsLocked(currentTime, entry, inputTargets, nextWakeupTime,
962 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963 } else {
964 // Non touch event. (eg. trackball)
Garfield Tane4fc0102019-09-11 13:16:25 -0700965 injectionResult =
966 findFocusedWindowTargetsLocked(currentTime, entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967 }
968 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
969 return false;
970 }
971
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800972 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100974 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700975 CancelationOptions::Mode mode(isPointerEvent
976 ? CancelationOptions::CANCEL_POINTER_EVENTS
977 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100978 CancelationOptions options(mode, "input event injection failed");
979 synthesizeCancelationEventsForMonitorsLocked(options);
980 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981 return true;
982 }
983
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800984 // Add monitor channels from event's or focused display.
Michael Wright3dd60e22019-03-27 22:06:44 +0000985 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800986
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800987 if (isPointerEvent) {
988 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId);
989 if (stateIndex >= 0) {
990 const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800991 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800992 // The event has gone through these portal windows, so we add monitoring targets of
993 // the corresponding displays as well.
994 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800995 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +0000996 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tane4fc0102019-09-11 13:16:25 -0700997 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800998 }
999 }
1000 }
1001 }
1002
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003 // Dispatch the motion.
1004 if (conflictingPointerActions) {
1005 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tane4fc0102019-09-11 13:16:25 -07001006 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007 synthesizeCancelationEventsForAllConnectionsLocked(options);
1008 }
1009 dispatchEventLocked(currentTime, entry, inputTargets);
1010 return true;
1011}
1012
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001013void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001015 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tane4fc0102019-09-11 13:16:25 -07001016 ", policyFlags=0x%x, "
1017 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1018 "metaState=0x%x, buttonState=0x%x,"
1019 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1020 prefix, entry->eventTime, entry->deviceId, entry->source, entry->displayId,
1021 entry->policyFlags, entry->action, entry->actionButton, entry->flags, entry->metaState,
1022 entry->buttonState, entry->edgeFlags, entry->xPrecision, entry->yPrecision,
1023 entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024
1025 for (uint32_t i = 0; i < entry->pointerCount; i++) {
1026 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tane4fc0102019-09-11 13:16:25 -07001027 "x=%f, y=%f, pressure=%f, size=%f, "
1028 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1029 "orientation=%f",
1030 i, entry->pointerProperties[i].id, entry->pointerProperties[i].toolType,
1031 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1032 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1033 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1034 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1035 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1036 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1037 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1038 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1039 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001040 }
1041#endif
1042}
1043
Garfield Tane4fc0102019-09-11 13:16:25 -07001044void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1045 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001046 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047#if DEBUG_DISPATCH_CYCLE
1048 ALOGD("dispatchEventToCurrentInputTargets");
1049#endif
1050
1051 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1052
1053 pokeUserActivityLocked(eventEntry);
1054
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001055 for (const InputTarget& inputTarget : inputTargets) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
1057 if (connectionIndex >= 0) {
1058 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1059 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
1060 } else {
1061#if DEBUG_FOCUS
1062 ALOGD("Dropping event delivery to target with channel '%s' because it "
Garfield Tane4fc0102019-09-11 13:16:25 -07001063 "is no longer registered with the input dispatcher.",
1064 inputTarget.inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065#endif
1066 }
1067 }
1068}
1069
Garfield Tane4fc0102019-09-11 13:16:25 -07001070int32_t InputDispatcher::handleTargetsNotReadyLocked(
1071 nsecs_t currentTime, const EventEntry* entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072 const sp<InputApplicationHandle>& applicationHandle,
Garfield Tane4fc0102019-09-11 13:16:25 -07001073 const sp<InputWindowHandle>& windowHandle, nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001074 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001075 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1076#if DEBUG_FOCUS
1077 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1078#endif
1079 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1080 mInputTargetWaitStartTime = currentTime;
1081 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1082 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001083 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001084 }
1085 } else {
1086 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1087#if DEBUG_FOCUS
1088 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
Garfield Tane4fc0102019-09-11 13:16:25 -07001089 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090#endif
1091 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001092 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001093 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001094 } else if (applicationHandle != nullptr) {
Garfield Tane4fc0102019-09-11 13:16:25 -07001095 timeout =
1096 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001097 } else {
1098 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1099 }
1100
1101 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1102 mInputTargetWaitStartTime = currentTime;
1103 mInputTargetWaitTimeoutTime = currentTime + timeout;
1104 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001105 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106
Yi Kong9b14ac62018-07-17 13:48:38 -07001107 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001108 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001109 }
Robert Carr740167f2018-10-11 19:03:41 -07001110 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1111 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112 }
1113 }
1114 }
1115
1116 if (mInputTargetWaitTimeoutExpired) {
1117 return INPUT_EVENT_INJECTION_TIMED_OUT;
1118 }
1119
1120 if (currentTime >= mInputTargetWaitTimeoutTime) {
Garfield Tane4fc0102019-09-11 13:16:25 -07001121 onANRLocked(currentTime, applicationHandle, windowHandle, entry->eventTime,
1122 mInputTargetWaitStartTime, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123
1124 // Force poll loop to wake up immediately on next iteration once we get the
1125 // ANR response back from the policy.
1126 *nextWakeupTime = LONG_LONG_MIN;
1127 return INPUT_EVENT_INJECTION_PENDING;
1128 } else {
1129 // Force poll loop to wake up when timeout is due.
1130 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1131 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1132 }
1133 return INPUT_EVENT_INJECTION_PENDING;
1134 }
1135}
1136
Robert Carr803535b2018-08-02 16:38:15 -07001137void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1138 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1139 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1140 state.removeWindowByToken(token);
1141 }
1142}
1143
Garfield Tane4fc0102019-09-11 13:16:25 -07001144void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(
1145 nsecs_t newTimeout, const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146 if (newTimeout > 0) {
1147 // Extend the timeout.
1148 mInputTargetWaitTimeoutTime = now() + newTimeout;
1149 } else {
1150 // Give up.
1151 mInputTargetWaitTimeoutExpired = true;
1152
1153 // Input state will not be realistic. Mark it out of sync.
1154 if (inputChannel.get()) {
1155 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1156 if (connectionIndex >= 0) {
1157 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Robert Carr803535b2018-08-02 16:38:15 -07001158 sp<IBinder> token = connection->inputChannel->getToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159
Robert Carr803535b2018-08-02 16:38:15 -07001160 if (token != nullptr) {
1161 removeWindowByTokenLocked(token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162 }
1163
1164 if (connection->status == Connection::STATUS_NORMAL) {
1165 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Garfield Tane4fc0102019-09-11 13:16:25 -07001166 "application not responding");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167 synthesizeCancelationEventsForConnectionLocked(connection, options);
1168 }
1169 }
1170 }
1171 }
1172}
1173
Garfield Tane4fc0102019-09-11 13:16:25 -07001174nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1176 return currentTime - mInputTargetWaitStartTime;
1177 }
1178 return 0;
1179}
1180
1181void InputDispatcher::resetANRTimeoutsLocked() {
1182#if DEBUG_FOCUS
Garfield Tane4fc0102019-09-11 13:16:25 -07001183 ALOGD("Resetting ANR timeouts.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184#endif
1185
1186 // Reset input target wait timeout.
1187 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001188 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189}
1190
Tiger Huang721e26f2018-07-24 22:26:19 +08001191/**
1192 * Get the display id that the given event should go to. If this event specifies a valid display id,
1193 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1194 * Focused display is the display that the user most recently interacted with.
1195 */
1196int32_t InputDispatcher::getTargetDisplayId(const EventEntry* entry) {
1197 int32_t displayId;
1198 switch (entry->type) {
Garfield Tane4fc0102019-09-11 13:16:25 -07001199 case EventEntry::TYPE_KEY: {
1200 const KeyEntry* typedEntry = static_cast<const KeyEntry*>(entry);
1201 displayId = typedEntry->displayId;
1202 break;
1203 }
1204 case EventEntry::TYPE_MOTION: {
1205 const MotionEntry* typedEntry = static_cast<const MotionEntry*>(entry);
1206 displayId = typedEntry->displayId;
1207 break;
1208 }
1209 default: {
1210 ALOGE("Unsupported event type '%" PRId32 "' for target display.", entry->type);
1211 return ADISPLAY_ID_NONE;
1212 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001213 }
1214 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1215}
1216
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Garfield Tane4fc0102019-09-11 13:16:25 -07001218 const EventEntry* entry,
1219 std::vector<InputTarget>& inputTargets,
1220 nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001222 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223
Tiger Huang721e26f2018-07-24 22:26:19 +08001224 int32_t displayId = getTargetDisplayId(entry);
1225 sp<InputWindowHandle> focusedWindowHandle =
1226 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1227 sp<InputApplicationHandle> focusedApplicationHandle =
1228 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1229
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230 // If there is no currently focused window and no focused application
1231 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001232 if (focusedWindowHandle == nullptr) {
1233 if (focusedApplicationHandle != nullptr) {
Garfield Tane4fc0102019-09-11 13:16:25 -07001234 injectionResult =
1235 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1236 nullptr, nextWakeupTime,
1237 "Waiting because no window has focus but there is "
1238 "a "
1239 "focused application that may eventually add a "
1240 "window "
1241 "when it finishes starting up.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001242 goto Unresponsive;
1243 }
1244
Arthur Hung3b413f22018-10-26 18:05:34 +08001245 ALOGI("Dropping event because there is no focused window or focused application in display "
Garfield Tane4fc0102019-09-11 13:16:25 -07001246 "%" PRId32 ".",
1247 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1249 goto Failed;
1250 }
1251
1252 // Check permissions.
Tiger Huang721e26f2018-07-24 22:26:19 +08001253 if (!checkInjectionPermission(focusedWindowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1255 goto Failed;
1256 }
1257
Jeff Brownffb49772014-10-10 19:01:34 -07001258 // Check whether the window is ready for more input.
Garfield Tane4fc0102019-09-11 13:16:25 -07001259 reason = checkWindowReadyForMoreInputLocked(currentTime, focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001260 if (!reason.empty()) {
Garfield Tane4fc0102019-09-11 13:16:25 -07001261 injectionResult =
1262 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1263 focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 goto Unresponsive;
1265 }
1266
1267 // Success! Output targets.
1268 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001269 addWindowTargetLocked(focusedWindowHandle,
Garfield Tane4fc0102019-09-11 13:16:25 -07001270 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1271 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272
1273 // Done.
1274Failed:
1275Unresponsive:
1276 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001277 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278#if DEBUG_FOCUS
1279 ALOGD("findFocusedWindow finished: injectionResult=%d, "
Garfield Tane4fc0102019-09-11 13:16:25 -07001280 "timeSpentWaitingForApplication=%0.1fms",
1281 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001282#endif
1283 return injectionResult;
1284}
1285
1286int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Garfield Tane4fc0102019-09-11 13:16:25 -07001287 const MotionEntry* entry,
1288 std::vector<InputTarget>& inputTargets,
1289 nsecs_t* nextWakeupTime,
1290 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001291 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001292 enum InjectionPermission {
1293 INJECTION_PERMISSION_UNKNOWN,
1294 INJECTION_PERMISSION_GRANTED,
1295 INJECTION_PERMISSION_DENIED
1296 };
1297
Michael Wrightd02c5b62014-02-10 15:10:22 -08001298 // For security reasons, we defer updating the touch state until we are sure that
1299 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001300 int32_t displayId = entry->displayId;
1301 int32_t action = entry->action;
1302 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1303
1304 // Update the touch state as needed based on the properties of the touch event.
1305 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1306 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1307 sp<InputWindowHandle> newHoverWindowHandle;
1308
Jeff Brownf086ddb2014-02-11 14:28:48 -08001309 // Copy current touch state into mTempTouchState.
1310 // This state is always reset at the end of this function, so if we don't find state
1311 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001312 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001313 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1314 if (oldStateIndex >= 0) {
1315 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1316 mTempTouchState.copyFrom(*oldState);
1317 }
1318
1319 bool isSplit = mTempTouchState.split;
Garfield Tane4fc0102019-09-11 13:16:25 -07001320 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0 &&
1321 (mTempTouchState.deviceId != entry->deviceId ||
1322 mTempTouchState.source != entry->source || mTempTouchState.displayId != displayId);
1323 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1324 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1325 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1326 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1327 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 bool wrongDevice = false;
1329 if (newGesture) {
1330 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001331 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001332#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001333 ALOGD("Dropping event because a pointer for a different device is already down "
Garfield Tane4fc0102019-09-11 13:16:25 -07001334 "in display %" PRId32,
1335 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001336#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001337 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001338 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1339 switchedDevice = false;
1340 wrongDevice = true;
1341 goto Failed;
1342 }
1343 mTempTouchState.reset();
1344 mTempTouchState.down = down;
1345 mTempTouchState.deviceId = entry->deviceId;
1346 mTempTouchState.source = entry->source;
1347 mTempTouchState.displayId = displayId;
1348 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001349 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1350#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001351 ALOGI("Dropping move event because a pointer for a different device is already active "
Garfield Tane4fc0102019-09-11 13:16:25 -07001352 "in display %" PRId32,
1353 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001354#endif
1355 // TODO: test multiple simultaneous input streams.
1356 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1357 switchedDevice = false;
1358 wrongDevice = true;
1359 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001360 }
1361
1362 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1363 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1364
1365 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tane4fc0102019-09-11 13:16:25 -07001366 int32_t x = int32_t(entry->pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1367 int32_t y = int32_t(entry->pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wright3dd60e22019-03-27 22:06:44 +00001368 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tane4fc0102019-09-11 13:16:25 -07001369 sp<InputWindowHandle> newTouchedWindowHandle =
1370 findTouchedWindowAtLocked(displayId, x, y, isDown /*addOutsideTargets*/,
1371 true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001372
1373 std::vector<TouchedMonitor> newGestureMonitors = isDown
1374 ? findTouchedGestureMonitorsLocked(displayId, mTempTouchState.portalWindows)
1375 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377 // Figure out whether splitting will be allowed for this window.
Garfield Tane4fc0102019-09-11 13:16:25 -07001378 if (newTouchedWindowHandle != nullptr &&
1379 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001380 // New window supports splitting.
1381 isSplit = true;
1382 } else if (isSplit) {
1383 // New window does not support splitting but we have already split events.
1384 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001385 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386 }
1387
1388 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001389 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390 // Try to assign the pointer to the first foreground window we find, if there is one.
1391 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001392 }
1393
1394 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1395 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tane4fc0102019-09-11 13:16:25 -07001396 "(%d, %d) in display %" PRId32 ".",
1397 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001398 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1399 goto Failed;
1400 }
1401
1402 if (newTouchedWindowHandle != nullptr) {
1403 // Set target flags.
1404 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1405 if (isSplit) {
1406 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001407 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001408 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1409 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1410 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1411 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1412 }
1413
1414 // Update hover state.
1415 if (isHoverAction) {
1416 newHoverWindowHandle = newTouchedWindowHandle;
1417 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1418 newHoverWindowHandle = mLastHoverWindowHandle;
1419 }
1420
1421 // Update the temporary touch state.
1422 BitSet32 pointerIds;
1423 if (isSplit) {
1424 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1425 pointerIds.markBit(pointerId);
1426 }
1427 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428 }
1429
Michael Wright3dd60e22019-03-27 22:06:44 +00001430 mTempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001431 } else {
1432 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1433
1434 // If the pointer is not currently down, then ignore the event.
Garfield Tane4fc0102019-09-11 13:16:25 -07001435 if (!mTempTouchState.down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436#if DEBUG_FOCUS
1437 ALOGD("Dropping event because the pointer is not down or we previously "
Garfield Tane4fc0102019-09-11 13:16:25 -07001438 "dropped the pointer down event in display %" PRId32,
1439 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440#endif
1441 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1442 goto Failed;
1443 }
1444
1445 // Check whether touches should slip outside of the current foreground window.
Garfield Tane4fc0102019-09-11 13:16:25 -07001446 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry->pointerCount == 1 &&
1447 mTempTouchState.isSlippery()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1449 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1450
1451 sp<InputWindowHandle> oldTouchedWindowHandle =
1452 mTempTouchState.getFirstForegroundWindowHandle();
1453 sp<InputWindowHandle> newTouchedWindowHandle =
1454 findTouchedWindowAtLocked(displayId, x, y);
Garfield Tane4fc0102019-09-11 13:16:25 -07001455 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1456 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001457#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001458 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
Garfield Tane4fc0102019-09-11 13:16:25 -07001459 oldTouchedWindowHandle->getName().c_str(),
1460 newTouchedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001461#endif
1462 // Make a slippery exit from the old window.
1463 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Garfield Tane4fc0102019-09-11 13:16:25 -07001464 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1465 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001466
1467 // Make a slippery entrance into the new window.
1468 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1469 isSplit = true;
1470 }
1471
Garfield Tane4fc0102019-09-11 13:16:25 -07001472 int32_t targetFlags =
1473 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001474 if (isSplit) {
1475 targetFlags |= InputTarget::FLAG_SPLIT;
1476 }
1477 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1478 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1479 }
1480
1481 BitSet32 pointerIds;
1482 if (isSplit) {
1483 pointerIds.markBit(entry->pointerProperties[0].id);
1484 }
1485 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1486 }
1487 }
1488 }
1489
1490 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1491 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001492 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493#if DEBUG_HOVER
1494 ALOGD("Sending hover exit event to window %s.",
Garfield Tane4fc0102019-09-11 13:16:25 -07001495 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496#endif
1497 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Garfield Tane4fc0102019-09-11 13:16:25 -07001498 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT,
1499 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001500 }
1501
1502 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001503 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504#if DEBUG_HOVER
1505 ALOGD("Sending hover enter event to window %s.",
Garfield Tane4fc0102019-09-11 13:16:25 -07001506 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507#endif
1508 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Garfield Tane4fc0102019-09-11 13:16:25 -07001509 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1510 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 }
1512 }
1513
1514 // Check permission to inject into all touched foreground windows and ensure there
1515 // is at least one touched foreground window.
1516 {
1517 bool haveForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001518 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1520 haveForegroundWindow = true;
Garfield Tane4fc0102019-09-11 13:16:25 -07001521 if (!checkInjectionPermission(touchedWindow.windowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1523 injectionPermission = INJECTION_PERMISSION_DENIED;
1524 goto Failed;
1525 }
1526 }
1527 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001528 bool hasGestureMonitor = !mTempTouchState.gestureMonitors.empty();
1529 if (!haveForegroundWindow && !hasGestureMonitor) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001530#if DEBUG_FOCUS
Garfield Tane4fc0102019-09-11 13:16:25 -07001531 ALOGD("Dropping event because there is no touched foreground window in display %" PRId32
1532 " or gesture monitor to receive it.",
1533 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534#endif
1535 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1536 goto Failed;
1537 }
1538
1539 // Permission granted to injection into all touched foreground windows.
1540 injectionPermission = INJECTION_PERMISSION_GRANTED;
1541 }
1542
1543 // Check whether windows listening for outside touches are owned by the same UID. If it is
1544 // set the policy flag that we will not reveal coordinate information to this window.
1545 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1546 sp<InputWindowHandle> foregroundWindowHandle =
1547 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001548 if (foregroundWindowHandle) {
1549 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1550 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
1551 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1552 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1553 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1554 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Garfield Tane4fc0102019-09-11 13:16:25 -07001555 InputTarget::FLAG_ZERO_COORDS,
1556 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001557 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001558 }
1559 }
1560 }
1561 }
1562
1563 // Ensure all touched foreground windows are ready for new input.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001564 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001566 // Check whether the window is ready for more input.
Garfield Tane4fc0102019-09-11 13:16:25 -07001567 std::string reason =
1568 checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle,
1569 entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001570 if (!reason.empty()) {
Garfield Tane4fc0102019-09-11 13:16:25 -07001571 injectionResult = handleTargetsNotReadyLocked(currentTime, entry, nullptr,
1572 touchedWindow.windowHandle,
1573 nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001574 goto Unresponsive;
1575 }
1576 }
1577 }
1578
1579 // If this is the first pointer going down and the touched window has a wallpaper
1580 // then also add the touched wallpaper windows so they are locked in for the duration
1581 // of the touch gesture.
1582 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1583 // engine only supports touch events. We would need to add a mechanism similar
1584 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1585 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1586 sp<InputWindowHandle> foregroundWindowHandle =
1587 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001588 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001589 const std::vector<sp<InputWindowHandle>> windowHandles =
1590 getWindowHandlesLocked(displayId);
1591 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tane4fc0102019-09-11 13:16:25 -07001593 if (info->displayId == displayId &&
1594 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
1595 mTempTouchState
1596 .addOrUpdateWindow(windowHandle,
1597 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1598 InputTarget::
1599 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1600 InputTarget::FLAG_DISPATCH_AS_IS,
1601 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001602 }
1603 }
1604 }
1605 }
1606
1607 // Success! Output targets.
1608 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1609
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001610 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001611 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tane4fc0102019-09-11 13:16:25 -07001612 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001613 }
1614
Michael Wright3dd60e22019-03-27 22:06:44 +00001615 for (const TouchedMonitor& touchedMonitor : mTempTouchState.gestureMonitors) {
1616 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tane4fc0102019-09-11 13:16:25 -07001617 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001618 }
1619
Michael Wrightd02c5b62014-02-10 15:10:22 -08001620 // Drop the outside or hover touch windows since we will not care about them
1621 // in the next iteration.
1622 mTempTouchState.filterNonAsIsTouchWindows();
1623
1624Failed:
1625 // Check injection permission once and for all.
1626 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001627 if (checkInjectionPermission(nullptr, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001628 injectionPermission = INJECTION_PERMISSION_GRANTED;
1629 } else {
1630 injectionPermission = INJECTION_PERMISSION_DENIED;
1631 }
1632 }
1633
1634 // Update final pieces of touch state if the injector had permission.
1635 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1636 if (!wrongDevice) {
1637 if (switchedDevice) {
1638#if DEBUG_FOCUS
1639 ALOGD("Conflicting pointer actions: Switched to a different device.");
1640#endif
1641 *outConflictingPointerActions = true;
1642 }
1643
1644 if (isHoverAction) {
1645 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001646 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647#if DEBUG_FOCUS
1648 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1649#endif
1650 *outConflictingPointerActions = true;
1651 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001652 mTempTouchState.reset();
Garfield Tane4fc0102019-09-11 13:16:25 -07001653 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1654 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001655 mTempTouchState.deviceId = entry->deviceId;
1656 mTempTouchState.source = entry->source;
1657 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001658 }
Garfield Tane4fc0102019-09-11 13:16:25 -07001659 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1660 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001661 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001662 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001663 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1664 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001665 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666#if DEBUG_FOCUS
1667 ALOGD("Conflicting pointer actions: Down received while already down.");
1668#endif
1669 *outConflictingPointerActions = true;
1670 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001671 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1672 // One pointer went up.
1673 if (isSplit) {
1674 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1675 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1676
Garfield Tane4fc0102019-09-11 13:16:25 -07001677 for (size_t i = 0; i < mTempTouchState.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001678 TouchedWindow& touchedWindow = mTempTouchState.windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001679 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1680 touchedWindow.pointerIds.clearBit(pointerId);
1681 if (touchedWindow.pointerIds.isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001682 mTempTouchState.windows.erase(mTempTouchState.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683 continue;
1684 }
1685 }
1686 i += 1;
1687 }
1688 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001689 }
1690
1691 // Save changes unless the action was scroll in which case the temporary touch
1692 // state was only valid for this one action.
1693 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1694 if (mTempTouchState.displayId >= 0) {
1695 if (oldStateIndex >= 0) {
1696 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1697 } else {
1698 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1699 }
1700 } else if (oldStateIndex >= 0) {
1701 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1702 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001703 }
1704
1705 // Update hover state.
1706 mLastHoverWindowHandle = newHoverWindowHandle;
1707 }
1708 } else {
1709#if DEBUG_FOCUS
1710 ALOGD("Not updating touch focus because injection was denied.");
1711#endif
1712 }
1713
1714Unresponsive:
1715 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1716 mTempTouchState.reset();
1717
1718 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001719 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720#if DEBUG_FOCUS
1721 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
Garfield Tane4fc0102019-09-11 13:16:25 -07001722 "timeSpentWaitingForApplication=%0.1fms",
1723 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724#endif
1725 return injectionResult;
1726}
1727
1728void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tane4fc0102019-09-11 13:16:25 -07001729 int32_t targetFlags, BitSet32 pointerIds,
1730 std::vector<InputTarget>& inputTargets) {
Arthur Hungceeb5d72018-12-05 16:14:18 +08001731 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1732 if (inputChannel == nullptr) {
1733 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1734 return;
1735 }
1736
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001738 InputTarget target;
Arthur Hungceeb5d72018-12-05 16:14:18 +08001739 target.inputChannel = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740 target.flags = targetFlags;
Garfield Tane4fc0102019-09-11 13:16:25 -07001741 target.xOffset = -windowInfo->frameLeft;
1742 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08001743 target.globalScaleFactor = windowInfo->globalScaleFactor;
1744 target.windowXScale = windowInfo->windowXScale;
1745 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001746 target.pointerIds = pointerIds;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001747 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748}
1749
Michael Wright3dd60e22019-03-27 22:06:44 +00001750void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tane4fc0102019-09-11 13:16:25 -07001751 int32_t displayId, float xOffset,
1752 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001753 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1754 mGlobalMonitorsByDisplay.find(displayId);
1755
1756 if (it != mGlobalMonitorsByDisplay.end()) {
1757 const std::vector<Monitor>& monitors = it->second;
1758 for (const Monitor& monitor : monitors) {
1759 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001760 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761 }
1762}
1763
Garfield Tane4fc0102019-09-11 13:16:25 -07001764void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
1765 float yOffset,
1766 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001767 InputTarget target;
1768 target.inputChannel = monitor.inputChannel;
1769 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1770 target.xOffset = xOffset;
1771 target.yOffset = yOffset;
1772 target.pointerIds.clear();
1773 target.globalScaleFactor = 1.0f;
1774 inputTargets.push_back(target);
1775}
1776
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tane4fc0102019-09-11 13:16:25 -07001778 const InjectionState* injectionState) {
1779 if (injectionState &&
1780 (windowHandle == nullptr ||
1781 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
1782 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001783 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001784 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tane4fc0102019-09-11 13:16:25 -07001785 "owned by uid %d",
1786 injectionState->injectorPid, injectionState->injectorUid,
1787 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788 } else {
1789 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tane4fc0102019-09-11 13:16:25 -07001790 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001791 }
1792 return false;
1793 }
1794 return true;
1795}
1796
Garfield Tane4fc0102019-09-11 13:16:25 -07001797bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1798 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001800 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1801 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001802 if (otherHandle == windowHandle) {
1803 break;
1804 }
1805
1806 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Garfield Tane4fc0102019-09-11 13:16:25 -07001807 if (otherInfo->displayId == displayId && otherInfo->visible &&
1808 !otherInfo->isTrustedOverlay() && otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809 return true;
1810 }
1811 }
1812 return false;
1813}
1814
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001815bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1816 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001817 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001818 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001819 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001820 if (otherHandle == windowHandle) {
1821 break;
1822 }
1823
1824 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Garfield Tane4fc0102019-09-11 13:16:25 -07001825 if (otherInfo->displayId == displayId && otherInfo->visible &&
1826 !otherInfo->isTrustedOverlay() && otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001827 return true;
1828 }
1829 }
1830 return false;
1831}
1832
Garfield Tane4fc0102019-09-11 13:16:25 -07001833std::string InputDispatcher::checkWindowReadyForMoreInputLocked(
1834 nsecs_t currentTime, const sp<InputWindowHandle>& windowHandle,
1835 const EventEntry* eventEntry, const char* targetType) {
Jeff Brownffb49772014-10-10 19:01:34 -07001836 // If the window is paused then keep waiting.
1837 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001838 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001839 }
1840
1841 // If the window's connection is not registered then keep waiting.
Garfield Tane4fc0102019-09-11 13:16:25 -07001842 ssize_t connectionIndex =
1843 getConnectionIndexLocked(getInputChannelLocked(windowHandle->getToken()));
Jeff Brownffb49772014-10-10 19:01:34 -07001844 if (connectionIndex < 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001845 return StringPrintf("Waiting because the %s window's input channel is not "
Garfield Tane4fc0102019-09-11 13:16:25 -07001846 "registered with the input dispatcher. The window may be in the "
1847 "process "
1848 "of being removed.",
1849 targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001850 }
1851
1852 // If the connection is dead then keep waiting.
1853 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1854 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001855 return StringPrintf("Waiting because the %s window's input connection is %s."
Garfield Tane4fc0102019-09-11 13:16:25 -07001856 "The window may be in the process of being removed.",
1857 targetType, connection->getStatusLabel());
Jeff Brownffb49772014-10-10 19:01:34 -07001858 }
1859
1860 // If the connection is backed up then keep waiting.
1861 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001862 return StringPrintf("Waiting because the %s window's input channel is full. "
Garfield Tane4fc0102019-09-11 13:16:25 -07001863 "Outbound queue length: %d. Wait queue length: %d.",
1864 targetType, connection->outboundQueue.count(),
1865 connection->waitQueue.count());
Jeff Brownffb49772014-10-10 19:01:34 -07001866 }
1867
1868 // Ensure that the dispatch queues aren't too far backed up for this event.
1869 if (eventEntry->type == EventEntry::TYPE_KEY) {
1870 // If the event is a key event, then we must wait for all previous events to
1871 // complete before delivering it because previous events may have the
1872 // side-effect of transferring focus to a different window and we want to
1873 // ensure that the following keys are sent to the new window.
1874 //
1875 // Suppose the user touches a button in a window then immediately presses "A".
1876 // If the button causes a pop-up window to appear then we want to ensure that
1877 // the "A" key is delivered to the new pop-up window. This is because users
1878 // often anticipate pending UI changes when typing on a keyboard.
1879 // To obtain this behavior, we must serialize key events with respect to all
1880 // prior input events.
1881 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001882 return StringPrintf("Waiting to send key event because the %s window has not "
Garfield Tane4fc0102019-09-11 13:16:25 -07001883 "finished processing all of the input events that were previously "
1884 "delivered to it. Outbound queue length: %d. Wait queue length: "
1885 "%d.",
1886 targetType, connection->outboundQueue.count(),
1887 connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888 }
Jeff Brownffb49772014-10-10 19:01:34 -07001889 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890 // Touch events can always be sent to a window immediately because the user intended
1891 // to touch whatever was visible at the time. Even if focus changes or a new
1892 // window appears moments later, the touch event was meant to be delivered to
1893 // whatever window happened to be on screen at the time.
1894 //
1895 // Generic motion events, such as trackball or joystick events are a little trickier.
1896 // Like key events, generic motion events are delivered to the focused window.
1897 // Unlike key events, generic motion events don't tend to transfer focus to other
1898 // windows and it is not important for them to be serialized. So we prefer to deliver
1899 // generic motion events as soon as possible to improve efficiency and reduce lag
1900 // through batching.
1901 //
1902 // The one case where we pause input event delivery is when the wait queue is piling
1903 // up with lots of events because the application is not responding.
1904 // This condition ensures that ANRs are detected reliably.
Garfield Tane4fc0102019-09-11 13:16:25 -07001905 if (!connection->waitQueue.isEmpty() &&
1906 currentTime >= connection->waitQueue.head->deliveryTime + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001907 return StringPrintf("Waiting to send non-key event because the %s window has not "
Garfield Tane4fc0102019-09-11 13:16:25 -07001908 "finished processing certain input events that were delivered to "
1909 "it over "
1910 "%0.1fms ago. Wait queue length: %d. Wait queue head age: "
1911 "%0.1fms.",
1912 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1913 connection->waitQueue.count(),
1914 (currentTime - connection->waitQueue.head->deliveryTime) *
1915 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001916 }
1917 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001918 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919}
1920
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001921std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001922 const sp<InputApplicationHandle>& applicationHandle,
1923 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001924 if (applicationHandle != nullptr) {
1925 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001926 std::string label(applicationHandle->getName());
1927 label += " - ";
1928 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929 return label;
1930 } else {
1931 return applicationHandle->getName();
1932 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001933 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934 return windowHandle->getName();
1935 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001936 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937 }
1938}
1939
1940void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001941 int32_t displayId = getTargetDisplayId(eventEntry);
1942 sp<InputWindowHandle> focusedWindowHandle =
1943 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1944 if (focusedWindowHandle != nullptr) {
1945 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1947#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001948 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001949#endif
1950 return;
1951 }
1952 }
1953
1954 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1955 switch (eventEntry->type) {
Garfield Tane4fc0102019-09-11 13:16:25 -07001956 case EventEntry::TYPE_MOTION: {
1957 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1958 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1959 return;
1960 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961
Garfield Tane4fc0102019-09-11 13:16:25 -07001962 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1963 eventType = USER_ACTIVITY_EVENT_TOUCH;
1964 }
1965 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966 }
Garfield Tane4fc0102019-09-11 13:16:25 -07001967 case EventEntry::TYPE_KEY: {
1968 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1969 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1970 return;
1971 }
1972 eventType = USER_ACTIVITY_EVENT_BUTTON;
1973 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001974 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975 }
1976
Garfield Tane4fc0102019-09-11 13:16:25 -07001977 CommandEntry* commandEntry =
1978 postCommandLocked(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979 commandEntry->eventTime = eventEntry->eventTime;
1980 commandEntry->userActivityEventType = eventType;
1981}
1982
1983void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tane4fc0102019-09-11 13:16:25 -07001984 const sp<Connection>& connection,
1985 EventEntry* eventEntry,
1986 const InputTarget* inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001987 if (ATRACE_ENABLED()) {
Garfield Tane4fc0102019-09-11 13:16:25 -07001988 std::string message =
1989 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, sequenceNum=%" PRIu32 ")",
1990 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
Michael Wright3dd60e22019-03-27 22:06:44 +00001991 ATRACE_NAME(message.c_str());
1992 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001993#if DEBUG_DISPATCH_CYCLE
1994 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Garfield Tane4fc0102019-09-11 13:16:25 -07001995 "xOffset=%f, yOffset=%f, globalScaleFactor=%f, "
1996 "windowScaleFactor=(%f, %f), pointerIds=0x%x",
1997 connection->getInputChannelName().c_str(), inputTarget->flags, inputTarget->xOffset,
1998 inputTarget->yOffset, inputTarget->globalScaleFactor, inputTarget->windowXScale,
1999 inputTarget->windowYScale, inputTarget->pointerIds.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000#endif
2001
2002 // Skip this event if the connection status is not normal.
2003 // We don't want to enqueue additional outbound events if the connection is broken.
2004 if (connection->status != Connection::STATUS_NORMAL) {
2005#if DEBUG_DISPATCH_CYCLE
2006 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tane4fc0102019-09-11 13:16:25 -07002007 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008#endif
2009 return;
2010 }
2011
2012 // Split a motion event if needed.
2013 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
2014 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
2015
2016 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
2017 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
Garfield Tane4fc0102019-09-11 13:16:25 -07002018 MotionEntry* splitMotionEntry =
2019 splitMotionEvent(originalMotionEntry, inputTarget->pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020 if (!splitMotionEntry) {
2021 return; // split event was dropped
2022 }
2023#if DEBUG_FOCUS
Garfield Tane4fc0102019-09-11 13:16:25 -07002024 ALOGD("channel '%s' ~ Split motion event.", connection->getInputChannelName().c_str());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002025 logOutboundMotionDetails(" ", splitMotionEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002026#endif
Garfield Tane4fc0102019-09-11 13:16:25 -07002027 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002028 splitMotionEntry->release();
2029 return;
2030 }
2031 }
2032
2033 // Not splitting. Enqueue dispatch entries for the event as is.
2034 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2035}
2036
2037void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tane4fc0102019-09-11 13:16:25 -07002038 const sp<Connection>& connection,
2039 EventEntry* eventEntry,
2040 const InputTarget* inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002041 if (ATRACE_ENABLED()) {
Garfield Tane4fc0102019-09-11 13:16:25 -07002042 std::string message =
2043 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, sequenceNum=%" PRIu32
2044 ")",
2045 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
Michael Wright3dd60e22019-03-27 22:06:44 +00002046 ATRACE_NAME(message.c_str());
2047 }
2048
Michael Wrightd02c5b62014-02-10 15:10:22 -08002049 bool wasEmpty = connection->outboundQueue.isEmpty();
2050
2051 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002052 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tane4fc0102019-09-11 13:16:25 -07002053 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002054 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tane4fc0102019-09-11 13:16:25 -07002055 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002056 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tane4fc0102019-09-11 13:16:25 -07002057 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002058 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tane4fc0102019-09-11 13:16:25 -07002059 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002060 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tane4fc0102019-09-11 13:16:25 -07002061 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002062 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tane4fc0102019-09-11 13:16:25 -07002063 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064
2065 // If the outbound queue was previously empty, start the dispatch cycle going.
2066 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
2067 startDispatchCycleLocked(currentTime, connection);
2068 }
2069}
2070
Garfield Tane4fc0102019-09-11 13:16:25 -07002071void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2072 EventEntry* eventEntry,
2073 const InputTarget* inputTarget,
2074 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002075 if (ATRACE_ENABLED()) {
Garfield Tane4fc0102019-09-11 13:16:25 -07002076 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2077 connection->getInputChannelName().c_str(),
2078 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002079 ATRACE_NAME(message.c_str());
2080 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002081 int32_t inputTargetFlags = inputTarget->flags;
2082 if (!(inputTargetFlags & dispatchMode)) {
2083 return;
2084 }
2085 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2086
2087 // This is a new event.
2088 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Garfield Tane4fc0102019-09-11 13:16:25 -07002089 DispatchEntry* dispatchEntry =
2090 new DispatchEntry(eventEntry, // increments ref
2091 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
2092 inputTarget->globalScaleFactor, inputTarget->windowXScale,
2093 inputTarget->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094
2095 // Apply target flags and update the connection's input state.
2096 switch (eventEntry->type) {
Garfield Tane4fc0102019-09-11 13:16:25 -07002097 case EventEntry::TYPE_KEY: {
2098 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2099 dispatchEntry->resolvedAction = keyEntry->action;
2100 dispatchEntry->resolvedFlags = keyEntry->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002101
Garfield Tane4fc0102019-09-11 13:16:25 -07002102 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2103 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104#if DEBUG_DISPATCH_CYCLE
Garfield Tane4fc0102019-09-11 13:16:25 -07002105 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2106 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002107#endif
Garfield Tane4fc0102019-09-11 13:16:25 -07002108 delete dispatchEntry;
2109 return; // skip the inconsistent event
2110 }
2111 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002112 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002113
Garfield Tane4fc0102019-09-11 13:16:25 -07002114 case EventEntry::TYPE_MOTION: {
2115 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2116 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2117 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2118 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2119 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2120 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2121 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2122 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2123 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2124 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2125 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2126 } else {
2127 dispatchEntry->resolvedAction = motionEntry->action;
2128 }
2129 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
2130 !connection->inputState.isHovering(motionEntry->deviceId, motionEntry->source,
2131 motionEntry->displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132#if DEBUG_DISPATCH_CYCLE
Garfield Tane4fc0102019-09-11 13:16:25 -07002133 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2134 "event",
2135 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002136#endif
Garfield Tane4fc0102019-09-11 13:16:25 -07002137 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2138 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139
Garfield Tane4fc0102019-09-11 13:16:25 -07002140 dispatchEntry->resolvedFlags = motionEntry->flags;
2141 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2142 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2143 }
2144 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2145 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2146 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147
Garfield Tane4fc0102019-09-11 13:16:25 -07002148 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2149 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150#if DEBUG_DISPATCH_CYCLE
Garfield Tane4fc0102019-09-11 13:16:25 -07002151 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2152 "event",
2153 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154#endif
Garfield Tane4fc0102019-09-11 13:16:25 -07002155 delete dispatchEntry;
2156 return; // skip the inconsistent event
2157 }
2158
2159 dispatchPointerDownOutsideFocus(motionEntry->source, dispatchEntry->resolvedAction,
2160 inputTarget->inputChannel->getToken());
2161
2162 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164 }
2165
2166 // Remember that we are waiting for this dispatch to complete.
2167 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002168 incrementPendingForegroundDispatches(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002169 }
2170
2171 // Enqueue the dispatch entry.
2172 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002173 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002174}
2175
chaviwfd6d3512019-03-25 13:23:49 -07002176void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tane4fc0102019-09-11 13:16:25 -07002177 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002178 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002179 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2180 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002181 return;
2182 }
2183
2184 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2185 if (inputWindowHandle == nullptr) {
2186 return;
2187 }
2188
chaviw8c9cf542019-03-25 13:02:48 -07002189 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002190 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002191
2192 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2193
2194 if (!hasFocusChanged) {
2195 return;
2196 }
2197
Garfield Tane4fc0102019-09-11 13:16:25 -07002198 CommandEntry* commandEntry =
2199 postCommandLocked(&InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002200 commandEntry->newToken = newToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201}
2202
2203void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tane4fc0102019-09-11 13:16:25 -07002204 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002205 if (ATRACE_ENABLED()) {
2206 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tane4fc0102019-09-11 13:16:25 -07002207 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002208 ATRACE_NAME(message.c_str());
2209 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002210#if DEBUG_DISPATCH_CYCLE
Garfield Tane4fc0102019-09-11 13:16:25 -07002211 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002212#endif
2213
Garfield Tane4fc0102019-09-11 13:16:25 -07002214 while (connection->status == Connection::STATUS_NORMAL &&
2215 !connection->outboundQueue.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
2217 dispatchEntry->deliveryTime = currentTime;
2218
2219 // Publish the event.
2220 status_t status;
2221 EventEntry* eventEntry = dispatchEntry->eventEntry;
2222 switch (eventEntry->type) {
Garfield Tane4fc0102019-09-11 13:16:25 -07002223 case EventEntry::TYPE_KEY: {
2224 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002225
Garfield Tane4fc0102019-09-11 13:16:25 -07002226 // Publish the key event.
2227 status = connection->inputPublisher
2228 .publishKeyEvent(dispatchEntry->seq, keyEntry->deviceId,
2229 keyEntry->source, keyEntry->displayId,
2230 dispatchEntry->resolvedAction,
2231 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2232 keyEntry->scanCode, keyEntry->metaState,
2233 keyEntry->repeatCount, keyEntry->downTime,
2234 keyEntry->eventTime);
2235 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236 }
2237
Garfield Tane4fc0102019-09-11 13:16:25 -07002238 case EventEntry::TYPE_MOTION: {
2239 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240
Garfield Tane4fc0102019-09-11 13:16:25 -07002241 PointerCoords scaledCoords[MAX_POINTERS];
2242 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2243
2244 // Set the X and Y offset depending on the input source.
2245 float xOffset, yOffset;
2246 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2247 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2248 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2249 float wxs = dispatchEntry->windowXScale;
2250 float wys = dispatchEntry->windowYScale;
2251 xOffset = dispatchEntry->xOffset * wxs;
2252 yOffset = dispatchEntry->yOffset * wys;
2253 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
2254 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2255 scaledCoords[i] = motionEntry->pointerCoords[i];
2256 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
2257 }
2258 usingCoords = scaledCoords;
2259 }
2260 } else {
2261 xOffset = 0.0f;
2262 yOffset = 0.0f;
2263
2264 // We don't want the dispatch target to know.
2265 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2266 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2267 scaledCoords[i].clear();
2268 }
2269 usingCoords = scaledCoords;
2270 }
2271 }
2272
2273 // Publish the motion event.
2274 status = connection->inputPublisher
2275 .publishMotionEvent(dispatchEntry->seq, motionEntry->deviceId,
2276 motionEntry->source, motionEntry->displayId,
2277 dispatchEntry->resolvedAction,
2278 motionEntry->actionButton,
2279 dispatchEntry->resolvedFlags,
2280 motionEntry->edgeFlags, motionEntry->metaState,
2281 motionEntry->buttonState,
2282 motionEntry->classification, xOffset, yOffset,
2283 motionEntry->xPrecision,
2284 motionEntry->yPrecision, motionEntry->downTime,
2285 motionEntry->eventTime,
2286 motionEntry->pointerCount,
2287 motionEntry->pointerProperties, usingCoords);
2288 break;
2289 }
2290
2291 default:
2292 ALOG_ASSERT(false);
2293 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 }
2295
2296 // Check the result.
2297 if (status) {
2298 if (status == WOULD_BLOCK) {
2299 if (connection->waitQueue.isEmpty()) {
2300 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tane4fc0102019-09-11 13:16:25 -07002301 "This is unexpected because the wait queue is empty, so the pipe "
2302 "should be empty and we shouldn't have any problems writing an "
2303 "event to it, status=%d",
2304 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2306 } else {
2307 // Pipe is full and we are waiting for the app to finish process some events
2308 // before sending more events to it.
2309#if DEBUG_DISPATCH_CYCLE
2310 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tane4fc0102019-09-11 13:16:25 -07002311 "waiting for the application to catch up",
2312 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002313#endif
2314 connection->inputPublisherBlocked = true;
2315 }
2316 } else {
2317 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tane4fc0102019-09-11 13:16:25 -07002318 "status=%d",
2319 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2321 }
2322 return;
2323 }
2324
2325 // Re-enqueue the event on the wait queue.
2326 connection->outboundQueue.dequeue(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002327 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002328 connection->waitQueue.enqueueAtTail(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002329 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330 }
2331}
2332
2333void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tane4fc0102019-09-11 13:16:25 -07002334 const sp<Connection>& connection, uint32_t seq,
2335 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336#if DEBUG_DISPATCH_CYCLE
2337 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tane4fc0102019-09-11 13:16:25 -07002338 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339#endif
2340
2341 connection->inputPublisherBlocked = false;
2342
Garfield Tane4fc0102019-09-11 13:16:25 -07002343 if (connection->status == Connection::STATUS_BROKEN ||
2344 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002345 return;
2346 }
2347
2348 // Notify other system components and prepare to start the next dispatch cycle.
2349 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2350}
2351
2352void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tane4fc0102019-09-11 13:16:25 -07002353 const sp<Connection>& connection,
2354 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355#if DEBUG_DISPATCH_CYCLE
2356 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tane4fc0102019-09-11 13:16:25 -07002357 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002358#endif
2359
2360 // Clear the dispatch queues.
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002361 drainDispatchQueue(&connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002362 traceOutboundQueueLength(connection);
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002363 drainDispatchQueue(&connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002364 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002365
2366 // The connection appears to be unrecoverably broken.
2367 // Ignore already broken or zombie connections.
2368 if (connection->status == Connection::STATUS_NORMAL) {
2369 connection->status = Connection::STATUS_BROKEN;
2370
2371 if (notify) {
2372 // Notify other system components.
2373 onDispatchCycleBrokenLocked(currentTime, connection);
2374 }
2375 }
2376}
2377
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002378void InputDispatcher::drainDispatchQueue(Queue<DispatchEntry>* queue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002379 while (!queue->isEmpty()) {
2380 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002381 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002382 }
2383}
2384
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002385void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002386 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002387 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002388 }
2389 delete dispatchEntry;
2390}
2391
2392int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2393 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2394
2395 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002396 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002397
2398 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2399 if (connectionIndex < 0) {
2400 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tane4fc0102019-09-11 13:16:25 -07002401 "fd=%d, events=0x%x",
2402 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403 return 0; // remove the callback
2404 }
2405
2406 bool notify;
2407 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2408 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2409 if (!(events & ALOOPER_EVENT_INPUT)) {
2410 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tane4fc0102019-09-11 13:16:25 -07002411 "events=0x%x",
2412 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002413 return 1;
2414 }
2415
2416 nsecs_t currentTime = now();
2417 bool gotOne = false;
2418 status_t status;
2419 for (;;) {
2420 uint32_t seq;
2421 bool handled;
2422 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2423 if (status) {
2424 break;
2425 }
2426 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2427 gotOne = true;
2428 }
2429 if (gotOne) {
2430 d->runCommandsLockedInterruptible();
2431 if (status == WOULD_BLOCK) {
2432 return 1;
2433 }
2434 }
2435
2436 notify = status != DEAD_OBJECT || !connection->monitor;
2437 if (notify) {
2438 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tane4fc0102019-09-11 13:16:25 -07002439 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002440 }
2441 } else {
2442 // Monitor channels are never explicitly unregistered.
2443 // We do it automatically when the remote endpoint is closed so don't warn
2444 // about them.
2445 notify = !connection->monitor;
2446 if (notify) {
2447 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tane4fc0102019-09-11 13:16:25 -07002448 "events=0x%x",
2449 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002450 }
2451 }
2452
2453 // Unregister the channel.
2454 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2455 return 0; // remove the callback
Garfield Tane4fc0102019-09-11 13:16:25 -07002456 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457}
2458
Garfield Tane4fc0102019-09-11 13:16:25 -07002459void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002460 const CancelationOptions& options) {
2461 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
Garfield Tane4fc0102019-09-11 13:16:25 -07002462 synthesizeCancelationEventsForConnectionLocked(mConnectionsByFd.valueAt(i), options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463 }
2464}
2465
Garfield Tane4fc0102019-09-11 13:16:25 -07002466void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002467 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002468 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2469 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2470}
2471
2472void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2473 const CancelationOptions& options,
2474 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2475 for (const auto& it : monitorsByDisplay) {
2476 const std::vector<Monitor>& monitors = it.second;
2477 for (const Monitor& monitor : monitors) {
2478 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002479 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002480 }
2481}
2482
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2484 const sp<InputChannel>& channel, const CancelationOptions& options) {
2485 ssize_t index = getConnectionIndexLocked(channel);
2486 if (index >= 0) {
Garfield Tane4fc0102019-09-11 13:16:25 -07002487 synthesizeCancelationEventsForConnectionLocked(mConnectionsByFd.valueAt(index), options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002488 }
2489}
2490
2491void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2492 const sp<Connection>& connection, const CancelationOptions& options) {
2493 if (connection->status == Connection::STATUS_BROKEN) {
2494 return;
2495 }
2496
2497 nsecs_t currentTime = now();
2498
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002499 std::vector<EventEntry*> cancelationEvents;
Garfield Tane4fc0102019-09-11 13:16:25 -07002500 connection->inputState.synthesizeCancelationEvents(currentTime, cancelationEvents, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002501
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002502 if (!cancelationEvents.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002503#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002504 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Garfield Tane4fc0102019-09-11 13:16:25 -07002505 "with reality: %s, mode=%d.",
2506 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2507 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002508#endif
2509 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002510 EventEntry* cancelationEventEntry = cancelationEvents[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002511 switch (cancelationEventEntry->type) {
Garfield Tane4fc0102019-09-11 13:16:25 -07002512 case EventEntry::TYPE_KEY:
2513 logOutboundKeyDetails("cancel - ",
2514 static_cast<KeyEntry*>(cancelationEventEntry));
2515 break;
2516 case EventEntry::TYPE_MOTION:
2517 logOutboundMotionDetails("cancel - ",
2518 static_cast<MotionEntry*>(cancelationEventEntry));
2519 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002520 }
2521
2522 InputTarget target;
Garfield Tane4fc0102019-09-11 13:16:25 -07002523 sp<InputWindowHandle> windowHandle =
2524 getWindowHandleLocked(connection->inputChannel->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002525 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002526 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2527 target.xOffset = -windowInfo->frameLeft;
2528 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002529 target.globalScaleFactor = windowInfo->globalScaleFactor;
2530 target.windowXScale = windowInfo->windowXScale;
2531 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002532 } else {
2533 target.xOffset = 0;
2534 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002535 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002536 }
2537 target.inputChannel = connection->inputChannel;
2538 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2539
chaviw8c9cf542019-03-25 13:02:48 -07002540 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Garfield Tane4fc0102019-09-11 13:16:25 -07002541 &target, InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002542
2543 cancelationEventEntry->release();
2544 }
2545
2546 startDispatchCycleLocked(currentTime, connection);
2547 }
2548}
2549
Garfield Tane4fc0102019-09-11 13:16:25 -07002550InputDispatcher::MotionEntry* InputDispatcher::splitMotionEvent(
2551 const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002552 ALOG_ASSERT(pointerIds.value != 0);
2553
2554 uint32_t splitPointerIndexMap[MAX_POINTERS];
2555 PointerProperties splitPointerProperties[MAX_POINTERS];
2556 PointerCoords splitPointerCoords[MAX_POINTERS];
2557
2558 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2559 uint32_t splitPointerCount = 0;
2560
2561 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tane4fc0102019-09-11 13:16:25 -07002562 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563 const PointerProperties& pointerProperties =
2564 originalMotionEntry->pointerProperties[originalPointerIndex];
2565 uint32_t pointerId = uint32_t(pointerProperties.id);
2566 if (pointerIds.hasBit(pointerId)) {
2567 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2568 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2569 splitPointerCoords[splitPointerCount].copyFrom(
2570 originalMotionEntry->pointerCoords[originalPointerIndex]);
2571 splitPointerCount += 1;
2572 }
2573 }
2574
2575 if (splitPointerCount != pointerIds.count()) {
2576 // This is bad. We are missing some of the pointers that we expected to deliver.
2577 // Most likely this indicates that we received an ACTION_MOVE events that has
2578 // different pointer ids than we expected based on the previous ACTION_DOWN
2579 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2580 // in this way.
2581 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tane4fc0102019-09-11 13:16:25 -07002582 "we expected there to be %d pointers. This probably means we received "
2583 "a broken sequence of pointer ids from the input device.",
2584 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002585 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586 }
2587
2588 int32_t action = originalMotionEntry->action;
2589 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tane4fc0102019-09-11 13:16:25 -07002590 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2591 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002592 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2593 const PointerProperties& pointerProperties =
2594 originalMotionEntry->pointerProperties[originalPointerIndex];
2595 uint32_t pointerId = uint32_t(pointerProperties.id);
2596 if (pointerIds.hasBit(pointerId)) {
2597 if (pointerIds.count() == 1) {
2598 // The first/last pointer went down/up.
2599 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tane4fc0102019-09-11 13:16:25 -07002600 ? AMOTION_EVENT_ACTION_DOWN
2601 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002602 } else {
2603 // A secondary pointer went down/up.
2604 uint32_t splitPointerIndex = 0;
2605 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2606 splitPointerIndex += 1;
2607 }
Garfield Tane4fc0102019-09-11 13:16:25 -07002608 action = maskedAction |
2609 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002610 }
2611 } else {
2612 // An unrelated pointer changed.
2613 action = AMOTION_EVENT_ACTION_MOVE;
2614 }
2615 }
2616
Garfield Tane4fc0102019-09-11 13:16:25 -07002617 MotionEntry* splitMotionEntry =
2618 new MotionEntry(originalMotionEntry->sequenceNum, originalMotionEntry->eventTime,
2619 originalMotionEntry->deviceId, originalMotionEntry->source,
2620 originalMotionEntry->displayId, originalMotionEntry->policyFlags,
2621 action, originalMotionEntry->actionButton, originalMotionEntry->flags,
2622 originalMotionEntry->metaState, originalMotionEntry->buttonState,
2623 originalMotionEntry->classification, originalMotionEntry->edgeFlags,
2624 originalMotionEntry->xPrecision, originalMotionEntry->yPrecision,
2625 originalMotionEntry->downTime, splitPointerCount,
2626 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002627
2628 if (originalMotionEntry->injectionState) {
2629 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2630 splitMotionEntry->injectionState->refCount += 1;
2631 }
2632
2633 return splitMotionEntry;
2634}
2635
2636void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2637#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002638 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002639#endif
2640
2641 bool needWake;
2642 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002643 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002644
Prabir Pradhan42611e02018-11-27 14:04:02 -08002645 ConfigurationChangedEntry* newEntry =
2646 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002647 needWake = enqueueInboundEventLocked(newEntry);
2648 } // release lock
2649
2650 if (needWake) {
2651 mLooper->wake();
2652 }
2653}
2654
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002655/**
2656 * If one of the meta shortcuts is detected, process them here:
2657 * Meta + Backspace -> generate BACK
2658 * Meta + Enter -> generate HOME
2659 * This will potentially overwrite keyCode and metaState.
2660 */
2661void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tane4fc0102019-09-11 13:16:25 -07002662 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002663 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2664 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2665 if (keyCode == AKEYCODE_DEL) {
2666 newKeyCode = AKEYCODE_BACK;
2667 } else if (keyCode == AKEYCODE_ENTER) {
2668 newKeyCode = AKEYCODE_HOME;
2669 }
2670 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002671 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002672 struct KeyReplacement replacement = {keyCode, deviceId};
2673 mReplacedKeys.add(replacement, newKeyCode);
2674 keyCode = newKeyCode;
2675 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2676 }
2677 } else if (action == AKEY_EVENT_ACTION_UP) {
2678 // In order to maintain a consistent stream of up and down events, check to see if the key
2679 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2680 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002681 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002682 struct KeyReplacement replacement = {keyCode, deviceId};
2683 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2684 if (index >= 0) {
2685 keyCode = mReplacedKeys.valueAt(index);
2686 mReplacedKeys.removeItemsAt(index);
2687 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2688 }
2689 }
2690}
2691
Michael Wrightd02c5b62014-02-10 15:10:22 -08002692void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2693#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tane4fc0102019-09-11 13:16:25 -07002694 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2695 "policyFlags=0x%x, action=0x%x, "
2696 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
2697 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2698 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
2699 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002700#endif
2701 if (!validateKeyEvent(args->action)) {
2702 return;
2703 }
2704
2705 uint32_t policyFlags = args->policyFlags;
2706 int32_t flags = args->flags;
2707 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002708 // InputDispatcher tracks and generates key repeats on behalf of
2709 // whatever notifies it, so repeatCount should always be set to 0
2710 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2712 policyFlags |= POLICY_FLAG_VIRTUAL;
2713 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2714 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002715 if (policyFlags & POLICY_FLAG_FUNCTION) {
2716 metaState |= AMETA_FUNCTION_ON;
2717 }
2718
2719 policyFlags |= POLICY_FLAG_TRUSTED;
2720
Michael Wright78f24442014-08-06 15:55:28 -07002721 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002722 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002723
Michael Wrightd02c5b62014-02-10 15:10:22 -08002724 KeyEvent event;
Garfield Tane4fc0102019-09-11 13:16:25 -07002725 event.initialize(args->deviceId, args->source, args->displayId, args->action, flags, keyCode,
2726 args->scanCode, metaState, repeatCount, args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002727
Michael Wright2b3c3302018-03-02 17:19:13 +00002728 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002729 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002730 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2731 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tane4fc0102019-09-11 13:16:25 -07002732 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002733 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734
Michael Wrightd02c5b62014-02-10 15:10:22 -08002735 bool needWake;
2736 { // acquire lock
2737 mLock.lock();
2738
2739 if (shouldSendKeyToInputFilterLocked(args)) {
2740 mLock.unlock();
2741
2742 policyFlags |= POLICY_FLAG_FILTERED;
2743 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2744 return; // event was consumed by the filter
2745 }
2746
2747 mLock.lock();
2748 }
2749
Garfield Tane4fc0102019-09-11 13:16:25 -07002750 KeyEntry* newEntry =
2751 new KeyEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2752 args->displayId, policyFlags, args->action, flags, keyCode,
2753 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002754
2755 needWake = enqueueInboundEventLocked(newEntry);
2756 mLock.unlock();
2757 } // release lock
2758
2759 if (needWake) {
2760 mLooper->wake();
2761 }
2762}
2763
2764bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2765 return mInputFilterEnabled;
2766}
2767
2768void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2769#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002770 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tane4fc0102019-09-11 13:16:25 -07002771 ", policyFlags=0x%x, "
2772 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
2773 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
2774 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2775 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
2776 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777 for (uint32_t i = 0; i < args->pointerCount; i++) {
2778 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tane4fc0102019-09-11 13:16:25 -07002779 "x=%f, y=%f, pressure=%f, size=%f, "
2780 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2781 "orientation=%f",
2782 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
2783 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2784 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2785 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2786 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2787 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2788 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2789 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2790 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2791 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002792 }
2793#endif
Garfield Tane4fc0102019-09-11 13:16:25 -07002794 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
2795 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002796 return;
2797 }
2798
2799 uint32_t policyFlags = args->policyFlags;
2800 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002801
2802 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002803 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002804 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2805 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tane4fc0102019-09-11 13:16:25 -07002806 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002807 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002808
2809 bool needWake;
2810 { // acquire lock
2811 mLock.lock();
2812
2813 if (shouldSendMotionToInputFilterLocked(args)) {
2814 mLock.unlock();
2815
2816 MotionEvent event;
Garfield Tane4fc0102019-09-11 13:16:25 -07002817 event.initialize(args->deviceId, args->source, args->displayId, args->action,
2818 args->actionButton, args->flags, args->edgeFlags, args->metaState,
2819 args->buttonState, args->classification, 0, 0, args->xPrecision,
2820 args->yPrecision, args->downTime, args->eventTime, args->pointerCount,
2821 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822
2823 policyFlags |= POLICY_FLAG_FILTERED;
2824 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2825 return; // event was consumed by the filter
2826 }
2827
2828 mLock.lock();
2829 }
2830
2831 // Just enqueue a new motion event.
Garfield Tane4fc0102019-09-11 13:16:25 -07002832 MotionEntry* newEntry =
2833 new MotionEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2834 args->displayId, policyFlags, args->action, args->actionButton,
2835 args->flags, args->metaState, args->buttonState,
2836 args->classification, args->edgeFlags, args->xPrecision,
2837 args->yPrecision, args->downTime, args->pointerCount,
2838 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002839
2840 needWake = enqueueInboundEventLocked(newEntry);
2841 mLock.unlock();
2842 } // release lock
2843
2844 if (needWake) {
2845 mLooper->wake();
2846 }
2847}
2848
2849bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08002850 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851}
2852
2853void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2854#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002855 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tane4fc0102019-09-11 13:16:25 -07002856 "switchMask=0x%08x",
2857 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858#endif
2859
2860 uint32_t policyFlags = args->policyFlags;
2861 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tane4fc0102019-09-11 13:16:25 -07002862 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002863}
2864
2865void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2866#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tane4fc0102019-09-11 13:16:25 -07002867 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
2868 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002869#endif
2870
2871 bool needWake;
2872 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002873 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002874
Prabir Pradhan42611e02018-11-27 14:04:02 -08002875 DeviceResetEntry* newEntry =
2876 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002877 needWake = enqueueInboundEventLocked(newEntry);
2878 } // release lock
2879
2880 if (needWake) {
2881 mLooper->wake();
2882 }
2883}
2884
Garfield Tane4fc0102019-09-11 13:16:25 -07002885int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
2886 int32_t injectorUid, int32_t syncMode,
2887 int32_t timeoutMillis, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888#if DEBUG_INBOUND_EVENT_DETAILS
2889 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Garfield Tane4fc0102019-09-11 13:16:25 -07002890 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2891 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002892#endif
2893
2894 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2895
2896 policyFlags |= POLICY_FLAG_INJECTED;
2897 if (hasInjectionPermission(injectorPid, injectorUid)) {
2898 policyFlags |= POLICY_FLAG_TRUSTED;
2899 }
2900
2901 EventEntry* firstInjectedEntry;
2902 EventEntry* lastInjectedEntry;
2903 switch (event->getType()) {
Garfield Tane4fc0102019-09-11 13:16:25 -07002904 case AINPUT_EVENT_TYPE_KEY: {
2905 KeyEvent keyEvent;
2906 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2907 int32_t action = keyEvent.getAction();
2908 if (!validateKeyEvent(action)) {
2909 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002910 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002911
Garfield Tane4fc0102019-09-11 13:16:25 -07002912 int32_t flags = keyEvent.getFlags();
2913 int32_t keyCode = keyEvent.getKeyCode();
2914 int32_t metaState = keyEvent.getMetaState();
2915 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2916 /*byref*/ keyCode, /*byref*/ metaState);
2917 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(),
2918 keyEvent.getDisplayId(), action, flags, keyCode,
2919 keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
2920 keyEvent.getDownTime(), keyEvent.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002921
Garfield Tane4fc0102019-09-11 13:16:25 -07002922 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2923 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00002924 }
Garfield Tane4fc0102019-09-11 13:16:25 -07002925
2926 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2927 android::base::Timer t;
2928 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
2929 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2930 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2931 std::to_string(t.duration().count()).c_str());
2932 }
2933 }
2934
2935 mLock.lock();
2936 firstInjectedEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM,
2937 keyEvent.getEventTime(), keyEvent.getDeviceId(),
2938 keyEvent.getSource(), keyEvent.getDisplayId(),
2939 policyFlags, action, flags, keyEvent.getKeyCode(),
2940 keyEvent.getScanCode(), keyEvent.getMetaState(),
2941 keyEvent.getRepeatCount(), keyEvent.getDownTime());
2942 lastInjectedEntry = firstInjectedEntry;
2943 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002944 }
2945
Garfield Tane4fc0102019-09-11 13:16:25 -07002946 case AINPUT_EVENT_TYPE_MOTION: {
2947 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2948 int32_t action = motionEvent->getAction();
2949 size_t pointerCount = motionEvent->getPointerCount();
2950 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2951 int32_t actionButton = motionEvent->getActionButton();
2952 int32_t displayId = motionEvent->getDisplayId();
2953 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
2954 return INPUT_EVENT_INJECTION_FAILED;
2955 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002956
Garfield Tane4fc0102019-09-11 13:16:25 -07002957 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2958 nsecs_t eventTime = motionEvent->getEventTime();
2959 android::base::Timer t;
2960 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
2961 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2962 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2963 std::to_string(t.duration().count()).c_str());
2964 }
2965 }
2966
2967 mLock.lock();
2968 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2969 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2970 firstInjectedEntry =
2971 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
2972 motionEvent->getDeviceId(), motionEvent->getSource(),
2973 motionEvent->getDisplayId(), policyFlags, action, actionButton,
2974 motionEvent->getFlags(), motionEvent->getMetaState(),
2975 motionEvent->getButtonState(), motionEvent->getClassification(),
2976 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
2977 motionEvent->getYPrecision(), motionEvent->getDownTime(),
2978 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2979 motionEvent->getXOffset(), motionEvent->getYOffset());
2980 lastInjectedEntry = firstInjectedEntry;
2981 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2982 sampleEventTimes += 1;
2983 samplePointerCoords += pointerCount;
2984 MotionEntry* nextInjectedEntry =
2985 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
2986 motionEvent->getDeviceId(), motionEvent->getSource(),
2987 motionEvent->getDisplayId(), policyFlags, action,
2988 actionButton, motionEvent->getFlags(),
2989 motionEvent->getMetaState(), motionEvent->getButtonState(),
2990 motionEvent->getClassification(),
2991 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
2992 motionEvent->getYPrecision(), motionEvent->getDownTime(),
2993 uint32_t(pointerCount), pointerProperties,
2994 samplePointerCoords, motionEvent->getXOffset(),
2995 motionEvent->getYOffset());
2996 lastInjectedEntry->next = nextInjectedEntry;
2997 lastInjectedEntry = nextInjectedEntry;
2998 }
2999 break;
3000 }
3001
3002 default:
3003 ALOGW("Cannot inject event of type %d", event->getType());
3004 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003005 }
3006
3007 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3008 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3009 injectionState->injectionIsAsync = true;
3010 }
3011
3012 injectionState->refCount += 1;
3013 lastInjectedEntry->injectionState = injectionState;
3014
3015 bool needWake = false;
Garfield Tane4fc0102019-09-11 13:16:25 -07003016 for (EventEntry* entry = firstInjectedEntry; entry != nullptr;) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003017 EventEntry* nextEntry = entry->next;
3018 needWake |= enqueueInboundEventLocked(entry);
3019 entry = nextEntry;
3020 }
3021
3022 mLock.unlock();
3023
3024 if (needWake) {
3025 mLooper->wake();
3026 }
3027
3028 int32_t injectionResult;
3029 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003030 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003031
3032 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3033 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3034 } else {
3035 for (;;) {
3036 injectionResult = injectionState->injectionResult;
3037 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3038 break;
3039 }
3040
3041 nsecs_t remainingTimeout = endTime - now();
3042 if (remainingTimeout <= 0) {
3043#if DEBUG_INJECTION
3044 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tane4fc0102019-09-11 13:16:25 -07003045 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003046#endif
3047 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3048 break;
3049 }
3050
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003051 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052 }
3053
Garfield Tane4fc0102019-09-11 13:16:25 -07003054 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3055 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003056 while (injectionState->pendingForegroundDispatches != 0) {
3057#if DEBUG_INJECTION
3058 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tane4fc0102019-09-11 13:16:25 -07003059 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003060#endif
3061 nsecs_t remainingTimeout = endTime - now();
3062 if (remainingTimeout <= 0) {
3063#if DEBUG_INJECTION
Garfield Tane4fc0102019-09-11 13:16:25 -07003064 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3065 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003066#endif
3067 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3068 break;
3069 }
3070
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003071 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003072 }
3073 }
3074 }
3075
3076 injectionState->release();
3077 } // release lock
3078
3079#if DEBUG_INJECTION
3080 ALOGD("injectInputEvent - Finished with result %d. "
Garfield Tane4fc0102019-09-11 13:16:25 -07003081 "injectorPid=%d, injectorUid=%d",
3082 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003083#endif
3084
3085 return injectionResult;
3086}
3087
3088bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tane4fc0102019-09-11 13:16:25 -07003089 return injectorUid == 0 ||
3090 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003091}
3092
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003093void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003094 InjectionState* injectionState = entry->injectionState;
3095 if (injectionState) {
3096#if DEBUG_INJECTION
3097 ALOGD("Setting input event injection result to %d. "
Garfield Tane4fc0102019-09-11 13:16:25 -07003098 "injectorPid=%d, injectorUid=%d",
3099 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100#endif
3101
Garfield Tane4fc0102019-09-11 13:16:25 -07003102 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103 // Log the outcome since the injector did not wait for the injection result.
3104 switch (injectionResult) {
Garfield Tane4fc0102019-09-11 13:16:25 -07003105 case INPUT_EVENT_INJECTION_SUCCEEDED:
3106 ALOGV("Asynchronous input event injection succeeded.");
3107 break;
3108 case INPUT_EVENT_INJECTION_FAILED:
3109 ALOGW("Asynchronous input event injection failed.");
3110 break;
3111 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3112 ALOGW("Asynchronous input event injection permission denied.");
3113 break;
3114 case INPUT_EVENT_INJECTION_TIMED_OUT:
3115 ALOGW("Asynchronous input event injection timed out.");
3116 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117 }
3118 }
3119
3120 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003121 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003122 }
3123}
3124
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003125void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003126 InjectionState* injectionState = entry->injectionState;
3127 if (injectionState) {
3128 injectionState->pendingForegroundDispatches += 1;
3129 }
3130}
3131
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003132void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003133 InjectionState* injectionState = entry->injectionState;
3134 if (injectionState) {
3135 injectionState->pendingForegroundDispatches -= 1;
3136
3137 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003138 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003139 }
3140 }
3141}
3142
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003143std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3144 int32_t displayId) const {
3145 std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>::const_iterator it =
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003146 mWindowHandlesByDisplay.find(displayId);
Garfield Tane4fc0102019-09-11 13:16:25 -07003147 if (it != mWindowHandlesByDisplay.end()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003148 return it->second;
3149 }
3150
3151 // Return an empty one if nothing found.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003152 return std::vector<sp<InputWindowHandle>>();
Arthur Hungb92218b2018-08-14 12:00:21 +08003153}
3154
Michael Wrightd02c5b62014-02-10 15:10:22 -08003155sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003156 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003157 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003158 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3159 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003160 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003161 return windowHandle;
3162 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003163 }
3164 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003165 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166}
3167
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003168bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003169 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003170 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3171 for (const sp<InputWindowHandle>& handle : windowHandles) {
3172 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003173 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003174 ALOGE("Found window %s in display %" PRId32
Garfield Tane4fc0102019-09-11 13:16:25 -07003175 ", but it should belong to display %" PRId32,
3176 windowHandle->getName().c_str(), it.first,
3177 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003178 }
3179 return true;
3180 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181 }
3182 }
3183 return false;
3184}
3185
Robert Carr5c8a0262018-10-03 16:30:44 -07003186sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3187 size_t count = mInputChannelsByToken.count(token);
3188 if (count == 0) {
3189 return nullptr;
3190 }
3191 return mInputChannelsByToken.at(token);
3192}
3193
Arthur Hungb92218b2018-08-14 12:00:21 +08003194/**
3195 * Called from InputManagerService, update window handle list by displayId that can receive input.
3196 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3197 * If set an empty list, remove all handles from the specific display.
3198 * For focused handle, check if need to change and send a cancel event to previous one.
3199 * For removed handle, check if need to send a cancel event if already in touch.
3200 */
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003201void InputDispatcher::setInputWindows(const std::vector<sp<InputWindowHandle>>& inputWindowHandles,
Garfield Tane4fc0102019-09-11 13:16:25 -07003202 int32_t displayId,
3203 const sp<ISetInputWindowsListener>& setInputWindowsListener) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003205 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003206#endif
3207 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003208 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003209
Arthur Hungb92218b2018-08-14 12:00:21 +08003210 // Copy old handles for release if they are no longer present.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003211 const std::vector<sp<InputWindowHandle>> oldWindowHandles =
3212 getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003213
Tiger Huang721e26f2018-07-24 22:26:19 +08003214 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003215 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003216
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003217 if (inputWindowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003218 // Remove all handles on a display if there are no windows left.
3219 mWindowHandlesByDisplay.erase(displayId);
3220 } else {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003221 // Since we compare the pointer of input window handles across window updates, we need
3222 // to make sure the handle object for the same window stays unchanged across updates.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003223 const std::vector<sp<InputWindowHandle>>& oldHandles =
3224 mWindowHandlesByDisplay[displayId];
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003225 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003226 for (const sp<InputWindowHandle>& handle : oldHandles) {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003227 oldHandlesByTokens[handle->getToken()] = handle;
3228 }
3229
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003230 std::vector<sp<InputWindowHandle>> newHandles;
3231 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
Siarhei Vishniakou3a179dc2019-01-30 09:50:04 -08003232 if (!handle->updateInfo()) {
3233 // handle no longer valid
3234 continue;
3235 }
3236 const InputWindowInfo* info = handle->getInfo();
3237
3238 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3239 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3240 const bool noInputChannel =
3241 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3242 const bool canReceiveInput =
3243 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3244 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3245 if (canReceiveInput && !noInputChannel) {
3246 ALOGE("Window handle %s has no registered input channel",
3247 handle->getName().c_str());
3248 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003249 continue;
3250 }
3251
Siarhei Vishniakou3a179dc2019-01-30 09:50:04 -08003252 if (info->displayId != displayId) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003253 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
Siarhei Vishniakou3a179dc2019-01-30 09:50:04 -08003254 handle->getName().c_str(), displayId, info->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003255 continue;
3256 }
3257
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003258 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3259 const sp<InputWindowHandle> oldHandle =
3260 oldHandlesByTokens.at(handle->getToken());
3261 oldHandle->updateFrom(handle);
3262 newHandles.push_back(oldHandle);
3263 } else {
3264 newHandles.push_back(handle);
3265 }
3266 }
3267
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003268 for (const sp<InputWindowHandle>& windowHandle : newHandles) {
Arthur Hung7ab76b12019-01-09 19:17:20 +08003269 // Set newFocusedWindowHandle to the top most focused window instead of the last one
Garfield Tane4fc0102019-09-11 13:16:25 -07003270 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3271 windowHandle->getInfo()->visible) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003272 newFocusedWindowHandle = windowHandle;
3273 }
3274 if (windowHandle == mLastHoverWindowHandle) {
3275 foundHoveredWindow = true;
3276 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003277 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003278
3279 // Insert or replace
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003280 mWindowHandlesByDisplay[displayId] = newHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281 }
3282
3283 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003284 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003285 }
3286
Tiger Huang721e26f2018-07-24 22:26:19 +08003287 sp<InputWindowHandle> oldFocusedWindowHandle =
3288 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3289
3290 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3291 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003292#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003293 ALOGD("Focus left window: %s in display %" PRId32,
Garfield Tane4fc0102019-09-11 13:16:25 -07003294 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003295#endif
Garfield Tane4fc0102019-09-11 13:16:25 -07003296 sp<InputChannel> focusedInputChannel =
3297 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003298 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003299 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
Garfield Tane4fc0102019-09-11 13:16:25 -07003300 "focus left window");
3301 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003303 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003304 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003305 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003306#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003307 ALOGD("Focus entered window: %s in display %" PRId32,
Garfield Tane4fc0102019-09-11 13:16:25 -07003308 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003309#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003310 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311 }
Robert Carrf759f162018-11-13 12:57:11 -08003312
3313 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003314 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003315 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003316 }
3317
Arthur Hungb92218b2018-08-14 12:00:21 +08003318 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3319 if (stateIndex >= 0) {
3320 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Garfield Tane4fc0102019-09-11 13:16:25 -07003321 for (size_t i = 0; i < state.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003322 TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003323 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003325 ALOGD("Touched window was removed: %s in display %" PRId32,
Garfield Tane4fc0102019-09-11 13:16:25 -07003326 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003327#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003328 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003329 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003330 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003331 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tane4fc0102019-09-11 13:16:25 -07003332 "touched window was removed");
3333 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel,
3334 options);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003335 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003336 state.windows.erase(state.windows.begin() + i);
Ivan Lozano96f12992017-11-09 14:45:38 -08003337 } else {
Garfield Tane4fc0102019-09-11 13:16:25 -07003338 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003339 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003340 }
3341 }
3342
3343 // Release information for windows that are no longer present.
3344 // This ensures that unused input channels are released promptly.
3345 // Otherwise, they might stick around until the window handle is destroyed
3346 // which might not happen until the next GC.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003347 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003348 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003349#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003350 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003351#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003352 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353 }
3354 }
3355 } // release lock
3356
3357 // Wake up poll loop since it may need to make new input dispatching choices.
3358 mLooper->wake();
chaviw291d88a2019-02-14 10:33:58 -08003359
3360 if (setInputWindowsListener) {
3361 setInputWindowsListener->onSetInputWindowsFinished();
3362 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003363}
3364
3365void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003366 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003367#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003368 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003369#endif
3370 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003371 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003372
Tiger Huang721e26f2018-07-24 22:26:19 +08003373 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3374 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003375 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003376 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3377 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003378 resetANRTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003379 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003380 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003381 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003382 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003384 oldFocusedApplicationHandle.clear();
3385 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003386 }
3387
3388#if DEBUG_FOCUS
Garfield Tane4fc0102019-09-11 13:16:25 -07003389 // logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390#endif
3391 } // release lock
3392
3393 // Wake up poll loop since it may need to make new input dispatching choices.
3394 mLooper->wake();
3395}
3396
Tiger Huang721e26f2018-07-24 22:26:19 +08003397/**
3398 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3399 * the display not specified.
3400 *
3401 * We track any unreleased events for each window. If a window loses the ability to receive the
3402 * released event, we will send a cancel event to it. So when the focused display is changed, we
3403 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3404 * display. The display-specified events won't be affected.
3405 */
3406void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3407#if DEBUG_FOCUS
3408 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3409#endif
3410 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003411 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003412
3413 if (mFocusedDisplayId != displayId) {
3414 sp<InputWindowHandle> oldFocusedWindowHandle =
3415 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3416 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003417 sp<InputChannel> inputChannel =
Garfield Tane4fc0102019-09-11 13:16:25 -07003418 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003419 if (inputChannel != nullptr) {
Garfield Tane4fc0102019-09-11 13:16:25 -07003420 CancelationOptions
3421 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3422 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003423 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003424 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3425 }
3426 }
3427 mFocusedDisplayId = displayId;
3428
3429 // Sanity check
3430 sp<InputWindowHandle> newFocusedWindowHandle =
3431 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003432 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003433
Tiger Huang721e26f2018-07-24 22:26:19 +08003434 if (newFocusedWindowHandle == nullptr) {
3435 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3436 if (!mFocusedWindowHandlesByDisplay.empty()) {
3437 ALOGE("But another display has a focused window:");
3438 for (auto& it : mFocusedWindowHandlesByDisplay) {
3439 const int32_t displayId = it.first;
3440 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tane4fc0102019-09-11 13:16:25 -07003441 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3442 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003443 }
3444 }
3445 }
3446 }
3447
3448#if DEBUG_FOCUS
3449 logDispatchStateLocked();
3450#endif
3451 } // release lock
3452
3453 // Wake up poll loop since it may need to make new input dispatching choices.
3454 mLooper->wake();
3455}
3456
Michael Wrightd02c5b62014-02-10 15:10:22 -08003457void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3458#if DEBUG_FOCUS
3459 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3460#endif
3461
3462 bool changed;
3463 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003464 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465
3466 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3467 if (mDispatchFrozen && !frozen) {
3468 resetANRTimeoutsLocked();
3469 }
3470
3471 if (mDispatchEnabled && !enabled) {
3472 resetAndDropEverythingLocked("dispatcher is being disabled");
3473 }
3474
3475 mDispatchEnabled = enabled;
3476 mDispatchFrozen = frozen;
3477 changed = true;
3478 } else {
3479 changed = false;
3480 }
3481
3482#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003483 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003484#endif
3485 } // release lock
3486
3487 if (changed) {
3488 // Wake up poll loop since it may need to make new input dispatching choices.
3489 mLooper->wake();
3490 }
3491}
3492
3493void InputDispatcher::setInputFilterEnabled(bool enabled) {
3494#if DEBUG_FOCUS
3495 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3496#endif
3497
3498 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003499 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500
3501 if (mInputFilterEnabled == enabled) {
3502 return;
3503 }
3504
3505 mInputFilterEnabled = enabled;
3506 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3507 } // release lock
3508
3509 // Wake up poll loop since there might be work to do to drop everything.
3510 mLooper->wake();
3511}
3512
chaviwfbe5d9c2018-12-26 12:23:37 -08003513bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3514 if (fromToken == toToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003515#if DEBUG_FOCUS
chaviwfbe5d9c2018-12-26 12:23:37 -08003516 ALOGD("Trivial transfer to same window.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003517#endif
chaviwfbe5d9c2018-12-26 12:23:37 -08003518 return true;
3519 }
3520
Michael Wrightd02c5b62014-02-10 15:10:22 -08003521 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003522 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523
chaviwfbe5d9c2018-12-26 12:23:37 -08003524 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3525 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003526 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003527 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528 return false;
3529 }
chaviw4f2dd402018-12-26 15:30:27 -08003530#if DEBUG_FOCUS
3531 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Garfield Tane4fc0102019-09-11 13:16:25 -07003532 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
chaviw4f2dd402018-12-26 15:30:27 -08003533#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3535#if DEBUG_FOCUS
3536 ALOGD("Cannot transfer focus because windows are on different displays.");
3537#endif
3538 return false;
3539 }
3540
3541 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003542 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3543 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3544 for (size_t i = 0; i < state.windows.size(); i++) {
3545 const TouchedWindow& touchedWindow = state.windows[i];
3546 if (touchedWindow.windowHandle == fromWindowHandle) {
3547 int32_t oldTargetFlags = touchedWindow.targetFlags;
3548 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003549
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003550 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551
Garfield Tane4fc0102019-09-11 13:16:25 -07003552 int32_t newTargetFlags = oldTargetFlags &
3553 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3554 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003555 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003556
Jeff Brownf086ddb2014-02-11 14:28:48 -08003557 found = true;
3558 goto Found;
3559 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560 }
3561 }
Garfield Tane4fc0102019-09-11 13:16:25 -07003562 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003563
Garfield Tane4fc0102019-09-11 13:16:25 -07003564 if (!found) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003565#if DEBUG_FOCUS
3566 ALOGD("Focus transfer failed because from window did not have focus.");
3567#endif
3568 return false;
3569 }
3570
chaviwfbe5d9c2018-12-26 12:23:37 -08003571 sp<InputChannel> fromChannel = getInputChannelLocked(fromToken);
3572 sp<InputChannel> toChannel = getInputChannelLocked(toToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003573 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3574 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3575 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3576 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3577 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3578
3579 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Garfield Tane4fc0102019-09-11 13:16:25 -07003580 CancelationOptions
3581 options(CancelationOptions::CANCEL_POINTER_EVENTS,
3582 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003583 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3584 }
3585
3586#if DEBUG_FOCUS
3587 logDispatchStateLocked();
3588#endif
3589 } // release lock
3590
3591 // Wake up poll loop since it may need to make new input dispatching choices.
3592 mLooper->wake();
3593 return true;
3594}
3595
3596void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3597#if DEBUG_FOCUS
3598 ALOGD("Resetting and dropping all events (%s).", reason);
3599#endif
3600
3601 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3602 synthesizeCancelationEventsForAllConnectionsLocked(options);
3603
3604 resetKeyRepeatLocked();
3605 releasePendingEventLocked();
3606 drainInboundQueueLocked();
3607 resetANRTimeoutsLocked();
3608
Jeff Brownf086ddb2014-02-11 14:28:48 -08003609 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003611 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612}
3613
3614void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003615 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003616 dumpDispatchStateLocked(dump);
3617
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003618 std::istringstream stream(dump);
3619 std::string line;
3620
3621 while (std::getline(stream, line, '\n')) {
3622 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623 }
3624}
3625
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003626void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07003627 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
3628 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
3629 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08003630 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631
Tiger Huang721e26f2018-07-24 22:26:19 +08003632 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3633 dump += StringPrintf(INDENT "FocusedApplications:\n");
3634 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3635 const int32_t displayId = it.first;
3636 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tane4fc0102019-09-11 13:16:25 -07003637 dump += StringPrintf(INDENT2 "displayId=%" PRId32
3638 ", name='%s', dispatchingTimeout=%0.3fms\n",
3639 displayId, applicationHandle->getName().c_str(),
3640 applicationHandle->getDispatchingTimeout(
3641 DEFAULT_INPUT_DISPATCHING_TIMEOUT) /
3642 1000000.0);
Tiger Huang721e26f2018-07-24 22:26:19 +08003643 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003645 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003647
3648 if (!mFocusedWindowHandlesByDisplay.empty()) {
3649 dump += StringPrintf(INDENT "FocusedWindows:\n");
3650 for (auto& it : mFocusedWindowHandlesByDisplay) {
3651 const int32_t displayId = it.first;
3652 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tane4fc0102019-09-11 13:16:25 -07003653 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
3654 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003655 }
3656 } else {
3657 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3658 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003659
Jeff Brownf086ddb2014-02-11 14:28:48 -08003660 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003661 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003662 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3663 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003664 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tane4fc0102019-09-11 13:16:25 -07003665 state.displayId, toString(state.down), toString(state.split),
3666 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003667 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003668 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003669 for (size_t i = 0; i < state.windows.size(); i++) {
3670 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tane4fc0102019-09-11 13:16:25 -07003671 dump += StringPrintf(INDENT4
3672 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3673 i, touchedWindow.windowHandle->getName().c_str(),
3674 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003675 }
3676 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003677 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003678 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003679 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003680 dump += INDENT3 "Portal windows:\n";
3681 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003682 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tane4fc0102019-09-11 13:16:25 -07003683 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
3684 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003685 }
3686 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687 }
3688 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003689 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690 }
3691
Arthur Hungb92218b2018-08-14 12:00:21 +08003692 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tane4fc0102019-09-11 13:16:25 -07003693 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003694 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003695 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003696 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003697 dump += INDENT2 "Windows:\n";
3698 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003699 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08003700 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003701
Arthur Hungb92218b2018-08-14 12:00:21 +08003702 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tane4fc0102019-09-11 13:16:25 -07003703 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
3704 "hasWallpaper=%s, "
3705 "visible=%s, canReceiveKeys=%s, flags=0x%08x, "
3706 "type=0x%08x, layer=%d, "
3707 "frame=[%d,%d][%d,%d], globalScale=%f, "
3708 "windowScale=(%f,%f), "
3709 "touchableRegion=",
3710 i, windowInfo->name.c_str(), windowInfo->displayId,
3711 windowInfo->portalToDisplayId,
3712 toString(windowInfo->paused),
3713 toString(windowInfo->hasFocus),
3714 toString(windowInfo->hasWallpaper),
3715 toString(windowInfo->visible),
3716 toString(windowInfo->canReceiveKeys),
3717 windowInfo->layoutParamsFlags,
3718 windowInfo->layoutParamsType, windowInfo->layer,
3719 windowInfo->frameLeft, windowInfo->frameTop,
3720 windowInfo->frameRight, windowInfo->frameBottom,
3721 windowInfo->globalScaleFactor, windowInfo->windowXScale,
3722 windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003723 dumpRegion(dump, windowInfo->touchableRegion);
3724 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3725 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Garfield Tane4fc0102019-09-11 13:16:25 -07003726 windowInfo->ownerPid, windowInfo->ownerUid,
3727 windowInfo->dispatchingTimeout / 1000000.0);
Arthur Hungb92218b2018-08-14 12:00:21 +08003728 }
3729 } else {
3730 dump += INDENT2 "Windows: <none>\n";
3731 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003732 }
3733 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003734 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003735 }
3736
Michael Wright3dd60e22019-03-27 22:06:44 +00003737 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tane4fc0102019-09-11 13:16:25 -07003738 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003739 const std::vector<Monitor>& monitors = it.second;
3740 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
3741 dumpMonitors(dump, monitors);
Garfield Tane4fc0102019-09-11 13:16:25 -07003742 }
3743 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003744 const std::vector<Monitor>& monitors = it.second;
3745 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
3746 dumpMonitors(dump, monitors);
Garfield Tane4fc0102019-09-11 13:16:25 -07003747 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003748 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00003749 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003750 }
3751
3752 nsecs_t currentTime = now();
3753
3754 // Dump recently dispatched or dropped events from oldest to newest.
3755 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003756 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003757 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003758 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003759 entry->appendDescription(dump);
Garfield Tane4fc0102019-09-11 13:16:25 -07003760 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003761 }
3762 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003763 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764 }
3765
3766 // Dump event currently being dispatched.
3767 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003768 dump += INDENT "PendingEvent:\n";
3769 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003770 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003771 dump += StringPrintf(", age=%0.1fms\n",
Garfield Tane4fc0102019-09-11 13:16:25 -07003772 (currentTime - mPendingEvent->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003774 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003775 }
3776
3777 // Dump inbound events from oldest to newest.
3778 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003779 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003781 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782 entry->appendDescription(dump);
Garfield Tane4fc0102019-09-11 13:16:25 -07003783 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784 }
3785 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003786 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003787 }
3788
Michael Wright78f24442014-08-06 15:55:28 -07003789 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003790 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003791 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3792 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3793 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Garfield Tane4fc0102019-09-11 13:16:25 -07003794 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n", i,
3795 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07003796 }
3797 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003798 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003799 }
3800
Michael Wrightd02c5b62014-02-10 15:10:22 -08003801 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003802 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3804 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003805 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Garfield Tane4fc0102019-09-11 13:16:25 -07003806 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3807 i, connection->getInputChannelName().c_str(),
3808 connection->getWindowName().c_str(), connection->getStatusLabel(),
3809 toString(connection->monitor),
3810 toString(connection->inputPublisherBlocked));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003811
3812 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003813 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Garfield Tane4fc0102019-09-11 13:16:25 -07003814 connection->outboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
Garfield Tane4fc0102019-09-11 13:16:25 -07003816 entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817 dump.append(INDENT4);
3818 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003819 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Garfield Tane4fc0102019-09-11 13:16:25 -07003820 entry->targetFlags, entry->resolvedAction,
3821 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003822 }
3823 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003824 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003825 }
3826
3827 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003828 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Garfield Tane4fc0102019-09-11 13:16:25 -07003829 connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003830 for (DispatchEntry* entry = connection->waitQueue.head; entry;
Garfield Tane4fc0102019-09-11 13:16:25 -07003831 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003832 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003833 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003834 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Garfield Tane4fc0102019-09-11 13:16:25 -07003835 "age=%0.1fms, wait=%0.1fms\n",
3836 entry->targetFlags, entry->resolvedAction,
3837 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3838 (currentTime - entry->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003839 }
3840 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003841 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003842 }
3843 }
3844 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003845 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003846 }
3847
3848 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003849 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Garfield Tane4fc0102019-09-11 13:16:25 -07003850 (mAppSwitchDueTime - now()) / 1000000.0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003851 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003852 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003853 }
3854
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003855 dump += INDENT "Configuration:\n";
Garfield Tane4fc0102019-09-11 13:16:25 -07003856 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003857 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Garfield Tane4fc0102019-09-11 13:16:25 -07003858 mConfig.keyRepeatTimeout * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003859}
3860
Michael Wright3dd60e22019-03-27 22:06:44 +00003861void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
3862 const size_t numMonitors = monitors.size();
3863 for (size_t i = 0; i < numMonitors; i++) {
3864 const Monitor& monitor = monitors[i];
3865 const sp<InputChannel>& channel = monitor.inputChannel;
3866 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
3867 dump += "\n";
3868 }
3869}
3870
3871status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
Garfield Tane4fc0102019-09-11 13:16:25 -07003872 int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003873#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003874 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
Garfield Tane4fc0102019-09-11 13:16:25 -07003875 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003876#endif
3877
3878 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003879 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003880
3881 if (getConnectionIndexLocked(inputChannel) >= 0) {
3882 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tane4fc0102019-09-11 13:16:25 -07003883 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884 return BAD_VALUE;
3885 }
3886
Michael Wright3dd60e22019-03-27 22:06:44 +00003887 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003888
3889 int fd = inputChannel->getFd();
3890 mConnectionsByFd.add(fd, connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07003891 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003892
Michael Wrightd02c5b62014-02-10 15:10:22 -08003893 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3894 } // release lock
3895
3896 // Wake the looper because some connections have changed.
3897 mLooper->wake();
3898 return OK;
3899}
3900
Michael Wright3dd60e22019-03-27 22:06:44 +00003901status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tane4fc0102019-09-11 13:16:25 -07003902 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003903 { // acquire lock
3904 std::scoped_lock _l(mLock);
3905
3906 if (displayId < 0) {
3907 ALOGW("Attempted to register input monitor without a specified display.");
3908 return BAD_VALUE;
3909 }
3910
3911 if (inputChannel->getToken() == nullptr) {
3912 ALOGW("Attempted to register input monitor without an identifying token.");
3913 return BAD_VALUE;
3914 }
3915
3916 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/);
3917
3918 const int fd = inputChannel->getFd();
3919 mConnectionsByFd.add(fd, connection);
3920 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
3921
Garfield Tane4fc0102019-09-11 13:16:25 -07003922 auto& monitorsByDisplay =
3923 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00003924 monitorsByDisplay[displayId].emplace_back(inputChannel);
3925
3926 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00003927 }
3928 // Wake the looper because some connections have changed.
3929 mLooper->wake();
3930 return OK;
3931}
3932
Michael Wrightd02c5b62014-02-10 15:10:22 -08003933status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3934#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003935 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003936#endif
3937
3938 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003939 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003940
3941 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3942 if (status) {
3943 return status;
3944 }
3945 } // release lock
3946
3947 // Wake the poll loop because removing the connection may have changed the current
3948 // synchronization state.
3949 mLooper->wake();
3950 return OK;
3951}
3952
3953status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tane4fc0102019-09-11 13:16:25 -07003954 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3956 if (connectionIndex < 0) {
3957 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tane4fc0102019-09-11 13:16:25 -07003958 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959 return BAD_VALUE;
3960 }
3961
3962 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3963 mConnectionsByFd.removeItemsAt(connectionIndex);
3964
Robert Carr5c8a0262018-10-03 16:30:44 -07003965 mInputChannelsByToken.erase(inputChannel->getToken());
3966
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967 if (connection->monitor) {
3968 removeMonitorChannelLocked(inputChannel);
3969 }
3970
3971 mLooper->removeFd(inputChannel->getFd());
3972
3973 nsecs_t currentTime = now();
3974 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3975
3976 connection->status = Connection::STATUS_ZOMBIE;
3977 return OK;
3978}
3979
3980void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003981 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
3982 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
3983}
3984
Garfield Tane4fc0102019-09-11 13:16:25 -07003985void InputDispatcher::removeMonitorChannelLocked(
3986 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00003987 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tane4fc0102019-09-11 13:16:25 -07003988 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003989 std::vector<Monitor>& monitors = it->second;
3990 const size_t numMonitors = monitors.size();
3991 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tane4fc0102019-09-11 13:16:25 -07003992 if (monitors[i].inputChannel == inputChannel) {
3993 monitors.erase(monitors.begin() + i);
3994 break;
3995 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003996 }
Michael Wright3dd60e22019-03-27 22:06:44 +00003997 if (monitors.empty()) {
3998 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003999 } else {
4000 ++it;
4001 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004002 }
4003}
4004
Michael Wright3dd60e22019-03-27 22:06:44 +00004005status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4006 { // acquire lock
4007 std::scoped_lock _l(mLock);
4008 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4009
4010 if (!foundDisplayId) {
4011 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4012 return BAD_VALUE;
4013 }
4014 int32_t displayId = foundDisplayId.value();
4015
4016 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
4017 if (stateIndex < 0) {
4018 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4019 return BAD_VALUE;
4020 }
4021
4022 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
4023 std::optional<int32_t> foundDeviceId;
4024 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
4025 if (touchedMonitor.monitor.inputChannel->getToken() == token) {
4026 foundDeviceId = state.deviceId;
4027 }
4028 }
4029 if (!foundDeviceId || !state.down) {
4030 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tane4fc0102019-09-11 13:16:25 -07004031 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004032 return BAD_VALUE;
4033 }
4034 int32_t deviceId = foundDeviceId.value();
4035
4036 // Send cancel events to all the input channels we're stealing from.
4037 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tane4fc0102019-09-11 13:16:25 -07004038 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004039 options.deviceId = deviceId;
4040 options.displayId = displayId;
4041 for (const TouchedWindow& window : state.windows) {
4042 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
4043 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4044 }
4045 // Then clear the current touch state so we stop dispatching to them as well.
4046 state.filterNonMonitors();
4047 }
4048 return OK;
4049}
4050
Michael Wright3dd60e22019-03-27 22:06:44 +00004051std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4052 const sp<IBinder>& token) {
4053 for (const auto& it : mGestureMonitorsByDisplay) {
4054 const std::vector<Monitor>& monitors = it.second;
4055 for (const Monitor& monitor : monitors) {
4056 if (monitor.inputChannel->getToken() == token) {
4057 return it.first;
4058 }
4059 }
4060 }
4061 return std::nullopt;
4062}
4063
Michael Wrightd02c5b62014-02-10 15:10:22 -08004064ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07004065 if (inputChannel == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08004066 return -1;
4067 }
4068
Robert Carr4e670e52018-08-15 13:26:12 -07004069 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
4070 sp<Connection> connection = mConnectionsByFd.valueAt(i);
4071 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
4072 return i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004073 }
4074 }
Robert Carr4e670e52018-08-15 13:26:12 -07004075
Michael Wrightd02c5b62014-02-10 15:10:22 -08004076 return -1;
4077}
4078
Garfield Tane4fc0102019-09-11 13:16:25 -07004079void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4080 const sp<Connection>& connection, uint32_t seq,
4081 bool handled) {
4082 CommandEntry* commandEntry =
4083 postCommandLocked(&InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004084 commandEntry->connection = connection;
4085 commandEntry->eventTime = currentTime;
4086 commandEntry->seq = seq;
4087 commandEntry->handled = handled;
4088}
4089
Garfield Tane4fc0102019-09-11 13:16:25 -07004090void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4091 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004092 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tane4fc0102019-09-11 13:16:25 -07004093 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004094
Garfield Tane4fc0102019-09-11 13:16:25 -07004095 CommandEntry* commandEntry =
4096 postCommandLocked(&InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097 commandEntry->connection = connection;
4098}
4099
chaviw0c06c6e2019-01-09 13:27:07 -08004100void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tane4fc0102019-09-11 13:16:25 -07004101 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004102 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4103 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Garfield Tane4fc0102019-09-11 13:16:25 -07004104 CommandEntry* commandEntry =
4105 postCommandLocked(&InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004106 commandEntry->oldToken = oldToken;
4107 commandEntry->newToken = newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004108}
4109
Garfield Tane4fc0102019-09-11 13:16:25 -07004110void InputDispatcher::onANRLocked(nsecs_t currentTime,
4111 const sp<InputApplicationHandle>& applicationHandle,
4112 const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4113 nsecs_t waitStartTime, const char* reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4115 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4116 ALOGI("Application is not responding: %s. "
Garfield Tane4fc0102019-09-11 13:16:25 -07004117 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
4118 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4119 waitDuration, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120
4121 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004122 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123 struct tm tm;
4124 localtime_r(&t, &tm);
4125 char timestr[64];
4126 strftime(timestr, sizeof(timestr), "%F %T", &tm);
4127 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004128 mLastANRState += INDENT "ANR:\n";
4129 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Garfield Tane4fc0102019-09-11 13:16:25 -07004130 mLastANRState +=
4131 StringPrintf(INDENT2 "Window: %s\n",
4132 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004133 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4134 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4135 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136 dumpDispatchStateLocked(mLastANRState);
4137
Garfield Tane4fc0102019-09-11 13:16:25 -07004138 CommandEntry* commandEntry =
4139 postCommandLocked(&InputDispatcher::doNotifyANRLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140 commandEntry->inputApplicationHandle = applicationHandle;
Garfield Tane4fc0102019-09-11 13:16:25 -07004141 commandEntry->inputChannel =
4142 windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004143 commandEntry->reason = reason;
4144}
4145
Garfield Tane4fc0102019-09-11 13:16:25 -07004146void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004147 mLock.unlock();
4148
4149 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4150
4151 mLock.lock();
4152}
4153
Garfield Tane4fc0102019-09-11 13:16:25 -07004154void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155 sp<Connection> connection = commandEntry->connection;
4156
4157 if (connection->status != Connection::STATUS_ZOMBIE) {
4158 mLock.unlock();
4159
Robert Carr803535b2018-08-02 16:38:15 -07004160 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161
4162 mLock.lock();
4163 }
4164}
4165
Garfield Tane4fc0102019-09-11 13:16:25 -07004166void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004167 sp<IBinder> oldToken = commandEntry->oldToken;
4168 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004169 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004170 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004171 mLock.lock();
4172}
4173
Garfield Tane4fc0102019-09-11 13:16:25 -07004174void InputDispatcher::doNotifyANRLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 mLock.unlock();
4176
Garfield Tane4fc0102019-09-11 13:16:25 -07004177 nsecs_t newTimeout =
4178 mPolicy->notifyANR(commandEntry->inputApplicationHandle,
4179 commandEntry->inputChannel ? commandEntry->inputChannel->getToken()
4180 : nullptr,
4181 commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004182
4183 mLock.lock();
4184
Garfield Tane4fc0102019-09-11 13:16:25 -07004185 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186}
4187
4188void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4189 CommandEntry* commandEntry) {
4190 KeyEntry* entry = commandEntry->keyEntry;
4191
4192 KeyEvent event;
4193 initializeKeyEvent(&event, entry);
4194
4195 mLock.unlock();
4196
Michael Wright2b3c3302018-03-02 17:19:13 +00004197 android::base::Timer t;
Garfield Tane4fc0102019-09-11 13:16:25 -07004198 sp<IBinder> token = commandEntry->inputChannel != nullptr
4199 ? commandEntry->inputChannel->getToken()
4200 : nullptr;
4201 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004202 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4203 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tane4fc0102019-09-11 13:16:25 -07004204 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004205 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004206
4207 mLock.lock();
4208
4209 if (delay < 0) {
4210 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4211 } else if (!delay) {
4212 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4213 } else {
4214 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4215 entry->interceptKeyWakeupTime = now() + delay;
4216 }
4217 entry->release();
4218}
4219
chaviwfd6d3512019-03-25 13:23:49 -07004220void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4221 mLock.unlock();
4222 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4223 mLock.lock();
4224}
4225
Garfield Tane4fc0102019-09-11 13:16:25 -07004226void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004227 sp<Connection> connection = commandEntry->connection;
4228 nsecs_t finishTime = commandEntry->eventTime;
4229 uint32_t seq = commandEntry->seq;
4230 bool handled = commandEntry->handled;
4231
4232 // Handle post-event policy actions.
4233 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
4234 if (dispatchEntry) {
4235 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4236 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004237 std::string msg =
4238 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Garfield Tane4fc0102019-09-11 13:16:25 -07004239 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004241 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004242 }
4243
4244 bool restartEvent;
4245 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
4246 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
Garfield Tane4fc0102019-09-11 13:16:25 -07004247 restartEvent =
4248 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004249 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
4250 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
Garfield Tane4fc0102019-09-11 13:16:25 -07004251 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry,
4252 motionEntry, handled);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253 } else {
4254 restartEvent = false;
4255 }
4256
4257 // Dequeue the event and start the next cycle.
4258 // Note that because the lock might have been released, it is possible that the
4259 // contents of the wait queue to have been drained, so we need to double-check
4260 // a few things.
4261 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
4262 connection->waitQueue.dequeue(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004263 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
4265 connection->outboundQueue.enqueueAtHead(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004266 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267 } else {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08004268 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269 }
4270 }
4271
4272 // Start the next dispatch cycle for this connection.
4273 startDispatchCycleLocked(now(), connection);
4274 }
4275}
4276
4277bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tane4fc0102019-09-11 13:16:25 -07004278 DispatchEntry* dispatchEntry,
4279 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004280 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004281 if (!handled) {
4282 // Report the key as unhandled, since the fallback was not handled.
4283 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4284 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004285 return false;
4286 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004288 // Get the fallback key state.
4289 // Clear it out after dispatching the UP.
4290 int32_t originalKeyCode = keyEntry->keyCode;
4291 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4292 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4293 connection->inputState.removeFallbackKey(originalKeyCode);
4294 }
4295
4296 if (handled || !dispatchEntry->hasForegroundTarget()) {
4297 // If the application handles the original key for which we previously
4298 // generated a fallback or if the window is not a foreground window,
4299 // then cancel the associated fallback key, if any.
4300 if (fallbackKeyCode != -1) {
4301 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004303 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tane4fc0102019-09-11 13:16:25 -07004304 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4305 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4306 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307#endif
4308 KeyEvent event;
4309 initializeKeyEvent(&event, keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004310 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311
4312 mLock.unlock();
4313
Garfield Tane4fc0102019-09-11 13:16:25 -07004314 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(), &event,
4315 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316
4317 mLock.lock();
4318
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004319 // Cancel the fallback key.
4320 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004322 "application handled the original non-fallback key "
4323 "or is no longer a foreground target, "
4324 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325 options.keyCode = fallbackKeyCode;
4326 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004328 connection->inputState.removeFallbackKey(originalKeyCode);
4329 }
4330 } else {
4331 // If the application did not handle a non-fallback key, first check
4332 // that we are in a good state to perform unhandled key event processing
4333 // Then ask the policy what to do with it.
Garfield Tane4fc0102019-09-11 13:16:25 -07004334 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004335 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004337 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tane4fc0102019-09-11 13:16:25 -07004338 "since this is not an initial down. "
4339 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4340 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004342 return false;
4343 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004345 // Dispatch the unhandled key to the policy.
4346#if DEBUG_OUTBOUND_EVENT_DETAILS
4347 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tane4fc0102019-09-11 13:16:25 -07004348 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4349 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004350#endif
4351 KeyEvent event;
4352 initializeKeyEvent(&event, keyEntry);
4353
4354 mLock.unlock();
4355
Garfield Tane4fc0102019-09-11 13:16:25 -07004356 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(), &event,
4357 keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004358
4359 mLock.lock();
4360
4361 if (connection->status != Connection::STATUS_NORMAL) {
4362 connection->inputState.removeFallbackKey(originalKeyCode);
4363 return false;
4364 }
4365
4366 // Latch the fallback keycode for this key on an initial down.
4367 // The fallback keycode cannot change at any other point in the lifecycle.
4368 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004370 fallbackKeyCode = event.getKeyCode();
4371 } else {
4372 fallbackKeyCode = AKEYCODE_UNKNOWN;
4373 }
4374 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4375 }
4376
4377 ALOG_ASSERT(fallbackKeyCode != -1);
4378
4379 // Cancel the fallback key if the policy decides not to send it anymore.
4380 // We will continue to dispatch the key to the policy but we will no
4381 // longer dispatch a fallback key to the application.
Garfield Tane4fc0102019-09-11 13:16:25 -07004382 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4383 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004384#if DEBUG_OUTBOUND_EVENT_DETAILS
4385 if (fallback) {
4386 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tane4fc0102019-09-11 13:16:25 -07004387 "as a fallback for %d, but on the DOWN it had requested "
4388 "to send %d instead. Fallback canceled.",
4389 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004390 } else {
4391 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tane4fc0102019-09-11 13:16:25 -07004392 "but on the DOWN it had requested to send %d. "
4393 "Fallback canceled.",
4394 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004395 }
4396#endif
4397
4398 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4399 "canceling fallback, policy no longer desires it");
4400 options.keyCode = fallbackKeyCode;
4401 synthesizeCancelationEventsForConnectionLocked(connection, options);
4402
4403 fallback = false;
4404 fallbackKeyCode = AKEYCODE_UNKNOWN;
4405 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tane4fc0102019-09-11 13:16:25 -07004406 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004407 }
4408 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004409
4410#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004411 {
4412 std::string msg;
4413 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4414 connection->inputState.getFallbackKeys();
4415 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tane4fc0102019-09-11 13:16:25 -07004416 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004417 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004418 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tane4fc0102019-09-11 13:16:25 -07004419 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004420 }
4421#endif
4422
4423 if (fallback) {
4424 // Restart the dispatch cycle using the fallback key.
4425 keyEntry->eventTime = event.getEventTime();
4426 keyEntry->deviceId = event.getDeviceId();
4427 keyEntry->source = event.getSource();
4428 keyEntry->displayId = event.getDisplayId();
4429 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4430 keyEntry->keyCode = fallbackKeyCode;
4431 keyEntry->scanCode = event.getScanCode();
4432 keyEntry->metaState = event.getMetaState();
4433 keyEntry->repeatCount = event.getRepeatCount();
4434 keyEntry->downTime = event.getDownTime();
4435 keyEntry->syntheticRepeat = false;
4436
4437#if DEBUG_OUTBOUND_EVENT_DETAILS
4438 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tane4fc0102019-09-11 13:16:25 -07004439 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4440 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004441#endif
4442 return true; // restart the event
4443 } else {
4444#if DEBUG_OUTBOUND_EVENT_DETAILS
4445 ALOGD("Unhandled key event: No fallback key.");
4446#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004447
4448 // Report the key as unhandled, since there is no fallback key.
4449 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004450 }
4451 }
4452 return false;
4453}
4454
4455bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tane4fc0102019-09-11 13:16:25 -07004456 DispatchEntry* dispatchEntry,
4457 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004458 return false;
4459}
4460
4461void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4462 mLock.unlock();
4463
4464 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4465
4466 mLock.lock();
4467}
4468
4469void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004470 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Garfield Tane4fc0102019-09-11 13:16:25 -07004471 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4472 entry->downTime, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004473}
4474
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004475void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry* entry,
Garfield Tane4fc0102019-09-11 13:16:25 -07004476 int32_t injectionResult,
4477 nsecs_t timeSpentWaitingForApplication) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004478 // TODO Write some statistics about how long we spend waiting.
4479}
4480
4481void InputDispatcher::traceInboundQueueLengthLocked() {
4482 if (ATRACE_ENABLED()) {
4483 ATRACE_INT("iq", mInboundQueue.count());
4484 }
4485}
4486
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004487void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004488 if (ATRACE_ENABLED()) {
4489 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004490 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004491 ATRACE_INT(counterName, connection->outboundQueue.count());
4492 }
4493}
4494
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004495void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004496 if (ATRACE_ENABLED()) {
4497 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004498 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004499 ATRACE_INT(counterName, connection->waitQueue.count());
4500 }
4501}
4502
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004503void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004504 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004505
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004506 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004507 dumpDispatchStateLocked(dump);
4508
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004509 if (!mLastANRState.empty()) {
4510 dump += "\nInput Dispatcher State at time of last ANR:\n";
4511 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004512 }
4513}
4514
4515void InputDispatcher::monitor() {
4516 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004517 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004518 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004519 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004520}
4521
Michael Wrightd02c5b62014-02-10 15:10:22 -08004522// --- InputDispatcher::InjectionState ---
4523
Garfield Tane4fc0102019-09-11 13:16:25 -07004524InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid)
4525 : refCount(1),
4526 injectorPid(injectorPid),
4527 injectorUid(injectorUid),
4528 injectionResult(INPUT_EVENT_INJECTION_PENDING),
4529 injectionIsAsync(false),
4530 pendingForegroundDispatches(0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004531
Garfield Tane4fc0102019-09-11 13:16:25 -07004532InputDispatcher::InjectionState::~InjectionState() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004533
4534void InputDispatcher::InjectionState::release() {
4535 refCount -= 1;
4536 if (refCount == 0) {
4537 delete this;
4538 } else {
4539 ALOG_ASSERT(refCount > 0);
4540 }
4541}
4542
Michael Wrightd02c5b62014-02-10 15:10:22 -08004543// --- InputDispatcher::EventEntry ---
4544
Garfield Tane4fc0102019-09-11 13:16:25 -07004545InputDispatcher::EventEntry::EventEntry(uint32_t sequenceNum, int32_t type, nsecs_t eventTime,
4546 uint32_t policyFlags)
4547 : sequenceNum(sequenceNum),
4548 refCount(1),
4549 type(type),
4550 eventTime(eventTime),
4551 policyFlags(policyFlags),
4552 injectionState(nullptr),
4553 dispatchInProgress(false) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554
4555InputDispatcher::EventEntry::~EventEntry() {
4556 releaseInjectionState();
4557}
4558
4559void InputDispatcher::EventEntry::release() {
4560 refCount -= 1;
4561 if (refCount == 0) {
4562 delete this;
4563 } else {
4564 ALOG_ASSERT(refCount > 0);
4565 }
4566}
4567
4568void InputDispatcher::EventEntry::releaseInjectionState() {
4569 if (injectionState) {
4570 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004571 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572 }
4573}
4574
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575// --- InputDispatcher::ConfigurationChangedEntry ---
4576
Garfield Tane4fc0102019-09-11 13:16:25 -07004577InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(uint32_t sequenceNum,
4578 nsecs_t eventTime)
4579 : EventEntry(sequenceNum, TYPE_CONFIGURATION_CHANGED, eventTime, 0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004580
Garfield Tane4fc0102019-09-11 13:16:25 -07004581InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004582
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004583void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4584 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004585}
4586
Michael Wrightd02c5b62014-02-10 15:10:22 -08004587// --- InputDispatcher::DeviceResetEntry ---
4588
Garfield Tane4fc0102019-09-11 13:16:25 -07004589InputDispatcher::DeviceResetEntry::DeviceResetEntry(uint32_t sequenceNum, nsecs_t eventTime,
4590 int32_t deviceId)
4591 : EventEntry(sequenceNum, TYPE_DEVICE_RESET, eventTime, 0), deviceId(deviceId) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004592
Garfield Tane4fc0102019-09-11 13:16:25 -07004593InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004594
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004595void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
Garfield Tane4fc0102019-09-11 13:16:25 -07004596 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x", deviceId, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004597}
4598
Michael Wrightd02c5b62014-02-10 15:10:22 -08004599// --- InputDispatcher::KeyEntry ---
4600
Garfield Tane4fc0102019-09-11 13:16:25 -07004601InputDispatcher::KeyEntry::KeyEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId,
4602 uint32_t source, int32_t displayId, uint32_t policyFlags,
4603 int32_t action, int32_t flags, int32_t keyCode,
4604 int32_t scanCode, int32_t metaState, int32_t repeatCount,
4605 nsecs_t downTime)
4606 : EventEntry(sequenceNum, TYPE_KEY, eventTime, policyFlags),
4607 deviceId(deviceId),
4608 source(source),
4609 displayId(displayId),
4610 action(action),
4611 flags(flags),
4612 keyCode(keyCode),
4613 scanCode(scanCode),
4614 metaState(metaState),
4615 repeatCount(repeatCount),
4616 downTime(downTime),
4617 syntheticRepeat(false),
4618 interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4619 interceptKeyWakeupTime(0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004620
Garfield Tane4fc0102019-09-11 13:16:25 -07004621InputDispatcher::KeyEntry::~KeyEntry() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004622
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004623void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004624 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Garfield Tane4fc0102019-09-11 13:16:25 -07004625 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4626 "repeatCount=%d), policyFlags=0x%08x",
4627 deviceId, source, displayId, keyActionToString(action).c_str(), flags,
4628 keyCode, scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004629}
4630
4631void InputDispatcher::KeyEntry::recycle() {
4632 releaseInjectionState();
4633
4634 dispatchInProgress = false;
4635 syntheticRepeat = false;
4636 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4637 interceptKeyWakeupTime = 0;
4638}
4639
Michael Wrightd02c5b62014-02-10 15:10:22 -08004640// --- InputDispatcher::MotionEntry ---
4641
Garfield Tane4fc0102019-09-11 13:16:25 -07004642InputDispatcher::MotionEntry::MotionEntry(
4643 uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId, uint32_t source,
4644 int32_t displayId, uint32_t policyFlags, int32_t action, int32_t actionButton,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004645 int32_t flags, int32_t metaState, int32_t buttonState, MotionClassification classification,
4646 int32_t edgeFlags, float xPrecision, float yPrecision, nsecs_t downTime,
Garfield Tane4fc0102019-09-11 13:16:25 -07004647 uint32_t pointerCount, const PointerProperties* pointerProperties,
4648 const PointerCoords* pointerCoords, float xOffset, float yOffset)
4649 : EventEntry(sequenceNum, TYPE_MOTION, eventTime, policyFlags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004650 eventTime(eventTime),
Garfield Tane4fc0102019-09-11 13:16:25 -07004651 deviceId(deviceId),
4652 source(source),
4653 displayId(displayId),
4654 action(action),
4655 actionButton(actionButton),
4656 flags(flags),
4657 metaState(metaState),
4658 buttonState(buttonState),
4659 classification(classification),
4660 edgeFlags(edgeFlags),
4661 xPrecision(xPrecision),
4662 yPrecision(yPrecision),
4663 downTime(downTime),
4664 pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004665 for (uint32_t i = 0; i < pointerCount; i++) {
4666 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4667 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004668 if (xOffset || yOffset) {
4669 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4670 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004671 }
4672}
4673
Garfield Tane4fc0102019-09-11 13:16:25 -07004674InputDispatcher::MotionEntry::~MotionEntry() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004675
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004676void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004677 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Garfield Tane4fc0102019-09-11 13:16:25 -07004678 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, "
4679 "buttonState=0x%08x, "
4680 "classification=%s, edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, "
4681 "pointers=[",
4682 deviceId, source, displayId, motionActionToString(action).c_str(),
4683 actionButton, flags, metaState, buttonState,
4684 motionClassificationToString(classification), edgeFlags, xPrecision,
4685 yPrecision);
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004686
Michael Wrightd02c5b62014-02-10 15:10:22 -08004687 for (uint32_t i = 0; i < pointerCount; i++) {
4688 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004689 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004690 }
Garfield Tane4fc0102019-09-11 13:16:25 -07004691 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id, pointerCoords[i].getX(),
4692 pointerCoords[i].getY());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004693 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004694 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004695}
4696
Michael Wrightd02c5b62014-02-10 15:10:22 -08004697// --- InputDispatcher::DispatchEntry ---
4698
4699volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4700
Garfield Tane4fc0102019-09-11 13:16:25 -07004701InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry, int32_t targetFlags,
4702 float xOffset, float yOffset, float globalScaleFactor,
4703 float windowXScale, float windowYScale)
4704 : seq(nextSeq()),
4705 eventEntry(eventEntry),
4706 targetFlags(targetFlags),
4707 xOffset(xOffset),
4708 yOffset(yOffset),
4709 globalScaleFactor(globalScaleFactor),
4710 windowXScale(windowXScale),
4711 windowYScale(windowYScale),
4712 deliveryTime(0),
4713 resolvedAction(0),
4714 resolvedFlags(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004715 eventEntry->refCount += 1;
4716}
4717
4718InputDispatcher::DispatchEntry::~DispatchEntry() {
4719 eventEntry->release();
4720}
4721
4722uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4723 // Sequence number 0 is reserved and will never be returned.
4724 uint32_t seq;
4725 do {
4726 seq = android_atomic_inc(&sNextSeqAtomic);
4727 } while (!seq);
4728 return seq;
4729}
4730
Michael Wrightd02c5b62014-02-10 15:10:22 -08004731// --- InputDispatcher::InputState ---
4732
Garfield Tane4fc0102019-09-11 13:16:25 -07004733InputDispatcher::InputState::InputState() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004734
Garfield Tane4fc0102019-09-11 13:16:25 -07004735InputDispatcher::InputState::~InputState() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004736
4737bool InputDispatcher::InputState::isNeutral() const {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004738 return mKeyMementos.empty() && mMotionMementos.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004739}
4740
4741bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
Garfield Tane4fc0102019-09-11 13:16:25 -07004742 int32_t displayId) const {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004743 for (const MotionMemento& memento : mMotionMementos) {
Garfield Tane4fc0102019-09-11 13:16:25 -07004744 if (memento.deviceId == deviceId && memento.source == source &&
4745 memento.displayId == displayId && memento.hovering) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004746 return true;
4747 }
4748 }
4749 return false;
4750}
4751
Garfield Tane4fc0102019-09-11 13:16:25 -07004752bool InputDispatcher::InputState::trackKey(const KeyEntry* entry, int32_t action, int32_t flags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753 switch (action) {
Garfield Tane4fc0102019-09-11 13:16:25 -07004754 case AKEY_EVENT_ACTION_UP: {
4755 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4756 for (size_t i = 0; i < mFallbackKeys.size();) {
4757 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4758 mFallbackKeys.removeItemsAt(i);
4759 } else {
4760 i += 1;
4761 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004762 }
4763 }
Garfield Tane4fc0102019-09-11 13:16:25 -07004764 ssize_t index = findKeyMemento(entry);
4765 if (index >= 0) {
4766 mKeyMementos.erase(mKeyMementos.begin() + index);
4767 return true;
4768 }
4769 /* FIXME: We can't just drop the key up event because that prevents creating
4770 * popup windows that are automatically shown when a key is held and then
4771 * dismissed when the key is released. The problem is that the popup will
4772 * not have received the original key down, so the key up will be considered
4773 * to be inconsistent with its observed state. We could perhaps handle this
4774 * by synthesizing a key down but that will cause other problems.
4775 *
4776 * So for now, allow inconsistent key up events to be dispatched.
4777 *
4778 #if DEBUG_OUTBOUND_EVENT_DETAILS
4779 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4780 "keyCode=%d, scanCode=%d",
4781 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4782 #endif
4783 return false;
4784 */
Michael Wrightd02c5b62014-02-10 15:10:22 -08004785 return true;
4786 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004787
Garfield Tane4fc0102019-09-11 13:16:25 -07004788 case AKEY_EVENT_ACTION_DOWN: {
4789 ssize_t index = findKeyMemento(entry);
4790 if (index >= 0) {
4791 mKeyMementos.erase(mKeyMementos.begin() + index);
4792 }
4793 addKeyMemento(entry, flags);
4794 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004795 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004796
Garfield Tane4fc0102019-09-11 13:16:25 -07004797 default:
4798 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004799 }
4800}
4801
Garfield Tane4fc0102019-09-11 13:16:25 -07004802bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry, int32_t action,
4803 int32_t flags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004804 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4805 switch (actionMasked) {
Garfield Tane4fc0102019-09-11 13:16:25 -07004806 case AMOTION_EVENT_ACTION_UP:
4807 case AMOTION_EVENT_ACTION_CANCEL: {
4808 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004809 if (index >= 0) {
Garfield Tane4fc0102019-09-11 13:16:25 -07004810 mMotionMementos.erase(mMotionMementos.begin() + index);
4811 return true;
4812 }
4813#if DEBUG_OUTBOUND_EVENT_DETAILS
4814 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
4815 "displayId=%" PRId32 ", actionMasked=%d",
4816 entry->deviceId, entry->source, entry->displayId, actionMasked);
4817#endif
4818 return false;
4819 }
4820
4821 case AMOTION_EVENT_ACTION_DOWN: {
4822 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4823 if (index >= 0) {
4824 mMotionMementos.erase(mMotionMementos.begin() + index);
4825 }
4826 addMotionMemento(entry, flags, false /*hovering*/);
4827 return true;
4828 }
4829
4830 case AMOTION_EVENT_ACTION_POINTER_UP:
4831 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4832 case AMOTION_EVENT_ACTION_MOVE: {
4833 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4834 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need
4835 // to generate cancellation events for these since they're based in relative rather
4836 // than absolute units.
4837 return true;
Michael Wright38dcdff2014-03-19 12:06:10 -07004838 }
4839
Garfield Tane4fc0102019-09-11 13:16:25 -07004840 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4841
4842 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4843 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4844 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral.
4845 // Any other value and we need to track the motion so we can send cancellation
4846 // events for anything generating fallback events (e.g. DPad keys for joystick
4847 // movements).
4848 if (index >= 0) {
4849 if (entry->pointerCoords[0].isEmpty()) {
4850 mMotionMementos.erase(mMotionMementos.begin() + index);
4851 } else {
4852 MotionMemento& memento = mMotionMementos[index];
4853 memento.setPointers(entry);
4854 }
4855 } else if (!entry->pointerCoords[0].isEmpty()) {
4856 addMotionMemento(entry, flags, false /*hovering*/);
4857 }
4858
4859 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4860 return true;
4861 }
4862 if (index >= 0) {
4863 MotionMemento& memento = mMotionMementos[index];
4864 memento.setPointers(entry);
4865 return true;
4866 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867#if DEBUG_OUTBOUND_EVENT_DETAILS
Garfield Tane4fc0102019-09-11 13:16:25 -07004868 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
4869 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4870 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871#endif
Garfield Tane4fc0102019-09-11 13:16:25 -07004872 return false;
4873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004874
Garfield Tane4fc0102019-09-11 13:16:25 -07004875 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4876 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4877 if (index >= 0) {
4878 mMotionMementos.erase(mMotionMementos.begin() + index);
4879 return true;
4880 }
4881#if DEBUG_OUTBOUND_EVENT_DETAILS
4882 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4883 "displayId=%" PRId32,
4884 entry->deviceId, entry->source, entry->displayId);
4885#endif
4886 return false;
4887 }
4888
4889 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4890 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4891 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4892 if (index >= 0) {
4893 mMotionMementos.erase(mMotionMementos.begin() + index);
4894 }
4895 addMotionMemento(entry, flags, true /*hovering*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004896 return true;
4897 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004898
Garfield Tane4fc0102019-09-11 13:16:25 -07004899 default:
4900 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004901 }
4902}
4903
4904ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4905 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004906 const KeyMemento& memento = mKeyMementos[i];
Garfield Tane4fc0102019-09-11 13:16:25 -07004907 if (memento.deviceId == entry->deviceId && memento.source == entry->source &&
4908 memento.displayId == entry->displayId && memento.keyCode == entry->keyCode &&
4909 memento.scanCode == entry->scanCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004910 return i;
4911 }
4912 }
4913 return -1;
4914}
4915
4916ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
Garfield Tane4fc0102019-09-11 13:16:25 -07004917 bool hovering) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004918 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004919 const MotionMemento& memento = mMotionMementos[i];
Garfield Tane4fc0102019-09-11 13:16:25 -07004920 if (memento.deviceId == entry->deviceId && memento.source == entry->source &&
4921 memento.displayId == entry->displayId && memento.hovering == hovering) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922 return i;
4923 }
4924 }
4925 return -1;
4926}
4927
4928void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004929 KeyMemento memento;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004930 memento.deviceId = entry->deviceId;
4931 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004932 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004933 memento.keyCode = entry->keyCode;
4934 memento.scanCode = entry->scanCode;
4935 memento.metaState = entry->metaState;
4936 memento.flags = flags;
4937 memento.downTime = entry->downTime;
4938 memento.policyFlags = entry->policyFlags;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004939 mKeyMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004940}
4941
Garfield Tane4fc0102019-09-11 13:16:25 -07004942void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry, int32_t flags,
4943 bool hovering) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004944 MotionMemento memento;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004945 memento.deviceId = entry->deviceId;
4946 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004947 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004948 memento.flags = flags;
4949 memento.xPrecision = entry->xPrecision;
4950 memento.yPrecision = entry->yPrecision;
4951 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004952 memento.setPointers(entry);
4953 memento.hovering = hovering;
4954 memento.policyFlags = entry->policyFlags;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004955 mMotionMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004956}
4957
4958void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4959 pointerCount = entry->pointerCount;
4960 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4961 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4962 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4963 }
4964}
4965
4966void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Garfield Tane4fc0102019-09-11 13:16:25 -07004967 std::vector<EventEntry*>& outEvents,
4968 const CancelationOptions& options) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004969 for (KeyMemento& memento : mKeyMementos) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004970 if (shouldCancelKey(memento, options)) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004971 outEvents.push_back(new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Garfield Tane4fc0102019-09-11 13:16:25 -07004972 memento.deviceId, memento.source, memento.displayId,
4973 memento.policyFlags, AKEY_EVENT_ACTION_UP,
4974 memento.flags | AKEY_EVENT_FLAG_CANCELED,
4975 memento.keyCode, memento.scanCode, memento.metaState,
4976 0, memento.downTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004977 }
4978 }
4979
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004980 for (const MotionMemento& memento : mMotionMementos) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004981 if (shouldCancelMotion(memento, options)) {
Garfield Tane4fc0102019-09-11 13:16:25 -07004982 const int32_t action = memento.hovering ? AMOTION_EVENT_ACTION_HOVER_EXIT
4983 : AMOTION_EVENT_ACTION_CANCEL;
4984 outEvents.push_back(
4985 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime, memento.deviceId,
4986 memento.source, memento.displayId, memento.policyFlags, action,
4987 0 /*actionButton*/, memento.flags, AMETA_NONE,
4988 0 /*buttonState*/, MotionClassification::NONE,
4989 AMOTION_EVENT_EDGE_FLAG_NONE, memento.xPrecision,
4990 memento.yPrecision, memento.downTime, memento.pointerCount,
4991 memento.pointerProperties, memento.pointerCoords, 0 /*xOffset*/,
4992 0 /*yOffset*/));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004993 }
4994 }
4995}
4996
4997void InputDispatcher::InputState::clear() {
4998 mKeyMementos.clear();
4999 mMotionMementos.clear();
5000 mFallbackKeys.clear();
5001}
5002
5003void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
5004 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005005 const MotionMemento& memento = mMotionMementos[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005006 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tane4fc0102019-09-11 13:16:25 -07005007 for (size_t j = 0; j < other.mMotionMementos.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005008 const MotionMemento& otherMemento = other.mMotionMementos[j];
Garfield Tane4fc0102019-09-11 13:16:25 -07005009 if (memento.deviceId == otherMemento.deviceId &&
5010 memento.source == otherMemento.source &&
5011 memento.displayId == otherMemento.displayId) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005012 other.mMotionMementos.erase(other.mMotionMementos.begin() + j);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005013 } else {
5014 j += 1;
5015 }
5016 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005017 other.mMotionMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005018 }
5019 }
5020}
5021
5022int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
5023 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
5024 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
5025}
5026
Garfield Tane4fc0102019-09-11 13:16:25 -07005027void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode, int32_t fallbackKeyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005028 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
5029 if (index >= 0) {
5030 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
5031 } else {
5032 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
5033 }
5034}
5035
5036void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
5037 mFallbackKeys.removeItem(originalKeyCode);
5038}
5039
5040bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Garfield Tane4fc0102019-09-11 13:16:25 -07005041 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005042 if (options.keyCode && memento.keyCode != options.keyCode.value()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005043 return false;
5044 }
5045
Michael Wright3dd60e22019-03-27 22:06:44 +00005046 if (options.deviceId && memento.deviceId != options.deviceId.value()) {
5047 return false;
5048 }
5049
5050 if (options.displayId && memento.displayId != options.displayId.value()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005051 return false;
5052 }
5053
5054 switch (options.mode) {
Garfield Tane4fc0102019-09-11 13:16:25 -07005055 case CancelationOptions::CANCEL_ALL_EVENTS:
5056 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
5057 return true;
5058 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
5059 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
5060 default:
5061 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005062 }
5063}
5064
Garfield Tane4fc0102019-09-11 13:16:25 -07005065bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
5066 const CancelationOptions& options) {
5067 if (options.deviceId && memento.deviceId != options.deviceId.value()) {
5068 return false;
5069 }
5070
5071 if (options.displayId && memento.displayId != options.displayId.value()) {
5072 return false;
5073 }
5074
5075 switch (options.mode) {
5076 case CancelationOptions::CANCEL_ALL_EVENTS:
5077 return true;
5078 case CancelationOptions::CANCEL_POINTER_EVENTS:
5079 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
5080 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
5081 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
5082 default:
5083 return false;
5084 }
5085}
Michael Wrightd02c5b62014-02-10 15:10:22 -08005086
5087// --- InputDispatcher::Connection ---
5088
Garfield Tane4fc0102019-09-11 13:16:25 -07005089InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor)
5090 : status(STATUS_NORMAL),
5091 inputChannel(inputChannel),
Michael Wrightd02c5b62014-02-10 15:10:22 -08005092 monitor(monitor),
Garfield Tane4fc0102019-09-11 13:16:25 -07005093 inputPublisher(inputChannel),
5094 inputPublisherBlocked(false) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08005095
Garfield Tane4fc0102019-09-11 13:16:25 -07005096InputDispatcher::Connection::~Connection() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08005097
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005098const std::string InputDispatcher::Connection::getWindowName() const {
Robert Carr803535b2018-08-02 16:38:15 -07005099 if (inputChannel != nullptr) {
5100 return inputChannel->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005101 }
5102 if (monitor) {
5103 return "monitor";
5104 }
5105 return "?";
5106}
5107
5108const char* InputDispatcher::Connection::getStatusLabel() const {
5109 switch (status) {
Garfield Tane4fc0102019-09-11 13:16:25 -07005110 case STATUS_NORMAL:
5111 return "NORMAL";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005112
Garfield Tane4fc0102019-09-11 13:16:25 -07005113 case STATUS_BROKEN:
5114 return "BROKEN";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005115
Garfield Tane4fc0102019-09-11 13:16:25 -07005116 case STATUS_ZOMBIE:
5117 return "ZOMBIE";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005118
Garfield Tane4fc0102019-09-11 13:16:25 -07005119 default:
5120 return "UNKNOWN";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005121 }
5122}
5123
5124InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07005125 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005126 if (entry->seq == seq) {
5127 return entry;
5128 }
5129 }
Yi Kong9b14ac62018-07-17 13:48:38 -07005130 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005131}
5132
Michael Wright3dd60e22019-03-27 22:06:44 +00005133// --- InputDispatcher::Monitor
Garfield Tane4fc0102019-09-11 13:16:25 -07005134InputDispatcher::Monitor::Monitor(const sp<InputChannel>& inputChannel)
5135 : inputChannel(inputChannel) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08005136
5137// --- InputDispatcher::CommandEntry ---
Michael Wright3dd60e22019-03-27 22:06:44 +00005138//
Garfield Tane4fc0102019-09-11 13:16:25 -07005139InputDispatcher::CommandEntry::CommandEntry(Command command)
5140 : command(command),
5141 eventTime(0),
5142 keyEntry(nullptr),
5143 userActivityEventType(0),
5144 seq(0),
5145 handled(false) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146
Garfield Tane4fc0102019-09-11 13:16:25 -07005147InputDispatcher::CommandEntry::~CommandEntry() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08005148
Michael Wright3dd60e22019-03-27 22:06:44 +00005149// --- InputDispatcher::TouchedMonitor ---
5150InputDispatcher::TouchedMonitor::TouchedMonitor(const Monitor& monitor, float xOffset,
Garfield Tane4fc0102019-09-11 13:16:25 -07005151 float yOffset)
5152 : monitor(monitor), xOffset(xOffset), yOffset(yOffset) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08005153
5154// --- InputDispatcher::TouchState ---
5155
Garfield Tane4fc0102019-09-11 13:16:25 -07005156InputDispatcher::TouchState::TouchState()
5157 : down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08005158
Garfield Tane4fc0102019-09-11 13:16:25 -07005159InputDispatcher::TouchState::~TouchState() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08005160
5161void InputDispatcher::TouchState::reset() {
5162 down = false;
5163 split = false;
5164 deviceId = -1;
5165 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01005166 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005167 windows.clear();
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005168 portalWindows.clear();
Michael Wright3dd60e22019-03-27 22:06:44 +00005169 gestureMonitors.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005170}
5171
5172void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
5173 down = other.down;
5174 split = other.split;
5175 deviceId = other.deviceId;
5176 source = other.source;
5177 displayId = other.displayId;
5178 windows = other.windows;
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005179 portalWindows = other.portalWindows;
Michael Wright3dd60e22019-03-27 22:06:44 +00005180 gestureMonitors = other.gestureMonitors;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005181}
5182
5183void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
Garfield Tane4fc0102019-09-11 13:16:25 -07005184 int32_t targetFlags, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005185 if (targetFlags & InputTarget::FLAG_SPLIT) {
5186 split = true;
5187 }
5188
5189 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005190 TouchedWindow& touchedWindow = windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005191 if (touchedWindow.windowHandle == windowHandle) {
5192 touchedWindow.targetFlags |= targetFlags;
5193 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
5194 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
5195 }
5196 touchedWindow.pointerIds.value |= pointerIds.value;
5197 return;
5198 }
5199 }
5200
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005201 TouchedWindow touchedWindow;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005202 touchedWindow.windowHandle = windowHandle;
5203 touchedWindow.targetFlags = targetFlags;
5204 touchedWindow.pointerIds = pointerIds;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005205 windows.push_back(touchedWindow);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005206}
5207
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005208void InputDispatcher::TouchState::addPortalWindow(const sp<InputWindowHandle>& windowHandle) {
5209 size_t numWindows = portalWindows.size();
5210 for (size_t i = 0; i < numWindows; i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005211 if (portalWindows[i] == windowHandle) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005212 return;
5213 }
5214 }
5215 portalWindows.push_back(windowHandle);
5216}
5217
Michael Wright3dd60e22019-03-27 22:06:44 +00005218void InputDispatcher::TouchState::addGestureMonitors(
5219 const std::vector<TouchedMonitor>& newMonitors) {
5220 const size_t newSize = gestureMonitors.size() + newMonitors.size();
5221 gestureMonitors.reserve(newSize);
Garfield Tane4fc0102019-09-11 13:16:25 -07005222 gestureMonitors.insert(std::end(gestureMonitors), std::begin(newMonitors),
5223 std::end(newMonitors));
Michael Wright3dd60e22019-03-27 22:06:44 +00005224}
5225
Michael Wrightd02c5b62014-02-10 15:10:22 -08005226void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
5227 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005228 if (windows[i].windowHandle == windowHandle) {
5229 windows.erase(windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005230 return;
5231 }
5232 }
5233}
5234
Robert Carr803535b2018-08-02 16:38:15 -07005235void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) {
5236 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005237 if (windows[i].windowHandle->getToken() == token) {
5238 windows.erase(windows.begin() + i);
Robert Carr803535b2018-08-02 16:38:15 -07005239 return;
5240 }
5241 }
5242}
5243
Michael Wrightd02c5b62014-02-10 15:10:22 -08005244void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Garfield Tane4fc0102019-09-11 13:16:25 -07005245 for (size_t i = 0; i < windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005246 TouchedWindow& window = windows[i];
Garfield Tane4fc0102019-09-11 13:16:25 -07005247 if (window.targetFlags &
5248 (InputTarget::FLAG_DISPATCH_AS_IS | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005249 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
5250 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
5251 i += 1;
5252 } else {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005253 windows.erase(windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005254 }
5255 }
5256}
5257
Michael Wright3dd60e22019-03-27 22:06:44 +00005258void InputDispatcher::TouchState::filterNonMonitors() {
5259 windows.clear();
5260 portalWindows.clear();
5261}
5262
Michael Wrightd02c5b62014-02-10 15:10:22 -08005263sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
5264 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005265 const TouchedWindow& window = windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005266 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5267 return window.windowHandle;
5268 }
5269 }
Yi Kong9b14ac62018-07-17 13:48:38 -07005270 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005271}
5272
5273bool InputDispatcher::TouchState::isSlippery() const {
5274 // Must have exactly one foreground window.
5275 bool haveSlipperyForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005276 for (const TouchedWindow& window : windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005277 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Garfield Tane4fc0102019-09-11 13:16:25 -07005278 if (haveSlipperyForegroundWindow ||
5279 !(window.windowHandle->getInfo()->layoutParamsFlags &
5280 InputWindowInfo::FLAG_SLIPPERY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005281 return false;
5282 }
5283 haveSlipperyForegroundWindow = true;
5284 }
5285 }
5286 return haveSlipperyForegroundWindow;
5287}
5288
Michael Wrightd02c5b62014-02-10 15:10:22 -08005289// --- InputDispatcherThread ---
5290
Garfield Tane4fc0102019-09-11 13:16:25 -07005291InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher)
5292 : Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08005293
Garfield Tane4fc0102019-09-11 13:16:25 -07005294InputDispatcherThread::~InputDispatcherThread() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08005295
5296bool InputDispatcherThread::threadLoop() {
5297 mDispatcher->dispatchOnce();
5298 return true;
5299}
5300
5301} // namespace android