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