1 /*
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
20 #define LOG_NDEBUG 1
21
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 static constexpr bool DEBUG_FOCUS = false;
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
48 #include "Connection.h"
49
50 #include <errno.h>
51 #include <inttypes.h>
52 #include <limits.h>
53 #include <statslog.h>
54 #include <stddef.h>
55 #include <time.h>
56 #include <unistd.h>
57 #include <queue>
58 #include <sstream>
59
60 #include <android-base/chrono_utils.h>
61 #include <android-base/stringprintf.h>
62 #include <binder/Binder.h>
63 #include <input/InputDevice.h>
64 #include <log/log.h>
65 #include <openssl/hmac.h>
66 #include <openssl/rand.h>
67 #include <powermanager/PowerManager.h>
68 #include <utils/Trace.h>
69
70 #define INDENT " "
71 #define INDENT2 " "
72 #define INDENT3 " "
73 #define INDENT4 " "
74
75 using android::base::StringPrintf;
76
77 namespace android::inputdispatcher {
78
79 // Default input dispatching timeout if there is no focused application or paused window
80 // from which to determine an appropriate dispatching timeout.
81 constexpr std::chrono::nanoseconds DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5s;
82
83 // Amount of time to allow for all pending events to be processed when an app switch
84 // key is on the way. This is used to preempt input dispatch and drop input events
85 // when an application takes too long to respond and the user has pressed an app switch key.
86 constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
87
88 // Amount of time to allow for an event to be dispatched (measured since its eventTime)
89 // before considering it stale and dropping it.
90 constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
91
92 // Log a warning when an event takes longer than this to process, even if an ANR does not occur.
93 constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
94
95 // Log a warning when an interception call takes longer than this to process.
96 constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
97
98 // Additional key latency in case a connection is still processing some motion events.
99 // This will help with the case when a user touched a button that opens a new window,
100 // and gives us the chance to dispatch the key to this new window.
101 constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
102
103 // Number of recent events to keep for debugging purposes.
104 constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
105
now()106 static inline nsecs_t now() {
107 return systemTime(SYSTEM_TIME_MONOTONIC);
108 }
109
toString(bool value)110 static inline const char* toString(bool value) {
111 return value ? "true" : "false";
112 }
113
getMotionEventActionPointerIndex(int32_t action)114 static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
115 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
116 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
117 }
118
isValidKeyAction(int32_t action)119 static bool isValidKeyAction(int32_t action) {
120 switch (action) {
121 case AKEY_EVENT_ACTION_DOWN:
122 case AKEY_EVENT_ACTION_UP:
123 return true;
124 default:
125 return false;
126 }
127 }
128
validateKeyEvent(int32_t action)129 static bool validateKeyEvent(int32_t action) {
130 if (!isValidKeyAction(action)) {
131 ALOGE("Key event has invalid action code 0x%x", action);
132 return false;
133 }
134 return true;
135 }
136
isValidMotionAction(int32_t action,int32_t actionButton,int32_t pointerCount)137 static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
138 switch (action & AMOTION_EVENT_ACTION_MASK) {
139 case AMOTION_EVENT_ACTION_DOWN:
140 case AMOTION_EVENT_ACTION_UP:
141 case AMOTION_EVENT_ACTION_CANCEL:
142 case AMOTION_EVENT_ACTION_MOVE:
143 case AMOTION_EVENT_ACTION_OUTSIDE:
144 case AMOTION_EVENT_ACTION_HOVER_ENTER:
145 case AMOTION_EVENT_ACTION_HOVER_MOVE:
146 case AMOTION_EVENT_ACTION_HOVER_EXIT:
147 case AMOTION_EVENT_ACTION_SCROLL:
148 return true;
149 case AMOTION_EVENT_ACTION_POINTER_DOWN:
150 case AMOTION_EVENT_ACTION_POINTER_UP: {
151 int32_t index = getMotionEventActionPointerIndex(action);
152 return index >= 0 && index < pointerCount;
153 }
154 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
155 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
156 return actionButton != 0;
157 default:
158 return false;
159 }
160 }
161
validateMotionEvent(int32_t action,int32_t actionButton,size_t pointerCount,const PointerProperties * pointerProperties)162 static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
163 const PointerProperties* pointerProperties) {
164 if (!isValidMotionAction(action, actionButton, pointerCount)) {
165 ALOGE("Motion event has invalid action code 0x%x", action);
166 return false;
167 }
168 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
169 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
170 pointerCount, MAX_POINTERS);
171 return false;
172 }
173 BitSet32 pointerIdBits;
174 for (size_t i = 0; i < pointerCount; i++) {
175 int32_t id = pointerProperties[i].id;
176 if (id < 0 || id > MAX_POINTER_ID) {
177 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
178 MAX_POINTER_ID);
179 return false;
180 }
181 if (pointerIdBits.hasBit(id)) {
182 ALOGE("Motion event has duplicate pointer id %d", id);
183 return false;
184 }
185 pointerIdBits.markBit(id);
186 }
187 return true;
188 }
189
dumpRegion(std::string & dump,const Region & region)190 static void dumpRegion(std::string& dump, const Region& region) {
191 if (region.isEmpty()) {
192 dump += "<empty>";
193 return;
194 }
195
196 bool first = true;
197 Region::const_iterator cur = region.begin();
198 Region::const_iterator const tail = region.end();
199 while (cur != tail) {
200 if (first) {
201 first = false;
202 } else {
203 dump += "|";
204 }
205 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
206 cur++;
207 }
208 }
209
210 /**
211 * Find the entry in std::unordered_map by key, and return it.
212 * If the entry is not found, return a default constructed entry.
213 *
214 * Useful when the entries are vectors, since an empty vector will be returned
215 * if the entry is not found.
216 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
217 */
218 template <typename K, typename V>
getValueByKey(const std::unordered_map<K,V> & map,K key)219 static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
220 auto it = map.find(key);
221 return it != map.end() ? it->second : V{};
222 }
223
224 /**
225 * Find the entry in std::unordered_map by value, and remove it.
226 * If more than one entry has the same value, then all matching
227 * key-value pairs will be removed.
228 *
229 * Return true if at least one value has been removed.
230 */
231 template <typename K, typename V>
removeByValue(std::unordered_map<K,V> & map,const V & value)232 static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
233 bool removed = false;
234 for (auto it = map.begin(); it != map.end();) {
235 if (it->second == value) {
236 it = map.erase(it);
237 removed = true;
238 } else {
239 it++;
240 }
241 }
242 return removed;
243 }
244
haveSameToken(const sp<InputWindowHandle> & first,const sp<InputWindowHandle> & second)245 static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
246 if (first == second) {
247 return true;
248 }
249
250 if (first == nullptr || second == nullptr) {
251 return false;
252 }
253
254 return first->getToken() == second->getToken();
255 }
256
isStaleEvent(nsecs_t currentTime,const EventEntry & entry)257 static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
258 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
259 }
260
createDispatchEntry(const InputTarget & inputTarget,EventEntry * eventEntry,int32_t inputTargetFlags)261 static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
262 EventEntry* eventEntry,
263 int32_t inputTargetFlags) {
264 if (inputTarget.useDefaultPointerInfo()) {
265 const PointerInfo& pointerInfo = inputTarget.getDefaultPointerInfo();
266 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
267 inputTargetFlags, pointerInfo.xOffset,
268 pointerInfo.yOffset, inputTarget.globalScaleFactor,
269 pointerInfo.windowXScale, pointerInfo.windowYScale);
270 }
271
272 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
273 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
274
275 PointerCoords pointerCoords[motionEntry.pointerCount];
276
277 // Use the first pointer information to normalize all other pointers. This could be any pointer
278 // as long as all other pointers are normalized to the same value and the final DispatchEntry
279 // uses the offset and scale for the normalized pointer.
280 const PointerInfo& firstPointerInfo =
281 inputTarget.pointerInfos[inputTarget.pointerIds.firstMarkedBit()];
282
283 // Iterate through all pointers in the event to normalize against the first.
284 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
285 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
286 uint32_t pointerId = uint32_t(pointerProperties.id);
287 const PointerInfo& currPointerInfo = inputTarget.pointerInfos[pointerId];
288
289 // The scale factor is the ratio of the current pointers scale to the normalized scale.
290 float scaleXDiff = currPointerInfo.windowXScale / firstPointerInfo.windowXScale;
291 float scaleYDiff = currPointerInfo.windowYScale / firstPointerInfo.windowYScale;
292
293 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
294 // First apply the current pointers offset to set the window at 0,0
295 pointerCoords[pointerIndex].applyOffset(currPointerInfo.xOffset, currPointerInfo.yOffset);
296 // Next scale the coordinates.
297 pointerCoords[pointerIndex].scale(1, scaleXDiff, scaleYDiff);
298 // Lastly, offset the coordinates so they're in the normalized pointer's frame.
299 pointerCoords[pointerIndex].applyOffset(-firstPointerInfo.xOffset,
300 -firstPointerInfo.yOffset);
301 }
302
303 MotionEntry* combinedMotionEntry =
304 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
305 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
306 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
307 motionEntry.metaState, motionEntry.buttonState,
308 motionEntry.classification, motionEntry.edgeFlags,
309 motionEntry.xPrecision, motionEntry.yPrecision,
310 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
311 motionEntry.downTime, motionEntry.pointerCount,
312 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
313 0 /* yOffset */);
314
315 if (motionEntry.injectionState) {
316 combinedMotionEntry->injectionState = motionEntry.injectionState;
317 combinedMotionEntry->injectionState->refCount += 1;
318 }
319
320 std::unique_ptr<DispatchEntry> dispatchEntry =
321 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
322 inputTargetFlags, firstPointerInfo.xOffset,
323 firstPointerInfo.yOffset, inputTarget.globalScaleFactor,
324 firstPointerInfo.windowXScale,
325 firstPointerInfo.windowYScale);
326 combinedMotionEntry->release();
327 return dispatchEntry;
328 }
329
addGestureMonitors(const std::vector<Monitor> & monitors,std::vector<TouchedMonitor> & outTouchedMonitors,float xOffset=0,float yOffset=0)330 static void addGestureMonitors(const std::vector<Monitor>& monitors,
331 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
332 float yOffset = 0) {
333 if (monitors.empty()) {
334 return;
335 }
336 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
337 for (const Monitor& monitor : monitors) {
338 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
339 }
340 }
341
getRandomKey()342 static std::array<uint8_t, 128> getRandomKey() {
343 std::array<uint8_t, 128> key;
344 if (RAND_bytes(key.data(), key.size()) != 1) {
345 LOG_ALWAYS_FATAL("Can't generate HMAC key");
346 }
347 return key;
348 }
349
350 // --- HmacKeyManager ---
351
HmacKeyManager()352 HmacKeyManager::HmacKeyManager() : mHmacKey(getRandomKey()) {}
353
sign(const VerifiedInputEvent & event) const354 std::array<uint8_t, 32> HmacKeyManager::sign(const VerifiedInputEvent& event) const {
355 size_t size;
356 switch (event.type) {
357 case VerifiedInputEvent::Type::KEY: {
358 size = sizeof(VerifiedKeyEvent);
359 break;
360 }
361 case VerifiedInputEvent::Type::MOTION: {
362 size = sizeof(VerifiedMotionEvent);
363 break;
364 }
365 }
366 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
367 return sign(start, size);
368 }
369
sign(const uint8_t * data,size_t size) const370 std::array<uint8_t, 32> HmacKeyManager::sign(const uint8_t* data, size_t size) const {
371 // SHA256 always generates 32-bytes result
372 std::array<uint8_t, 32> hash;
373 unsigned int hashLen = 0;
374 uint8_t* result =
375 HMAC(EVP_sha256(), mHmacKey.data(), mHmacKey.size(), data, size, hash.data(), &hashLen);
376 if (result == nullptr) {
377 ALOGE("Could not sign the data using HMAC");
378 return INVALID_HMAC;
379 }
380
381 if (hashLen != hash.size()) {
382 ALOGE("HMAC-SHA256 has unexpected length");
383 return INVALID_HMAC;
384 }
385
386 return hash;
387 }
388
389 // --- InputDispatcher ---
390
InputDispatcher(const sp<InputDispatcherPolicyInterface> & policy)391 InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
392 : mPolicy(policy),
393 mPendingEvent(nullptr),
394 mLastDropReason(DropReason::NOT_DROPPED),
395 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
396 mAppSwitchSawKeyDown(false),
397 mAppSwitchDueTime(LONG_LONG_MAX),
398 mNextUnblockedEvent(nullptr),
399 mDispatchEnabled(false),
400 mDispatchFrozen(false),
401 mInputFilterEnabled(false),
402 // mInTouchMode will be initialized by the WindowManager to the default device config.
403 // To avoid leaking stack in case that call never comes, and for tests,
404 // initialize it here anyways.
405 mInTouchMode(true),
406 mFocusedDisplayId(ADISPLAY_ID_DEFAULT) {
407 mLooper = new Looper(false);
408 mReporter = createInputReporter();
409
410 mKeyRepeatState.lastKeyEntry = nullptr;
411
412 policy->getDispatcherConfiguration(&mConfig);
413 }
414
~InputDispatcher()415 InputDispatcher::~InputDispatcher() {
416 { // acquire lock
417 std::scoped_lock _l(mLock);
418
419 resetKeyRepeatLocked();
420 releasePendingEventLocked();
421 drainInboundQueueLocked();
422 }
423
424 while (!mConnectionsByFd.empty()) {
425 sp<Connection> connection = mConnectionsByFd.begin()->second;
426 unregisterInputChannel(connection->inputChannel);
427 }
428 }
429
start()430 status_t InputDispatcher::start() {
431 if (mThread) {
432 return ALREADY_EXISTS;
433 }
434 mThread = std::make_unique<InputThread>(
435 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
436 return OK;
437 }
438
stop()439 status_t InputDispatcher::stop() {
440 if (mThread && mThread->isCallingThread()) {
441 ALOGE("InputDispatcher cannot be stopped from its own thread!");
442 return INVALID_OPERATION;
443 }
444 mThread.reset();
445 return OK;
446 }
447
dispatchOnce()448 void InputDispatcher::dispatchOnce() {
449 nsecs_t nextWakeupTime = LONG_LONG_MAX;
450 { // acquire lock
451 std::scoped_lock _l(mLock);
452 mDispatcherIsAlive.notify_all();
453
454 // Run a dispatch loop if there are no pending commands.
455 // The dispatch loop might enqueue commands to run afterwards.
456 if (!haveCommandsLocked()) {
457 dispatchOnceInnerLocked(&nextWakeupTime);
458 }
459
460 // Run all pending commands if there are any.
461 // If any commands were run then force the next poll to wake up immediately.
462 if (runCommandsLockedInterruptible()) {
463 nextWakeupTime = LONG_LONG_MIN;
464 }
465
466 // If we are still waiting for ack on some events,
467 // we might have to wake up earlier to check if an app is anr'ing.
468 const nsecs_t nextAnrCheck = processAnrsLocked();
469 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
470
471 // We are about to enter an infinitely long sleep, because we have no commands or
472 // pending or queued events
473 if (nextWakeupTime == LONG_LONG_MAX) {
474 mDispatcherEnteredIdle.notify_all();
475 }
476 } // release lock
477
478 // Wait for callback or timeout or wake. (make sure we round up, not down)
479 nsecs_t currentTime = now();
480 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
481 mLooper->pollOnce(timeoutMillis);
482 }
483
484 /**
485 * Check if any of the connections' wait queues have events that are too old.
486 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
487 * Return the time at which we should wake up next.
488 */
processAnrsLocked()489 nsecs_t InputDispatcher::processAnrsLocked() {
490 const nsecs_t currentTime = now();
491 nsecs_t nextAnrCheck = LONG_LONG_MAX;
492 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
493 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
494 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
495 onAnrLocked(mAwaitedFocusedApplication);
496 mAwaitedFocusedApplication.clear();
497 return LONG_LONG_MIN;
498 } else {
499 // Keep waiting
500 const nsecs_t millisRemaining = ns2ms(*mNoFocusedWindowTimeoutTime - currentTime);
501 ALOGW("Still no focused window. Will drop the event in %" PRId64 "ms", millisRemaining);
502 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
503 }
504 }
505
506 // Check if any connection ANRs are due
507 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
508 if (currentTime < nextAnrCheck) { // most likely scenario
509 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
510 }
511
512 // If we reached here, we have an unresponsive connection.
513 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
514 if (connection == nullptr) {
515 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
516 return nextAnrCheck;
517 }
518 connection->responsive = false;
519 // Stop waking up for this unresponsive connection
520 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
521 onAnrLocked(connection);
522 return LONG_LONG_MIN;
523 }
524
getDispatchingTimeoutLocked(const sp<IBinder> & token)525 nsecs_t InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
526 sp<InputWindowHandle> window = getWindowHandleLocked(token);
527 if (window != nullptr) {
528 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT).count();
529 }
530 return DEFAULT_INPUT_DISPATCHING_TIMEOUT.count();
531 }
532
dispatchOnceInnerLocked(nsecs_t * nextWakeupTime)533 void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
534 nsecs_t currentTime = now();
535
536 // Reset the key repeat timer whenever normal dispatch is suspended while the
537 // device is in a non-interactive state. This is to ensure that we abort a key
538 // repeat if the device is just coming out of sleep.
539 if (!mDispatchEnabled) {
540 resetKeyRepeatLocked();
541 }
542
543 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
544 if (mDispatchFrozen) {
545 if (DEBUG_FOCUS) {
546 ALOGD("Dispatch frozen. Waiting some more.");
547 }
548 return;
549 }
550
551 // Optimize latency of app switches.
552 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
553 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
554 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
555 if (mAppSwitchDueTime < *nextWakeupTime) {
556 *nextWakeupTime = mAppSwitchDueTime;
557 }
558
559 // Ready to start a new event.
560 // If we don't already have a pending event, go grab one.
561 if (!mPendingEvent) {
562 if (mInboundQueue.empty()) {
563 if (isAppSwitchDue) {
564 // The inbound queue is empty so the app switch key we were waiting
565 // for will never arrive. Stop waiting for it.
566 resetPendingAppSwitchLocked(false);
567 isAppSwitchDue = false;
568 }
569
570 // Synthesize a key repeat if appropriate.
571 if (mKeyRepeatState.lastKeyEntry) {
572 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
573 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
574 } else {
575 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
576 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
577 }
578 }
579 }
580
581 // Nothing to do if there is no pending event.
582 if (!mPendingEvent) {
583 return;
584 }
585 } else {
586 // Inbound queue has at least one entry.
587 mPendingEvent = mInboundQueue.front();
588 mInboundQueue.pop_front();
589 traceInboundQueueLengthLocked();
590 }
591
592 // Poke user activity for this event.
593 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
594 pokeUserActivityLocked(*mPendingEvent);
595 }
596 }
597
598 // Now we have an event to dispatch.
599 // All events are eventually dequeued and processed this way, even if we intend to drop them.
600 ALOG_ASSERT(mPendingEvent != nullptr);
601 bool done = false;
602 DropReason dropReason = DropReason::NOT_DROPPED;
603 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
604 dropReason = DropReason::POLICY;
605 } else if (!mDispatchEnabled) {
606 dropReason = DropReason::DISABLED;
607 }
608
609 if (mNextUnblockedEvent == mPendingEvent) {
610 mNextUnblockedEvent = nullptr;
611 }
612
613 switch (mPendingEvent->type) {
614 case EventEntry::Type::CONFIGURATION_CHANGED: {
615 ConfigurationChangedEntry* typedEntry =
616 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
617 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
618 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
619 break;
620 }
621
622 case EventEntry::Type::DEVICE_RESET: {
623 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
624 done = dispatchDeviceResetLocked(currentTime, typedEntry);
625 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
626 break;
627 }
628
629 case EventEntry::Type::FOCUS: {
630 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
631 dispatchFocusLocked(currentTime, typedEntry);
632 done = true;
633 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
634 break;
635 }
636
637 case EventEntry::Type::KEY: {
638 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
639 if (isAppSwitchDue) {
640 if (isAppSwitchKeyEvent(*typedEntry)) {
641 resetPendingAppSwitchLocked(true);
642 isAppSwitchDue = false;
643 } else if (dropReason == DropReason::NOT_DROPPED) {
644 dropReason = DropReason::APP_SWITCH;
645 }
646 }
647 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
648 dropReason = DropReason::STALE;
649 }
650 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
651 dropReason = DropReason::BLOCKED;
652 }
653 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
654 break;
655 }
656
657 case EventEntry::Type::MOTION: {
658 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
659 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
660 dropReason = DropReason::APP_SWITCH;
661 }
662 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
663 dropReason = DropReason::STALE;
664 }
665 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
666 dropReason = DropReason::BLOCKED;
667 }
668 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
669 break;
670 }
671 }
672
673 if (done) {
674 if (dropReason != DropReason::NOT_DROPPED) {
675 dropInboundEventLocked(*mPendingEvent, dropReason);
676 }
677 mLastDropReason = dropReason;
678
679 releasePendingEventLocked();
680 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
681 }
682 }
683
684 /**
685 * Return true if the events preceding this incoming motion event should be dropped
686 * Return false otherwise (the default behaviour)
687 */
shouldPruneInboundQueueLocked(const MotionEntry & motionEntry)688 bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
689 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
690 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
691
692 // Optimize case where the current application is unresponsive and the user
693 // decides to touch a window in a different application.
694 // If the application takes too long to catch up then we drop all events preceding
695 // the touch into the other window.
696 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
697 int32_t displayId = motionEntry.displayId;
698 int32_t x = static_cast<int32_t>(
699 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
700 int32_t y = static_cast<int32_t>(
701 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
702 sp<InputWindowHandle> touchedWindowHandle =
703 findTouchedWindowAtLocked(displayId, x, y, nullptr);
704 if (touchedWindowHandle != nullptr &&
705 touchedWindowHandle->getApplicationToken() !=
706 mAwaitedFocusedApplication->getApplicationToken()) {
707 // User touched a different application than the one we are waiting on.
708 ALOGI("Pruning input queue because user touched a different application while waiting "
709 "for %s",
710 mAwaitedFocusedApplication->getName().c_str());
711 return true;
712 }
713
714 // Alternatively, maybe there's a gesture monitor that could handle this event
715 std::vector<TouchedMonitor> gestureMonitors =
716 findTouchedGestureMonitorsLocked(displayId, {});
717 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
718 sp<Connection> connection =
719 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
720 if (connection != nullptr && connection->responsive) {
721 // This monitor could take more input. Drop all events preceding this
722 // event, so that gesture monitor could get a chance to receive the stream
723 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
724 "responsive gesture monitor that may handle the event",
725 mAwaitedFocusedApplication->getName().c_str());
726 return true;
727 }
728 }
729 }
730
731 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
732 // yet been processed by some connections, the dispatcher will wait for these motion
733 // events to be processed before dispatching the key event. This is because these motion events
734 // may cause a new window to be launched, which the user might expect to receive focus.
735 // To prevent waiting forever for such events, just send the key to the currently focused window
736 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
737 ALOGD("Received a new pointer down event, stop waiting for events to process and "
738 "just send the pending key event to the focused window.");
739 mKeyIsWaitingForEventsTimeout = now();
740 }
741 return false;
742 }
743
enqueueInboundEventLocked(EventEntry * entry)744 bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
745 bool needWake = mInboundQueue.empty();
746 mInboundQueue.push_back(entry);
747 traceInboundQueueLengthLocked();
748
749 switch (entry->type) {
750 case EventEntry::Type::KEY: {
751 // Optimize app switch latency.
752 // If the application takes too long to catch up then we drop all events preceding
753 // the app switch key.
754 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
755 if (isAppSwitchKeyEvent(keyEntry)) {
756 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
757 mAppSwitchSawKeyDown = true;
758 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
759 if (mAppSwitchSawKeyDown) {
760 #if DEBUG_APP_SWITCH
761 ALOGD("App switch is pending!");
762 #endif
763 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
764 mAppSwitchSawKeyDown = false;
765 needWake = true;
766 }
767 }
768 }
769 break;
770 }
771
772 case EventEntry::Type::MOTION: {
773 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
774 mNextUnblockedEvent = entry;
775 needWake = true;
776 }
777 break;
778 }
779 case EventEntry::Type::FOCUS: {
780 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
781 break;
782 }
783 case EventEntry::Type::CONFIGURATION_CHANGED:
784 case EventEntry::Type::DEVICE_RESET: {
785 // nothing to do
786 break;
787 }
788 }
789
790 return needWake;
791 }
792
addRecentEventLocked(EventEntry * entry)793 void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
794 entry->refCount += 1;
795 mRecentQueue.push_back(entry);
796 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
797 mRecentQueue.front()->release();
798 mRecentQueue.pop_front();
799 }
800 }
801
findTouchedWindowAtLocked(int32_t displayId,int32_t x,int32_t y,TouchState * touchState,bool addOutsideTargets,bool addPortalWindows)802 sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
803 int32_t y, TouchState* touchState,
804 bool addOutsideTargets,
805 bool addPortalWindows) {
806 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
807 LOG_ALWAYS_FATAL(
808 "Must provide a valid touch state if adding portal windows or outside targets");
809 }
810 // Traverse windows from front to back to find touched window.
811 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
812 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
813 const InputWindowInfo* windowInfo = windowHandle->getInfo();
814 if (windowInfo->displayId == displayId) {
815 int32_t flags = windowInfo->layoutParamsFlags;
816
817 if (windowInfo->visible) {
818 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
819 bool isTouchModal = (flags &
820 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
821 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
822 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
823 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
824 if (portalToDisplayId != ADISPLAY_ID_NONE &&
825 portalToDisplayId != displayId) {
826 if (addPortalWindows) {
827 // For the monitoring channels of the display.
828 touchState->addPortalWindow(windowHandle);
829 }
830 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
831 addOutsideTargets, addPortalWindows);
832 }
833 // Found window.
834 return windowHandle;
835 }
836 }
837
838 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
839 touchState->addOrUpdateWindow(windowHandle,
840 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
841 BitSet32(0));
842 }
843 }
844 }
845 }
846 return nullptr;
847 }
848
findTouchedGestureMonitorsLocked(int32_t displayId,const std::vector<sp<InputWindowHandle>> & portalWindows) const849 std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
850 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
851 std::vector<TouchedMonitor> touchedMonitors;
852
853 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
854 addGestureMonitors(monitors, touchedMonitors);
855 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
856 const InputWindowInfo* windowInfo = portalWindow->getInfo();
857 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
858 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
859 -windowInfo->frameTop);
860 }
861 return touchedMonitors;
862 }
863
dropInboundEventLocked(const EventEntry & entry,DropReason dropReason)864 void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
865 const char* reason;
866 switch (dropReason) {
867 case DropReason::POLICY:
868 #if DEBUG_INBOUND_EVENT_DETAILS
869 ALOGD("Dropped event because policy consumed it.");
870 #endif
871 reason = "inbound event was dropped because the policy consumed it";
872 break;
873 case DropReason::DISABLED:
874 if (mLastDropReason != DropReason::DISABLED) {
875 ALOGI("Dropped event because input dispatch is disabled.");
876 }
877 reason = "inbound event was dropped because input dispatch is disabled";
878 break;
879 case DropReason::APP_SWITCH:
880 ALOGI("Dropped event because of pending overdue app switch.");
881 reason = "inbound event was dropped because of pending overdue app switch";
882 break;
883 case DropReason::BLOCKED:
884 ALOGI("Dropped event because the current application is not responding and the user "
885 "has started interacting with a different application.");
886 reason = "inbound event was dropped because the current application is not responding "
887 "and the user has started interacting with a different application";
888 break;
889 case DropReason::STALE:
890 ALOGI("Dropped event because it is stale.");
891 reason = "inbound event was dropped because it is stale";
892 break;
893 case DropReason::NOT_DROPPED: {
894 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
895 return;
896 }
897 }
898
899 switch (entry.type) {
900 case EventEntry::Type::KEY: {
901 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
902 synthesizeCancelationEventsForAllConnectionsLocked(options);
903 break;
904 }
905 case EventEntry::Type::MOTION: {
906 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
907 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
908 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
909 synthesizeCancelationEventsForAllConnectionsLocked(options);
910 } else {
911 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
912 synthesizeCancelationEventsForAllConnectionsLocked(options);
913 }
914 break;
915 }
916 case EventEntry::Type::FOCUS:
917 case EventEntry::Type::CONFIGURATION_CHANGED:
918 case EventEntry::Type::DEVICE_RESET: {
919 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
920 break;
921 }
922 }
923 }
924
isAppSwitchKeyCode(int32_t keyCode)925 static bool isAppSwitchKeyCode(int32_t keyCode) {
926 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
927 keyCode == AKEYCODE_APP_SWITCH;
928 }
929
isAppSwitchKeyEvent(const KeyEntry & keyEntry)930 bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
931 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
932 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
933 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
934 }
935
isAppSwitchPendingLocked()936 bool InputDispatcher::isAppSwitchPendingLocked() {
937 return mAppSwitchDueTime != LONG_LONG_MAX;
938 }
939
resetPendingAppSwitchLocked(bool handled)940 void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
941 mAppSwitchDueTime = LONG_LONG_MAX;
942
943 #if DEBUG_APP_SWITCH
944 if (handled) {
945 ALOGD("App switch has arrived.");
946 } else {
947 ALOGD("App switch was abandoned.");
948 }
949 #endif
950 }
951
haveCommandsLocked() const952 bool InputDispatcher::haveCommandsLocked() const {
953 return !mCommandQueue.empty();
954 }
955
runCommandsLockedInterruptible()956 bool InputDispatcher::runCommandsLockedInterruptible() {
957 if (mCommandQueue.empty()) {
958 return false;
959 }
960
961 do {
962 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
963 mCommandQueue.pop_front();
964 Command command = commandEntry->command;
965 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
966
967 commandEntry->connection.clear();
968 } while (!mCommandQueue.empty());
969 return true;
970 }
971
postCommandLocked(std::unique_ptr<CommandEntry> commandEntry)972 void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
973 mCommandQueue.push_back(std::move(commandEntry));
974 }
975
drainInboundQueueLocked()976 void InputDispatcher::drainInboundQueueLocked() {
977 while (!mInboundQueue.empty()) {
978 EventEntry* entry = mInboundQueue.front();
979 mInboundQueue.pop_front();
980 releaseInboundEventLocked(entry);
981 }
982 traceInboundQueueLengthLocked();
983 }
984
releasePendingEventLocked()985 void InputDispatcher::releasePendingEventLocked() {
986 if (mPendingEvent) {
987 releaseInboundEventLocked(mPendingEvent);
988 mPendingEvent = nullptr;
989 }
990 }
991
releaseInboundEventLocked(EventEntry * entry)992 void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
993 InjectionState* injectionState = entry->injectionState;
994 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
995 #if DEBUG_DISPATCH_CYCLE
996 ALOGD("Injected inbound event was dropped.");
997 #endif
998 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
999 }
1000 if (entry == mNextUnblockedEvent) {
1001 mNextUnblockedEvent = nullptr;
1002 }
1003 addRecentEventLocked(entry);
1004 entry->release();
1005 }
1006
resetKeyRepeatLocked()1007 void InputDispatcher::resetKeyRepeatLocked() {
1008 if (mKeyRepeatState.lastKeyEntry) {
1009 mKeyRepeatState.lastKeyEntry->release();
1010 mKeyRepeatState.lastKeyEntry = nullptr;
1011 }
1012 }
1013
synthesizeKeyRepeatLocked(nsecs_t currentTime)1014 KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1015 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
1016
1017 // Reuse the repeated key entry if it is otherwise unreferenced.
1018 uint32_t policyFlags = entry->policyFlags &
1019 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
1020 if (entry->refCount == 1) {
1021 entry->recycle();
1022 entry->id = mIdGenerator.nextId();
1023 entry->eventTime = currentTime;
1024 entry->policyFlags = policyFlags;
1025 entry->repeatCount += 1;
1026 } else {
1027 KeyEntry* newEntry =
1028 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
1029 entry->displayId, policyFlags, entry->action, entry->flags,
1030 entry->keyCode, entry->scanCode, entry->metaState,
1031 entry->repeatCount + 1, entry->downTime);
1032
1033 mKeyRepeatState.lastKeyEntry = newEntry;
1034 entry->release();
1035
1036 entry = newEntry;
1037 }
1038 entry->syntheticRepeat = true;
1039
1040 // Increment reference count since we keep a reference to the event in
1041 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
1042 entry->refCount += 1;
1043
1044 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1045 return entry;
1046 }
1047
dispatchConfigurationChangedLocked(nsecs_t currentTime,ConfigurationChangedEntry * entry)1048 bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1049 ConfigurationChangedEntry* entry) {
1050 #if DEBUG_OUTBOUND_EVENT_DETAILS
1051 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
1052 #endif
1053
1054 // Reset key repeating in case a keyboard device was added or removed or something.
1055 resetKeyRepeatLocked();
1056
1057 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
1058 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1059 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
1060 commandEntry->eventTime = entry->eventTime;
1061 postCommandLocked(std::move(commandEntry));
1062 return true;
1063 }
1064
dispatchDeviceResetLocked(nsecs_t currentTime,DeviceResetEntry * entry)1065 bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
1066 #if DEBUG_OUTBOUND_EVENT_DETAILS
1067 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
1068 entry->deviceId);
1069 #endif
1070
1071 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
1072 options.deviceId = entry->deviceId;
1073 synthesizeCancelationEventsForAllConnectionsLocked(options);
1074 return true;
1075 }
1076
enqueueFocusEventLocked(const InputWindowHandle & window,bool hasFocus)1077 void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus) {
1078 if (mPendingEvent != nullptr) {
1079 // Move the pending event to the front of the queue. This will give the chance
1080 // for the pending event to get dispatched to the newly focused window
1081 mInboundQueue.push_front(mPendingEvent);
1082 mPendingEvent = nullptr;
1083 }
1084
1085 FocusEntry* focusEntry =
1086 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), hasFocus);
1087
1088 // This event should go to the front of the queue, but behind all other focus events
1089 // Find the last focus event, and insert right after it
1090 std::deque<EventEntry*>::reverse_iterator it =
1091 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1092 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1093
1094 // Maintain the order of focus events. Insert the entry after all other focus events.
1095 mInboundQueue.insert(it.base(), focusEntry);
1096 }
1097
dispatchFocusLocked(nsecs_t currentTime,FocusEntry * entry)1098 void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
1099 sp<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1100 if (channel == nullptr) {
1101 return; // Window has gone away
1102 }
1103 InputTarget target;
1104 target.inputChannel = channel;
1105 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1106 entry->dispatchInProgress = true;
1107
1108 dispatchEventLocked(currentTime, entry, {target});
1109 }
1110
dispatchKeyLocked(nsecs_t currentTime,KeyEntry * entry,DropReason * dropReason,nsecs_t * nextWakeupTime)1111 bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
1112 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1113 // Preprocessing.
1114 if (!entry->dispatchInProgress) {
1115 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1116 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1117 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1118 if (mKeyRepeatState.lastKeyEntry &&
1119 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
1120 // We have seen two identical key downs in a row which indicates that the device
1121 // driver is automatically generating key repeats itself. We take note of the
1122 // repeat here, but we disable our own next key repeat timer since it is clear that
1123 // we will not need to synthesize key repeats ourselves.
1124 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1125 resetKeyRepeatLocked();
1126 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1127 } else {
1128 // Not a repeat. Save key down state in case we do see a repeat later.
1129 resetKeyRepeatLocked();
1130 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1131 }
1132 mKeyRepeatState.lastKeyEntry = entry;
1133 entry->refCount += 1;
1134 } else if (!entry->syntheticRepeat) {
1135 resetKeyRepeatLocked();
1136 }
1137
1138 if (entry->repeatCount == 1) {
1139 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1140 } else {
1141 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1142 }
1143
1144 entry->dispatchInProgress = true;
1145
1146 logOutboundKeyDetails("dispatchKey - ", *entry);
1147 }
1148
1149 // Handle case where the policy asked us to try again later last time.
1150 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1151 if (currentTime < entry->interceptKeyWakeupTime) {
1152 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1153 *nextWakeupTime = entry->interceptKeyWakeupTime;
1154 }
1155 return false; // wait until next wakeup
1156 }
1157 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1158 entry->interceptKeyWakeupTime = 0;
1159 }
1160
1161 // Give the policy a chance to intercept the key.
1162 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1163 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
1164 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1165 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
1166 sp<InputWindowHandle> focusedWindowHandle =
1167 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
1168 if (focusedWindowHandle != nullptr) {
1169 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
1170 }
1171 commandEntry->keyEntry = entry;
1172 postCommandLocked(std::move(commandEntry));
1173 entry->refCount += 1;
1174 return false; // wait for the command to run
1175 } else {
1176 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1177 }
1178 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
1179 if (*dropReason == DropReason::NOT_DROPPED) {
1180 *dropReason = DropReason::POLICY;
1181 }
1182 }
1183
1184 // Clean up if dropping the event.
1185 if (*dropReason != DropReason::NOT_DROPPED) {
1186 setInjectionResult(entry,
1187 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
1188 : INPUT_EVENT_INJECTION_FAILED);
1189 mReporter->reportDroppedKey(entry->id);
1190 return true;
1191 }
1192
1193 // Identify targets.
1194 std::vector<InputTarget> inputTargets;
1195 int32_t injectionResult =
1196 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
1197 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1198 return false;
1199 }
1200
1201 setInjectionResult(entry, injectionResult);
1202 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1203 return true;
1204 }
1205
1206 // Add monitor channels from event's or focused display.
1207 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
1208
1209 // Dispatch the key.
1210 dispatchEventLocked(currentTime, entry, inputTargets);
1211 return true;
1212 }
1213
logOutboundKeyDetails(const char * prefix,const KeyEntry & entry)1214 void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
1215 #if DEBUG_OUTBOUND_EVENT_DETAILS
1216 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1217 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1218 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1219 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1220 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1221 entry.repeatCount, entry.downTime);
1222 #endif
1223 }
1224
dispatchMotionLocked(nsecs_t currentTime,MotionEntry * entry,DropReason * dropReason,nsecs_t * nextWakeupTime)1225 bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1226 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1227 ATRACE_CALL();
1228 // Preprocessing.
1229 if (!entry->dispatchInProgress) {
1230 entry->dispatchInProgress = true;
1231
1232 logOutboundMotionDetails("dispatchMotion - ", *entry);
1233 }
1234
1235 // Clean up if dropping the event.
1236 if (*dropReason != DropReason::NOT_DROPPED) {
1237 setInjectionResult(entry,
1238 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
1239 : INPUT_EVENT_INJECTION_FAILED);
1240 return true;
1241 }
1242
1243 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1244
1245 // Identify targets.
1246 std::vector<InputTarget> inputTargets;
1247
1248 bool conflictingPointerActions = false;
1249 int32_t injectionResult;
1250 if (isPointerEvent) {
1251 // Pointer event. (eg. touchscreen)
1252 injectionResult =
1253 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
1254 &conflictingPointerActions);
1255 } else {
1256 // Non touch event. (eg. trackball)
1257 injectionResult =
1258 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
1259 }
1260 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1261 return false;
1262 }
1263
1264 setInjectionResult(entry, injectionResult);
1265 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1266 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1267 return true;
1268 }
1269 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1270 CancelationOptions::Mode mode(isPointerEvent
1271 ? CancelationOptions::CANCEL_POINTER_EVENTS
1272 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1273 CancelationOptions options(mode, "input event injection failed");
1274 synthesizeCancelationEventsForMonitorsLocked(options);
1275 return true;
1276 }
1277
1278 // Add monitor channels from event's or focused display.
1279 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
1280
1281 if (isPointerEvent) {
1282 std::unordered_map<int32_t, TouchState>::iterator it =
1283 mTouchStatesByDisplay.find(entry->displayId);
1284 if (it != mTouchStatesByDisplay.end()) {
1285 const TouchState& state = it->second;
1286 if (!state.portalWindows.empty()) {
1287 // The event has gone through these portal windows, so we add monitoring targets of
1288 // the corresponding displays as well.
1289 for (size_t i = 0; i < state.portalWindows.size(); i++) {
1290 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
1291 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
1292 -windowInfo->frameLeft, -windowInfo->frameTop);
1293 }
1294 }
1295 }
1296 }
1297
1298 // Dispatch the motion.
1299 if (conflictingPointerActions) {
1300 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
1301 "conflicting pointer actions");
1302 synthesizeCancelationEventsForAllConnectionsLocked(options);
1303 }
1304 dispatchEventLocked(currentTime, entry, inputTargets);
1305 return true;
1306 }
1307
logOutboundMotionDetails(const char * prefix,const MotionEntry & entry)1308 void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
1309 #if DEBUG_OUTBOUND_EVENT_DETAILS
1310 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1311 ", policyFlags=0x%x, "
1312 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1313 "metaState=0x%x, buttonState=0x%x,"
1314 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1315 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1316 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1317 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
1318
1319 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1320 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1321 "x=%f, y=%f, pressure=%f, size=%f, "
1322 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1323 "orientation=%f",
1324 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1325 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1326 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1327 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1328 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1329 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1330 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1331 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1332 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1333 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1334 }
1335 #endif
1336 }
1337
dispatchEventLocked(nsecs_t currentTime,EventEntry * eventEntry,const std::vector<InputTarget> & inputTargets)1338 void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1339 const std::vector<InputTarget>& inputTargets) {
1340 ATRACE_CALL();
1341 #if DEBUG_DISPATCH_CYCLE
1342 ALOGD("dispatchEventToCurrentInputTargets");
1343 #endif
1344
1345 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1346
1347 pokeUserActivityLocked(*eventEntry);
1348
1349 for (const InputTarget& inputTarget : inputTargets) {
1350 sp<Connection> connection =
1351 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
1352 if (connection != nullptr) {
1353 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
1354 } else {
1355 if (DEBUG_FOCUS) {
1356 ALOGD("Dropping event delivery to target with channel '%s' because it "
1357 "is no longer registered with the input dispatcher.",
1358 inputTarget.inputChannel->getName().c_str());
1359 }
1360 }
1361 }
1362 }
1363
cancelEventsForAnrLocked(const sp<Connection> & connection)1364 void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1365 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1366 // If the policy decides to close the app, we will get a channel removal event via
1367 // unregisterInputChannel, and will clean up the connection that way. We are already not
1368 // sending new pointers to the connection when it blocked, but focused events will continue to
1369 // pile up.
1370 ALOGW("Canceling events for %s because it is unresponsive",
1371 connection->inputChannel->getName().c_str());
1372 if (connection->status == Connection::STATUS_NORMAL) {
1373 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1374 "application not responding");
1375 synthesizeCancelationEventsForConnectionLocked(connection, options);
1376 }
1377 }
1378
resetNoFocusedWindowTimeoutLocked()1379 void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
1380 if (DEBUG_FOCUS) {
1381 ALOGD("Resetting ANR timeouts.");
1382 }
1383
1384 // Reset input target wait timeout.
1385 mNoFocusedWindowTimeoutTime = std::nullopt;
1386 mAwaitedFocusedApplication.clear();
1387 }
1388
1389 /**
1390 * Get the display id that the given event should go to. If this event specifies a valid display id,
1391 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1392 * Focused display is the display that the user most recently interacted with.
1393 */
getTargetDisplayId(const EventEntry & entry)1394 int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
1395 int32_t displayId;
1396 switch (entry.type) {
1397 case EventEntry::Type::KEY: {
1398 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1399 displayId = keyEntry.displayId;
1400 break;
1401 }
1402 case EventEntry::Type::MOTION: {
1403 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1404 displayId = motionEntry.displayId;
1405 break;
1406 }
1407 case EventEntry::Type::FOCUS:
1408 case EventEntry::Type::CONFIGURATION_CHANGED:
1409 case EventEntry::Type::DEVICE_RESET: {
1410 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
1411 return ADISPLAY_ID_NONE;
1412 }
1413 }
1414 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1415 }
1416
shouldWaitToSendKeyLocked(nsecs_t currentTime,const char * focusedWindowName)1417 bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1418 const char* focusedWindowName) {
1419 if (mAnrTracker.empty()) {
1420 // already processed all events that we waited for
1421 mKeyIsWaitingForEventsTimeout = std::nullopt;
1422 return false;
1423 }
1424
1425 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1426 // Start the timer
1427 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1428 "focus to change",
1429 focusedWindowName);
1430 mKeyIsWaitingForEventsTimeout = currentTime + KEY_WAITING_FOR_EVENTS_TIMEOUT.count();
1431 return true;
1432 }
1433
1434 // We still have pending events, and already started the timer
1435 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1436 return true; // Still waiting
1437 }
1438
1439 // Waited too long, and some connection still hasn't processed all motions
1440 // Just send the key to the focused window
1441 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1442 focusedWindowName);
1443 mKeyIsWaitingForEventsTimeout = std::nullopt;
1444 return false;
1445 }
1446
findFocusedWindowTargetsLocked(nsecs_t currentTime,const EventEntry & entry,std::vector<InputTarget> & inputTargets,nsecs_t * nextWakeupTime)1447 int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1448 const EventEntry& entry,
1449 std::vector<InputTarget>& inputTargets,
1450 nsecs_t* nextWakeupTime) {
1451 std::string reason;
1452
1453 int32_t displayId = getTargetDisplayId(entry);
1454 sp<InputWindowHandle> focusedWindowHandle =
1455 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1456 sp<InputApplicationHandle> focusedApplicationHandle =
1457 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1458
1459 // If there is no currently focused window and no focused application
1460 // then drop the event.
1461 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1462 ALOGI("Dropping %s event because there is no focused window or focused application in "
1463 "display %" PRId32 ".",
1464 EventEntry::typeToString(entry.type), displayId);
1465 return INPUT_EVENT_INJECTION_FAILED;
1466 }
1467
1468 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1469 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1470 // start interacting with another application via touch (app switch). This code can be removed
1471 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1472 // an app is expected to have a focused window.
1473 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1474 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1475 // We just discovered that there's no focused window. Start the ANR timer
1476 const nsecs_t timeout = focusedApplicationHandle->getDispatchingTimeout(
1477 DEFAULT_INPUT_DISPATCHING_TIMEOUT.count());
1478 mNoFocusedWindowTimeoutTime = currentTime + timeout;
1479 mAwaitedFocusedApplication = focusedApplicationHandle;
1480 ALOGW("Waiting because no window has focus but %s may eventually add a "
1481 "window when it finishes starting up. Will wait for %" PRId64 "ms",
1482 mAwaitedFocusedApplication->getName().c_str(), ns2ms(timeout));
1483 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1484 return INPUT_EVENT_INJECTION_PENDING;
1485 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1486 // Already raised ANR. Drop the event
1487 ALOGE("Dropping %s event because there is no focused window",
1488 EventEntry::typeToString(entry.type));
1489 return INPUT_EVENT_INJECTION_FAILED;
1490 } else {
1491 // Still waiting for the focused window
1492 return INPUT_EVENT_INJECTION_PENDING;
1493 }
1494 }
1495
1496 // we have a valid, non-null focused window
1497 resetNoFocusedWindowTimeoutLocked();
1498
1499 // Check permissions.
1500 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
1501 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1502 }
1503
1504 if (focusedWindowHandle->getInfo()->paused) {
1505 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1506 return INPUT_EVENT_INJECTION_PENDING;
1507 }
1508
1509 // If the event is a key event, then we must wait for all previous events to
1510 // complete before delivering it because previous events may have the
1511 // side-effect of transferring focus to a different window and we want to
1512 // ensure that the following keys are sent to the new window.
1513 //
1514 // Suppose the user touches a button in a window then immediately presses "A".
1515 // If the button causes a pop-up window to appear then we want to ensure that
1516 // the "A" key is delivered to the new pop-up window. This is because users
1517 // often anticipate pending UI changes when typing on a keyboard.
1518 // To obtain this behavior, we must serialize key events with respect to all
1519 // prior input events.
1520 if (entry.type == EventEntry::Type::KEY) {
1521 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1522 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1523 return INPUT_EVENT_INJECTION_PENDING;
1524 }
1525 }
1526
1527 // Success! Output targets.
1528 addWindowTargetLocked(focusedWindowHandle,
1529 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1530 BitSet32(0), inputTargets);
1531
1532 // Done.
1533 return INPUT_EVENT_INJECTION_SUCCEEDED;
1534 }
1535
1536 /**
1537 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1538 * that are currently unresponsive.
1539 */
selectResponsiveMonitorsLocked(const std::vector<TouchedMonitor> & monitors) const1540 std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1541 const std::vector<TouchedMonitor>& monitors) const {
1542 std::vector<TouchedMonitor> responsiveMonitors;
1543 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1544 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1545 sp<Connection> connection = getConnectionLocked(
1546 monitor.monitor.inputChannel->getConnectionToken());
1547 if (connection == nullptr) {
1548 ALOGE("Could not find connection for monitor %s",
1549 monitor.monitor.inputChannel->getName().c_str());
1550 return false;
1551 }
1552 if (!connection->responsive) {
1553 ALOGW("Unresponsive monitor %s will not get the new gesture",
1554 connection->inputChannel->getName().c_str());
1555 return false;
1556 }
1557 return true;
1558 });
1559 return responsiveMonitors;
1560 }
1561
findTouchedWindowTargetsLocked(nsecs_t currentTime,const MotionEntry & entry,std::vector<InputTarget> & inputTargets,nsecs_t * nextWakeupTime,bool * outConflictingPointerActions)1562 int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
1563 const MotionEntry& entry,
1564 std::vector<InputTarget>& inputTargets,
1565 nsecs_t* nextWakeupTime,
1566 bool* outConflictingPointerActions) {
1567 ATRACE_CALL();
1568 enum InjectionPermission {
1569 INJECTION_PERMISSION_UNKNOWN,
1570 INJECTION_PERMISSION_GRANTED,
1571 INJECTION_PERMISSION_DENIED
1572 };
1573
1574 // For security reasons, we defer updating the touch state until we are sure that
1575 // event injection will be allowed.
1576 int32_t displayId = entry.displayId;
1577 int32_t action = entry.action;
1578 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1579
1580 // Update the touch state as needed based on the properties of the touch event.
1581 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1582 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1583 sp<InputWindowHandle> newHoverWindowHandle;
1584
1585 // Copy current touch state into tempTouchState.
1586 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1587 // If no state for the specified display exists, then our initial state will be empty.
1588 const TouchState* oldState = nullptr;
1589 TouchState tempTouchState;
1590 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1591 mTouchStatesByDisplay.find(displayId);
1592 if (oldStateIt != mTouchStatesByDisplay.end()) {
1593 oldState = &(oldStateIt->second);
1594 tempTouchState.copyFrom(*oldState);
1595 }
1596
1597 bool isSplit = tempTouchState.split;
1598 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1599 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1600 tempTouchState.displayId != displayId);
1601 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1602 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1603 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1604 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1605 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
1606 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
1607 bool wrongDevice = false;
1608 if (newGesture) {
1609 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
1610 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
1611 ALOGI("Dropping event because a pointer for a different device is already down "
1612 "in display %" PRId32,
1613 displayId);
1614 // TODO: test multiple simultaneous input streams.
1615 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1616 switchedDevice = false;
1617 wrongDevice = true;
1618 goto Failed;
1619 }
1620 tempTouchState.reset();
1621 tempTouchState.down = down;
1622 tempTouchState.deviceId = entry.deviceId;
1623 tempTouchState.source = entry.source;
1624 tempTouchState.displayId = displayId;
1625 isSplit = false;
1626 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1627 ALOGI("Dropping move event because a pointer for a different device is already active "
1628 "in display %" PRId32,
1629 displayId);
1630 // TODO: test multiple simultaneous input streams.
1631 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1632 switchedDevice = false;
1633 wrongDevice = true;
1634 goto Failed;
1635 }
1636
1637 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1638 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1639
1640 int32_t x;
1641 int32_t y;
1642 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1643 // Always dispatch mouse events to cursor position.
1644 if (isFromMouse) {
1645 x = int32_t(entry.xCursorPosition);
1646 y = int32_t(entry.yCursorPosition);
1647 } else {
1648 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1649 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
1650 }
1651 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
1652 sp<InputWindowHandle> newTouchedWindowHandle =
1653 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1654 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
1655
1656 std::vector<TouchedMonitor> newGestureMonitors = isDown
1657 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
1658 : std::vector<TouchedMonitor>{};
1659
1660 // Figure out whether splitting will be allowed for this window.
1661 if (newTouchedWindowHandle != nullptr &&
1662 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1663 // New window supports splitting, but we should never split mouse events.
1664 isSplit = !isFromMouse;
1665 } else if (isSplit) {
1666 // New window does not support splitting but we have already split events.
1667 // Ignore the new window.
1668 newTouchedWindowHandle = nullptr;
1669 }
1670
1671 // Handle the case where we did not find a window.
1672 if (newTouchedWindowHandle == nullptr) {
1673 // Try to assign the pointer to the first foreground window we find, if there is one.
1674 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
1675 }
1676
1677 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1678 ALOGI("Not sending touch event to %s because it is paused",
1679 newTouchedWindowHandle->getName().c_str());
1680 newTouchedWindowHandle = nullptr;
1681 }
1682
1683 if (newTouchedWindowHandle != nullptr) {
1684 sp<Connection> connection = getConnectionLocked(newTouchedWindowHandle->getToken());
1685 if (connection == nullptr) {
1686 ALOGI("Could not find connection for %s",
1687 newTouchedWindowHandle->getName().c_str());
1688 newTouchedWindowHandle = nullptr;
1689 } else if (!connection->responsive) {
1690 // don't send the new touch to an unresponsive window
1691 ALOGW("Unresponsive window %s will not get the new gesture at %" PRIu64,
1692 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1693 newTouchedWindowHandle = nullptr;
1694 }
1695 }
1696
1697 // Also don't send the new touch event to unresponsive gesture monitors
1698 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1699
1700 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1701 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
1702 "(%d, %d) in display %" PRId32 ".",
1703 x, y, displayId);
1704 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1705 goto Failed;
1706 }
1707
1708 if (newTouchedWindowHandle != nullptr) {
1709 // Set target flags.
1710 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1711 if (isSplit) {
1712 targetFlags |= InputTarget::FLAG_SPLIT;
1713 }
1714 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1715 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1716 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1717 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1718 }
1719
1720 // Update hover state.
1721 if (isHoverAction) {
1722 newHoverWindowHandle = newTouchedWindowHandle;
1723 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1724 newHoverWindowHandle = mLastHoverWindowHandle;
1725 }
1726
1727 // Update the temporary touch state.
1728 BitSet32 pointerIds;
1729 if (isSplit) {
1730 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
1731 pointerIds.markBit(pointerId);
1732 }
1733 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1734 }
1735
1736 tempTouchState.addGestureMonitors(newGestureMonitors);
1737 } else {
1738 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1739
1740 // If the pointer is not currently down, then ignore the event.
1741 if (!tempTouchState.down) {
1742 if (DEBUG_FOCUS) {
1743 ALOGD("Dropping event because the pointer is not down or we previously "
1744 "dropped the pointer down event in display %" PRId32,
1745 displayId);
1746 }
1747 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1748 goto Failed;
1749 }
1750
1751 // Check whether touches should slip outside of the current foreground window.
1752 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
1753 tempTouchState.isSlippery()) {
1754 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1755 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1756
1757 sp<InputWindowHandle> oldTouchedWindowHandle =
1758 tempTouchState.getFirstForegroundWindowHandle();
1759 sp<InputWindowHandle> newTouchedWindowHandle =
1760 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
1761 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1762 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
1763 if (DEBUG_FOCUS) {
1764 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1765 oldTouchedWindowHandle->getName().c_str(),
1766 newTouchedWindowHandle->getName().c_str(), displayId);
1767 }
1768 // Make a slippery exit from the old window.
1769 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1770 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1771 BitSet32(0));
1772
1773 // Make a slippery entrance into the new window.
1774 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1775 isSplit = true;
1776 }
1777
1778 int32_t targetFlags =
1779 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1780 if (isSplit) {
1781 targetFlags |= InputTarget::FLAG_SPLIT;
1782 }
1783 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1784 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1785 }
1786
1787 BitSet32 pointerIds;
1788 if (isSplit) {
1789 pointerIds.markBit(entry.pointerProperties[0].id);
1790 }
1791 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1792 }
1793 }
1794 }
1795
1796 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1797 // Let the previous window know that the hover sequence is over.
1798 if (mLastHoverWindowHandle != nullptr) {
1799 #if DEBUG_HOVER
1800 ALOGD("Sending hover exit event to window %s.",
1801 mLastHoverWindowHandle->getName().c_str());
1802 #endif
1803 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1804 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1805 }
1806
1807 // Let the new window know that the hover sequence is starting.
1808 if (newHoverWindowHandle != nullptr) {
1809 #if DEBUG_HOVER
1810 ALOGD("Sending hover enter event to window %s.",
1811 newHoverWindowHandle->getName().c_str());
1812 #endif
1813 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1814 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1815 BitSet32(0));
1816 }
1817 }
1818
1819 // Check permission to inject into all touched foreground windows and ensure there
1820 // is at least one touched foreground window.
1821 {
1822 bool haveForegroundWindow = false;
1823 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
1824 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1825 haveForegroundWindow = true;
1826 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
1827 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1828 injectionPermission = INJECTION_PERMISSION_DENIED;
1829 goto Failed;
1830 }
1831 }
1832 }
1833 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
1834 if (!haveForegroundWindow && !hasGestureMonitor) {
1835 ALOGI("Dropping event because there is no touched foreground window in display "
1836 "%" PRId32 " or gesture monitor to receive it.",
1837 displayId);
1838 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1839 goto Failed;
1840 }
1841
1842 // Permission granted to injection into all touched foreground windows.
1843 injectionPermission = INJECTION_PERMISSION_GRANTED;
1844 }
1845
1846 // Check whether windows listening for outside touches are owned by the same UID. If it is
1847 // set the policy flag that we will not reveal coordinate information to this window.
1848 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1849 sp<InputWindowHandle> foregroundWindowHandle =
1850 tempTouchState.getFirstForegroundWindowHandle();
1851 if (foregroundWindowHandle) {
1852 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1853 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
1854 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1855 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1856 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1857 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1858 InputTarget::FLAG_ZERO_COORDS,
1859 BitSet32(0));
1860 }
1861 }
1862 }
1863 }
1864 }
1865
1866 // If this is the first pointer going down and the touched window has a wallpaper
1867 // then also add the touched wallpaper windows so they are locked in for the duration
1868 // of the touch gesture.
1869 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1870 // engine only supports touch events. We would need to add a mechanism similar
1871 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1872 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1873 sp<InputWindowHandle> foregroundWindowHandle =
1874 tempTouchState.getFirstForegroundWindowHandle();
1875 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
1876 const std::vector<sp<InputWindowHandle>> windowHandles =
1877 getWindowHandlesLocked(displayId);
1878 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
1879 const InputWindowInfo* info = windowHandle->getInfo();
1880 if (info->displayId == displayId &&
1881 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
1882 tempTouchState
1883 .addOrUpdateWindow(windowHandle,
1884 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1885 InputTarget::
1886 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1887 InputTarget::FLAG_DISPATCH_AS_IS,
1888 BitSet32(0));
1889 }
1890 }
1891 }
1892 }
1893
1894 // Success! Output targets.
1895 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1896
1897 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
1898 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1899 touchedWindow.pointerIds, inputTargets);
1900 }
1901
1902 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
1903 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
1904 touchedMonitor.yOffset, inputTargets);
1905 }
1906
1907 // Drop the outside or hover touch windows since we will not care about them
1908 // in the next iteration.
1909 tempTouchState.filterNonAsIsTouchWindows();
1910
1911 Failed:
1912 // Check injection permission once and for all.
1913 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
1914 if (checkInjectionPermission(nullptr, entry.injectionState)) {
1915 injectionPermission = INJECTION_PERMISSION_GRANTED;
1916 } else {
1917 injectionPermission = INJECTION_PERMISSION_DENIED;
1918 }
1919 }
1920
1921 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1922 return injectionResult;
1923 }
1924
1925 // Update final pieces of touch state if the injector had permission.
1926 if (!wrongDevice) {
1927 if (switchedDevice) {
1928 if (DEBUG_FOCUS) {
1929 ALOGD("Conflicting pointer actions: Switched to a different device.");
1930 }
1931 *outConflictingPointerActions = true;
1932 }
1933
1934 if (isHoverAction) {
1935 // Started hovering, therefore no longer down.
1936 if (oldState && oldState->down) {
1937 if (DEBUG_FOCUS) {
1938 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1939 "down.");
1940 }
1941 *outConflictingPointerActions = true;
1942 }
1943 tempTouchState.reset();
1944 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1945 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1946 tempTouchState.deviceId = entry.deviceId;
1947 tempTouchState.source = entry.source;
1948 tempTouchState.displayId = displayId;
1949 }
1950 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1951 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1952 // All pointers up or canceled.
1953 tempTouchState.reset();
1954 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1955 // First pointer went down.
1956 if (oldState && oldState->down) {
1957 if (DEBUG_FOCUS) {
1958 ALOGD("Conflicting pointer actions: Down received while already down.");
1959 }
1960 *outConflictingPointerActions = true;
1961 }
1962 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1963 // One pointer went up.
1964 if (isSplit) {
1965 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1966 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
1967
1968 for (size_t i = 0; i < tempTouchState.windows.size();) {
1969 TouchedWindow& touchedWindow = tempTouchState.windows[i];
1970 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1971 touchedWindow.pointerIds.clearBit(pointerId);
1972 if (touchedWindow.pointerIds.isEmpty()) {
1973 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
1974 continue;
1975 }
1976 }
1977 i += 1;
1978 }
1979 }
1980 }
1981
1982 // Save changes unless the action was scroll in which case the temporary touch
1983 // state was only valid for this one action.
1984 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1985 if (tempTouchState.displayId >= 0) {
1986 mTouchStatesByDisplay[displayId] = tempTouchState;
1987 } else {
1988 mTouchStatesByDisplay.erase(displayId);
1989 }
1990 }
1991
1992 // Update hover state.
1993 mLastHoverWindowHandle = newHoverWindowHandle;
1994 }
1995
1996 return injectionResult;
1997 }
1998
addWindowTargetLocked(const sp<InputWindowHandle> & windowHandle,int32_t targetFlags,BitSet32 pointerIds,std::vector<InputTarget> & inputTargets)1999 void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
2000 int32_t targetFlags, BitSet32 pointerIds,
2001 std::vector<InputTarget>& inputTargets) {
2002 std::vector<InputTarget>::iterator it =
2003 std::find_if(inputTargets.begin(), inputTargets.end(),
2004 [&windowHandle](const InputTarget& inputTarget) {
2005 return inputTarget.inputChannel->getConnectionToken() ==
2006 windowHandle->getToken();
2007 });
2008
2009 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2010
2011 if (it == inputTargets.end()) {
2012 InputTarget inputTarget;
2013 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2014 if (inputChannel == nullptr) {
2015 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2016 return;
2017 }
2018 inputTarget.inputChannel = inputChannel;
2019 inputTarget.flags = targetFlags;
2020 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2021 inputTargets.push_back(inputTarget);
2022 it = inputTargets.end() - 1;
2023 }
2024
2025 ALOG_ASSERT(it->flags == targetFlags);
2026 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2027
2028 it->addPointers(pointerIds, -windowInfo->frameLeft, -windowInfo->frameTop,
2029 windowInfo->windowXScale, windowInfo->windowYScale);
2030 }
2031
addGlobalMonitoringTargetsLocked(std::vector<InputTarget> & inputTargets,int32_t displayId,float xOffset,float yOffset)2032 void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
2033 int32_t displayId, float xOffset,
2034 float yOffset) {
2035 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2036 mGlobalMonitorsByDisplay.find(displayId);
2037
2038 if (it != mGlobalMonitorsByDisplay.end()) {
2039 const std::vector<Monitor>& monitors = it->second;
2040 for (const Monitor& monitor : monitors) {
2041 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
2042 }
2043 }
2044 }
2045
addMonitoringTargetLocked(const Monitor & monitor,float xOffset,float yOffset,std::vector<InputTarget> & inputTargets)2046 void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2047 float yOffset,
2048 std::vector<InputTarget>& inputTargets) {
2049 InputTarget target;
2050 target.inputChannel = monitor.inputChannel;
2051 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2052 target.setDefaultPointerInfo(xOffset, yOffset, 1 /* windowXScale */, 1 /* windowYScale */);
2053 inputTargets.push_back(target);
2054 }
2055
checkInjectionPermission(const sp<InputWindowHandle> & windowHandle,const InjectionState * injectionState)2056 bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
2057 const InjectionState* injectionState) {
2058 if (injectionState &&
2059 (windowHandle == nullptr ||
2060 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2061 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
2062 if (windowHandle != nullptr) {
2063 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
2064 "owned by uid %d",
2065 injectionState->injectorPid, injectionState->injectorUid,
2066 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
2067 } else {
2068 ALOGW("Permission denied: injecting event from pid %d uid %d",
2069 injectionState->injectorPid, injectionState->injectorUid);
2070 }
2071 return false;
2072 }
2073 return true;
2074 }
2075
2076 /**
2077 * Indicate whether one window handle should be considered as obscuring
2078 * another window handle. We only check a few preconditions. Actually
2079 * checking the bounds is left to the caller.
2080 */
canBeObscuredBy(const sp<InputWindowHandle> & windowHandle,const sp<InputWindowHandle> & otherHandle)2081 static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2082 const sp<InputWindowHandle>& otherHandle) {
2083 // Compare by token so cloned layers aren't counted
2084 if (haveSameToken(windowHandle, otherHandle)) {
2085 return false;
2086 }
2087 auto info = windowHandle->getInfo();
2088 auto otherInfo = otherHandle->getInfo();
2089 if (!otherInfo->visible) {
2090 return false;
2091 } else if (info->ownerPid == otherInfo->ownerPid) {
2092 // If ownerPid is the same we don't generate occlusion events as there
2093 // is no in-process security boundary.
2094 return false;
2095 } else if (otherInfo->isTrustedOverlay()) {
2096 return false;
2097 } else if (otherInfo->displayId != info->displayId) {
2098 return false;
2099 }
2100 return true;
2101 }
2102
isWindowObscuredAtPointLocked(const sp<InputWindowHandle> & windowHandle,int32_t x,int32_t y) const2103 bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2104 int32_t x, int32_t y) const {
2105 int32_t displayId = windowHandle->getInfo()->displayId;
2106 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
2107 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2108 if (windowHandle == otherHandle) {
2109 break; // All future windows are below us. Exit early.
2110 }
2111 const InputWindowInfo* otherInfo = otherHandle->getInfo();
2112 if (canBeObscuredBy(windowHandle, otherHandle) &&
2113 otherInfo->frameContainsPoint(x, y)) {
2114 return true;
2115 }
2116 }
2117 return false;
2118 }
2119
isWindowObscuredLocked(const sp<InputWindowHandle> & windowHandle) const2120 bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2121 int32_t displayId = windowHandle->getInfo()->displayId;
2122 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
2123 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2124 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
2125 if (windowHandle == otherHandle) {
2126 break; // All future windows are below us. Exit early.
2127 }
2128
2129 const InputWindowInfo* otherInfo = otherHandle->getInfo();
2130 if (canBeObscuredBy(windowHandle, otherHandle) &&
2131 otherInfo->overlaps(windowInfo)) {
2132 return true;
2133 }
2134 }
2135 return false;
2136 }
2137
getApplicationWindowLabel(const sp<InputApplicationHandle> & applicationHandle,const sp<InputWindowHandle> & windowHandle)2138 std::string InputDispatcher::getApplicationWindowLabel(
2139 const sp<InputApplicationHandle>& applicationHandle,
2140 const sp<InputWindowHandle>& windowHandle) {
2141 if (applicationHandle != nullptr) {
2142 if (windowHandle != nullptr) {
2143 return applicationHandle->getName() + " - " + windowHandle->getName();
2144 } else {
2145 return applicationHandle->getName();
2146 }
2147 } else if (windowHandle != nullptr) {
2148 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
2149 } else {
2150 return "<unknown application or window>";
2151 }
2152 }
2153
pokeUserActivityLocked(const EventEntry & eventEntry)2154 void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
2155 if (eventEntry.type == EventEntry::Type::FOCUS) {
2156 // Focus events are passed to apps, but do not represent user activity.
2157 return;
2158 }
2159 int32_t displayId = getTargetDisplayId(eventEntry);
2160 sp<InputWindowHandle> focusedWindowHandle =
2161 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2162 if (focusedWindowHandle != nullptr) {
2163 const InputWindowInfo* info = focusedWindowHandle->getInfo();
2164 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
2165 #if DEBUG_DISPATCH_CYCLE
2166 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2167 #endif
2168 return;
2169 }
2170 }
2171
2172 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
2173 switch (eventEntry.type) {
2174 case EventEntry::Type::MOTION: {
2175 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2176 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2177 return;
2178 }
2179
2180 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
2181 eventType = USER_ACTIVITY_EVENT_TOUCH;
2182 }
2183 break;
2184 }
2185 case EventEntry::Type::KEY: {
2186 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2187 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
2188 return;
2189 }
2190 eventType = USER_ACTIVITY_EVENT_BUTTON;
2191 break;
2192 }
2193 case EventEntry::Type::FOCUS:
2194 case EventEntry::Type::CONFIGURATION_CHANGED:
2195 case EventEntry::Type::DEVICE_RESET: {
2196 LOG_ALWAYS_FATAL("%s events are not user activity",
2197 EventEntry::typeToString(eventEntry.type));
2198 break;
2199 }
2200 }
2201
2202 std::unique_ptr<CommandEntry> commandEntry =
2203 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
2204 commandEntry->eventTime = eventEntry.eventTime;
2205 commandEntry->userActivityEventType = eventType;
2206 postCommandLocked(std::move(commandEntry));
2207 }
2208
prepareDispatchCycleLocked(nsecs_t currentTime,const sp<Connection> & connection,EventEntry * eventEntry,const InputTarget & inputTarget)2209 void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
2210 const sp<Connection>& connection,
2211 EventEntry* eventEntry,
2212 const InputTarget& inputTarget) {
2213 if (ATRACE_ENABLED()) {
2214 std::string message =
2215 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
2216 connection->getInputChannelName().c_str(), eventEntry->id);
2217 ATRACE_NAME(message.c_str());
2218 }
2219 #if DEBUG_DISPATCH_CYCLE
2220 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2221 "globalScaleFactor=%f, pointerIds=0x%x %s",
2222 connection->getInputChannelName().c_str(), inputTarget.flags,
2223 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2224 inputTarget.getPointerInfoString().c_str());
2225 #endif
2226
2227 // Skip this event if the connection status is not normal.
2228 // We don't want to enqueue additional outbound events if the connection is broken.
2229 if (connection->status != Connection::STATUS_NORMAL) {
2230 #if DEBUG_DISPATCH_CYCLE
2231 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
2232 connection->getInputChannelName().c_str(), connection->getStatusLabel());
2233 #endif
2234 return;
2235 }
2236
2237 // Split a motion event if needed.
2238 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2239 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2240 "Entry type %s should not have FLAG_SPLIT",
2241 EventEntry::typeToString(eventEntry->type));
2242
2243 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
2244 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
2245 MotionEntry* splitMotionEntry =
2246 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
2247 if (!splitMotionEntry) {
2248 return; // split event was dropped
2249 }
2250 if (DEBUG_FOCUS) {
2251 ALOGD("channel '%s' ~ Split motion event.",
2252 connection->getInputChannelName().c_str());
2253 logOutboundMotionDetails(" ", *splitMotionEntry);
2254 }
2255 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
2256 splitMotionEntry->release();
2257 return;
2258 }
2259 }
2260
2261 // Not splitting. Enqueue dispatch entries for the event as is.
2262 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2263 }
2264
enqueueDispatchEntriesLocked(nsecs_t currentTime,const sp<Connection> & connection,EventEntry * eventEntry,const InputTarget & inputTarget)2265 void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
2266 const sp<Connection>& connection,
2267 EventEntry* eventEntry,
2268 const InputTarget& inputTarget) {
2269 if (ATRACE_ENABLED()) {
2270 std::string message =
2271 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
2272 connection->getInputChannelName().c_str(), eventEntry->id);
2273 ATRACE_NAME(message.c_str());
2274 }
2275
2276 bool wasEmpty = connection->outboundQueue.empty();
2277
2278 // Enqueue dispatch entries for the requested modes.
2279 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2280 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
2281 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2282 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
2283 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2284 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
2285 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2286 InputTarget::FLAG_DISPATCH_AS_IS);
2287 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2288 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
2289 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2290 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
2291
2292 // If the outbound queue was previously empty, start the dispatch cycle going.
2293 if (wasEmpty && !connection->outboundQueue.empty()) {
2294 startDispatchCycleLocked(currentTime, connection);
2295 }
2296 }
2297
enqueueDispatchEntryLocked(const sp<Connection> & connection,EventEntry * eventEntry,const InputTarget & inputTarget,int32_t dispatchMode)2298 void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2299 EventEntry* eventEntry,
2300 const InputTarget& inputTarget,
2301 int32_t dispatchMode) {
2302 if (ATRACE_ENABLED()) {
2303 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2304 connection->getInputChannelName().c_str(),
2305 dispatchModeToString(dispatchMode).c_str());
2306 ATRACE_NAME(message.c_str());
2307 }
2308 int32_t inputTargetFlags = inputTarget.flags;
2309 if (!(inputTargetFlags & dispatchMode)) {
2310 return;
2311 }
2312 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2313
2314 // This is a new event.
2315 // Enqueue a new dispatch entry onto the outbound queue for this connection.
2316 std::unique_ptr<DispatchEntry> dispatchEntry =
2317 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
2318
2319 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2320 // different EventEntry than what was passed in.
2321 EventEntry* newEntry = dispatchEntry->eventEntry;
2322 // Apply target flags and update the connection's input state.
2323 switch (newEntry->type) {
2324 case EventEntry::Type::KEY: {
2325 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
2326 dispatchEntry->resolvedEventId = keyEntry.id;
2327 dispatchEntry->resolvedAction = keyEntry.action;
2328 dispatchEntry->resolvedFlags = keyEntry.flags;
2329
2330 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2331 dispatchEntry->resolvedFlags)) {
2332 #if DEBUG_DISPATCH_CYCLE
2333 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2334 connection->getInputChannelName().c_str());
2335 #endif
2336 return; // skip the inconsistent event
2337 }
2338 break;
2339 }
2340
2341 case EventEntry::Type::MOTION: {
2342 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
2343 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2344 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2345 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2346 static_cast<int32_t>(IdGenerator::Source::OTHER);
2347 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
2348 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2349 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2350 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2351 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2352 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2353 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2354 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2355 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2356 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2357 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2358 } else {
2359 dispatchEntry->resolvedAction = motionEntry.action;
2360 dispatchEntry->resolvedEventId = motionEntry.id;
2361 }
2362 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
2363 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2364 motionEntry.displayId)) {
2365 #if DEBUG_DISPATCH_CYCLE
2366 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2367 "event",
2368 connection->getInputChannelName().c_str());
2369 #endif
2370 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2371 }
2372
2373 dispatchEntry->resolvedFlags = motionEntry.flags;
2374 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2375 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2376 }
2377 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2378 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2379 }
2380
2381 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2382 dispatchEntry->resolvedFlags)) {
2383 #if DEBUG_DISPATCH_CYCLE
2384 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2385 "event",
2386 connection->getInputChannelName().c_str());
2387 #endif
2388 return; // skip the inconsistent event
2389 }
2390
2391 dispatchEntry->resolvedEventId =
2392 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2393 ? mIdGenerator.nextId()
2394 : motionEntry.id;
2395 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2396 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2397 ") to MotionEvent(id=0x%" PRIx32 ").",
2398 motionEntry.id, dispatchEntry->resolvedEventId);
2399 ATRACE_NAME(message.c_str());
2400 }
2401
2402 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
2403 inputTarget.inputChannel->getConnectionToken());
2404
2405 break;
2406 }
2407 case EventEntry::Type::FOCUS: {
2408 break;
2409 }
2410 case EventEntry::Type::CONFIGURATION_CHANGED:
2411 case EventEntry::Type::DEVICE_RESET: {
2412 LOG_ALWAYS_FATAL("%s events should not go to apps",
2413 EventEntry::typeToString(newEntry->type));
2414 break;
2415 }
2416 }
2417
2418 // Remember that we are waiting for this dispatch to complete.
2419 if (dispatchEntry->hasForegroundTarget()) {
2420 incrementPendingForegroundDispatches(newEntry);
2421 }
2422
2423 // Enqueue the dispatch entry.
2424 connection->outboundQueue.push_back(dispatchEntry.release());
2425 traceOutboundQueueLength(connection);
2426 }
2427
dispatchPointerDownOutsideFocus(uint32_t source,int32_t action,const sp<IBinder> & newToken)2428 void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
2429 const sp<IBinder>& newToken) {
2430 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2431 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2432 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
2433 return;
2434 }
2435
2436 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2437 if (inputWindowHandle == nullptr) {
2438 return;
2439 }
2440
2441 sp<InputWindowHandle> focusedWindowHandle =
2442 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
2443
2444 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2445
2446 if (!hasFocusChanged) {
2447 return;
2448 }
2449
2450 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2451 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
2452 commandEntry->newToken = newToken;
2453 postCommandLocked(std::move(commandEntry));
2454 }
2455
startDispatchCycleLocked(nsecs_t currentTime,const sp<Connection> & connection)2456 void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
2457 const sp<Connection>& connection) {
2458 if (ATRACE_ENABLED()) {
2459 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
2460 connection->getInputChannelName().c_str());
2461 ATRACE_NAME(message.c_str());
2462 }
2463 #if DEBUG_DISPATCH_CYCLE
2464 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
2465 #endif
2466
2467 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2468 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
2469 dispatchEntry->deliveryTime = currentTime;
2470 const nsecs_t timeout =
2471 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
2472 dispatchEntry->timeoutTime = currentTime + timeout;
2473
2474 // Publish the event.
2475 status_t status;
2476 EventEntry* eventEntry = dispatchEntry->eventEntry;
2477 switch (eventEntry->type) {
2478 case EventEntry::Type::KEY: {
2479 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2480 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
2481
2482 // Publish the key event.
2483 status =
2484 connection->inputPublisher
2485 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2486 keyEntry->deviceId, keyEntry->source,
2487 keyEntry->displayId, std::move(hmac),
2488 dispatchEntry->resolvedAction,
2489 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2490 keyEntry->scanCode, keyEntry->metaState,
2491 keyEntry->repeatCount, keyEntry->downTime,
2492 keyEntry->eventTime);
2493 break;
2494 }
2495
2496 case EventEntry::Type::MOTION: {
2497 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2498
2499 PointerCoords scaledCoords[MAX_POINTERS];
2500 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2501
2502 // Set the X and Y offset and X and Y scale depending on the input source.
2503 float xOffset = 0.0f, yOffset = 0.0f;
2504 float xScale = 1.0f, yScale = 1.0f;
2505 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2506 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2507 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2508 xScale = dispatchEntry->windowXScale;
2509 yScale = dispatchEntry->windowYScale;
2510 xOffset = dispatchEntry->xOffset * xScale;
2511 yOffset = dispatchEntry->yOffset * yScale;
2512 if (globalScaleFactor != 1.0f) {
2513 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2514 scaledCoords[i] = motionEntry->pointerCoords[i];
2515 // Don't apply window scale here since we don't want scale to affect raw
2516 // coordinates. The scale will be sent back to the client and applied
2517 // later when requesting relative coordinates.
2518 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2519 1 /* windowYScale */);
2520 }
2521 usingCoords = scaledCoords;
2522 }
2523 } else {
2524 // We don't want the dispatch target to know.
2525 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2526 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2527 scaledCoords[i].clear();
2528 }
2529 usingCoords = scaledCoords;
2530 }
2531 }
2532
2533 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
2534
2535 // Publish the motion event.
2536 status = connection->inputPublisher
2537 .publishMotionEvent(dispatchEntry->seq,
2538 dispatchEntry->resolvedEventId,
2539 motionEntry->deviceId, motionEntry->source,
2540 motionEntry->displayId, std::move(hmac),
2541 dispatchEntry->resolvedAction,
2542 motionEntry->actionButton,
2543 dispatchEntry->resolvedFlags,
2544 motionEntry->edgeFlags, motionEntry->metaState,
2545 motionEntry->buttonState,
2546 motionEntry->classification, xScale, yScale,
2547 xOffset, yOffset, motionEntry->xPrecision,
2548 motionEntry->yPrecision,
2549 motionEntry->xCursorPosition,
2550 motionEntry->yCursorPosition,
2551 motionEntry->downTime, motionEntry->eventTime,
2552 motionEntry->pointerCount,
2553 motionEntry->pointerProperties, usingCoords);
2554 reportTouchEventForStatistics(*motionEntry);
2555 break;
2556 }
2557 case EventEntry::Type::FOCUS: {
2558 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2559 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
2560 focusEntry->id,
2561 focusEntry->hasFocus,
2562 mInTouchMode);
2563 break;
2564 }
2565
2566 case EventEntry::Type::CONFIGURATION_CHANGED:
2567 case EventEntry::Type::DEVICE_RESET: {
2568 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2569 EventEntry::typeToString(eventEntry->type));
2570 return;
2571 }
2572 }
2573
2574 // Check the result.
2575 if (status) {
2576 if (status == WOULD_BLOCK) {
2577 if (connection->waitQueue.empty()) {
2578 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2579 "This is unexpected because the wait queue is empty, so the pipe "
2580 "should be empty and we shouldn't have any problems writing an "
2581 "event to it, status=%d",
2582 connection->getInputChannelName().c_str(), status);
2583 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2584 } else {
2585 // Pipe is full and we are waiting for the app to finish process some events
2586 // before sending more events to it.
2587 #if DEBUG_DISPATCH_CYCLE
2588 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2589 "waiting for the application to catch up",
2590 connection->getInputChannelName().c_str());
2591 #endif
2592 }
2593 } else {
2594 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
2595 "status=%d",
2596 connection->getInputChannelName().c_str(), status);
2597 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2598 }
2599 return;
2600 }
2601
2602 // Re-enqueue the event on the wait queue.
2603 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2604 connection->outboundQueue.end(),
2605 dispatchEntry));
2606 traceOutboundQueueLength(connection);
2607 connection->waitQueue.push_back(dispatchEntry);
2608 if (connection->responsive) {
2609 mAnrTracker.insert(dispatchEntry->timeoutTime,
2610 connection->inputChannel->getConnectionToken());
2611 }
2612 traceWaitQueueLength(connection);
2613 }
2614 }
2615
getSignature(const MotionEntry & motionEntry,const DispatchEntry & dispatchEntry) const2616 const std::array<uint8_t, 32> InputDispatcher::getSignature(
2617 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2618 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2619 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2620 // Only sign events up and down events as the purely move events
2621 // are tied to their up/down counterparts so signing would be redundant.
2622 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2623 verifiedEvent.actionMasked = actionMasked;
2624 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2625 return mHmacKeyManager.sign(verifiedEvent);
2626 }
2627 return INVALID_HMAC;
2628 }
2629
getSignature(const KeyEntry & keyEntry,const DispatchEntry & dispatchEntry) const2630 const std::array<uint8_t, 32> InputDispatcher::getSignature(
2631 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2632 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2633 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2634 verifiedEvent.action = dispatchEntry.resolvedAction;
2635 return mHmacKeyManager.sign(verifiedEvent);
2636 }
2637
finishDispatchCycleLocked(nsecs_t currentTime,const sp<Connection> & connection,uint32_t seq,bool handled)2638 void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2639 const sp<Connection>& connection, uint32_t seq,
2640 bool handled) {
2641 #if DEBUG_DISPATCH_CYCLE
2642 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
2643 connection->getInputChannelName().c_str(), seq, toString(handled));
2644 #endif
2645
2646 if (connection->status == Connection::STATUS_BROKEN ||
2647 connection->status == Connection::STATUS_ZOMBIE) {
2648 return;
2649 }
2650
2651 // Notify other system components and prepare to start the next dispatch cycle.
2652 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2653 }
2654
abortBrokenDispatchCycleLocked(nsecs_t currentTime,const sp<Connection> & connection,bool notify)2655 void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2656 const sp<Connection>& connection,
2657 bool notify) {
2658 #if DEBUG_DISPATCH_CYCLE
2659 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
2660 connection->getInputChannelName().c_str(), toString(notify));
2661 #endif
2662
2663 // Clear the dispatch queues.
2664 drainDispatchQueue(connection->outboundQueue);
2665 traceOutboundQueueLength(connection);
2666 drainDispatchQueue(connection->waitQueue);
2667 traceWaitQueueLength(connection);
2668
2669 // The connection appears to be unrecoverably broken.
2670 // Ignore already broken or zombie connections.
2671 if (connection->status == Connection::STATUS_NORMAL) {
2672 connection->status = Connection::STATUS_BROKEN;
2673
2674 if (notify) {
2675 // Notify other system components.
2676 onDispatchCycleBrokenLocked(currentTime, connection);
2677 }
2678 }
2679 }
2680
drainDispatchQueue(std::deque<DispatchEntry * > & queue)2681 void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2682 while (!queue.empty()) {
2683 DispatchEntry* dispatchEntry = queue.front();
2684 queue.pop_front();
2685 releaseDispatchEntry(dispatchEntry);
2686 }
2687 }
2688
releaseDispatchEntry(DispatchEntry * dispatchEntry)2689 void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
2690 if (dispatchEntry->hasForegroundTarget()) {
2691 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
2692 }
2693 delete dispatchEntry;
2694 }
2695
handleReceiveCallback(int fd,int events,void * data)2696 int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2697 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2698
2699 { // acquire lock
2700 std::scoped_lock _l(d->mLock);
2701
2702 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
2703 ALOGE("Received spurious receive callback for unknown input channel. "
2704 "fd=%d, events=0x%x",
2705 fd, events);
2706 return 0; // remove the callback
2707 }
2708
2709 bool notify;
2710 sp<Connection> connection = d->mConnectionsByFd[fd];
2711 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2712 if (!(events & ALOOPER_EVENT_INPUT)) {
2713 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
2714 "events=0x%x",
2715 connection->getInputChannelName().c_str(), events);
2716 return 1;
2717 }
2718
2719 nsecs_t currentTime = now();
2720 bool gotOne = false;
2721 status_t status;
2722 for (;;) {
2723 uint32_t seq;
2724 bool handled;
2725 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2726 if (status) {
2727 break;
2728 }
2729 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2730 gotOne = true;
2731 }
2732 if (gotOne) {
2733 d->runCommandsLockedInterruptible();
2734 if (status == WOULD_BLOCK) {
2735 return 1;
2736 }
2737 }
2738
2739 notify = status != DEAD_OBJECT || !connection->monitor;
2740 if (notify) {
2741 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2742 connection->getInputChannelName().c_str(), status);
2743 }
2744 } else {
2745 // Monitor channels are never explicitly unregistered.
2746 // We do it automatically when the remote endpoint is closed so don't warn
2747 // about them.
2748 const bool stillHaveWindowHandle =
2749 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2750 nullptr;
2751 notify = !connection->monitor && stillHaveWindowHandle;
2752 if (notify) {
2753 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
2754 "events=0x%x",
2755 connection->getInputChannelName().c_str(), events);
2756 }
2757 }
2758
2759 // Unregister the channel.
2760 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2761 return 0; // remove the callback
2762 } // release lock
2763 }
2764
synthesizeCancelationEventsForAllConnectionsLocked(const CancelationOptions & options)2765 void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2766 const CancelationOptions& options) {
2767 for (const auto& pair : mConnectionsByFd) {
2768 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
2769 }
2770 }
2771
synthesizeCancelationEventsForMonitorsLocked(const CancelationOptions & options)2772 void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2773 const CancelationOptions& options) {
2774 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2775 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2776 }
2777
synthesizeCancelationEventsForMonitorsLocked(const CancelationOptions & options,std::unordered_map<int32_t,std::vector<Monitor>> & monitorsByDisplay)2778 void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2779 const CancelationOptions& options,
2780 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2781 for (const auto& it : monitorsByDisplay) {
2782 const std::vector<Monitor>& monitors = it.second;
2783 for (const Monitor& monitor : monitors) {
2784 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
2785 }
2786 }
2787 }
2788
synthesizeCancelationEventsForInputChannelLocked(const sp<InputChannel> & channel,const CancelationOptions & options)2789 void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2790 const sp<InputChannel>& channel, const CancelationOptions& options) {
2791 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
2792 if (connection == nullptr) {
2793 return;
2794 }
2795
2796 synthesizeCancelationEventsForConnectionLocked(connection, options);
2797 }
2798
synthesizeCancelationEventsForConnectionLocked(const sp<Connection> & connection,const CancelationOptions & options)2799 void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2800 const sp<Connection>& connection, const CancelationOptions& options) {
2801 if (connection->status == Connection::STATUS_BROKEN) {
2802 return;
2803 }
2804
2805 nsecs_t currentTime = now();
2806
2807 std::vector<EventEntry*> cancelationEvents =
2808 connection->inputState.synthesizeCancelationEvents(currentTime, options);
2809
2810 if (cancelationEvents.empty()) {
2811 return;
2812 }
2813 #if DEBUG_OUTBOUND_EVENT_DETAILS
2814 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2815 "with reality: %s, mode=%d.",
2816 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2817 options.mode);
2818 #endif
2819
2820 InputTarget target;
2821 sp<InputWindowHandle> windowHandle =
2822 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2823 if (windowHandle != nullptr) {
2824 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2825 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2826 windowInfo->windowXScale, windowInfo->windowYScale);
2827 target.globalScaleFactor = windowInfo->globalScaleFactor;
2828 }
2829 target.inputChannel = connection->inputChannel;
2830 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2831
2832 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2833 EventEntry* cancelationEventEntry = cancelationEvents[i];
2834 switch (cancelationEventEntry->type) {
2835 case EventEntry::Type::KEY: {
2836 logOutboundKeyDetails("cancel - ",
2837 static_cast<const KeyEntry&>(*cancelationEventEntry));
2838 break;
2839 }
2840 case EventEntry::Type::MOTION: {
2841 logOutboundMotionDetails("cancel - ",
2842 static_cast<const MotionEntry&>(*cancelationEventEntry));
2843 break;
2844 }
2845 case EventEntry::Type::FOCUS: {
2846 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2847 break;
2848 }
2849 case EventEntry::Type::CONFIGURATION_CHANGED:
2850 case EventEntry::Type::DEVICE_RESET: {
2851 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2852 EventEntry::typeToString(cancelationEventEntry->type));
2853 break;
2854 }
2855 }
2856
2857 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2858 target, InputTarget::FLAG_DISPATCH_AS_IS);
2859
2860 cancelationEventEntry->release();
2861 }
2862
2863 startDispatchCycleLocked(currentTime, connection);
2864 }
2865
synthesizePointerDownEventsForConnectionLocked(const sp<Connection> & connection)2866 void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2867 const sp<Connection>& connection) {
2868 if (connection->status == Connection::STATUS_BROKEN) {
2869 return;
2870 }
2871
2872 nsecs_t currentTime = now();
2873
2874 std::vector<EventEntry*> downEvents =
2875 connection->inputState.synthesizePointerDownEvents(currentTime);
2876
2877 if (downEvents.empty()) {
2878 return;
2879 }
2880
2881 #if DEBUG_OUTBOUND_EVENT_DETAILS
2882 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2883 connection->getInputChannelName().c_str(), downEvents.size());
2884 #endif
2885
2886 InputTarget target;
2887 sp<InputWindowHandle> windowHandle =
2888 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2889 if (windowHandle != nullptr) {
2890 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2891 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2892 windowInfo->windowXScale, windowInfo->windowYScale);
2893 target.globalScaleFactor = windowInfo->globalScaleFactor;
2894 }
2895 target.inputChannel = connection->inputChannel;
2896 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2897
2898 for (EventEntry* downEventEntry : downEvents) {
2899 switch (downEventEntry->type) {
2900 case EventEntry::Type::MOTION: {
2901 logOutboundMotionDetails("down - ",
2902 static_cast<const MotionEntry&>(*downEventEntry));
2903 break;
2904 }
2905
2906 case EventEntry::Type::KEY:
2907 case EventEntry::Type::FOCUS:
2908 case EventEntry::Type::CONFIGURATION_CHANGED:
2909 case EventEntry::Type::DEVICE_RESET: {
2910 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2911 EventEntry::typeToString(downEventEntry->type));
2912 break;
2913 }
2914 }
2915
2916 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2917 target, InputTarget::FLAG_DISPATCH_AS_IS);
2918
2919 downEventEntry->release();
2920 }
2921
2922 startDispatchCycleLocked(currentTime, connection);
2923 }
2924
splitMotionEvent(const MotionEntry & originalMotionEntry,BitSet32 pointerIds)2925 MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
2926 BitSet32 pointerIds) {
2927 ALOG_ASSERT(pointerIds.value != 0);
2928
2929 uint32_t splitPointerIndexMap[MAX_POINTERS];
2930 PointerProperties splitPointerProperties[MAX_POINTERS];
2931 PointerCoords splitPointerCoords[MAX_POINTERS];
2932
2933 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
2934 uint32_t splitPointerCount = 0;
2935
2936 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2937 originalPointerIndex++) {
2938 const PointerProperties& pointerProperties =
2939 originalMotionEntry.pointerProperties[originalPointerIndex];
2940 uint32_t pointerId = uint32_t(pointerProperties.id);
2941 if (pointerIds.hasBit(pointerId)) {
2942 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2943 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2944 splitPointerCoords[splitPointerCount].copyFrom(
2945 originalMotionEntry.pointerCoords[originalPointerIndex]);
2946 splitPointerCount += 1;
2947 }
2948 }
2949
2950 if (splitPointerCount != pointerIds.count()) {
2951 // This is bad. We are missing some of the pointers that we expected to deliver.
2952 // Most likely this indicates that we received an ACTION_MOVE events that has
2953 // different pointer ids than we expected based on the previous ACTION_DOWN
2954 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2955 // in this way.
2956 ALOGW("Dropping split motion event because the pointer count is %d but "
2957 "we expected there to be %d pointers. This probably means we received "
2958 "a broken sequence of pointer ids from the input device.",
2959 splitPointerCount, pointerIds.count());
2960 return nullptr;
2961 }
2962
2963 int32_t action = originalMotionEntry.action;
2964 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2965 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2966 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2967 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2968 const PointerProperties& pointerProperties =
2969 originalMotionEntry.pointerProperties[originalPointerIndex];
2970 uint32_t pointerId = uint32_t(pointerProperties.id);
2971 if (pointerIds.hasBit(pointerId)) {
2972 if (pointerIds.count() == 1) {
2973 // The first/last pointer went down/up.
2974 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2975 ? AMOTION_EVENT_ACTION_DOWN
2976 : AMOTION_EVENT_ACTION_UP;
2977 } else {
2978 // A secondary pointer went down/up.
2979 uint32_t splitPointerIndex = 0;
2980 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2981 splitPointerIndex += 1;
2982 }
2983 action = maskedAction |
2984 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2985 }
2986 } else {
2987 // An unrelated pointer changed.
2988 action = AMOTION_EVENT_ACTION_MOVE;
2989 }
2990 }
2991
2992 int32_t newId = mIdGenerator.nextId();
2993 if (ATRACE_ENABLED()) {
2994 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
2995 ") to MotionEvent(id=0x%" PRIx32 ").",
2996 originalMotionEntry.id, newId);
2997 ATRACE_NAME(message.c_str());
2998 }
2999 MotionEntry* splitMotionEntry =
3000 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3001 originalMotionEntry.source, originalMotionEntry.displayId,
3002 originalMotionEntry.policyFlags, action,
3003 originalMotionEntry.actionButton, originalMotionEntry.flags,
3004 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3005 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3006 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3007 originalMotionEntry.xCursorPosition,
3008 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
3009 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
3010
3011 if (originalMotionEntry.injectionState) {
3012 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
3013 splitMotionEntry->injectionState->refCount += 1;
3014 }
3015
3016 return splitMotionEntry;
3017 }
3018
notifyConfigurationChanged(const NotifyConfigurationChangedArgs * args)3019 void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3020 #if DEBUG_INBOUND_EVENT_DETAILS
3021 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3022 #endif
3023
3024 bool needWake;
3025 { // acquire lock
3026 std::scoped_lock _l(mLock);
3027
3028 ConfigurationChangedEntry* newEntry =
3029 new ConfigurationChangedEntry(args->id, args->eventTime);
3030 needWake = enqueueInboundEventLocked(newEntry);
3031 } // release lock
3032
3033 if (needWake) {
3034 mLooper->wake();
3035 }
3036 }
3037
3038 /**
3039 * If one of the meta shortcuts is detected, process them here:
3040 * Meta + Backspace -> generate BACK
3041 * Meta + Enter -> generate HOME
3042 * This will potentially overwrite keyCode and metaState.
3043 */
accelerateMetaShortcuts(const int32_t deviceId,const int32_t action,int32_t & keyCode,int32_t & metaState)3044 void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
3045 int32_t& keyCode, int32_t& metaState) {
3046 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3047 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3048 if (keyCode == AKEYCODE_DEL) {
3049 newKeyCode = AKEYCODE_BACK;
3050 } else if (keyCode == AKEYCODE_ENTER) {
3051 newKeyCode = AKEYCODE_HOME;
3052 }
3053 if (newKeyCode != AKEYCODE_UNKNOWN) {
3054 std::scoped_lock _l(mLock);
3055 struct KeyReplacement replacement = {keyCode, deviceId};
3056 mReplacedKeys[replacement] = newKeyCode;
3057 keyCode = newKeyCode;
3058 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3059 }
3060 } else if (action == AKEY_EVENT_ACTION_UP) {
3061 // In order to maintain a consistent stream of up and down events, check to see if the key
3062 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3063 // even if the modifier was released between the down and the up events.
3064 std::scoped_lock _l(mLock);
3065 struct KeyReplacement replacement = {keyCode, deviceId};
3066 auto replacementIt = mReplacedKeys.find(replacement);
3067 if (replacementIt != mReplacedKeys.end()) {
3068 keyCode = replacementIt->second;
3069 mReplacedKeys.erase(replacementIt);
3070 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3071 }
3072 }
3073 }
3074
notifyKey(const NotifyKeyArgs * args)3075 void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3076 #if DEBUG_INBOUND_EVENT_DETAILS
3077 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3078 "policyFlags=0x%x, action=0x%x, "
3079 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3080 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3081 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3082 args->downTime);
3083 #endif
3084 if (!validateKeyEvent(args->action)) {
3085 return;
3086 }
3087
3088 uint32_t policyFlags = args->policyFlags;
3089 int32_t flags = args->flags;
3090 int32_t metaState = args->metaState;
3091 // InputDispatcher tracks and generates key repeats on behalf of
3092 // whatever notifies it, so repeatCount should always be set to 0
3093 constexpr int32_t repeatCount = 0;
3094 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3095 policyFlags |= POLICY_FLAG_VIRTUAL;
3096 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3097 }
3098 if (policyFlags & POLICY_FLAG_FUNCTION) {
3099 metaState |= AMETA_FUNCTION_ON;
3100 }
3101
3102 policyFlags |= POLICY_FLAG_TRUSTED;
3103
3104 int32_t keyCode = args->keyCode;
3105 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
3106
3107 KeyEvent event;
3108 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3109 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3110 args->downTime, args->eventTime);
3111
3112 android::base::Timer t;
3113 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
3114 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3115 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3116 std::to_string(t.duration().count()).c_str());
3117 }
3118
3119 bool needWake;
3120 { // acquire lock
3121 mLock.lock();
3122
3123 if (shouldSendKeyToInputFilterLocked(args)) {
3124 mLock.unlock();
3125
3126 policyFlags |= POLICY_FLAG_FILTERED;
3127 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3128 return; // event was consumed by the filter
3129 }
3130
3131 mLock.lock();
3132 }
3133
3134 KeyEntry* newEntry =
3135 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
3136 args->displayId, policyFlags, args->action, flags, keyCode,
3137 args->scanCode, metaState, repeatCount, args->downTime);
3138
3139 needWake = enqueueInboundEventLocked(newEntry);
3140 mLock.unlock();
3141 } // release lock
3142
3143 if (needWake) {
3144 mLooper->wake();
3145 }
3146 }
3147
shouldSendKeyToInputFilterLocked(const NotifyKeyArgs * args)3148 bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3149 return mInputFilterEnabled;
3150 }
3151
notifyMotion(const NotifyMotionArgs * args)3152 void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3153 #if DEBUG_INBOUND_EVENT_DETAILS
3154 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3155 "displayId=%" PRId32 ", policyFlags=0x%x, "
3156 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3157 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3158 "yCursorPosition=%f, downTime=%" PRId64,
3159 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3160 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3161 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3162 args->xCursorPosition, args->yCursorPosition, args->downTime);
3163 for (uint32_t i = 0; i < args->pointerCount; i++) {
3164 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3165 "x=%f, y=%f, pressure=%f, size=%f, "
3166 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3167 "orientation=%f",
3168 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3169 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3170 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3171 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3172 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3173 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3174 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3175 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3176 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3177 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
3178 }
3179 #endif
3180 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3181 args->pointerProperties)) {
3182 return;
3183 }
3184
3185 uint32_t policyFlags = args->policyFlags;
3186 policyFlags |= POLICY_FLAG_TRUSTED;
3187
3188 android::base::Timer t;
3189 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
3190 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3191 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3192 std::to_string(t.duration().count()).c_str());
3193 }
3194
3195 bool needWake;
3196 { // acquire lock
3197 mLock.lock();
3198
3199 if (shouldSendMotionToInputFilterLocked(args)) {
3200 mLock.unlock();
3201
3202 MotionEvent event;
3203 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3204 args->action, args->actionButton, args->flags, args->edgeFlags,
3205 args->metaState, args->buttonState, args->classification, 1 /*xScale*/,
3206 1 /*yScale*/, 0 /* xOffset */, 0 /* yOffset */, args->xPrecision,
3207 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3208 args->downTime, args->eventTime, args->pointerCount,
3209 args->pointerProperties, args->pointerCoords);
3210
3211 policyFlags |= POLICY_FLAG_FILTERED;
3212 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3213 return; // event was consumed by the filter
3214 }
3215
3216 mLock.lock();
3217 }
3218
3219 // Just enqueue a new motion event.
3220 MotionEntry* newEntry =
3221 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
3222 args->displayId, policyFlags, args->action, args->actionButton,
3223 args->flags, args->metaState, args->buttonState,
3224 args->classification, args->edgeFlags, args->xPrecision,
3225 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3226 args->downTime, args->pointerCount, args->pointerProperties,
3227 args->pointerCoords, 0, 0);
3228
3229 needWake = enqueueInboundEventLocked(newEntry);
3230 mLock.unlock();
3231 } // release lock
3232
3233 if (needWake) {
3234 mLooper->wake();
3235 }
3236 }
3237
shouldSendMotionToInputFilterLocked(const NotifyMotionArgs * args)3238 bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
3239 return mInputFilterEnabled;
3240 }
3241
notifySwitch(const NotifySwitchArgs * args)3242 void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3243 #if DEBUG_INBOUND_EVENT_DETAILS
3244 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
3245 "switchMask=0x%08x",
3246 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
3247 #endif
3248
3249 uint32_t policyFlags = args->policyFlags;
3250 policyFlags |= POLICY_FLAG_TRUSTED;
3251 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
3252 }
3253
notifyDeviceReset(const NotifyDeviceResetArgs * args)3254 void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3255 #if DEBUG_INBOUND_EVENT_DETAILS
3256 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3257 args->deviceId);
3258 #endif
3259
3260 bool needWake;
3261 { // acquire lock
3262 std::scoped_lock _l(mLock);
3263
3264 DeviceResetEntry* newEntry =
3265 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
3266 needWake = enqueueInboundEventLocked(newEntry);
3267 } // release lock
3268
3269 if (needWake) {
3270 mLooper->wake();
3271 }
3272 }
3273
injectInputEvent(const InputEvent * event,int32_t injectorPid,int32_t injectorUid,int32_t syncMode,std::chrono::milliseconds timeout,uint32_t policyFlags)3274 int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3275 int32_t injectorUid, int32_t syncMode,
3276 std::chrono::milliseconds timeout, uint32_t policyFlags) {
3277 #if DEBUG_INBOUND_EVENT_DETAILS
3278 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
3279 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3280 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
3281 #endif
3282
3283 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
3284
3285 policyFlags |= POLICY_FLAG_INJECTED;
3286 if (hasInjectionPermission(injectorPid, injectorUid)) {
3287 policyFlags |= POLICY_FLAG_TRUSTED;
3288 }
3289
3290 std::queue<EventEntry*> injectedEntries;
3291 switch (event->getType()) {
3292 case AINPUT_EVENT_TYPE_KEY: {
3293 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3294 int32_t action = incomingKey.getAction();
3295 if (!validateKeyEvent(action)) {
3296 return INPUT_EVENT_INJECTION_FAILED;
3297 }
3298
3299 int32_t flags = incomingKey.getFlags();
3300 int32_t keyCode = incomingKey.getKeyCode();
3301 int32_t metaState = incomingKey.getMetaState();
3302 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
3303 /*byref*/ keyCode, /*byref*/ metaState);
3304 KeyEvent keyEvent;
3305 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
3306 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3307 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3308 incomingKey.getDownTime(), incomingKey.getEventTime());
3309
3310 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3311 policyFlags |= POLICY_FLAG_VIRTUAL;
3312 }
3313
3314 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3315 android::base::Timer t;
3316 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3317 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3318 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3319 std::to_string(t.duration().count()).c_str());
3320 }
3321 }
3322
3323 mLock.lock();
3324 KeyEntry* injectedEntry =
3325 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3326 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
3327 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3328 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3329 incomingKey.getDownTime());
3330 injectedEntries.push(injectedEntry);
3331 break;
3332 }
3333
3334 case AINPUT_EVENT_TYPE_MOTION: {
3335 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3336 int32_t action = motionEvent->getAction();
3337 size_t pointerCount = motionEvent->getPointerCount();
3338 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3339 int32_t actionButton = motionEvent->getActionButton();
3340 int32_t displayId = motionEvent->getDisplayId();
3341 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3342 return INPUT_EVENT_INJECTION_FAILED;
3343 }
3344
3345 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3346 nsecs_t eventTime = motionEvent->getEventTime();
3347 android::base::Timer t;
3348 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3349 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3350 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3351 std::to_string(t.duration().count()).c_str());
3352 }
3353 }
3354
3355 mLock.lock();
3356 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3357 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3358 MotionEntry* injectedEntry =
3359 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3360 motionEvent->getSource(), motionEvent->getDisplayId(),
3361 policyFlags, action, actionButton, motionEvent->getFlags(),
3362 motionEvent->getMetaState(), motionEvent->getButtonState(),
3363 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3364 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
3365 motionEvent->getRawXCursorPosition(),
3366 motionEvent->getRawYCursorPosition(),
3367 motionEvent->getDownTime(), uint32_t(pointerCount),
3368 pointerProperties, samplePointerCoords,
3369 motionEvent->getXOffset(), motionEvent->getYOffset());
3370 injectedEntries.push(injectedEntry);
3371 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3372 sampleEventTimes += 1;
3373 samplePointerCoords += pointerCount;
3374 MotionEntry* nextInjectedEntry =
3375 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
3376 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
3377 motionEvent->getDisplayId(), policyFlags, action,
3378 actionButton, motionEvent->getFlags(),
3379 motionEvent->getMetaState(), motionEvent->getButtonState(),
3380 motionEvent->getClassification(),
3381 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3382 motionEvent->getYPrecision(),
3383 motionEvent->getRawXCursorPosition(),
3384 motionEvent->getRawYCursorPosition(),
3385 motionEvent->getDownTime(), uint32_t(pointerCount),
3386 pointerProperties, samplePointerCoords,
3387 motionEvent->getXOffset(), motionEvent->getYOffset());
3388 injectedEntries.push(nextInjectedEntry);
3389 }
3390 break;
3391 }
3392
3393 default:
3394 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
3395 return INPUT_EVENT_INJECTION_FAILED;
3396 }
3397
3398 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3399 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3400 injectionState->injectionIsAsync = true;
3401 }
3402
3403 injectionState->refCount += 1;
3404 injectedEntries.back()->injectionState = injectionState;
3405
3406 bool needWake = false;
3407 while (!injectedEntries.empty()) {
3408 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3409 injectedEntries.pop();
3410 }
3411
3412 mLock.unlock();
3413
3414 if (needWake) {
3415 mLooper->wake();
3416 }
3417
3418 int32_t injectionResult;
3419 { // acquire lock
3420 std::unique_lock _l(mLock);
3421
3422 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3423 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3424 } else {
3425 for (;;) {
3426 injectionResult = injectionState->injectionResult;
3427 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3428 break;
3429 }
3430
3431 nsecs_t remainingTimeout = endTime - now();
3432 if (remainingTimeout <= 0) {
3433 #if DEBUG_INJECTION
3434 ALOGD("injectInputEvent - Timed out waiting for injection result "
3435 "to become available.");
3436 #endif
3437 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3438 break;
3439 }
3440
3441 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
3442 }
3443
3444 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3445 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
3446 while (injectionState->pendingForegroundDispatches != 0) {
3447 #if DEBUG_INJECTION
3448 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
3449 injectionState->pendingForegroundDispatches);
3450 #endif
3451 nsecs_t remainingTimeout = endTime - now();
3452 if (remainingTimeout <= 0) {
3453 #if DEBUG_INJECTION
3454 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3455 "dispatches to finish.");
3456 #endif
3457 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3458 break;
3459 }
3460
3461 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
3462 }
3463 }
3464 }
3465
3466 injectionState->release();
3467 } // release lock
3468
3469 #if DEBUG_INJECTION
3470 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
3471 injectionResult, injectorPid, injectorUid);
3472 #endif
3473
3474 return injectionResult;
3475 }
3476
verifyInputEvent(const InputEvent & event)3477 std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
3478 std::array<uint8_t, 32> calculatedHmac;
3479 std::unique_ptr<VerifiedInputEvent> result;
3480 switch (event.getType()) {
3481 case AINPUT_EVENT_TYPE_KEY: {
3482 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3483 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3484 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3485 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3486 break;
3487 }
3488 case AINPUT_EVENT_TYPE_MOTION: {
3489 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3490 VerifiedMotionEvent verifiedMotionEvent =
3491 verifiedMotionEventFromMotionEvent(motionEvent);
3492 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3493 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3494 break;
3495 }
3496 default: {
3497 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3498 return nullptr;
3499 }
3500 }
3501 if (calculatedHmac == INVALID_HMAC) {
3502 return nullptr;
3503 }
3504 if (calculatedHmac != event.getHmac()) {
3505 return nullptr;
3506 }
3507 return result;
3508 }
3509
hasInjectionPermission(int32_t injectorPid,int32_t injectorUid)3510 bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
3511 return injectorUid == 0 ||
3512 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
3513 }
3514
setInjectionResult(EventEntry * entry,int32_t injectionResult)3515 void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
3516 InjectionState* injectionState = entry->injectionState;
3517 if (injectionState) {
3518 #if DEBUG_INJECTION
3519 ALOGD("Setting input event injection result to %d. "
3520 "injectorPid=%d, injectorUid=%d",
3521 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
3522 #endif
3523
3524 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
3525 // Log the outcome since the injector did not wait for the injection result.
3526 switch (injectionResult) {
3527 case INPUT_EVENT_INJECTION_SUCCEEDED:
3528 ALOGV("Asynchronous input event injection succeeded.");
3529 break;
3530 case INPUT_EVENT_INJECTION_FAILED:
3531 ALOGW("Asynchronous input event injection failed.");
3532 break;
3533 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3534 ALOGW("Asynchronous input event injection permission denied.");
3535 break;
3536 case INPUT_EVENT_INJECTION_TIMED_OUT:
3537 ALOGW("Asynchronous input event injection timed out.");
3538 break;
3539 }
3540 }
3541
3542 injectionState->injectionResult = injectionResult;
3543 mInjectionResultAvailable.notify_all();
3544 }
3545 }
3546
incrementPendingForegroundDispatches(EventEntry * entry)3547 void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
3548 InjectionState* injectionState = entry->injectionState;
3549 if (injectionState) {
3550 injectionState->pendingForegroundDispatches += 1;
3551 }
3552 }
3553
decrementPendingForegroundDispatches(EventEntry * entry)3554 void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
3555 InjectionState* injectionState = entry->injectionState;
3556 if (injectionState) {
3557 injectionState->pendingForegroundDispatches -= 1;
3558
3559 if (injectionState->pendingForegroundDispatches == 0) {
3560 mInjectionSyncFinished.notify_all();
3561 }
3562 }
3563 }
3564
getWindowHandlesLocked(int32_t displayId) const3565 std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3566 int32_t displayId) const {
3567 return getValueByKey(mWindowHandlesByDisplay, displayId);
3568 }
3569
getWindowHandleLocked(const sp<IBinder> & windowHandleToken) const3570 sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
3571 const sp<IBinder>& windowHandleToken) const {
3572 if (windowHandleToken == nullptr) {
3573 return nullptr;
3574 }
3575
3576 for (auto& it : mWindowHandlesByDisplay) {
3577 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3578 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
3579 if (windowHandle->getToken() == windowHandleToken) {
3580 return windowHandle;
3581 }
3582 }
3583 }
3584 return nullptr;
3585 }
3586
hasWindowHandleLocked(const sp<InputWindowHandle> & windowHandle) const3587 bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3588 for (auto& it : mWindowHandlesByDisplay) {
3589 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3590 for (const sp<InputWindowHandle>& handle : windowHandles) {
3591 if (handle->getId() == windowHandle->getId() &&
3592 handle->getToken() == windowHandle->getToken()) {
3593 if (windowHandle->getInfo()->displayId != it.first) {
3594 ALOGE("Found window %s in display %" PRId32
3595 ", but it should belong to display %" PRId32,
3596 windowHandle->getName().c_str(), it.first,
3597 windowHandle->getInfo()->displayId);
3598 }
3599 return true;
3600 }
3601 }
3602 }
3603 return false;
3604 }
3605
getInputChannelLocked(const sp<IBinder> & token) const3606 sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3607 size_t count = mInputChannelsByToken.count(token);
3608 if (count == 0) {
3609 return nullptr;
3610 }
3611 return mInputChannelsByToken.at(token);
3612 }
3613
updateWindowHandlesForDisplayLocked(const std::vector<sp<InputWindowHandle>> & inputWindowHandles,int32_t displayId)3614 void InputDispatcher::updateWindowHandlesForDisplayLocked(
3615 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3616 if (inputWindowHandles.empty()) {
3617 // Remove all handles on a display if there are no windows left.
3618 mWindowHandlesByDisplay.erase(displayId);
3619 return;
3620 }
3621
3622 // Since we compare the pointer of input window handles across window updates, we need
3623 // to make sure the handle object for the same window stays unchanged across updates.
3624 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
3625 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
3626 for (const sp<InputWindowHandle>& handle : oldHandles) {
3627 oldHandlesById[handle->getId()] = handle;
3628 }
3629
3630 std::vector<sp<InputWindowHandle>> newHandles;
3631 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3632 if (!handle->updateInfo()) {
3633 // handle no longer valid
3634 continue;
3635 }
3636
3637 const InputWindowInfo* info = handle->getInfo();
3638 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3639 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3640 const bool noInputChannel =
3641 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3642 const bool canReceiveInput =
3643 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3644 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3645 if (canReceiveInput && !noInputChannel) {
3646 ALOGV("Window handle %s has no registered input channel",
3647 handle->getName().c_str());
3648 continue;
3649 }
3650 }
3651
3652 if (info->displayId != displayId) {
3653 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3654 handle->getName().c_str(), displayId, info->displayId);
3655 continue;
3656 }
3657
3658 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3659 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
3660 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
3661 oldHandle->updateFrom(handle);
3662 newHandles.push_back(oldHandle);
3663 } else {
3664 newHandles.push_back(handle);
3665 }
3666 }
3667
3668 // Insert or replace
3669 mWindowHandlesByDisplay[displayId] = newHandles;
3670 }
3671
setInputWindows(const std::unordered_map<int32_t,std::vector<sp<InputWindowHandle>>> & handlesPerDisplay)3672 void InputDispatcher::setInputWindows(
3673 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3674 { // acquire lock
3675 std::scoped_lock _l(mLock);
3676 for (auto const& i : handlesPerDisplay) {
3677 setInputWindowsLocked(i.second, i.first);
3678 }
3679 }
3680 // Wake up poll loop since it may need to make new input dispatching choices.
3681 mLooper->wake();
3682 }
3683
3684 /**
3685 * Called from InputManagerService, update window handle list by displayId that can receive input.
3686 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3687 * If set an empty list, remove all handles from the specific display.
3688 * For focused handle, check if need to change and send a cancel event to previous one.
3689 * For removed handle, check if need to send a cancel event if already in touch.
3690 */
setInputWindowsLocked(const std::vector<sp<InputWindowHandle>> & inputWindowHandles,int32_t displayId)3691 void InputDispatcher::setInputWindowsLocked(
3692 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3693 if (DEBUG_FOCUS) {
3694 std::string windowList;
3695 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3696 windowList += iwh->getName() + " ";
3697 }
3698 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3699 }
3700
3701 // Copy old handles for release if they are no longer present.
3702 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
3703
3704 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
3705
3706 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3707 bool foundHoveredWindow = false;
3708 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3709 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3710 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3711 windowHandle->getInfo()->visible) {
3712 newFocusedWindowHandle = windowHandle;
3713 }
3714 if (windowHandle == mLastHoverWindowHandle) {
3715 foundHoveredWindow = true;
3716 }
3717 }
3718
3719 if (!foundHoveredWindow) {
3720 mLastHoverWindowHandle = nullptr;
3721 }
3722
3723 sp<InputWindowHandle> oldFocusedWindowHandle =
3724 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3725
3726 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
3727 if (oldFocusedWindowHandle != nullptr) {
3728 if (DEBUG_FOCUS) {
3729 ALOGD("Focus left window: %s in display %" PRId32,
3730 oldFocusedWindowHandle->getName().c_str(), displayId);
3731 }
3732 sp<InputChannel> focusedInputChannel =
3733 getInputChannelLocked(oldFocusedWindowHandle->getToken());
3734 if (focusedInputChannel != nullptr) {
3735 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3736 "focus left window");
3737 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
3738 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
3739 }
3740 mFocusedWindowHandlesByDisplay.erase(displayId);
3741 }
3742 if (newFocusedWindowHandle != nullptr) {
3743 if (DEBUG_FOCUS) {
3744 ALOGD("Focus entered window: %s in display %" PRId32,
3745 newFocusedWindowHandle->getName().c_str(), displayId);
3746 }
3747 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
3748 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
3749 }
3750
3751 if (mFocusedDisplayId == displayId) {
3752 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
3753 }
3754 }
3755
3756 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3757 mTouchStatesByDisplay.find(displayId);
3758 if (stateIt != mTouchStatesByDisplay.end()) {
3759 TouchState& state = stateIt->second;
3760 for (size_t i = 0; i < state.windows.size();) {
3761 TouchedWindow& touchedWindow = state.windows[i];
3762 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
3763 if (DEBUG_FOCUS) {
3764 ALOGD("Touched window was removed: %s in display %" PRId32,
3765 touchedWindow.windowHandle->getName().c_str(), displayId);
3766 }
3767 sp<InputChannel> touchedInputChannel =
3768 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3769 if (touchedInputChannel != nullptr) {
3770 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3771 "touched window was removed");
3772 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
3773 }
3774 state.windows.erase(state.windows.begin() + i);
3775 } else {
3776 ++i;
3777 }
3778 }
3779 }
3780
3781 // Release information for windows that are no longer present.
3782 // This ensures that unused input channels are released promptly.
3783 // Otherwise, they might stick around until the window handle is destroyed
3784 // which might not happen until the next GC.
3785 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
3786 if (!hasWindowHandleLocked(oldWindowHandle)) {
3787 if (DEBUG_FOCUS) {
3788 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
3789 }
3790 oldWindowHandle->releaseChannel();
3791 }
3792 }
3793 }
3794
setFocusedApplication(int32_t displayId,const sp<InputApplicationHandle> & inputApplicationHandle)3795 void InputDispatcher::setFocusedApplication(
3796 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
3797 if (DEBUG_FOCUS) {
3798 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3799 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3800 }
3801 { // acquire lock
3802 std::scoped_lock _l(mLock);
3803
3804 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3805 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
3806
3807 if (oldFocusedApplicationHandle == mAwaitedFocusedApplication &&
3808 inputApplicationHandle != oldFocusedApplicationHandle) {
3809 resetNoFocusedWindowTimeoutLocked();
3810 }
3811
3812 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
3813 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3814 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
3815 }
3816 } else if (oldFocusedApplicationHandle != nullptr) {
3817 oldFocusedApplicationHandle.clear();
3818 mFocusedApplicationHandlesByDisplay.erase(displayId);
3819 }
3820 } // release lock
3821
3822 // Wake up poll loop since it may need to make new input dispatching choices.
3823 mLooper->wake();
3824 }
3825
3826 /**
3827 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3828 * the display not specified.
3829 *
3830 * We track any unreleased events for each window. If a window loses the ability to receive the
3831 * released event, we will send a cancel event to it. So when the focused display is changed, we
3832 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3833 * display. The display-specified events won't be affected.
3834 */
setFocusedDisplay(int32_t displayId)3835 void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3836 if (DEBUG_FOCUS) {
3837 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3838 }
3839 { // acquire lock
3840 std::scoped_lock _l(mLock);
3841
3842 if (mFocusedDisplayId != displayId) {
3843 sp<InputWindowHandle> oldFocusedWindowHandle =
3844 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3845 if (oldFocusedWindowHandle != nullptr) {
3846 sp<InputChannel> inputChannel =
3847 getInputChannelLocked(oldFocusedWindowHandle->getToken());
3848 if (inputChannel != nullptr) {
3849 CancelationOptions
3850 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3851 "The display which contains this window no longer has focus.");
3852 options.displayId = ADISPLAY_ID_NONE;
3853 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3854 }
3855 }
3856 mFocusedDisplayId = displayId;
3857
3858 // Sanity check
3859 sp<InputWindowHandle> newFocusedWindowHandle =
3860 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3861 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
3862
3863 if (newFocusedWindowHandle == nullptr) {
3864 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3865 if (!mFocusedWindowHandlesByDisplay.empty()) {
3866 ALOGE("But another display has a focused window:");
3867 for (auto& it : mFocusedWindowHandlesByDisplay) {
3868 const int32_t displayId = it.first;
3869 const sp<InputWindowHandle>& windowHandle = it.second;
3870 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3871 windowHandle->getName().c_str());
3872 }
3873 }
3874 }
3875 }
3876
3877 if (DEBUG_FOCUS) {
3878 logDispatchStateLocked();
3879 }
3880 } // release lock
3881
3882 // Wake up poll loop since it may need to make new input dispatching choices.
3883 mLooper->wake();
3884 }
3885
setInputDispatchMode(bool enabled,bool frozen)3886 void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3887 if (DEBUG_FOCUS) {
3888 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3889 }
3890
3891 bool changed;
3892 { // acquire lock
3893 std::scoped_lock _l(mLock);
3894
3895 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3896 if (mDispatchFrozen && !frozen) {
3897 resetNoFocusedWindowTimeoutLocked();
3898 }
3899
3900 if (mDispatchEnabled && !enabled) {
3901 resetAndDropEverythingLocked("dispatcher is being disabled");
3902 }
3903
3904 mDispatchEnabled = enabled;
3905 mDispatchFrozen = frozen;
3906 changed = true;
3907 } else {
3908 changed = false;
3909 }
3910
3911 if (DEBUG_FOCUS) {
3912 logDispatchStateLocked();
3913 }
3914 } // release lock
3915
3916 if (changed) {
3917 // Wake up poll loop since it may need to make new input dispatching choices.
3918 mLooper->wake();
3919 }
3920 }
3921
setInputFilterEnabled(bool enabled)3922 void InputDispatcher::setInputFilterEnabled(bool enabled) {
3923 if (DEBUG_FOCUS) {
3924 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3925 }
3926
3927 { // acquire lock
3928 std::scoped_lock _l(mLock);
3929
3930 if (mInputFilterEnabled == enabled) {
3931 return;
3932 }
3933
3934 mInputFilterEnabled = enabled;
3935 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3936 } // release lock
3937
3938 // Wake up poll loop since there might be work to do to drop everything.
3939 mLooper->wake();
3940 }
3941
setInTouchMode(bool inTouchMode)3942 void InputDispatcher::setInTouchMode(bool inTouchMode) {
3943 std::scoped_lock lock(mLock);
3944 mInTouchMode = inTouchMode;
3945 }
3946
transferTouchFocus(const sp<IBinder> & fromToken,const sp<IBinder> & toToken)3947 bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3948 if (fromToken == toToken) {
3949 if (DEBUG_FOCUS) {
3950 ALOGD("Trivial transfer to same window.");
3951 }
3952 return true;
3953 }
3954
3955 { // acquire lock
3956 std::scoped_lock _l(mLock);
3957
3958 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3959 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
3960 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
3961 ALOGW("Cannot transfer focus because from or to window not found.");
3962 return false;
3963 }
3964 if (DEBUG_FOCUS) {
3965 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3966 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3967 }
3968 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3969 if (DEBUG_FOCUS) {
3970 ALOGD("Cannot transfer focus because windows are on different displays.");
3971 }
3972 return false;
3973 }
3974
3975 bool found = false;
3976 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
3977 TouchState& state = pair.second;
3978 for (size_t i = 0; i < state.windows.size(); i++) {
3979 const TouchedWindow& touchedWindow = state.windows[i];
3980 if (touchedWindow.windowHandle == fromWindowHandle) {
3981 int32_t oldTargetFlags = touchedWindow.targetFlags;
3982 BitSet32 pointerIds = touchedWindow.pointerIds;
3983
3984 state.windows.erase(state.windows.begin() + i);
3985
3986 int32_t newTargetFlags = oldTargetFlags &
3987 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3988 InputTarget::FLAG_DISPATCH_AS_IS);
3989 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
3990
3991 found = true;
3992 goto Found;
3993 }
3994 }
3995 }
3996 Found:
3997
3998 if (!found) {
3999 if (DEBUG_FOCUS) {
4000 ALOGD("Focus transfer failed because from window did not have focus.");
4001 }
4002 return false;
4003 }
4004
4005 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4006 sp<Connection> toConnection = getConnectionLocked(toToken);
4007 if (fromConnection != nullptr && toConnection != nullptr) {
4008 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
4009 CancelationOptions
4010 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4011 "transferring touch focus from this window to another window");
4012 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
4013 synthesizePointerDownEventsForConnectionLocked(toConnection);
4014 }
4015
4016 if (DEBUG_FOCUS) {
4017 logDispatchStateLocked();
4018 }
4019 } // release lock
4020
4021 // Wake up poll loop since it may need to make new input dispatching choices.
4022 mLooper->wake();
4023 return true;
4024 }
4025
resetAndDropEverythingLocked(const char * reason)4026 void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
4027 if (DEBUG_FOCUS) {
4028 ALOGD("Resetting and dropping all events (%s).", reason);
4029 }
4030
4031 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4032 synthesizeCancelationEventsForAllConnectionsLocked(options);
4033
4034 resetKeyRepeatLocked();
4035 releasePendingEventLocked();
4036 drainInboundQueueLocked();
4037 resetNoFocusedWindowTimeoutLocked();
4038
4039 mAnrTracker.clear();
4040 mTouchStatesByDisplay.clear();
4041 mLastHoverWindowHandle.clear();
4042 mReplacedKeys.clear();
4043 }
4044
logDispatchStateLocked()4045 void InputDispatcher::logDispatchStateLocked() {
4046 std::string dump;
4047 dumpDispatchStateLocked(dump);
4048
4049 std::istringstream stream(dump);
4050 std::string line;
4051
4052 while (std::getline(stream, line, '\n')) {
4053 ALOGD("%s", line.c_str());
4054 }
4055 }
4056
dumpDispatchStateLocked(std::string & dump)4057 void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
4058 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4059 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4060 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
4061 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
4062
4063 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4064 dump += StringPrintf(INDENT "FocusedApplications:\n");
4065 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4066 const int32_t displayId = it.first;
4067 const sp<InputApplicationHandle>& applicationHandle = it.second;
4068 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4069 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
4070 displayId, applicationHandle->getName().c_str(),
4071 ns2ms(applicationHandle
4072 ->getDispatchingTimeout(
4073 DEFAULT_INPUT_DISPATCHING_TIMEOUT)
4074 .count()));
4075 }
4076 } else {
4077 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
4078 }
4079
4080 if (!mFocusedWindowHandlesByDisplay.empty()) {
4081 dump += StringPrintf(INDENT "FocusedWindows:\n");
4082 for (auto& it : mFocusedWindowHandlesByDisplay) {
4083 const int32_t displayId = it.first;
4084 const sp<InputWindowHandle>& windowHandle = it.second;
4085 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4086 windowHandle->getName().c_str());
4087 }
4088 } else {
4089 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4090 }
4091
4092 if (!mTouchStatesByDisplay.empty()) {
4093 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
4094 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4095 const TouchState& state = pair.second;
4096 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
4097 state.displayId, toString(state.down), toString(state.split),
4098 state.deviceId, state.source);
4099 if (!state.windows.empty()) {
4100 dump += INDENT3 "Windows:\n";
4101 for (size_t i = 0; i < state.windows.size(); i++) {
4102 const TouchedWindow& touchedWindow = state.windows[i];
4103 dump += StringPrintf(INDENT4
4104 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4105 i, touchedWindow.windowHandle->getName().c_str(),
4106 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
4107 }
4108 } else {
4109 dump += INDENT3 "Windows: <none>\n";
4110 }
4111 if (!state.portalWindows.empty()) {
4112 dump += INDENT3 "Portal windows:\n";
4113 for (size_t i = 0; i < state.portalWindows.size(); i++) {
4114 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
4115 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4116 portalWindowHandle->getName().c_str());
4117 }
4118 }
4119 }
4120 } else {
4121 dump += INDENT "TouchStates: <no displays touched>\n";
4122 }
4123
4124 if (!mWindowHandlesByDisplay.empty()) {
4125 for (auto& it : mWindowHandlesByDisplay) {
4126 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
4127 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
4128 if (!windowHandles.empty()) {
4129 dump += INDENT2 "Windows:\n";
4130 for (size_t i = 0; i < windowHandles.size(); i++) {
4131 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
4132 const InputWindowInfo* windowInfo = windowHandle->getInfo();
4133
4134 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
4135 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
4136 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
4137 "flags=0x%08x, type=0x%08x, "
4138 "frame=[%d,%d][%d,%d], globalScale=%f, "
4139 "windowScale=(%f,%f), touchableRegion=",
4140 i, windowInfo->name.c_str(), windowInfo->displayId,
4141 windowInfo->portalToDisplayId,
4142 toString(windowInfo->paused),
4143 toString(windowInfo->hasFocus),
4144 toString(windowInfo->hasWallpaper),
4145 toString(windowInfo->visible),
4146 toString(windowInfo->canReceiveKeys),
4147 windowInfo->layoutParamsFlags,
4148 windowInfo->layoutParamsType, windowInfo->frameLeft,
4149 windowInfo->frameTop, windowInfo->frameRight,
4150 windowInfo->frameBottom, windowInfo->globalScaleFactor,
4151 windowInfo->windowXScale, windowInfo->windowYScale);
4152 dumpRegion(dump, windowInfo->touchableRegion);
4153 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
4154 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4155 "ms\n",
4156 windowInfo->ownerPid, windowInfo->ownerUid,
4157 ns2ms(windowInfo->dispatchingTimeout));
4158 }
4159 } else {
4160 dump += INDENT2 "Windows: <none>\n";
4161 }
4162 }
4163 } else {
4164 dump += INDENT "Displays: <none>\n";
4165 }
4166
4167 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
4168 for (auto& it : mGlobalMonitorsByDisplay) {
4169 const std::vector<Monitor>& monitors = it.second;
4170 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4171 dumpMonitors(dump, monitors);
4172 }
4173 for (auto& it : mGestureMonitorsByDisplay) {
4174 const std::vector<Monitor>& monitors = it.second;
4175 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4176 dumpMonitors(dump, monitors);
4177 }
4178 } else {
4179 dump += INDENT "Monitors: <none>\n";
4180 }
4181
4182 nsecs_t currentTime = now();
4183
4184 // Dump recently dispatched or dropped events from oldest to newest.
4185 if (!mRecentQueue.empty()) {
4186 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4187 for (EventEntry* entry : mRecentQueue) {
4188 dump += INDENT2;
4189 entry->appendDescription(dump);
4190 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
4191 }
4192 } else {
4193 dump += INDENT "RecentQueue: <empty>\n";
4194 }
4195
4196 // Dump event currently being dispatched.
4197 if (mPendingEvent) {
4198 dump += INDENT "PendingEvent:\n";
4199 dump += INDENT2;
4200 mPendingEvent->appendDescription(dump);
4201 dump += StringPrintf(", age=%" PRId64 "ms\n",
4202 ns2ms(currentTime - mPendingEvent->eventTime));
4203 } else {
4204 dump += INDENT "PendingEvent: <none>\n";
4205 }
4206
4207 // Dump inbound events from oldest to newest.
4208 if (!mInboundQueue.empty()) {
4209 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4210 for (EventEntry* entry : mInboundQueue) {
4211 dump += INDENT2;
4212 entry->appendDescription(dump);
4213 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
4214 }
4215 } else {
4216 dump += INDENT "InboundQueue: <empty>\n";
4217 }
4218
4219 if (!mReplacedKeys.empty()) {
4220 dump += INDENT "ReplacedKeys:\n";
4221 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4222 const KeyReplacement& replacement = pair.first;
4223 int32_t newKeyCode = pair.second;
4224 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
4225 replacement.keyCode, replacement.deviceId, newKeyCode);
4226 }
4227 } else {
4228 dump += INDENT "ReplacedKeys: <empty>\n";
4229 }
4230
4231 if (!mConnectionsByFd.empty()) {
4232 dump += INDENT "Connections:\n";
4233 for (const auto& pair : mConnectionsByFd) {
4234 const sp<Connection>& connection = pair.second;
4235 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
4236 "status=%s, monitor=%s, responsive=%s\n",
4237 pair.first, connection->getInputChannelName().c_str(),
4238 connection->getWindowName().c_str(), connection->getStatusLabel(),
4239 toString(connection->monitor), toString(connection->responsive));
4240
4241 if (!connection->outboundQueue.empty()) {
4242 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4243 connection->outboundQueue.size());
4244 for (DispatchEntry* entry : connection->outboundQueue) {
4245 dump.append(INDENT4);
4246 entry->eventEntry->appendDescription(dump);
4247 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4248 "ms\n",
4249 entry->targetFlags, entry->resolvedAction,
4250 ns2ms(currentTime - entry->eventEntry->eventTime));
4251 }
4252 } else {
4253 dump += INDENT3 "OutboundQueue: <empty>\n";
4254 }
4255
4256 if (!connection->waitQueue.empty()) {
4257 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4258 connection->waitQueue.size());
4259 for (DispatchEntry* entry : connection->waitQueue) {
4260 dump += INDENT4;
4261 entry->eventEntry->appendDescription(dump);
4262 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
4263 "age=%" PRId64 "ms, wait=%" PRId64 "ms\n",
4264 entry->targetFlags, entry->resolvedAction,
4265 ns2ms(currentTime - entry->eventEntry->eventTime),
4266 ns2ms(currentTime - entry->deliveryTime));
4267 }
4268 } else {
4269 dump += INDENT3 "WaitQueue: <empty>\n";
4270 }
4271 }
4272 } else {
4273 dump += INDENT "Connections: <none>\n";
4274 }
4275
4276 if (isAppSwitchPendingLocked()) {
4277 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4278 ns2ms(mAppSwitchDueTime - now()));
4279 } else {
4280 dump += INDENT "AppSwitch: not pending\n";
4281 }
4282
4283 dump += INDENT "Configuration:\n";
4284 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4285 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4286 ns2ms(mConfig.keyRepeatTimeout));
4287 }
4288
dumpMonitors(std::string & dump,const std::vector<Monitor> & monitors)4289 void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4290 const size_t numMonitors = monitors.size();
4291 for (size_t i = 0; i < numMonitors; i++) {
4292 const Monitor& monitor = monitors[i];
4293 const sp<InputChannel>& channel = monitor.inputChannel;
4294 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4295 dump += "\n";
4296 }
4297 }
4298
registerInputChannel(const sp<InputChannel> & inputChannel)4299 status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
4300 #if DEBUG_REGISTRATION
4301 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
4302 #endif
4303
4304 { // acquire lock
4305 std::scoped_lock _l(mLock);
4306 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
4307 if (existingConnection != nullptr) {
4308 ALOGW("Attempted to register already registered input channel '%s'",
4309 inputChannel->getName().c_str());
4310 return BAD_VALUE;
4311 }
4312
4313 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
4314
4315 int fd = inputChannel->getFd();
4316 mConnectionsByFd[fd] = connection;
4317 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
4318
4319 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4320 } // release lock
4321
4322 // Wake the looper because some connections have changed.
4323 mLooper->wake();
4324 return OK;
4325 }
4326
registerInputMonitor(const sp<InputChannel> & inputChannel,int32_t displayId,bool isGestureMonitor)4327 status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
4328 int32_t displayId, bool isGestureMonitor) {
4329 { // acquire lock
4330 std::scoped_lock _l(mLock);
4331
4332 if (displayId < 0) {
4333 ALOGW("Attempted to register input monitor without a specified display.");
4334 return BAD_VALUE;
4335 }
4336
4337 if (inputChannel->getConnectionToken() == nullptr) {
4338 ALOGW("Attempted to register input monitor without an identifying token.");
4339 return BAD_VALUE;
4340 }
4341
4342 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
4343
4344 const int fd = inputChannel->getFd();
4345 mConnectionsByFd[fd] = connection;
4346 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
4347
4348 auto& monitorsByDisplay =
4349 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
4350 monitorsByDisplay[displayId].emplace_back(inputChannel);
4351
4352 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4353 }
4354 // Wake the looper because some connections have changed.
4355 mLooper->wake();
4356 return OK;
4357 }
4358
unregisterInputChannel(const sp<InputChannel> & inputChannel)4359 status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4360 #if DEBUG_REGISTRATION
4361 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
4362 #endif
4363
4364 { // acquire lock
4365 std::scoped_lock _l(mLock);
4366
4367 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4368 if (status) {
4369 return status;
4370 }
4371 } // release lock
4372
4373 // Wake the poll loop because removing the connection may have changed the current
4374 // synchronization state.
4375 mLooper->wake();
4376 return OK;
4377 }
4378
unregisterInputChannelLocked(const sp<InputChannel> & inputChannel,bool notify)4379 status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
4380 bool notify) {
4381 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
4382 if (connection == nullptr) {
4383 ALOGW("Attempted to unregister already unregistered input channel '%s'",
4384 inputChannel->getName().c_str());
4385 return BAD_VALUE;
4386 }
4387
4388 removeConnectionLocked(connection);
4389 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
4390
4391 if (connection->monitor) {
4392 removeMonitorChannelLocked(inputChannel);
4393 }
4394
4395 mLooper->removeFd(inputChannel->getFd());
4396
4397 nsecs_t currentTime = now();
4398 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4399
4400 connection->status = Connection::STATUS_ZOMBIE;
4401 return OK;
4402 }
4403
removeMonitorChannelLocked(const sp<InputChannel> & inputChannel)4404 void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
4405 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4406 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4407 }
4408
removeMonitorChannelLocked(const sp<InputChannel> & inputChannel,std::unordered_map<int32_t,std::vector<Monitor>> & monitorsByDisplay)4409 void InputDispatcher::removeMonitorChannelLocked(
4410 const sp<InputChannel>& inputChannel,
4411 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
4412 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
4413 std::vector<Monitor>& monitors = it->second;
4414 const size_t numMonitors = monitors.size();
4415 for (size_t i = 0; i < numMonitors; i++) {
4416 if (monitors[i].inputChannel == inputChannel) {
4417 monitors.erase(monitors.begin() + i);
4418 break;
4419 }
4420 }
4421 if (monitors.empty()) {
4422 it = monitorsByDisplay.erase(it);
4423 } else {
4424 ++it;
4425 }
4426 }
4427 }
4428
pilferPointers(const sp<IBinder> & token)4429 status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4430 { // acquire lock
4431 std::scoped_lock _l(mLock);
4432 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4433
4434 if (!foundDisplayId) {
4435 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4436 return BAD_VALUE;
4437 }
4438 int32_t displayId = foundDisplayId.value();
4439
4440 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4441 mTouchStatesByDisplay.find(displayId);
4442 if (stateIt == mTouchStatesByDisplay.end()) {
4443 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4444 return BAD_VALUE;
4445 }
4446
4447 TouchState& state = stateIt->second;
4448 std::optional<int32_t> foundDeviceId;
4449 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
4450 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
4451 foundDeviceId = state.deviceId;
4452 }
4453 }
4454 if (!foundDeviceId || !state.down) {
4455 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
4456 " Ignoring.");
4457 return BAD_VALUE;
4458 }
4459 int32_t deviceId = foundDeviceId.value();
4460
4461 // Send cancel events to all the input channels we're stealing from.
4462 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4463 "gesture monitor stole pointer stream");
4464 options.deviceId = deviceId;
4465 options.displayId = displayId;
4466 for (const TouchedWindow& window : state.windows) {
4467 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
4468 if (channel != nullptr) {
4469 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4470 }
4471 }
4472 // Then clear the current touch state so we stop dispatching to them as well.
4473 state.filterNonMonitors();
4474 }
4475 return OK;
4476 }
4477
findGestureMonitorDisplayByTokenLocked(const sp<IBinder> & token)4478 std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4479 const sp<IBinder>& token) {
4480 for (const auto& it : mGestureMonitorsByDisplay) {
4481 const std::vector<Monitor>& monitors = it.second;
4482 for (const Monitor& monitor : monitors) {
4483 if (monitor.inputChannel->getConnectionToken() == token) {
4484 return it.first;
4485 }
4486 }
4487 }
4488 return std::nullopt;
4489 }
4490
getConnectionLocked(const sp<IBinder> & inputConnectionToken) const4491 sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
4492 if (inputConnectionToken == nullptr) {
4493 return nullptr;
4494 }
4495
4496 for (const auto& pair : mConnectionsByFd) {
4497 const sp<Connection>& connection = pair.second;
4498 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
4499 return connection;
4500 }
4501 }
4502
4503 return nullptr;
4504 }
4505
removeConnectionLocked(const sp<Connection> & connection)4506 void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
4507 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
4508 removeByValue(mConnectionsByFd, connection);
4509 }
4510
onDispatchCycleFinishedLocked(nsecs_t currentTime,const sp<Connection> & connection,uint32_t seq,bool handled)4511 void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4512 const sp<Connection>& connection, uint32_t seq,
4513 bool handled) {
4514 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4515 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
4516 commandEntry->connection = connection;
4517 commandEntry->eventTime = currentTime;
4518 commandEntry->seq = seq;
4519 commandEntry->handled = handled;
4520 postCommandLocked(std::move(commandEntry));
4521 }
4522
onDispatchCycleBrokenLocked(nsecs_t currentTime,const sp<Connection> & connection)4523 void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4524 const sp<Connection>& connection) {
4525 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
4526 connection->getInputChannelName().c_str());
4527
4528 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4529 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
4530 commandEntry->connection = connection;
4531 postCommandLocked(std::move(commandEntry));
4532 }
4533
onFocusChangedLocked(const sp<InputWindowHandle> & oldFocus,const sp<InputWindowHandle> & newFocus)4534 void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
4535 const sp<InputWindowHandle>& newFocus) {
4536 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4537 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
4538 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4539 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
4540 commandEntry->oldToken = oldToken;
4541 commandEntry->newToken = newToken;
4542 postCommandLocked(std::move(commandEntry));
4543 }
4544
onAnrLocked(const sp<Connection> & connection)4545 void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
4546 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4547 // is already healthy again. Don't raise ANR in this situation
4548 if (connection->waitQueue.empty()) {
4549 ALOGI("Not raising ANR because the connection %s has recovered",
4550 connection->inputChannel->getName().c_str());
4551 return;
4552 }
4553 /**
4554 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4555 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4556 * has changed. This could cause newer entries to time out before the already dispatched
4557 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4558 * processes the events linearly. So providing information about the oldest entry seems to be
4559 * most useful.
4560 */
4561 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
4562 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4563 std::string reason =
4564 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
4565 connection->inputChannel->getName().c_str(),
4566 ns2ms(currentWait),
4567 oldestEntry->eventEntry->getDescription().c_str());
4568
4569 updateLastAnrStateLocked(getWindowHandleLocked(connection->inputChannel->getConnectionToken()),
4570 reason);
4571
4572 std::unique_ptr<CommandEntry> commandEntry =
4573 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4574 commandEntry->inputApplicationHandle = nullptr;
4575 commandEntry->inputChannel = connection->inputChannel;
4576 commandEntry->reason = std::move(reason);
4577 postCommandLocked(std::move(commandEntry));
4578 }
4579
onAnrLocked(const sp<InputApplicationHandle> & application)4580 void InputDispatcher::onAnrLocked(const sp<InputApplicationHandle>& application) {
4581 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4582 application->getName().c_str());
4583
4584 updateLastAnrStateLocked(application, reason);
4585
4586 std::unique_ptr<CommandEntry> commandEntry =
4587 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4588 commandEntry->inputApplicationHandle = application;
4589 commandEntry->inputChannel = nullptr;
4590 commandEntry->reason = std::move(reason);
4591 postCommandLocked(std::move(commandEntry));
4592 }
4593
updateLastAnrStateLocked(const sp<InputWindowHandle> & window,const std::string & reason)4594 void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4595 const std::string& reason) {
4596 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4597 updateLastAnrStateLocked(windowLabel, reason);
4598 }
4599
updateLastAnrStateLocked(const sp<InputApplicationHandle> & application,const std::string & reason)4600 void InputDispatcher::updateLastAnrStateLocked(const sp<InputApplicationHandle>& application,
4601 const std::string& reason) {
4602 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4603 updateLastAnrStateLocked(windowLabel, reason);
4604 }
4605
updateLastAnrStateLocked(const std::string & windowLabel,const std::string & reason)4606 void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4607 const std::string& reason) {
4608 // Capture a record of the InputDispatcher state at the time of the ANR.
4609 time_t t = time(nullptr);
4610 struct tm tm;
4611 localtime_r(&t, &tm);
4612 char timestr[64];
4613 strftime(timestr, sizeof(timestr), "%F %T", &tm);
4614 mLastAnrState.clear();
4615 mLastAnrState += INDENT "ANR:\n";
4616 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
4617 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4618 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
4619 dumpDispatchStateLocked(mLastAnrState);
4620 }
4621
doNotifyConfigurationChangedLockedInterruptible(CommandEntry * commandEntry)4622 void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
4623 mLock.unlock();
4624
4625 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4626
4627 mLock.lock();
4628 }
4629
doNotifyInputChannelBrokenLockedInterruptible(CommandEntry * commandEntry)4630 void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
4631 sp<Connection> connection = commandEntry->connection;
4632
4633 if (connection->status != Connection::STATUS_ZOMBIE) {
4634 mLock.unlock();
4635
4636 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
4637
4638 mLock.lock();
4639 }
4640 }
4641
doNotifyFocusChangedLockedInterruptible(CommandEntry * commandEntry)4642 void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
4643 sp<IBinder> oldToken = commandEntry->oldToken;
4644 sp<IBinder> newToken = commandEntry->newToken;
4645 mLock.unlock();
4646 mPolicy->notifyFocusChanged(oldToken, newToken);
4647 mLock.lock();
4648 }
4649
doNotifyAnrLockedInterruptible(CommandEntry * commandEntry)4650 void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
4651 sp<IBinder> token =
4652 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
4653 mLock.unlock();
4654
4655 const nsecs_t timeoutExtension =
4656 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
4657
4658 mLock.lock();
4659
4660 if (timeoutExtension > 0) {
4661 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4662 } else {
4663 // stop waking up for events in this connection, it is already not responding
4664 sp<Connection> connection = getConnectionLocked(token);
4665 if (connection == nullptr) {
4666 return;
4667 }
4668 cancelEventsForAnrLocked(connection);
4669 }
4670 }
4671
extendAnrTimeoutsLocked(const sp<InputApplicationHandle> & application,const sp<IBinder> & connectionToken,nsecs_t timeoutExtension)4672 void InputDispatcher::extendAnrTimeoutsLocked(const sp<InputApplicationHandle>& application,
4673 const sp<IBinder>& connectionToken,
4674 nsecs_t timeoutExtension) {
4675 sp<Connection> connection = getConnectionLocked(connectionToken);
4676 if (connection == nullptr) {
4677 if (mNoFocusedWindowTimeoutTime.has_value() && application != nullptr) {
4678 // Maybe ANR happened because there's no focused window?
4679 mNoFocusedWindowTimeoutTime = now() + timeoutExtension;
4680 mAwaitedFocusedApplication = application;
4681 } else {
4682 // It's also possible that the connection already disappeared. No action necessary.
4683 }
4684 return;
4685 }
4686
4687 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
4688 connection->inputChannel->getName().c_str(), ns2ms(timeoutExtension));
4689
4690 connection->responsive = true;
4691 const nsecs_t newTimeout = now() + timeoutExtension;
4692 for (DispatchEntry* entry : connection->waitQueue) {
4693 if (newTimeout >= entry->timeoutTime) {
4694 // Already removed old entries when connection was marked unresponsive
4695 entry->timeoutTime = newTimeout;
4696 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4697 }
4698 }
4699 }
4700
doInterceptKeyBeforeDispatchingLockedInterruptible(CommandEntry * commandEntry)4701 void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4702 CommandEntry* commandEntry) {
4703 KeyEntry* entry = commandEntry->keyEntry;
4704 KeyEvent event = createKeyEvent(*entry);
4705
4706 mLock.unlock();
4707
4708 android::base::Timer t;
4709 sp<IBinder> token = commandEntry->inputChannel != nullptr
4710 ? commandEntry->inputChannel->getConnectionToken()
4711 : nullptr;
4712 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
4713 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4714 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
4715 std::to_string(t.duration().count()).c_str());
4716 }
4717
4718 mLock.lock();
4719
4720 if (delay < 0) {
4721 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4722 } else if (!delay) {
4723 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4724 } else {
4725 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4726 entry->interceptKeyWakeupTime = now() + delay;
4727 }
4728 entry->release();
4729 }
4730
doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry * commandEntry)4731 void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4732 mLock.unlock();
4733 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4734 mLock.lock();
4735 }
4736
4737 /**
4738 * Connection is responsive if it has no events in the waitQueue that are older than the
4739 * current time.
4740 */
isConnectionResponsive(const Connection & connection)4741 static bool isConnectionResponsive(const Connection& connection) {
4742 const nsecs_t currentTime = now();
4743 for (const DispatchEntry* entry : connection.waitQueue) {
4744 if (entry->timeoutTime < currentTime) {
4745 return false;
4746 }
4747 }
4748 return true;
4749 }
4750
doDispatchCycleFinishedLockedInterruptible(CommandEntry * commandEntry)4751 void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
4752 sp<Connection> connection = commandEntry->connection;
4753 const nsecs_t finishTime = commandEntry->eventTime;
4754 uint32_t seq = commandEntry->seq;
4755 const bool handled = commandEntry->handled;
4756
4757 // Handle post-event policy actions.
4758 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
4759 if (dispatchEntryIt == connection->waitQueue.end()) {
4760 return;
4761 }
4762 DispatchEntry* dispatchEntry = *dispatchEntryIt;
4763 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4764 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
4765 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4766 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
4767 }
4768 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
4769
4770 bool restartEvent;
4771 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
4772 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4773 restartEvent =
4774 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
4775 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
4776 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4777 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4778 handled);
4779 } else {
4780 restartEvent = false;
4781 }
4782
4783 // Dequeue the event and start the next cycle.
4784 // Because the lock might have been released, it is possible that the
4785 // contents of the wait queue to have been drained, so we need to double-check
4786 // a few things.
4787 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4788 if (dispatchEntryIt != connection->waitQueue.end()) {
4789 dispatchEntry = *dispatchEntryIt;
4790 connection->waitQueue.erase(dispatchEntryIt);
4791 mAnrTracker.erase(dispatchEntry->timeoutTime,
4792 connection->inputChannel->getConnectionToken());
4793 if (!connection->responsive) {
4794 connection->responsive = isConnectionResponsive(*connection);
4795 }
4796 traceWaitQueueLength(connection);
4797 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
4798 connection->outboundQueue.push_front(dispatchEntry);
4799 traceOutboundQueueLength(connection);
4800 } else {
4801 releaseDispatchEntry(dispatchEntry);
4802 }
4803 }
4804
4805 // Start the next dispatch cycle for this connection.
4806 startDispatchCycleLocked(now(), connection);
4807 }
4808
afterKeyEventLockedInterruptible(const sp<Connection> & connection,DispatchEntry * dispatchEntry,KeyEntry * keyEntry,bool handled)4809 bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
4810 DispatchEntry* dispatchEntry,
4811 KeyEntry* keyEntry, bool handled) {
4812 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4813 if (!handled) {
4814 // Report the key as unhandled, since the fallback was not handled.
4815 mReporter->reportUnhandledKey(keyEntry->id);
4816 }
4817 return false;
4818 }
4819
4820 // Get the fallback key state.
4821 // Clear it out after dispatching the UP.
4822 int32_t originalKeyCode = keyEntry->keyCode;
4823 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4824 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4825 connection->inputState.removeFallbackKey(originalKeyCode);
4826 }
4827
4828 if (handled || !dispatchEntry->hasForegroundTarget()) {
4829 // If the application handles the original key for which we previously
4830 // generated a fallback or if the window is not a foreground window,
4831 // then cancel the associated fallback key, if any.
4832 if (fallbackKeyCode != -1) {
4833 // Dispatch the unhandled key to the policy with the cancel flag.
4834 #if DEBUG_OUTBOUND_EVENT_DETAILS
4835 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
4836 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4837 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4838 keyEntry->policyFlags);
4839 #endif
4840 KeyEvent event = createKeyEvent(*keyEntry);
4841 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
4842
4843 mLock.unlock();
4844
4845 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
4846 keyEntry->policyFlags, &event);
4847
4848 mLock.lock();
4849
4850 // Cancel the fallback key.
4851 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
4852 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4853 "application handled the original non-fallback key "
4854 "or is no longer a foreground target, "
4855 "canceling previously dispatched fallback key");
4856 options.keyCode = fallbackKeyCode;
4857 synthesizeCancelationEventsForConnectionLocked(connection, options);
4858 }
4859 connection->inputState.removeFallbackKey(originalKeyCode);
4860 }
4861 } else {
4862 // If the application did not handle a non-fallback key, first check
4863 // that we are in a good state to perform unhandled key event processing
4864 // Then ask the policy what to do with it.
4865 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
4866 if (fallbackKeyCode == -1 && !initialDown) {
4867 #if DEBUG_OUTBOUND_EVENT_DETAILS
4868 ALOGD("Unhandled key event: Skipping unhandled key event processing "
4869 "since this is not an initial down. "
4870 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4871 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
4872 #endif
4873 return false;
4874 }
4875
4876 // Dispatch the unhandled key to the policy.
4877 #if DEBUG_OUTBOUND_EVENT_DETAILS
4878 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4879 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4880 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
4881 #endif
4882 KeyEvent event = createKeyEvent(*keyEntry);
4883
4884 mLock.unlock();
4885
4886 bool fallback =
4887 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4888 &event, keyEntry->policyFlags, &event);
4889
4890 mLock.lock();
4891
4892 if (connection->status != Connection::STATUS_NORMAL) {
4893 connection->inputState.removeFallbackKey(originalKeyCode);
4894 return false;
4895 }
4896
4897 // Latch the fallback keycode for this key on an initial down.
4898 // The fallback keycode cannot change at any other point in the lifecycle.
4899 if (initialDown) {
4900 if (fallback) {
4901 fallbackKeyCode = event.getKeyCode();
4902 } else {
4903 fallbackKeyCode = AKEYCODE_UNKNOWN;
4904 }
4905 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4906 }
4907
4908 ALOG_ASSERT(fallbackKeyCode != -1);
4909
4910 // Cancel the fallback key if the policy decides not to send it anymore.
4911 // We will continue to dispatch the key to the policy but we will no
4912 // longer dispatch a fallback key to the application.
4913 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4914 (!fallback || fallbackKeyCode != event.getKeyCode())) {
4915 #if DEBUG_OUTBOUND_EVENT_DETAILS
4916 if (fallback) {
4917 ALOGD("Unhandled key event: Policy requested to send key %d"
4918 "as a fallback for %d, but on the DOWN it had requested "
4919 "to send %d instead. Fallback canceled.",
4920 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4921 } else {
4922 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4923 "but on the DOWN it had requested to send %d. "
4924 "Fallback canceled.",
4925 originalKeyCode, fallbackKeyCode);
4926 }
4927 #endif
4928
4929 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4930 "canceling fallback, policy no longer desires it");
4931 options.keyCode = fallbackKeyCode;
4932 synthesizeCancelationEventsForConnectionLocked(connection, options);
4933
4934 fallback = false;
4935 fallbackKeyCode = AKEYCODE_UNKNOWN;
4936 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4937 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4938 }
4939 }
4940
4941 #if DEBUG_OUTBOUND_EVENT_DETAILS
4942 {
4943 std::string msg;
4944 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4945 connection->inputState.getFallbackKeys();
4946 for (size_t i = 0; i < fallbackKeys.size(); i++) {
4947 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
4948 }
4949 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
4950 fallbackKeys.size(), msg.c_str());
4951 }
4952 #endif
4953
4954 if (fallback) {
4955 // Restart the dispatch cycle using the fallback key.
4956 keyEntry->eventTime = event.getEventTime();
4957 keyEntry->deviceId = event.getDeviceId();
4958 keyEntry->source = event.getSource();
4959 keyEntry->displayId = event.getDisplayId();
4960 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4961 keyEntry->keyCode = fallbackKeyCode;
4962 keyEntry->scanCode = event.getScanCode();
4963 keyEntry->metaState = event.getMetaState();
4964 keyEntry->repeatCount = event.getRepeatCount();
4965 keyEntry->downTime = event.getDownTime();
4966 keyEntry->syntheticRepeat = false;
4967
4968 #if DEBUG_OUTBOUND_EVENT_DETAILS
4969 ALOGD("Unhandled key event: Dispatching fallback key. "
4970 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4971 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4972 #endif
4973 return true; // restart the event
4974 } else {
4975 #if DEBUG_OUTBOUND_EVENT_DETAILS
4976 ALOGD("Unhandled key event: No fallback key.");
4977 #endif
4978
4979 // Report the key as unhandled, since there is no fallback key.
4980 mReporter->reportUnhandledKey(keyEntry->id);
4981 }
4982 }
4983 return false;
4984 }
4985
afterMotionEventLockedInterruptible(const sp<Connection> & connection,DispatchEntry * dispatchEntry,MotionEntry * motionEntry,bool handled)4986 bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4987 DispatchEntry* dispatchEntry,
4988 MotionEntry* motionEntry, bool handled) {
4989 return false;
4990 }
4991
doPokeUserActivityLockedInterruptible(CommandEntry * commandEntry)4992 void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4993 mLock.unlock();
4994
4995 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4996
4997 mLock.lock();
4998 }
4999
createKeyEvent(const KeyEntry & entry)5000 KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5001 KeyEvent event;
5002 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
5003 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5004 entry.repeatCount, entry.downTime, entry.eventTime);
5005 return event;
5006 }
5007
reportDispatchStatistics(std::chrono::nanoseconds eventDuration,const Connection & connection,bool handled)5008 void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5009 const Connection& connection, bool handled) {
5010 // TODO Write some statistics about how long we spend waiting.
5011 }
5012
5013 /**
5014 * Report the touch event latency to the statsd server.
5015 * Input events are reported for statistics if:
5016 * - This is a touchscreen event
5017 * - InputFilter is not enabled
5018 * - Event is not injected or synthesized
5019 *
5020 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5021 * from getting aggregated with the "old" data.
5022 */
reportTouchEventForStatistics(const MotionEntry & motionEntry)5023 void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5024 REQUIRES(mLock) {
5025 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5026 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5027 if (!reportForStatistics) {
5028 return;
5029 }
5030
5031 if (mTouchStatistics.shouldReport()) {
5032 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5033 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5034 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5035 mTouchStatistics.reset();
5036 }
5037 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5038 mTouchStatistics.addValue(latencyMicros);
5039 }
5040
traceInboundQueueLengthLocked()5041 void InputDispatcher::traceInboundQueueLengthLocked() {
5042 if (ATRACE_ENABLED()) {
5043 ATRACE_INT("iq", mInboundQueue.size());
5044 }
5045 }
5046
traceOutboundQueueLength(const sp<Connection> & connection)5047 void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
5048 if (ATRACE_ENABLED()) {
5049 char counterName[40];
5050 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
5051 ATRACE_INT(counterName, connection->outboundQueue.size());
5052 }
5053 }
5054
traceWaitQueueLength(const sp<Connection> & connection)5055 void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
5056 if (ATRACE_ENABLED()) {
5057 char counterName[40];
5058 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
5059 ATRACE_INT(counterName, connection->waitQueue.size());
5060 }
5061 }
5062
dump(std::string & dump)5063 void InputDispatcher::dump(std::string& dump) {
5064 std::scoped_lock _l(mLock);
5065
5066 dump += "Input Dispatcher State:\n";
5067 dumpDispatchStateLocked(dump);
5068
5069 if (!mLastAnrState.empty()) {
5070 dump += "\nInput Dispatcher State at time of last ANR:\n";
5071 dump += mLastAnrState;
5072 }
5073 }
5074
monitor()5075 void InputDispatcher::monitor() {
5076 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
5077 std::unique_lock _l(mLock);
5078 mLooper->wake();
5079 mDispatcherIsAlive.wait(_l);
5080 }
5081
5082 /**
5083 * Wake up the dispatcher and wait until it processes all events and commands.
5084 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5085 * this method can be safely called from any thread, as long as you've ensured that
5086 * the work you are interested in completing has already been queued.
5087 */
waitForIdle()5088 bool InputDispatcher::waitForIdle() {
5089 /**
5090 * Timeout should represent the longest possible time that a device might spend processing
5091 * events and commands.
5092 */
5093 constexpr std::chrono::duration TIMEOUT = 100ms;
5094 std::unique_lock lock(mLock);
5095 mLooper->wake();
5096 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5097 return result == std::cv_status::no_timeout;
5098 }
5099
5100 } // namespace android::inputdispatcher
5101