1 /*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define LOG_TAG "InputDispatcher"
18 #define ATRACE_TAG ATRACE_TAG_INPUT
19
20 #define LOG_NDEBUG 1
21
22 // Log detailed debug messages about each inbound event notification to the dispatcher.
23 #define DEBUG_INBOUND_EVENT_DETAILS 0
24
25 // Log detailed debug messages about each outbound event processed by the dispatcher.
26 #define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28 // Log debug messages about the dispatch cycle.
29 #define DEBUG_DISPATCH_CYCLE 0
30
31 // Log debug messages about channel creation
32 #define DEBUG_CHANNEL_CREATION 0
33
34 // Log debug messages about input event injection.
35 #define DEBUG_INJECTION 0
36
37 // Log debug messages about input focus tracking.
38 static constexpr bool DEBUG_FOCUS = false;
39
40 // Log debug messages about touch occlusion
41 // STOPSHIP(b/169067926): Set to false
42 static constexpr bool DEBUG_TOUCH_OCCLUSION = true;
43
44 // Log debug messages about the app switch latency optimization.
45 #define DEBUG_APP_SWITCH 0
46
47 // Log debug messages about hover events.
48 #define DEBUG_HOVER 0
49
50 #include <InputFlingerProperties.sysprop.h>
51 #include <android-base/chrono_utils.h>
52 #include <android-base/properties.h>
53 #include <android-base/stringprintf.h>
54 #include <android/os/IInputConstants.h>
55 #include <binder/Binder.h>
56 #include <binder/IServiceManager.h>
57 #include <com/android/internal/compat/IPlatformCompatNative.h>
58 #include <gui/SurfaceComposerClient.h>
59 #include <input/InputDevice.h>
60 #include <log/log.h>
61 #include <log/log_event_list.h>
62 #include <powermanager/PowerManager.h>
63 #include <unistd.h>
64 #include <utils/Trace.h>
65
66 #include <cerrno>
67 #include <cinttypes>
68 #include <climits>
69 #include <cstddef>
70 #include <ctime>
71 #include <queue>
72 #include <sstream>
73
74 #include "Connection.h"
75 #include "InputDispatcher.h"
76
77 #define INDENT " "
78 #define INDENT2 " "
79 #define INDENT3 " "
80 #define INDENT4 " "
81
82 using android::base::HwTimeoutMultiplier;
83 using android::base::Result;
84 using android::base::StringPrintf;
85 using android::gui::FocusRequest;
86 using android::gui::TouchOcclusionMode;
87 using android::gui::WindowInfo;
88 using android::gui::WindowInfoHandle;
89 using android::os::BlockUntrustedTouchesMode;
90 using android::os::IInputConstants;
91 using android::os::InputEventInjectionResult;
92 using android::os::InputEventInjectionSync;
93 using com::android::internal::compat::IPlatformCompatNative;
94
95 namespace android::inputdispatcher {
96
97 // When per-window-input-rotation is enabled, InputFlinger works in the un-rotated display
98 // coordinates and SurfaceFlinger includes the display rotation in the input window transforms.
isPerWindowInputRotationEnabled()99 static bool isPerWindowInputRotationEnabled() {
100 static const bool PER_WINDOW_INPUT_ROTATION =
101 sysprop::InputFlingerProperties::per_window_input_rotation().value_or(false);
102
103 return PER_WINDOW_INPUT_ROTATION;
104 }
105
106 // Default input dispatching timeout if there is no focused application or paused window
107 // from which to determine an appropriate dispatching timeout.
108 const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
109 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
110 HwTimeoutMultiplier());
111
112 // Amount of time to allow for all pending events to be processed when an app switch
113 // key is on the way. This is used to preempt input dispatch and drop input events
114 // when an application takes too long to respond and the user has pressed an app switch key.
115 constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
116
117 // Amount of time to allow for an event to be dispatched (measured since its eventTime)
118 // before considering it stale and dropping it.
119 constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
120
121 // Log a warning when an event takes longer than this to process, even if an ANR does not occur.
122 constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
123
124 // Log a warning when an interception call takes longer than this to process.
125 constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
126
127 // Additional key latency in case a connection is still processing some motion events.
128 // This will help with the case when a user touched a button that opens a new window,
129 // and gives us the chance to dispatch the key to this new window.
130 constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
131
132 // Number of recent events to keep for debugging purposes.
133 constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
134
135 // Event log tags. See EventLogTags.logtags for reference
136 constexpr int LOGTAG_INPUT_INTERACTION = 62000;
137 constexpr int LOGTAG_INPUT_FOCUS = 62001;
138
now()139 static inline nsecs_t now() {
140 return systemTime(SYSTEM_TIME_MONOTONIC);
141 }
142
toString(bool value)143 static inline const char* toString(bool value) {
144 return value ? "true" : "false";
145 }
146
toString(sp<IBinder> binder)147 static inline const std::string toString(sp<IBinder> binder) {
148 if (binder == nullptr) {
149 return "<null>";
150 }
151 return StringPrintf("%p", binder.get());
152 }
153
getMotionEventActionPointerIndex(int32_t action)154 static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
155 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
156 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
157 }
158
isValidKeyAction(int32_t action)159 static bool isValidKeyAction(int32_t action) {
160 switch (action) {
161 case AKEY_EVENT_ACTION_DOWN:
162 case AKEY_EVENT_ACTION_UP:
163 return true;
164 default:
165 return false;
166 }
167 }
168
validateKeyEvent(int32_t action)169 static bool validateKeyEvent(int32_t action) {
170 if (!isValidKeyAction(action)) {
171 ALOGE("Key event has invalid action code 0x%x", action);
172 return false;
173 }
174 return true;
175 }
176
isValidMotionAction(int32_t action,int32_t actionButton,int32_t pointerCount)177 static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
178 switch (action & AMOTION_EVENT_ACTION_MASK) {
179 case AMOTION_EVENT_ACTION_DOWN:
180 case AMOTION_EVENT_ACTION_UP:
181 case AMOTION_EVENT_ACTION_CANCEL:
182 case AMOTION_EVENT_ACTION_MOVE:
183 case AMOTION_EVENT_ACTION_OUTSIDE:
184 case AMOTION_EVENT_ACTION_HOVER_ENTER:
185 case AMOTION_EVENT_ACTION_HOVER_MOVE:
186 case AMOTION_EVENT_ACTION_HOVER_EXIT:
187 case AMOTION_EVENT_ACTION_SCROLL:
188 return true;
189 case AMOTION_EVENT_ACTION_POINTER_DOWN:
190 case AMOTION_EVENT_ACTION_POINTER_UP: {
191 int32_t index = getMotionEventActionPointerIndex(action);
192 return index >= 0 && index < pointerCount;
193 }
194 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
195 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
196 return actionButton != 0;
197 default:
198 return false;
199 }
200 }
201
millis(std::chrono::nanoseconds t)202 static int64_t millis(std::chrono::nanoseconds t) {
203 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
204 }
205
validateMotionEvent(int32_t action,int32_t actionButton,size_t pointerCount,const PointerProperties * pointerProperties)206 static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
207 const PointerProperties* pointerProperties) {
208 if (!isValidMotionAction(action, actionButton, pointerCount)) {
209 ALOGE("Motion event has invalid action code 0x%x", action);
210 return false;
211 }
212 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
213 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
214 pointerCount, MAX_POINTERS);
215 return false;
216 }
217 BitSet32 pointerIdBits;
218 for (size_t i = 0; i < pointerCount; i++) {
219 int32_t id = pointerProperties[i].id;
220 if (id < 0 || id > MAX_POINTER_ID) {
221 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
222 MAX_POINTER_ID);
223 return false;
224 }
225 if (pointerIdBits.hasBit(id)) {
226 ALOGE("Motion event has duplicate pointer id %d", id);
227 return false;
228 }
229 pointerIdBits.markBit(id);
230 }
231 return true;
232 }
233
dumpRegion(const Region & region)234 static std::string dumpRegion(const Region& region) {
235 if (region.isEmpty()) {
236 return "<empty>";
237 }
238
239 std::string dump;
240 bool first = true;
241 Region::const_iterator cur = region.begin();
242 Region::const_iterator const tail = region.end();
243 while (cur != tail) {
244 if (first) {
245 first = false;
246 } else {
247 dump += "|";
248 }
249 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
250 cur++;
251 }
252 return dump;
253 }
254
dumpQueue(const std::deque<DispatchEntry * > & queue,nsecs_t currentTime)255 static std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
256 constexpr size_t maxEntries = 50; // max events to print
257 constexpr size_t skipBegin = maxEntries / 2;
258 const size_t skipEnd = queue.size() - maxEntries / 2;
259 // skip from maxEntries / 2 ... size() - maxEntries/2
260 // only print from 0 .. skipBegin and then from skipEnd .. size()
261
262 std::string dump;
263 for (size_t i = 0; i < queue.size(); i++) {
264 const DispatchEntry& entry = *queue[i];
265 if (i >= skipBegin && i < skipEnd) {
266 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
267 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
268 continue;
269 }
270 dump.append(INDENT4);
271 dump += entry.eventEntry->getDescription();
272 dump += StringPrintf(", seq=%" PRIu32
273 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
274 entry.seq, entry.targetFlags, entry.resolvedAction,
275 ns2ms(currentTime - entry.eventEntry->eventTime));
276 if (entry.deliveryTime != 0) {
277 // This entry was delivered, so add information on how long we've been waiting
278 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
279 }
280 dump.append("\n");
281 }
282 return dump;
283 }
284
285 /**
286 * Find the entry in std::unordered_map by key, and return it.
287 * If the entry is not found, return a default constructed entry.
288 *
289 * Useful when the entries are vectors, since an empty vector will be returned
290 * if the entry is not found.
291 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
292 */
293 template <typename K, typename V>
getValueByKey(const std::unordered_map<K,V> & map,K key)294 static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
295 auto it = map.find(key);
296 return it != map.end() ? it->second : V{};
297 }
298
haveSameToken(const sp<WindowInfoHandle> & first,const sp<WindowInfoHandle> & second)299 static bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
300 if (first == second) {
301 return true;
302 }
303
304 if (first == nullptr || second == nullptr) {
305 return false;
306 }
307
308 return first->getToken() == second->getToken();
309 }
310
haveSameApplicationToken(const WindowInfo * first,const WindowInfo * second)311 static bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
312 if (first == nullptr || second == nullptr) {
313 return false;
314 }
315 return first->applicationInfo.token != nullptr &&
316 first->applicationInfo.token == second->applicationInfo.token;
317 }
318
isStaleEvent(nsecs_t currentTime,const EventEntry & entry)319 static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
320 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
321 }
322
createDispatchEntry(const InputTarget & inputTarget,std::shared_ptr<EventEntry> eventEntry,int32_t inputTargetFlags)323 static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
324 std::shared_ptr<EventEntry> eventEntry,
325 int32_t inputTargetFlags) {
326 if (eventEntry->type == EventEntry::Type::MOTION) {
327 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
328 if ((motionEntry.source & AINPUT_SOURCE_CLASS_JOYSTICK) ||
329 (motionEntry.source & AINPUT_SOURCE_CLASS_POSITION)) {
330 const ui::Transform identityTransform;
331 // Use identity transform for joystick and position-based (touchpad) events because they
332 // don't depend on the window transform.
333 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, identityTransform,
334 1.0f /*globalScaleFactor*/,
335 inputTarget.displayOrientation,
336 inputTarget.displaySize);
337 }
338 }
339
340 if (inputTarget.useDefaultPointerTransform()) {
341 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
342 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
343 inputTarget.globalScaleFactor,
344 inputTarget.displayOrientation,
345 inputTarget.displaySize);
346 }
347
348 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
349 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
350
351 std::vector<PointerCoords> pointerCoords;
352 pointerCoords.resize(motionEntry.pointerCount);
353
354 // Use the first pointer information to normalize all other pointers. This could be any pointer
355 // as long as all other pointers are normalized to the same value and the final DispatchEntry
356 // uses the transform for the normalized pointer.
357 const ui::Transform& firstPointerTransform =
358 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
359 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
360
361 // Iterate through all pointers in the event to normalize against the first.
362 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
363 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
364 uint32_t pointerId = uint32_t(pointerProperties.id);
365 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
366
367 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
368 // First, apply the current pointer's transform to update the coordinates into
369 // window space.
370 pointerCoords[pointerIndex].transform(currTransform);
371 // Next, apply the inverse transform of the normalized coordinates so the
372 // current coordinates are transformed into the normalized coordinate space.
373 pointerCoords[pointerIndex].transform(inverseFirstTransform);
374 }
375
376 std::unique_ptr<MotionEntry> combinedMotionEntry =
377 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
378 motionEntry.deviceId, motionEntry.source,
379 motionEntry.displayId, motionEntry.policyFlags,
380 motionEntry.action, motionEntry.actionButton,
381 motionEntry.flags, motionEntry.metaState,
382 motionEntry.buttonState, motionEntry.classification,
383 motionEntry.edgeFlags, motionEntry.xPrecision,
384 motionEntry.yPrecision, motionEntry.xCursorPosition,
385 motionEntry.yCursorPosition, motionEntry.downTime,
386 motionEntry.pointerCount, motionEntry.pointerProperties,
387 pointerCoords.data(), 0 /* xOffset */, 0 /* yOffset */);
388
389 if (motionEntry.injectionState) {
390 combinedMotionEntry->injectionState = motionEntry.injectionState;
391 combinedMotionEntry->injectionState->refCount += 1;
392 }
393
394 std::unique_ptr<DispatchEntry> dispatchEntry =
395 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
396 firstPointerTransform, inputTarget.globalScaleFactor,
397 inputTarget.displayOrientation,
398 inputTarget.displaySize);
399 return dispatchEntry;
400 }
401
addGestureMonitors(const std::vector<Monitor> & monitors,std::vector<TouchedMonitor> & outTouchedMonitors,float xOffset=0,float yOffset=0)402 static void addGestureMonitors(const std::vector<Monitor>& monitors,
403 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
404 float yOffset = 0) {
405 if (monitors.empty()) {
406 return;
407 }
408 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
409 for (const Monitor& monitor : monitors) {
410 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
411 }
412 }
413
openInputChannelPair(const std::string & name,std::shared_ptr<InputChannel> & serverChannel,std::unique_ptr<InputChannel> & clientChannel)414 static status_t openInputChannelPair(const std::string& name,
415 std::shared_ptr<InputChannel>& serverChannel,
416 std::unique_ptr<InputChannel>& clientChannel) {
417 std::unique_ptr<InputChannel> uniqueServerChannel;
418 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
419
420 serverChannel = std::move(uniqueServerChannel);
421 return result;
422 }
423
424 template <typename T>
sharedPointersEqual(const std::shared_ptr<T> & lhs,const std::shared_ptr<T> & rhs)425 static bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
426 if (lhs == nullptr && rhs == nullptr) {
427 return true;
428 }
429 if (lhs == nullptr || rhs == nullptr) {
430 return false;
431 }
432 return *lhs == *rhs;
433 }
434
getCompatService()435 static sp<IPlatformCompatNative> getCompatService() {
436 sp<IBinder> service(defaultServiceManager()->getService(String16("platform_compat_native")));
437 if (service == nullptr) {
438 ALOGE("Failed to link to compat service");
439 return nullptr;
440 }
441 return interface_cast<IPlatformCompatNative>(service);
442 }
443
createKeyEvent(const KeyEntry & entry)444 static KeyEvent createKeyEvent(const KeyEntry& entry) {
445 KeyEvent event;
446 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
447 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
448 entry.repeatCount, entry.downTime, entry.eventTime);
449 return event;
450 }
451
findMonitorPidByToken(const std::unordered_map<int32_t,std::vector<Monitor>> & monitorsByDisplay,const sp<IBinder> & token)452 static std::optional<int32_t> findMonitorPidByToken(
453 const std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay,
454 const sp<IBinder>& token) {
455 for (const auto& it : monitorsByDisplay) {
456 const std::vector<Monitor>& monitors = it.second;
457 for (const Monitor& monitor : monitors) {
458 if (monitor.inputChannel->getConnectionToken() == token) {
459 return monitor.pid;
460 }
461 }
462 }
463 return std::nullopt;
464 }
465
shouldReportMetricsForConnection(const Connection & connection)466 static bool shouldReportMetricsForConnection(const Connection& connection) {
467 // Do not keep track of gesture monitors. They receive every event and would disproportionately
468 // affect the statistics.
469 if (connection.monitor) {
470 return false;
471 }
472 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
473 if (!connection.responsive) {
474 return false;
475 }
476 return true;
477 }
478
shouldReportFinishedEvent(const DispatchEntry & dispatchEntry,const Connection & connection)479 static bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry,
480 const Connection& connection) {
481 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
482 const int32_t& inputEventId = eventEntry.id;
483 if (inputEventId != dispatchEntry.resolvedEventId) {
484 // Event was transmuted
485 return false;
486 }
487 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
488 return false;
489 }
490 // Only track latency for events that originated from hardware
491 if (eventEntry.isSynthesized()) {
492 return false;
493 }
494 const EventEntry::Type& inputEventEntryType = eventEntry.type;
495 if (inputEventEntryType == EventEntry::Type::KEY) {
496 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
497 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
498 return false;
499 }
500 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
501 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
502 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
503 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
504 return false;
505 }
506 } else {
507 // Not a key or a motion
508 return false;
509 }
510 if (!shouldReportMetricsForConnection(connection)) {
511 return false;
512 }
513 return true;
514 }
515
516 // --- InputDispatcher ---
517
InputDispatcher(const sp<InputDispatcherPolicyInterface> & policy)518 InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
519 : mPolicy(policy),
520 mPendingEvent(nullptr),
521 mLastDropReason(DropReason::NOT_DROPPED),
522 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
523 mAppSwitchSawKeyDown(false),
524 mAppSwitchDueTime(LONG_LONG_MAX),
525 mNextUnblockedEvent(nullptr),
526 mDispatchEnabled(false),
527 mDispatchFrozen(false),
528 mInputFilterEnabled(false),
529 // mInTouchMode will be initialized by the WindowManager to the default device config.
530 // To avoid leaking stack in case that call never comes, and for tests,
531 // initialize it here anyways.
532 mInTouchMode(true),
533 mMaximumObscuringOpacityForTouch(1.0f),
534 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
535 mWindowTokenWithPointerCapture(nullptr),
536 mLatencyAggregator(),
537 mLatencyTracker(&mLatencyAggregator),
538 mCompatService(getCompatService()) {
539 mLooper = new Looper(false);
540 mReporter = createInputReporter();
541
542 mKeyRepeatState.lastKeyEntry = nullptr;
543
544 policy->getDispatcherConfiguration(&mConfig);
545 }
546
~InputDispatcher()547 InputDispatcher::~InputDispatcher() {
548 { // acquire lock
549 std::scoped_lock _l(mLock);
550
551 resetKeyRepeatLocked();
552 releasePendingEventLocked();
553 drainInboundQueueLocked();
554 }
555
556 while (!mConnectionsByToken.empty()) {
557 sp<Connection> connection = mConnectionsByToken.begin()->second;
558 removeInputChannel(connection->inputChannel->getConnectionToken());
559 }
560 }
561
onFirstRef()562 void InputDispatcher::onFirstRef() {
563 SurfaceComposerClient::getDefault()->addWindowInfosListener(this);
564 }
565
start()566 status_t InputDispatcher::start() {
567 if (mThread) {
568 return ALREADY_EXISTS;
569 }
570 mThread = std::make_unique<InputThread>(
571 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
572 return OK;
573 }
574
stop()575 status_t InputDispatcher::stop() {
576 if (mThread && mThread->isCallingThread()) {
577 ALOGE("InputDispatcher cannot be stopped from its own thread!");
578 return INVALID_OPERATION;
579 }
580 mThread.reset();
581 return OK;
582 }
583
dispatchOnce()584 void InputDispatcher::dispatchOnce() {
585 nsecs_t nextWakeupTime = LONG_LONG_MAX;
586 { // acquire lock
587 std::scoped_lock _l(mLock);
588 mDispatcherIsAlive.notify_all();
589
590 // Run a dispatch loop if there are no pending commands.
591 // The dispatch loop might enqueue commands to run afterwards.
592 if (!haveCommandsLocked()) {
593 dispatchOnceInnerLocked(&nextWakeupTime);
594 }
595
596 // Run all pending commands if there are any.
597 // If any commands were run then force the next poll to wake up immediately.
598 if (runCommandsLockedInterruptible()) {
599 nextWakeupTime = LONG_LONG_MIN;
600 }
601
602 // If we are still waiting for ack on some events,
603 // we might have to wake up earlier to check if an app is anr'ing.
604 const nsecs_t nextAnrCheck = processAnrsLocked();
605 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
606
607 // We are about to enter an infinitely long sleep, because we have no commands or
608 // pending or queued events
609 if (nextWakeupTime == LONG_LONG_MAX) {
610 mDispatcherEnteredIdle.notify_all();
611 }
612 } // release lock
613
614 // Wait for callback or timeout or wake. (make sure we round up, not down)
615 nsecs_t currentTime = now();
616 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
617 mLooper->pollOnce(timeoutMillis);
618 }
619
620 /**
621 * Raise ANR if there is no focused window.
622 * Before the ANR is raised, do a final state check:
623 * 1. The currently focused application must be the same one we are waiting for.
624 * 2. Ensure we still don't have a focused window.
625 */
processNoFocusedWindowAnrLocked()626 void InputDispatcher::processNoFocusedWindowAnrLocked() {
627 // Check if the application that we are waiting for is still focused.
628 std::shared_ptr<InputApplicationHandle> focusedApplication =
629 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
630 if (focusedApplication == nullptr ||
631 focusedApplication->getApplicationToken() !=
632 mAwaitedFocusedApplication->getApplicationToken()) {
633 // Unexpected because we should have reset the ANR timer when focused application changed
634 ALOGE("Waited for a focused window, but focused application has already changed to %s",
635 focusedApplication->getName().c_str());
636 return; // The focused application has changed.
637 }
638
639 const sp<WindowInfoHandle>& focusedWindowHandle =
640 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
641 if (focusedWindowHandle != nullptr) {
642 return; // We now have a focused window. No need for ANR.
643 }
644 onAnrLocked(mAwaitedFocusedApplication);
645 }
646
647 /**
648 * Check if any of the connections' wait queues have events that are too old.
649 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
650 * Return the time at which we should wake up next.
651 */
processAnrsLocked()652 nsecs_t InputDispatcher::processAnrsLocked() {
653 const nsecs_t currentTime = now();
654 nsecs_t nextAnrCheck = LONG_LONG_MAX;
655 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
656 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
657 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
658 processNoFocusedWindowAnrLocked();
659 mAwaitedFocusedApplication.reset();
660 mNoFocusedWindowTimeoutTime = std::nullopt;
661 return LONG_LONG_MIN;
662 } else {
663 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
664 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
665 }
666 }
667
668 // Check if any connection ANRs are due
669 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
670 if (currentTime < nextAnrCheck) { // most likely scenario
671 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
672 }
673
674 // If we reached here, we have an unresponsive connection.
675 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
676 if (connection == nullptr) {
677 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
678 return nextAnrCheck;
679 }
680 connection->responsive = false;
681 // Stop waking up for this unresponsive connection
682 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
683 onAnrLocked(connection);
684 return LONG_LONG_MIN;
685 }
686
getDispatchingTimeoutLocked(const sp<IBinder> & token)687 std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
688 sp<WindowInfoHandle> window = getWindowHandleLocked(token);
689 if (window != nullptr) {
690 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
691 }
692 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
693 }
694
dispatchOnceInnerLocked(nsecs_t * nextWakeupTime)695 void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
696 nsecs_t currentTime = now();
697
698 // Reset the key repeat timer whenever normal dispatch is suspended while the
699 // device is in a non-interactive state. This is to ensure that we abort a key
700 // repeat if the device is just coming out of sleep.
701 if (!mDispatchEnabled) {
702 resetKeyRepeatLocked();
703 }
704
705 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
706 if (mDispatchFrozen) {
707 if (DEBUG_FOCUS) {
708 ALOGD("Dispatch frozen. Waiting some more.");
709 }
710 return;
711 }
712
713 // Optimize latency of app switches.
714 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
715 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
716 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
717 if (mAppSwitchDueTime < *nextWakeupTime) {
718 *nextWakeupTime = mAppSwitchDueTime;
719 }
720
721 // Ready to start a new event.
722 // If we don't already have a pending event, go grab one.
723 if (!mPendingEvent) {
724 if (mInboundQueue.empty()) {
725 if (isAppSwitchDue) {
726 // The inbound queue is empty so the app switch key we were waiting
727 // for will never arrive. Stop waiting for it.
728 resetPendingAppSwitchLocked(false);
729 isAppSwitchDue = false;
730 }
731
732 // Synthesize a key repeat if appropriate.
733 if (mKeyRepeatState.lastKeyEntry) {
734 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
735 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
736 } else {
737 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
738 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
739 }
740 }
741 }
742
743 // Nothing to do if there is no pending event.
744 if (!mPendingEvent) {
745 return;
746 }
747 } else {
748 // Inbound queue has at least one entry.
749 mPendingEvent = mInboundQueue.front();
750 mInboundQueue.pop_front();
751 traceInboundQueueLengthLocked();
752 }
753
754 // Poke user activity for this event.
755 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
756 pokeUserActivityLocked(*mPendingEvent);
757 }
758 }
759
760 // Now we have an event to dispatch.
761 // All events are eventually dequeued and processed this way, even if we intend to drop them.
762 ALOG_ASSERT(mPendingEvent != nullptr);
763 bool done = false;
764 DropReason dropReason = DropReason::NOT_DROPPED;
765 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
766 dropReason = DropReason::POLICY;
767 } else if (!mDispatchEnabled) {
768 dropReason = DropReason::DISABLED;
769 }
770
771 if (mNextUnblockedEvent == mPendingEvent) {
772 mNextUnblockedEvent = nullptr;
773 }
774
775 switch (mPendingEvent->type) {
776 case EventEntry::Type::CONFIGURATION_CHANGED: {
777 const ConfigurationChangedEntry& typedEntry =
778 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
779 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
780 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
781 break;
782 }
783
784 case EventEntry::Type::DEVICE_RESET: {
785 const DeviceResetEntry& typedEntry =
786 static_cast<const DeviceResetEntry&>(*mPendingEvent);
787 done = dispatchDeviceResetLocked(currentTime, typedEntry);
788 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
789 break;
790 }
791
792 case EventEntry::Type::FOCUS: {
793 std::shared_ptr<FocusEntry> typedEntry =
794 std::static_pointer_cast<FocusEntry>(mPendingEvent);
795 dispatchFocusLocked(currentTime, typedEntry);
796 done = true;
797 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
798 break;
799 }
800
801 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
802 const auto typedEntry =
803 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
804 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
805 done = true;
806 break;
807 }
808
809 case EventEntry::Type::DRAG: {
810 std::shared_ptr<DragEntry> typedEntry =
811 std::static_pointer_cast<DragEntry>(mPendingEvent);
812 dispatchDragLocked(currentTime, typedEntry);
813 done = true;
814 break;
815 }
816
817 case EventEntry::Type::KEY: {
818 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
819 if (isAppSwitchDue) {
820 if (isAppSwitchKeyEvent(*keyEntry)) {
821 resetPendingAppSwitchLocked(true);
822 isAppSwitchDue = false;
823 } else if (dropReason == DropReason::NOT_DROPPED) {
824 dropReason = DropReason::APP_SWITCH;
825 }
826 }
827 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
828 dropReason = DropReason::STALE;
829 }
830 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
831 dropReason = DropReason::BLOCKED;
832 }
833 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
834 break;
835 }
836
837 case EventEntry::Type::MOTION: {
838 std::shared_ptr<MotionEntry> motionEntry =
839 std::static_pointer_cast<MotionEntry>(mPendingEvent);
840 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
841 dropReason = DropReason::APP_SWITCH;
842 }
843 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
844 dropReason = DropReason::STALE;
845 }
846 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
847 dropReason = DropReason::BLOCKED;
848 }
849 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
850 break;
851 }
852
853 case EventEntry::Type::SENSOR: {
854 std::shared_ptr<SensorEntry> sensorEntry =
855 std::static_pointer_cast<SensorEntry>(mPendingEvent);
856 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
857 dropReason = DropReason::APP_SWITCH;
858 }
859 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
860 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
861 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
862 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
863 dropReason = DropReason::STALE;
864 }
865 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
866 done = true;
867 break;
868 }
869 }
870
871 if (done) {
872 if (dropReason != DropReason::NOT_DROPPED) {
873 dropInboundEventLocked(*mPendingEvent, dropReason);
874 }
875 mLastDropReason = dropReason;
876
877 releasePendingEventLocked();
878 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
879 }
880 }
881
882 /**
883 * Return true if the events preceding this incoming motion event should be dropped
884 * Return false otherwise (the default behaviour)
885 */
shouldPruneInboundQueueLocked(const MotionEntry & motionEntry)886 bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
887 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
888 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
889
890 // Optimize case where the current application is unresponsive and the user
891 // decides to touch a window in a different application.
892 // If the application takes too long to catch up then we drop all events preceding
893 // the touch into the other window.
894 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
895 int32_t displayId = motionEntry.displayId;
896 int32_t x = static_cast<int32_t>(
897 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
898 int32_t y = static_cast<int32_t>(
899 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
900 sp<WindowInfoHandle> touchedWindowHandle =
901 findTouchedWindowAtLocked(displayId, x, y, nullptr);
902 if (touchedWindowHandle != nullptr &&
903 touchedWindowHandle->getApplicationToken() !=
904 mAwaitedFocusedApplication->getApplicationToken()) {
905 // User touched a different application than the one we are waiting on.
906 ALOGI("Pruning input queue because user touched a different application while waiting "
907 "for %s",
908 mAwaitedFocusedApplication->getName().c_str());
909 return true;
910 }
911
912 // Alternatively, maybe there's a gesture monitor that could handle this event
913 std::vector<TouchedMonitor> gestureMonitors =
914 findTouchedGestureMonitorsLocked(displayId, {});
915 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
916 sp<Connection> connection =
917 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
918 if (connection != nullptr && connection->responsive) {
919 // This monitor could take more input. Drop all events preceding this
920 // event, so that gesture monitor could get a chance to receive the stream
921 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
922 "responsive gesture monitor that may handle the event",
923 mAwaitedFocusedApplication->getName().c_str());
924 return true;
925 }
926 }
927 }
928
929 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
930 // yet been processed by some connections, the dispatcher will wait for these motion
931 // events to be processed before dispatching the key event. This is because these motion events
932 // may cause a new window to be launched, which the user might expect to receive focus.
933 // To prevent waiting forever for such events, just send the key to the currently focused window
934 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
935 ALOGD("Received a new pointer down event, stop waiting for events to process and "
936 "just send the pending key event to the focused window.");
937 mKeyIsWaitingForEventsTimeout = now();
938 }
939 return false;
940 }
941
enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry)942 bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
943 bool needWake = mInboundQueue.empty();
944 mInboundQueue.push_back(std::move(newEntry));
945 EventEntry& entry = *(mInboundQueue.back());
946 traceInboundQueueLengthLocked();
947
948 switch (entry.type) {
949 case EventEntry::Type::KEY: {
950 // Optimize app switch latency.
951 // If the application takes too long to catch up then we drop all events preceding
952 // the app switch key.
953 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
954 if (isAppSwitchKeyEvent(keyEntry)) {
955 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
956 mAppSwitchSawKeyDown = true;
957 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
958 if (mAppSwitchSawKeyDown) {
959 #if DEBUG_APP_SWITCH
960 ALOGD("App switch is pending!");
961 #endif
962 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
963 mAppSwitchSawKeyDown = false;
964 needWake = true;
965 }
966 }
967 }
968 break;
969 }
970
971 case EventEntry::Type::MOTION: {
972 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
973 mNextUnblockedEvent = mInboundQueue.back();
974 needWake = true;
975 }
976 break;
977 }
978 case EventEntry::Type::FOCUS: {
979 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
980 break;
981 }
982 case EventEntry::Type::CONFIGURATION_CHANGED:
983 case EventEntry::Type::DEVICE_RESET:
984 case EventEntry::Type::SENSOR:
985 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
986 case EventEntry::Type::DRAG: {
987 // nothing to do
988 break;
989 }
990 }
991
992 return needWake;
993 }
994
addRecentEventLocked(std::shared_ptr<EventEntry> entry)995 void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
996 // Do not store sensor event in recent queue to avoid flooding the queue.
997 if (entry->type != EventEntry::Type::SENSOR) {
998 mRecentQueue.push_back(entry);
999 }
1000 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
1001 mRecentQueue.pop_front();
1002 }
1003 }
1004
findTouchedWindowAtLocked(int32_t displayId,int32_t x,int32_t y,TouchState * touchState,bool addOutsideTargets,bool addPortalWindows,bool ignoreDragWindow)1005 sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1006 int32_t y, TouchState* touchState,
1007 bool addOutsideTargets,
1008 bool addPortalWindows,
1009 bool ignoreDragWindow) {
1010 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
1011 LOG_ALWAYS_FATAL(
1012 "Must provide a valid touch state if adding portal windows or outside targets");
1013 }
1014 // Traverse windows from front to back to find touched window.
1015 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
1016 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1017 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
1018 continue;
1019 }
1020 const WindowInfo* windowInfo = windowHandle->getInfo();
1021 if (windowInfo->displayId == displayId) {
1022 auto flags = windowInfo->flags;
1023
1024 if (windowInfo->visible) {
1025 if (!flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
1026 bool isTouchModal = !flags.test(WindowInfo::Flag::NOT_FOCUSABLE) &&
1027 !flags.test(WindowInfo::Flag::NOT_TOUCH_MODAL);
1028 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
1029 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
1030 if (portalToDisplayId != ADISPLAY_ID_NONE &&
1031 portalToDisplayId != displayId) {
1032 if (addPortalWindows) {
1033 // For the monitoring channels of the display.
1034 touchState->addPortalWindow(windowHandle);
1035 }
1036 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
1037 addOutsideTargets, addPortalWindows);
1038 }
1039 // Found window.
1040 return windowHandle;
1041 }
1042 }
1043
1044 if (addOutsideTargets && flags.test(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
1045 touchState->addOrUpdateWindow(windowHandle,
1046 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1047 BitSet32(0));
1048 }
1049 }
1050 }
1051 }
1052 return nullptr;
1053 }
1054
findTouchedGestureMonitorsLocked(int32_t displayId,const std::vector<sp<WindowInfoHandle>> & portalWindows) const1055 std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
1056 int32_t displayId, const std::vector<sp<WindowInfoHandle>>& portalWindows) const {
1057 std::vector<TouchedMonitor> touchedMonitors;
1058
1059 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
1060 addGestureMonitors(monitors, touchedMonitors);
1061 for (const sp<WindowInfoHandle>& portalWindow : portalWindows) {
1062 const WindowInfo* windowInfo = portalWindow->getInfo();
1063 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
1064 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
1065 -windowInfo->frameTop);
1066 }
1067 return touchedMonitors;
1068 }
1069
dropInboundEventLocked(const EventEntry & entry,DropReason dropReason)1070 void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
1071 const char* reason;
1072 switch (dropReason) {
1073 case DropReason::POLICY:
1074 #if DEBUG_INBOUND_EVENT_DETAILS
1075 ALOGD("Dropped event because policy consumed it.");
1076 #endif
1077 reason = "inbound event was dropped because the policy consumed it";
1078 break;
1079 case DropReason::DISABLED:
1080 if (mLastDropReason != DropReason::DISABLED) {
1081 ALOGI("Dropped event because input dispatch is disabled.");
1082 }
1083 reason = "inbound event was dropped because input dispatch is disabled";
1084 break;
1085 case DropReason::APP_SWITCH:
1086 ALOGI("Dropped event because of pending overdue app switch.");
1087 reason = "inbound event was dropped because of pending overdue app switch";
1088 break;
1089 case DropReason::BLOCKED:
1090 ALOGI("Dropped event because the current application is not responding and the user "
1091 "has started interacting with a different application.");
1092 reason = "inbound event was dropped because the current application is not responding "
1093 "and the user has started interacting with a different application";
1094 break;
1095 case DropReason::STALE:
1096 ALOGI("Dropped event because it is stale.");
1097 reason = "inbound event was dropped because it is stale";
1098 break;
1099 case DropReason::NO_POINTER_CAPTURE:
1100 ALOGI("Dropped event because there is no window with Pointer Capture.");
1101 reason = "inbound event was dropped because there is no window with Pointer Capture";
1102 break;
1103 case DropReason::NOT_DROPPED: {
1104 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
1105 return;
1106 }
1107 }
1108
1109 switch (entry.type) {
1110 case EventEntry::Type::KEY: {
1111 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1112 synthesizeCancelationEventsForAllConnectionsLocked(options);
1113 break;
1114 }
1115 case EventEntry::Type::MOTION: {
1116 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1117 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
1118 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1119 synthesizeCancelationEventsForAllConnectionsLocked(options);
1120 } else {
1121 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1122 synthesizeCancelationEventsForAllConnectionsLocked(options);
1123 }
1124 break;
1125 }
1126 case EventEntry::Type::SENSOR: {
1127 break;
1128 }
1129 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1130 case EventEntry::Type::DRAG: {
1131 break;
1132 }
1133 case EventEntry::Type::FOCUS:
1134 case EventEntry::Type::CONFIGURATION_CHANGED:
1135 case EventEntry::Type::DEVICE_RESET: {
1136 LOG_ALWAYS_FATAL("Should not drop %s events", NamedEnum::string(entry.type).c_str());
1137 break;
1138 }
1139 }
1140 }
1141
isAppSwitchKeyCode(int32_t keyCode)1142 static bool isAppSwitchKeyCode(int32_t keyCode) {
1143 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1144 keyCode == AKEYCODE_APP_SWITCH;
1145 }
1146
isAppSwitchKeyEvent(const KeyEntry & keyEntry)1147 bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1148 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1149 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1150 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
1151 }
1152
isAppSwitchPendingLocked()1153 bool InputDispatcher::isAppSwitchPendingLocked() {
1154 return mAppSwitchDueTime != LONG_LONG_MAX;
1155 }
1156
resetPendingAppSwitchLocked(bool handled)1157 void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1158 mAppSwitchDueTime = LONG_LONG_MAX;
1159
1160 #if DEBUG_APP_SWITCH
1161 if (handled) {
1162 ALOGD("App switch has arrived.");
1163 } else {
1164 ALOGD("App switch was abandoned.");
1165 }
1166 #endif
1167 }
1168
haveCommandsLocked() const1169 bool InputDispatcher::haveCommandsLocked() const {
1170 return !mCommandQueue.empty();
1171 }
1172
runCommandsLockedInterruptible()1173 bool InputDispatcher::runCommandsLockedInterruptible() {
1174 if (mCommandQueue.empty()) {
1175 return false;
1176 }
1177
1178 do {
1179 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
1180 mCommandQueue.pop_front();
1181 Command command = commandEntry->command;
1182 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
1183
1184 commandEntry->connection.clear();
1185 } while (!mCommandQueue.empty());
1186 return true;
1187 }
1188
postCommandLocked(std::unique_ptr<CommandEntry> commandEntry)1189 void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1190 mCommandQueue.push_back(std::move(commandEntry));
1191 }
1192
drainInboundQueueLocked()1193 void InputDispatcher::drainInboundQueueLocked() {
1194 while (!mInboundQueue.empty()) {
1195 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
1196 mInboundQueue.pop_front();
1197 releaseInboundEventLocked(entry);
1198 }
1199 traceInboundQueueLengthLocked();
1200 }
1201
releasePendingEventLocked()1202 void InputDispatcher::releasePendingEventLocked() {
1203 if (mPendingEvent) {
1204 releaseInboundEventLocked(mPendingEvent);
1205 mPendingEvent = nullptr;
1206 }
1207 }
1208
releaseInboundEventLocked(std::shared_ptr<EventEntry> entry)1209 void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
1210 InjectionState* injectionState = entry->injectionState;
1211 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
1212 #if DEBUG_DISPATCH_CYCLE
1213 ALOGD("Injected inbound event was dropped.");
1214 #endif
1215 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
1216 }
1217 if (entry == mNextUnblockedEvent) {
1218 mNextUnblockedEvent = nullptr;
1219 }
1220 addRecentEventLocked(entry);
1221 }
1222
resetKeyRepeatLocked()1223 void InputDispatcher::resetKeyRepeatLocked() {
1224 if (mKeyRepeatState.lastKeyEntry) {
1225 mKeyRepeatState.lastKeyEntry = nullptr;
1226 }
1227 }
1228
synthesizeKeyRepeatLocked(nsecs_t currentTime)1229 std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1230 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
1231
1232 uint32_t policyFlags = entry->policyFlags &
1233 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
1234
1235 std::shared_ptr<KeyEntry> newEntry =
1236 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1237 entry->source, entry->displayId, policyFlags, entry->action,
1238 entry->flags, entry->keyCode, entry->scanCode,
1239 entry->metaState, entry->repeatCount + 1, entry->downTime);
1240
1241 newEntry->syntheticRepeat = true;
1242 mKeyRepeatState.lastKeyEntry = newEntry;
1243 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1244 return newEntry;
1245 }
1246
dispatchConfigurationChangedLocked(nsecs_t currentTime,const ConfigurationChangedEntry & entry)1247 bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1248 const ConfigurationChangedEntry& entry) {
1249 #if DEBUG_OUTBOUND_EVENT_DETAILS
1250 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1251 #endif
1252
1253 // Reset key repeating in case a keyboard device was added or removed or something.
1254 resetKeyRepeatLocked();
1255
1256 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
1257 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1258 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
1259 commandEntry->eventTime = entry.eventTime;
1260 postCommandLocked(std::move(commandEntry));
1261 return true;
1262 }
1263
dispatchDeviceResetLocked(nsecs_t currentTime,const DeviceResetEntry & entry)1264 bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1265 const DeviceResetEntry& entry) {
1266 #if DEBUG_OUTBOUND_EVENT_DETAILS
1267 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1268 entry.deviceId);
1269 #endif
1270
1271 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
1272 options.deviceId = entry.deviceId;
1273 synthesizeCancelationEventsForAllConnectionsLocked(options);
1274 return true;
1275 }
1276
enqueueFocusEventLocked(const sp<IBinder> & windowToken,bool hasFocus,const std::string & reason)1277 void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
1278 const std::string& reason) {
1279 if (mPendingEvent != nullptr) {
1280 // Move the pending event to the front of the queue. This will give the chance
1281 // for the pending event to get dispatched to the newly focused window
1282 mInboundQueue.push_front(mPendingEvent);
1283 mPendingEvent = nullptr;
1284 }
1285
1286 std::unique_ptr<FocusEntry> focusEntry =
1287 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1288 reason);
1289
1290 // This event should go to the front of the queue, but behind all other focus events
1291 // Find the last focus event, and insert right after it
1292 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
1293 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1294 [](const std::shared_ptr<EventEntry>& event) {
1295 return event->type == EventEntry::Type::FOCUS;
1296 });
1297
1298 // Maintain the order of focus events. Insert the entry after all other focus events.
1299 mInboundQueue.insert(it.base(), std::move(focusEntry));
1300 }
1301
dispatchFocusLocked(nsecs_t currentTime,std::shared_ptr<FocusEntry> entry)1302 void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
1303 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1304 if (channel == nullptr) {
1305 return; // Window has gone away
1306 }
1307 InputTarget target;
1308 target.inputChannel = channel;
1309 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1310 entry->dispatchInProgress = true;
1311 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1312 channel->getName();
1313 std::string reason = std::string("reason=").append(entry->reason);
1314 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
1315 dispatchEventLocked(currentTime, entry, {target});
1316 }
1317
dispatchPointerCaptureChangedLocked(nsecs_t currentTime,const std::shared_ptr<PointerCaptureChangedEntry> & entry,DropReason & dropReason)1318 void InputDispatcher::dispatchPointerCaptureChangedLocked(
1319 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1320 DropReason& dropReason) {
1321 dropReason = DropReason::NOT_DROPPED;
1322
1323 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
1324 sp<IBinder> token;
1325
1326 if (entry->pointerCaptureRequest.enable) {
1327 // Enable Pointer Capture.
1328 if (haveWindowWithPointerCapture &&
1329 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
1330 LOG_ALWAYS_FATAL("This request to enable Pointer Capture has already been dispatched "
1331 "to the window.");
1332 }
1333 if (!mCurrentPointerCaptureRequest.enable) {
1334 // This can happen if a window requests capture and immediately releases capture.
1335 ALOGW("No window requested Pointer Capture.");
1336 dropReason = DropReason::NO_POINTER_CAPTURE;
1337 return;
1338 }
1339 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1340 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1341 return;
1342 }
1343
1344 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
1345 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1346 mWindowTokenWithPointerCapture = token;
1347 } else {
1348 // Disable Pointer Capture.
1349 // We do not check if the sequence number matches for requests to disable Pointer Capture
1350 // for two reasons:
1351 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1352 // to disable capture with the same sequence number: one generated by
1353 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1354 // Capture being disabled in InputReader.
1355 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1356 // actual Pointer Capture state that affects events being generated by input devices is
1357 // in InputReader.
1358 if (!haveWindowWithPointerCapture) {
1359 // Pointer capture was already forcefully disabled because of focus change.
1360 dropReason = DropReason::NOT_DROPPED;
1361 return;
1362 }
1363 token = mWindowTokenWithPointerCapture;
1364 mWindowTokenWithPointerCapture = nullptr;
1365 if (mCurrentPointerCaptureRequest.enable) {
1366 setPointerCaptureLocked(false);
1367 }
1368 }
1369
1370 auto channel = getInputChannelLocked(token);
1371 if (channel == nullptr) {
1372 // Window has gone away, clean up Pointer Capture state.
1373 mWindowTokenWithPointerCapture = nullptr;
1374 if (mCurrentPointerCaptureRequest.enable) {
1375 setPointerCaptureLocked(false);
1376 }
1377 return;
1378 }
1379 InputTarget target;
1380 target.inputChannel = channel;
1381 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1382 entry->dispatchInProgress = true;
1383 dispatchEventLocked(currentTime, entry, {target});
1384
1385 dropReason = DropReason::NOT_DROPPED;
1386 }
1387
dispatchKeyLocked(nsecs_t currentTime,std::shared_ptr<KeyEntry> entry,DropReason * dropReason,nsecs_t * nextWakeupTime)1388 bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
1389 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1390 // Preprocessing.
1391 if (!entry->dispatchInProgress) {
1392 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1393 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1394 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1395 if (mKeyRepeatState.lastKeyEntry &&
1396 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
1397 // We have seen two identical key downs in a row which indicates that the device
1398 // driver is automatically generating key repeats itself. We take note of the
1399 // repeat here, but we disable our own next key repeat timer since it is clear that
1400 // we will not need to synthesize key repeats ourselves.
1401 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1402 // Make sure we don't get key down from a different device. If a different
1403 // device Id has same key pressed down, the new device Id will replace the
1404 // current one to hold the key repeat with repeat count reset.
1405 // In the future when got a KEY_UP on the device id, drop it and do not
1406 // stop the key repeat on current device.
1407 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1408 resetKeyRepeatLocked();
1409 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1410 } else {
1411 // Not a repeat. Save key down state in case we do see a repeat later.
1412 resetKeyRepeatLocked();
1413 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1414 }
1415 mKeyRepeatState.lastKeyEntry = entry;
1416 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1417 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
1418 // The key on device 'deviceId' is still down, do not stop key repeat
1419 #if DEBUG_INBOUND_EVENT_DETAILS
1420 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1421 #endif
1422 } else if (!entry->syntheticRepeat) {
1423 resetKeyRepeatLocked();
1424 }
1425
1426 if (entry->repeatCount == 1) {
1427 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1428 } else {
1429 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1430 }
1431
1432 entry->dispatchInProgress = true;
1433
1434 logOutboundKeyDetails("dispatchKey - ", *entry);
1435 }
1436
1437 // Handle case where the policy asked us to try again later last time.
1438 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1439 if (currentTime < entry->interceptKeyWakeupTime) {
1440 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1441 *nextWakeupTime = entry->interceptKeyWakeupTime;
1442 }
1443 return false; // wait until next wakeup
1444 }
1445 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1446 entry->interceptKeyWakeupTime = 0;
1447 }
1448
1449 // Give the policy a chance to intercept the key.
1450 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1451 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
1452 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1453 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
1454 sp<IBinder> focusedWindowToken =
1455 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
1456 commandEntry->connectionToken = focusedWindowToken;
1457 commandEntry->keyEntry = entry;
1458 postCommandLocked(std::move(commandEntry));
1459 return false; // wait for the command to run
1460 } else {
1461 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1462 }
1463 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
1464 if (*dropReason == DropReason::NOT_DROPPED) {
1465 *dropReason = DropReason::POLICY;
1466 }
1467 }
1468
1469 // Clean up if dropping the event.
1470 if (*dropReason != DropReason::NOT_DROPPED) {
1471 setInjectionResult(*entry,
1472 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1473 : InputEventInjectionResult::FAILED);
1474 mReporter->reportDroppedKey(entry->id);
1475 return true;
1476 }
1477
1478 // Identify targets.
1479 std::vector<InputTarget> inputTargets;
1480 InputEventInjectionResult injectionResult =
1481 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
1482 if (injectionResult == InputEventInjectionResult::PENDING) {
1483 return false;
1484 }
1485
1486 setInjectionResult(*entry, injectionResult);
1487 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
1488 return true;
1489 }
1490
1491 // Add monitor channels from event's or focused display.
1492 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
1493
1494 // Dispatch the key.
1495 dispatchEventLocked(currentTime, entry, inputTargets);
1496 return true;
1497 }
1498
logOutboundKeyDetails(const char * prefix,const KeyEntry & entry)1499 void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
1500 #if DEBUG_OUTBOUND_EVENT_DETAILS
1501 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1502 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1503 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1504 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1505 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1506 entry.repeatCount, entry.downTime);
1507 #endif
1508 }
1509
doNotifySensorLockedInterruptible(CommandEntry * commandEntry)1510 void InputDispatcher::doNotifySensorLockedInterruptible(CommandEntry* commandEntry) {
1511 mLock.unlock();
1512
1513 const std::shared_ptr<SensorEntry>& entry = commandEntry->sensorEntry;
1514 if (entry->accuracyChanged) {
1515 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1516 }
1517 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1518 entry->hwTimestamp, entry->values);
1519 mLock.lock();
1520 }
1521
dispatchSensorLocked(nsecs_t currentTime,std::shared_ptr<SensorEntry> entry,DropReason * dropReason,nsecs_t * nextWakeupTime)1522 void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime, std::shared_ptr<SensorEntry> entry,
1523 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1524 #if DEBUG_OUTBOUND_EVENT_DETAILS
1525 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1526 "source=0x%x, sensorType=%s",
1527 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
1528 NamedEnum::string(entry->sensorType).c_str());
1529 #endif
1530 std::unique_ptr<CommandEntry> commandEntry =
1531 std::make_unique<CommandEntry>(&InputDispatcher::doNotifySensorLockedInterruptible);
1532 commandEntry->sensorEntry = entry;
1533 postCommandLocked(std::move(commandEntry));
1534 }
1535
flushSensor(int deviceId,InputDeviceSensorType sensorType)1536 bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
1537 #if DEBUG_OUTBOUND_EVENT_DETAILS
1538 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
1539 NamedEnum::string(sensorType).c_str());
1540 #endif
1541 { // acquire lock
1542 std::scoped_lock _l(mLock);
1543
1544 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1545 std::shared_ptr<EventEntry> entry = *it;
1546 if (entry->type == EventEntry::Type::SENSOR) {
1547 it = mInboundQueue.erase(it);
1548 releaseInboundEventLocked(entry);
1549 }
1550 }
1551 }
1552 return true;
1553 }
1554
dispatchMotionLocked(nsecs_t currentTime,std::shared_ptr<MotionEntry> entry,DropReason * dropReason,nsecs_t * nextWakeupTime)1555 bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
1556 DropReason* dropReason, nsecs_t* nextWakeupTime) {
1557 ATRACE_CALL();
1558 // Preprocessing.
1559 if (!entry->dispatchInProgress) {
1560 entry->dispatchInProgress = true;
1561
1562 logOutboundMotionDetails("dispatchMotion - ", *entry);
1563 }
1564
1565 // Clean up if dropping the event.
1566 if (*dropReason != DropReason::NOT_DROPPED) {
1567 setInjectionResult(*entry,
1568 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1569 : InputEventInjectionResult::FAILED);
1570 return true;
1571 }
1572
1573 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1574
1575 // Identify targets.
1576 std::vector<InputTarget> inputTargets;
1577
1578 bool conflictingPointerActions = false;
1579 InputEventInjectionResult injectionResult;
1580 if (isPointerEvent) {
1581 // Pointer event. (eg. touchscreen)
1582 injectionResult =
1583 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
1584 &conflictingPointerActions);
1585 } else {
1586 // Non touch event. (eg. trackball)
1587 injectionResult =
1588 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
1589 }
1590 if (injectionResult == InputEventInjectionResult::PENDING) {
1591 return false;
1592 }
1593
1594 setInjectionResult(*entry, injectionResult);
1595 if (injectionResult == InputEventInjectionResult::PERMISSION_DENIED) {
1596 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1597 return true;
1598 }
1599 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
1600 CancelationOptions::Mode mode(isPointerEvent
1601 ? CancelationOptions::CANCEL_POINTER_EVENTS
1602 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1603 CancelationOptions options(mode, "input event injection failed");
1604 synthesizeCancelationEventsForMonitorsLocked(options);
1605 return true;
1606 }
1607
1608 // Add monitor channels from event's or focused display.
1609 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
1610
1611 if (isPointerEvent) {
1612 std::unordered_map<int32_t, TouchState>::iterator it =
1613 mTouchStatesByDisplay.find(entry->displayId);
1614 if (it != mTouchStatesByDisplay.end()) {
1615 const TouchState& state = it->second;
1616 if (!state.portalWindows.empty()) {
1617 // The event has gone through these portal windows, so we add monitoring targets of
1618 // the corresponding displays as well.
1619 for (size_t i = 0; i < state.portalWindows.size(); i++) {
1620 const WindowInfo* windowInfo = state.portalWindows[i]->getInfo();
1621 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
1622 -windowInfo->frameLeft, -windowInfo->frameTop);
1623 }
1624 }
1625 }
1626 }
1627
1628 // Dispatch the motion.
1629 if (conflictingPointerActions) {
1630 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
1631 "conflicting pointer actions");
1632 synthesizeCancelationEventsForAllConnectionsLocked(options);
1633 }
1634 dispatchEventLocked(currentTime, entry, inputTargets);
1635 return true;
1636 }
1637
enqueueDragEventLocked(const sp<WindowInfoHandle> & windowHandle,bool isExiting,const MotionEntry & motionEntry)1638 void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
1639 bool isExiting, const MotionEntry& motionEntry) {
1640 // If the window needs enqueue a drag event, the pointerCount should be 1 and the action should
1641 // be AMOTION_EVENT_ACTION_MOVE, that could guarantee the first pointer is always valid.
1642 LOG_ALWAYS_FATAL_IF(motionEntry.pointerCount != 1);
1643 PointerCoords pointerCoords;
1644 pointerCoords.copyFrom(motionEntry.pointerCoords[0]);
1645 pointerCoords.transform(windowHandle->getInfo()->transform);
1646
1647 std::unique_ptr<DragEntry> dragEntry =
1648 std::make_unique<DragEntry>(mIdGenerator.nextId(), motionEntry.eventTime,
1649 windowHandle->getToken(), isExiting, pointerCoords.getX(),
1650 pointerCoords.getY());
1651
1652 enqueueInboundEventLocked(std::move(dragEntry));
1653 }
1654
dispatchDragLocked(nsecs_t currentTime,std::shared_ptr<DragEntry> entry)1655 void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1656 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1657 if (channel == nullptr) {
1658 return; // Window has gone away
1659 }
1660 InputTarget target;
1661 target.inputChannel = channel;
1662 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1663 entry->dispatchInProgress = true;
1664 dispatchEventLocked(currentTime, entry, {target});
1665 }
1666
logOutboundMotionDetails(const char * prefix,const MotionEntry & entry)1667 void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
1668 #if DEBUG_OUTBOUND_EVENT_DETAILS
1669 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1670 ", policyFlags=0x%x, "
1671 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1672 "metaState=0x%x, buttonState=0x%x,"
1673 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1674 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1675 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1676 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
1677
1678 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1679 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1680 "x=%f, y=%f, pressure=%f, size=%f, "
1681 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1682 "orientation=%f",
1683 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1684 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1685 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1686 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1687 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1688 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1689 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1690 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1691 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1692 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1693 }
1694 #endif
1695 }
1696
dispatchEventLocked(nsecs_t currentTime,std::shared_ptr<EventEntry> eventEntry,const std::vector<InputTarget> & inputTargets)1697 void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1698 std::shared_ptr<EventEntry> eventEntry,
1699 const std::vector<InputTarget>& inputTargets) {
1700 ATRACE_CALL();
1701 #if DEBUG_DISPATCH_CYCLE
1702 ALOGD("dispatchEventToCurrentInputTargets");
1703 #endif
1704
1705 updateInteractionTokensLocked(*eventEntry, inputTargets);
1706
1707 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1708
1709 pokeUserActivityLocked(*eventEntry);
1710
1711 for (const InputTarget& inputTarget : inputTargets) {
1712 sp<Connection> connection =
1713 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
1714 if (connection != nullptr) {
1715 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
1716 } else {
1717 if (DEBUG_FOCUS) {
1718 ALOGD("Dropping event delivery to target with channel '%s' because it "
1719 "is no longer registered with the input dispatcher.",
1720 inputTarget.inputChannel->getName().c_str());
1721 }
1722 }
1723 }
1724 }
1725
cancelEventsForAnrLocked(const sp<Connection> & connection)1726 void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1727 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1728 // If the policy decides to close the app, we will get a channel removal event via
1729 // unregisterInputChannel, and will clean up the connection that way. We are already not
1730 // sending new pointers to the connection when it blocked, but focused events will continue to
1731 // pile up.
1732 ALOGW("Canceling events for %s because it is unresponsive",
1733 connection->inputChannel->getName().c_str());
1734 if (connection->status == Connection::STATUS_NORMAL) {
1735 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1736 "application not responding");
1737 synthesizeCancelationEventsForConnectionLocked(connection, options);
1738 }
1739 }
1740
resetNoFocusedWindowTimeoutLocked()1741 void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
1742 if (DEBUG_FOCUS) {
1743 ALOGD("Resetting ANR timeouts.");
1744 }
1745
1746 // Reset input target wait timeout.
1747 mNoFocusedWindowTimeoutTime = std::nullopt;
1748 mAwaitedFocusedApplication.reset();
1749 }
1750
1751 /**
1752 * Get the display id that the given event should go to. If this event specifies a valid display id,
1753 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1754 * Focused display is the display that the user most recently interacted with.
1755 */
getTargetDisplayId(const EventEntry & entry)1756 int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
1757 int32_t displayId;
1758 switch (entry.type) {
1759 case EventEntry::Type::KEY: {
1760 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1761 displayId = keyEntry.displayId;
1762 break;
1763 }
1764 case EventEntry::Type::MOTION: {
1765 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1766 displayId = motionEntry.displayId;
1767 break;
1768 }
1769 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1770 case EventEntry::Type::FOCUS:
1771 case EventEntry::Type::CONFIGURATION_CHANGED:
1772 case EventEntry::Type::DEVICE_RESET:
1773 case EventEntry::Type::SENSOR:
1774 case EventEntry::Type::DRAG: {
1775 ALOGE("%s events do not have a target display", NamedEnum::string(entry.type).c_str());
1776 return ADISPLAY_ID_NONE;
1777 }
1778 }
1779 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1780 }
1781
shouldWaitToSendKeyLocked(nsecs_t currentTime,const char * focusedWindowName)1782 bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1783 const char* focusedWindowName) {
1784 if (mAnrTracker.empty()) {
1785 // already processed all events that we waited for
1786 mKeyIsWaitingForEventsTimeout = std::nullopt;
1787 return false;
1788 }
1789
1790 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1791 // Start the timer
1792 // Wait to send key because there are unprocessed events that may cause focus to change
1793 mKeyIsWaitingForEventsTimeout = currentTime +
1794 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1795 .count();
1796 return true;
1797 }
1798
1799 // We still have pending events, and already started the timer
1800 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1801 return true; // Still waiting
1802 }
1803
1804 // Waited too long, and some connection still hasn't processed all motions
1805 // Just send the key to the focused window
1806 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1807 focusedWindowName);
1808 mKeyIsWaitingForEventsTimeout = std::nullopt;
1809 return false;
1810 }
1811
findFocusedWindowTargetsLocked(nsecs_t currentTime,const EventEntry & entry,std::vector<InputTarget> & inputTargets,nsecs_t * nextWakeupTime)1812 InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1813 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1814 nsecs_t* nextWakeupTime) {
1815 std::string reason;
1816
1817 int32_t displayId = getTargetDisplayId(entry);
1818 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
1819 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
1820 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1821
1822 // If there is no currently focused window and no focused application
1823 // then drop the event.
1824 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1825 ALOGI("Dropping %s event because there is no focused window or focused application in "
1826 "display %" PRId32 ".",
1827 NamedEnum::string(entry.type).c_str(), displayId);
1828 return InputEventInjectionResult::FAILED;
1829 }
1830
1831 // Drop key events if requested by input feature
1832 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1833 return InputEventInjectionResult::FAILED;
1834 }
1835
1836 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1837 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1838 // start interacting with another application via touch (app switch). This code can be removed
1839 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1840 // an app is expected to have a focused window.
1841 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1842 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1843 // We just discovered that there's no focused window. Start the ANR timer
1844 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1845 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1846 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
1847 mAwaitedFocusedApplication = focusedApplicationHandle;
1848 mAwaitedApplicationDisplayId = displayId;
1849 ALOGW("Waiting because no window has focus but %s may eventually add a "
1850 "window when it finishes starting up. Will wait for %" PRId64 "ms",
1851 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
1852 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1853 return InputEventInjectionResult::PENDING;
1854 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1855 // Already raised ANR. Drop the event
1856 ALOGE("Dropping %s event because there is no focused window",
1857 NamedEnum::string(entry.type).c_str());
1858 return InputEventInjectionResult::FAILED;
1859 } else {
1860 // Still waiting for the focused window
1861 return InputEventInjectionResult::PENDING;
1862 }
1863 }
1864
1865 // we have a valid, non-null focused window
1866 resetNoFocusedWindowTimeoutLocked();
1867
1868 // Check permissions.
1869 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
1870 return InputEventInjectionResult::PERMISSION_DENIED;
1871 }
1872
1873 if (focusedWindowHandle->getInfo()->paused) {
1874 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1875 return InputEventInjectionResult::PENDING;
1876 }
1877
1878 // If the event is a key event, then we must wait for all previous events to
1879 // complete before delivering it because previous events may have the
1880 // side-effect of transferring focus to a different window and we want to
1881 // ensure that the following keys are sent to the new window.
1882 //
1883 // Suppose the user touches a button in a window then immediately presses "A".
1884 // If the button causes a pop-up window to appear then we want to ensure that
1885 // the "A" key is delivered to the new pop-up window. This is because users
1886 // often anticipate pending UI changes when typing on a keyboard.
1887 // To obtain this behavior, we must serialize key events with respect to all
1888 // prior input events.
1889 if (entry.type == EventEntry::Type::KEY) {
1890 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1891 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1892 return InputEventInjectionResult::PENDING;
1893 }
1894 }
1895
1896 // Success! Output targets.
1897 addWindowTargetLocked(focusedWindowHandle,
1898 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1899 BitSet32(0), inputTargets);
1900
1901 // Done.
1902 return InputEventInjectionResult::SUCCEEDED;
1903 }
1904
1905 /**
1906 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1907 * that are currently unresponsive.
1908 */
selectResponsiveMonitorsLocked(const std::vector<TouchedMonitor> & monitors) const1909 std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1910 const std::vector<TouchedMonitor>& monitors) const {
1911 std::vector<TouchedMonitor> responsiveMonitors;
1912 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1913 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1914 sp<Connection> connection = getConnectionLocked(
1915 monitor.monitor.inputChannel->getConnectionToken());
1916 if (connection == nullptr) {
1917 ALOGE("Could not find connection for monitor %s",
1918 monitor.monitor.inputChannel->getName().c_str());
1919 return false;
1920 }
1921 if (!connection->responsive) {
1922 ALOGW("Unresponsive monitor %s will not get the new gesture",
1923 connection->inputChannel->getName().c_str());
1924 return false;
1925 }
1926 return true;
1927 });
1928 return responsiveMonitors;
1929 }
1930
findTouchedWindowTargetsLocked(nsecs_t currentTime,const MotionEntry & entry,std::vector<InputTarget> & inputTargets,nsecs_t * nextWakeupTime,bool * outConflictingPointerActions)1931 InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1932 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1933 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
1934 ATRACE_CALL();
1935 enum InjectionPermission {
1936 INJECTION_PERMISSION_UNKNOWN,
1937 INJECTION_PERMISSION_GRANTED,
1938 INJECTION_PERMISSION_DENIED
1939 };
1940
1941 // For security reasons, we defer updating the touch state until we are sure that
1942 // event injection will be allowed.
1943 int32_t displayId = entry.displayId;
1944 int32_t action = entry.action;
1945 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1946
1947 // Update the touch state as needed based on the properties of the touch event.
1948 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
1949 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1950 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1951 sp<WindowInfoHandle> newTouchedWindowHandle;
1952
1953 // Copy current touch state into tempTouchState.
1954 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1955 // If no state for the specified display exists, then our initial state will be empty.
1956 const TouchState* oldState = nullptr;
1957 TouchState tempTouchState;
1958 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1959 mTouchStatesByDisplay.find(displayId);
1960 if (oldStateIt != mTouchStatesByDisplay.end()) {
1961 oldState = &(oldStateIt->second);
1962 tempTouchState.copyFrom(*oldState);
1963 }
1964
1965 bool isSplit = tempTouchState.split;
1966 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1967 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1968 tempTouchState.displayId != displayId);
1969 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1970 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1971 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1972 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1973 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
1974 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
1975 bool wrongDevice = false;
1976 if (newGesture) {
1977 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
1978 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
1979 ALOGI("Dropping event because a pointer for a different device is already down "
1980 "in display %" PRId32,
1981 displayId);
1982 // TODO: test multiple simultaneous input streams.
1983 injectionResult = InputEventInjectionResult::FAILED;
1984 switchedDevice = false;
1985 wrongDevice = true;
1986 goto Failed;
1987 }
1988 tempTouchState.reset();
1989 tempTouchState.down = down;
1990 tempTouchState.deviceId = entry.deviceId;
1991 tempTouchState.source = entry.source;
1992 tempTouchState.displayId = displayId;
1993 isSplit = false;
1994 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1995 ALOGI("Dropping move event because a pointer for a different device is already active "
1996 "in display %" PRId32,
1997 displayId);
1998 // TODO: test multiple simultaneous input streams.
1999 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
2000 switchedDevice = false;
2001 wrongDevice = true;
2002 goto Failed;
2003 }
2004
2005 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2006 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2007
2008 int32_t x;
2009 int32_t y;
2010 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2011 // Always dispatch mouse events to cursor position.
2012 if (isFromMouse) {
2013 x = int32_t(entry.xCursorPosition);
2014 y = int32_t(entry.yCursorPosition);
2015 } else {
2016 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2017 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
2018 }
2019 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
2020 newTouchedWindowHandle =
2021 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
2022 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
2023
2024 // Figure out whether splitting will be allowed for this window.
2025 if (newTouchedWindowHandle != nullptr &&
2026 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2027 // New window supports splitting, but we should never split mouse events.
2028 isSplit = !isFromMouse;
2029 } else if (isSplit) {
2030 // New window does not support splitting but we have already split events.
2031 // Ignore the new window.
2032 newTouchedWindowHandle = nullptr;
2033 }
2034
2035 // Handle the case where we did not find a window.
2036 if (newTouchedWindowHandle == nullptr) {
2037 // Try to assign the pointer to the first foreground window we find, if there is one.
2038 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
2039 }
2040
2041 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
2042 ALOGI("Not sending touch event to %s because it is paused",
2043 newTouchedWindowHandle->getName().c_str());
2044 newTouchedWindowHandle = nullptr;
2045 }
2046
2047 // Ensure the window has a connection and the connection is responsive
2048 if (newTouchedWindowHandle != nullptr) {
2049 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
2050 if (!isResponsive) {
2051 ALOGW("%s will not receive the new gesture at %" PRIu64,
2052 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
2053 newTouchedWindowHandle = nullptr;
2054 }
2055 }
2056
2057 // Drop events that can't be trusted due to occlusion
2058 if (newTouchedWindowHandle != nullptr &&
2059 mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2060 TouchOcclusionInfo occlusionInfo =
2061 computeTouchOcclusionInfoLocked(newTouchedWindowHandle, x, y);
2062 if (!isTouchTrustedLocked(occlusionInfo)) {
2063 if (DEBUG_TOUCH_OCCLUSION) {
2064 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2065 for (const auto& log : occlusionInfo.debugInfo) {
2066 ALOGD("%s", log.c_str());
2067 }
2068 }
2069 onUntrustedTouchLocked(occlusionInfo.obscuringPackage);
2070 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2071 ALOGW("Dropping untrusted touch event due to %s/%d",
2072 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2073 newTouchedWindowHandle = nullptr;
2074 }
2075 }
2076 }
2077
2078 // Drop touch events if requested by input feature
2079 if (newTouchedWindowHandle != nullptr && shouldDropInput(entry, newTouchedWindowHandle)) {
2080 newTouchedWindowHandle = nullptr;
2081 }
2082
2083 const std::vector<TouchedMonitor> newGestureMonitors = isDown
2084 ? selectResponsiveMonitorsLocked(
2085 findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows))
2086 : tempTouchState.gestureMonitors;
2087
2088 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
2089 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
2090 "(%d, %d) in display %" PRId32 ".",
2091 x, y, displayId);
2092 injectionResult = InputEventInjectionResult::FAILED;
2093 goto Failed;
2094 }
2095
2096 if (newTouchedWindowHandle != nullptr) {
2097 // Set target flags.
2098 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
2099 if (isSplit) {
2100 targetFlags |= InputTarget::FLAG_SPLIT;
2101 }
2102 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2103 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2104 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2105 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2106 }
2107
2108 // Update hover state.
2109 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2110 newHoverWindowHandle = nullptr;
2111 } else if (isHoverAction) {
2112 newHoverWindowHandle = newTouchedWindowHandle;
2113 }
2114
2115 // Update the temporary touch state.
2116 BitSet32 pointerIds;
2117 if (isSplit) {
2118 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2119 pointerIds.markBit(pointerId);
2120 }
2121 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
2122 } else if (tempTouchState.windows.empty()) {
2123 // If no window is touched, set split to true. This will allow the next pointer down to
2124 // be delivered to a new window which supports split touch.
2125 tempTouchState.split = true;
2126 }
2127 if (isDown) {
2128 tempTouchState.addGestureMonitors(newGestureMonitors);
2129 }
2130 } else {
2131 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2132
2133 // If the pointer is not currently down, then ignore the event.
2134 if (!tempTouchState.down) {
2135 if (DEBUG_FOCUS) {
2136 ALOGD("Dropping event because the pointer is not down or we previously "
2137 "dropped the pointer down event in display %" PRId32,
2138 displayId);
2139 }
2140 injectionResult = InputEventInjectionResult::FAILED;
2141 goto Failed;
2142 }
2143
2144 addDragEventLocked(entry);
2145
2146 // Check whether touches should slip outside of the current foreground window.
2147 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
2148 tempTouchState.isSlippery()) {
2149 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2150 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2151
2152 sp<WindowInfoHandle> oldTouchedWindowHandle =
2153 tempTouchState.getFirstForegroundWindowHandle();
2154 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
2155
2156 // Drop touch events if requested by input feature
2157 if (newTouchedWindowHandle != nullptr &&
2158 shouldDropInput(entry, newTouchedWindowHandle)) {
2159 newTouchedWindowHandle = nullptr;
2160 }
2161
2162 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2163 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
2164 if (DEBUG_FOCUS) {
2165 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2166 oldTouchedWindowHandle->getName().c_str(),
2167 newTouchedWindowHandle->getName().c_str(), displayId);
2168 }
2169 // Make a slippery exit from the old window.
2170 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2171 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2172 BitSet32(0));
2173
2174 // Make a slippery entrance into the new window.
2175 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2176 isSplit = true;
2177 }
2178
2179 int32_t targetFlags =
2180 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
2181 if (isSplit) {
2182 targetFlags |= InputTarget::FLAG_SPLIT;
2183 }
2184 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2185 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2186 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2187 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2188 }
2189
2190 BitSet32 pointerIds;
2191 if (isSplit) {
2192 pointerIds.markBit(entry.pointerProperties[0].id);
2193 }
2194 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
2195 }
2196 }
2197 }
2198
2199 if (newHoverWindowHandle != mLastHoverWindowHandle) {
2200 // Let the previous window know that the hover sequence is over, unless we already did it
2201 // when dispatching it as is to newTouchedWindowHandle.
2202 if (mLastHoverWindowHandle != nullptr &&
2203 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2204 mLastHoverWindowHandle != newTouchedWindowHandle)) {
2205 #if DEBUG_HOVER
2206 ALOGD("Sending hover exit event to window %s.",
2207 mLastHoverWindowHandle->getName().c_str());
2208 #endif
2209 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2210 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
2211 }
2212
2213 // Let the new window know that the hover sequence is starting, unless we already did it
2214 // when dispatching it as is to newTouchedWindowHandle.
2215 if (newHoverWindowHandle != nullptr &&
2216 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2217 newHoverWindowHandle != newTouchedWindowHandle)) {
2218 #if DEBUG_HOVER
2219 ALOGD("Sending hover enter event to window %s.",
2220 newHoverWindowHandle->getName().c_str());
2221 #endif
2222 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2223 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2224 BitSet32(0));
2225 }
2226 }
2227
2228 // Check permission to inject into all touched foreground windows and ensure there
2229 // is at least one touched foreground window.
2230 {
2231 bool haveForegroundWindow = false;
2232 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
2233 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
2234 haveForegroundWindow = true;
2235 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
2236 injectionResult = InputEventInjectionResult::PERMISSION_DENIED;
2237 injectionPermission = INJECTION_PERMISSION_DENIED;
2238 goto Failed;
2239 }
2240 }
2241 }
2242 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
2243 if (!haveForegroundWindow && !hasGestureMonitor) {
2244 ALOGI("Dropping event because there is no touched foreground window in display "
2245 "%" PRId32 " or gesture monitor to receive it.",
2246 displayId);
2247 injectionResult = InputEventInjectionResult::FAILED;
2248 goto Failed;
2249 }
2250
2251 // Permission granted to injection into all touched foreground windows.
2252 injectionPermission = INJECTION_PERMISSION_GRANTED;
2253 }
2254
2255 // Check whether windows listening for outside touches are owned by the same UID. If it is
2256 // set the policy flag that we will not reveal coordinate information to this window.
2257 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2258 sp<WindowInfoHandle> foregroundWindowHandle =
2259 tempTouchState.getFirstForegroundWindowHandle();
2260 if (foregroundWindowHandle) {
2261 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
2262 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
2263 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2264 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2265 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2266 tempTouchState.addOrUpdateWindow(windowInfoHandle,
2267 InputTarget::FLAG_ZERO_COORDS,
2268 BitSet32(0));
2269 }
2270 }
2271 }
2272 }
2273 }
2274
2275 // If this is the first pointer going down and the touched window has a wallpaper
2276 // then also add the touched wallpaper windows so they are locked in for the duration
2277 // of the touch gesture.
2278 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2279 // engine only supports touch events. We would need to add a mechanism similar
2280 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2281 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2282 sp<WindowInfoHandle> foregroundWindowHandle =
2283 tempTouchState.getFirstForegroundWindowHandle();
2284 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
2285 const std::vector<sp<WindowInfoHandle>>& windowHandles =
2286 getWindowHandlesLocked(displayId);
2287 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2288 const WindowInfo* info = windowHandle->getInfo();
2289 if (info->displayId == displayId &&
2290 windowHandle->getInfo()->type == WindowInfo::Type::WALLPAPER) {
2291 tempTouchState
2292 .addOrUpdateWindow(windowHandle,
2293 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2294 InputTarget::
2295 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2296 InputTarget::FLAG_DISPATCH_AS_IS,
2297 BitSet32(0));
2298 }
2299 }
2300 }
2301 }
2302
2303 // Success! Output targets.
2304 injectionResult = InputEventInjectionResult::SUCCEEDED;
2305
2306 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
2307 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2308 touchedWindow.pointerIds, inputTargets);
2309 }
2310
2311 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
2312 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
2313 touchedMonitor.yOffset, inputTargets);
2314 }
2315
2316 // Drop the outside or hover touch windows since we will not care about them
2317 // in the next iteration.
2318 tempTouchState.filterNonAsIsTouchWindows();
2319
2320 Failed:
2321 // Check injection permission once and for all.
2322 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
2323 if (checkInjectionPermission(nullptr, entry.injectionState)) {
2324 injectionPermission = INJECTION_PERMISSION_GRANTED;
2325 } else {
2326 injectionPermission = INJECTION_PERMISSION_DENIED;
2327 }
2328 }
2329
2330 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
2331 return injectionResult;
2332 }
2333
2334 // Update final pieces of touch state if the injector had permission.
2335 if (!wrongDevice) {
2336 if (switchedDevice) {
2337 if (DEBUG_FOCUS) {
2338 ALOGD("Conflicting pointer actions: Switched to a different device.");
2339 }
2340 *outConflictingPointerActions = true;
2341 }
2342
2343 if (isHoverAction) {
2344 // Started hovering, therefore no longer down.
2345 if (oldState && oldState->down) {
2346 if (DEBUG_FOCUS) {
2347 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2348 "down.");
2349 }
2350 *outConflictingPointerActions = true;
2351 }
2352 tempTouchState.reset();
2353 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2354 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2355 tempTouchState.deviceId = entry.deviceId;
2356 tempTouchState.source = entry.source;
2357 tempTouchState.displayId = displayId;
2358 }
2359 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2360 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2361 // All pointers up or canceled.
2362 tempTouchState.reset();
2363 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2364 // First pointer went down.
2365 if (oldState && oldState->down) {
2366 if (DEBUG_FOCUS) {
2367 ALOGD("Conflicting pointer actions: Down received while already down.");
2368 }
2369 *outConflictingPointerActions = true;
2370 }
2371 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2372 // One pointer went up.
2373 if (isSplit) {
2374 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2375 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2376
2377 for (size_t i = 0; i < tempTouchState.windows.size();) {
2378 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2379 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2380 touchedWindow.pointerIds.clearBit(pointerId);
2381 if (touchedWindow.pointerIds.isEmpty()) {
2382 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2383 continue;
2384 }
2385 }
2386 i += 1;
2387 }
2388 }
2389 }
2390
2391 // Save changes unless the action was scroll in which case the temporary touch
2392 // state was only valid for this one action.
2393 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2394 if (tempTouchState.displayId >= 0) {
2395 mTouchStatesByDisplay[displayId] = tempTouchState;
2396 } else {
2397 mTouchStatesByDisplay.erase(displayId);
2398 }
2399 }
2400
2401 // Update hover state.
2402 mLastHoverWindowHandle = newHoverWindowHandle;
2403 }
2404
2405 return injectionResult;
2406 }
2407
finishDragAndDrop(int32_t displayId,float x,float y)2408 void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
2409 const sp<WindowInfoHandle> dropWindow =
2410 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/,
2411 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2412 true /*ignoreDragWindow*/);
2413 if (dropWindow) {
2414 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
2415 notifyDropWindowLocked(dropWindow->getToken(), local.x, local.y);
2416 } else {
2417 notifyDropWindowLocked(nullptr, 0, 0);
2418 }
2419 mDragState.reset();
2420 }
2421
addDragEventLocked(const MotionEntry & entry)2422 void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
2423 if (entry.pointerCount != 1 || !mDragState) {
2424 return;
2425 }
2426
2427 if (!mDragState->isStartDrag) {
2428 mDragState->isStartDrag = true;
2429 mDragState->isStylusButtonDownAtStart =
2430 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2431 }
2432
2433 int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2434 int32_t x = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2435 int32_t y = static_cast<int32_t>(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
2436 if (maskedAction == AMOTION_EVENT_ACTION_MOVE) {
2437 // Handle the special case : stylus button no longer pressed.
2438 bool isStylusButtonDown = (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2439 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2440 finishDragAndDrop(entry.displayId, x, y);
2441 return;
2442 }
2443
2444 const sp<WindowInfoHandle> hoverWindowHandle =
2445 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2446 false /*addOutsideTargets*/, false /*addPortalWindows*/,
2447 true /*ignoreDragWindow*/);
2448 // enqueue drag exit if needed.
2449 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2450 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2451 if (mDragState->dragHoverWindowHandle != nullptr) {
2452 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/,
2453 entry);
2454 }
2455 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2456 }
2457 // enqueue drag location if needed.
2458 if (hoverWindowHandle != nullptr) {
2459 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, entry);
2460 }
2461 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2462 finishDragAndDrop(entry.displayId, x, y);
2463 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2464 notifyDropWindowLocked(nullptr, 0, 0);
2465 mDragState.reset();
2466 }
2467 }
2468
addWindowTargetLocked(const sp<WindowInfoHandle> & windowHandle,int32_t targetFlags,BitSet32 pointerIds,std::vector<InputTarget> & inputTargets)2469 void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
2470 int32_t targetFlags, BitSet32 pointerIds,
2471 std::vector<InputTarget>& inputTargets) {
2472 std::vector<InputTarget>::iterator it =
2473 std::find_if(inputTargets.begin(), inputTargets.end(),
2474 [&windowHandle](const InputTarget& inputTarget) {
2475 return inputTarget.inputChannel->getConnectionToken() ==
2476 windowHandle->getToken();
2477 });
2478
2479 const WindowInfo* windowInfo = windowHandle->getInfo();
2480
2481 if (it == inputTargets.end()) {
2482 InputTarget inputTarget;
2483 std::shared_ptr<InputChannel> inputChannel =
2484 getInputChannelLocked(windowHandle->getToken());
2485 if (inputChannel == nullptr) {
2486 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2487 return;
2488 }
2489 inputTarget.inputChannel = inputChannel;
2490 inputTarget.flags = targetFlags;
2491 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2492 inputTarget.displayOrientation = windowInfo->displayOrientation;
2493 inputTarget.displaySize =
2494 int2(windowHandle->getInfo()->displayWidth, windowHandle->getInfo()->displayHeight);
2495 inputTargets.push_back(inputTarget);
2496 it = inputTargets.end() - 1;
2497 }
2498
2499 ALOG_ASSERT(it->flags == targetFlags);
2500 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2501
2502 it->addPointers(pointerIds, windowInfo->transform);
2503 }
2504
addGlobalMonitoringTargetsLocked(std::vector<InputTarget> & inputTargets,int32_t displayId,float xOffset,float yOffset)2505 void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
2506 int32_t displayId, float xOffset,
2507 float yOffset) {
2508 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2509 mGlobalMonitorsByDisplay.find(displayId);
2510
2511 if (it != mGlobalMonitorsByDisplay.end()) {
2512 const std::vector<Monitor>& monitors = it->second;
2513 for (const Monitor& monitor : monitors) {
2514 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
2515 }
2516 }
2517 }
2518
addMonitoringTargetLocked(const Monitor & monitor,float xOffset,float yOffset,std::vector<InputTarget> & inputTargets)2519 void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2520 float yOffset,
2521 std::vector<InputTarget>& inputTargets) {
2522 InputTarget target;
2523 target.inputChannel = monitor.inputChannel;
2524 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2525 ui::Transform t;
2526 t.set(xOffset, yOffset);
2527 target.setDefaultPointerTransform(t);
2528 inputTargets.push_back(target);
2529 }
2530
checkInjectionPermission(const sp<WindowInfoHandle> & windowHandle,const InjectionState * injectionState)2531 bool InputDispatcher::checkInjectionPermission(const sp<WindowInfoHandle>& windowHandle,
2532 const InjectionState* injectionState) {
2533 if (injectionState &&
2534 (windowHandle == nullptr ||
2535 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2536 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
2537 if (windowHandle != nullptr) {
2538 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
2539 "owned by uid %d",
2540 injectionState->injectorPid, injectionState->injectorUid,
2541 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
2542 } else {
2543 ALOGW("Permission denied: injecting event from pid %d uid %d",
2544 injectionState->injectorPid, injectionState->injectorUid);
2545 }
2546 return false;
2547 }
2548 return true;
2549 }
2550
2551 /**
2552 * Indicate whether one window handle should be considered as obscuring
2553 * another window handle. We only check a few preconditions. Actually
2554 * checking the bounds is left to the caller.
2555 */
canBeObscuredBy(const sp<WindowInfoHandle> & windowHandle,const sp<WindowInfoHandle> & otherHandle)2556 static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2557 const sp<WindowInfoHandle>& otherHandle) {
2558 // Compare by token so cloned layers aren't counted
2559 if (haveSameToken(windowHandle, otherHandle)) {
2560 return false;
2561 }
2562 auto info = windowHandle->getInfo();
2563 auto otherInfo = otherHandle->getInfo();
2564 if (!otherInfo->visible) {
2565 return false;
2566 } else if (otherInfo->alpha == 0 && otherInfo->flags.test(WindowInfo::Flag::NOT_TOUCHABLE)) {
2567 // Those act as if they were invisible, so we don't need to flag them.
2568 // We do want to potentially flag touchable windows even if they have 0
2569 // opacity, since they can consume touches and alter the effects of the
2570 // user interaction (eg. apps that rely on
2571 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2572 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2573 return false;
2574 } else if (info->ownerUid == otherInfo->ownerUid) {
2575 // If ownerUid is the same we don't generate occlusion events as there
2576 // is no security boundary within an uid.
2577 return false;
2578 } else if (otherInfo->trustedOverlay) {
2579 return false;
2580 } else if (otherInfo->displayId != info->displayId) {
2581 return false;
2582 }
2583 return true;
2584 }
2585
2586 /**
2587 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2588 * untrusted, one should check:
2589 *
2590 * 1. If result.hasBlockingOcclusion is true.
2591 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2592 * BLOCK_UNTRUSTED.
2593 *
2594 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2595 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2596 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2597 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2598 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2599 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2600 *
2601 * If neither of those is true, then it means the touch can be allowed.
2602 */
computeTouchOcclusionInfoLocked(const sp<WindowInfoHandle> & windowHandle,int32_t x,int32_t y) const2603 InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
2604 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2605 const WindowInfo* windowInfo = windowHandle->getInfo();
2606 int32_t displayId = windowInfo->displayId;
2607 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2608 TouchOcclusionInfo info;
2609 info.hasBlockingOcclusion = false;
2610 info.obscuringOpacity = 0;
2611 info.obscuringUid = -1;
2612 std::map<int32_t, float> opacityByUid;
2613 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
2614 if (windowHandle == otherHandle) {
2615 break; // All future windows are below us. Exit early.
2616 }
2617 const WindowInfo* otherInfo = otherHandle->getInfo();
2618 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2619 !haveSameApplicationToken(windowInfo, otherInfo)) {
2620 if (DEBUG_TOUCH_OCCLUSION) {
2621 info.debugInfo.push_back(
2622 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2623 }
2624 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2625 // we perform the checks below to see if the touch can be propagated or not based on the
2626 // window's touch occlusion mode
2627 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2628 info.hasBlockingOcclusion = true;
2629 info.obscuringUid = otherInfo->ownerUid;
2630 info.obscuringPackage = otherInfo->packageName;
2631 break;
2632 }
2633 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2634 uint32_t uid = otherInfo->ownerUid;
2635 float opacity =
2636 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2637 // Given windows A and B:
2638 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2639 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2640 opacityByUid[uid] = opacity;
2641 if (opacity > info.obscuringOpacity) {
2642 info.obscuringOpacity = opacity;
2643 info.obscuringUid = uid;
2644 info.obscuringPackage = otherInfo->packageName;
2645 }
2646 }
2647 }
2648 }
2649 if (DEBUG_TOUCH_OCCLUSION) {
2650 info.debugInfo.push_back(
2651 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2652 }
2653 return info;
2654 }
2655
dumpWindowForTouchOcclusion(const WindowInfo * info,bool isTouchedWindow) const2656 std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
2657 bool isTouchedWindow) const {
2658 return StringPrintf(INDENT2
2659 "* %stype=%s, package=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2660 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2661 "], touchableRegion=%s, window={%s}, flags={%s}, inputFeatures={%s}, "
2662 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
2663 (isTouchedWindow) ? "[TOUCHED] " : "",
2664 NamedEnum::string(info->type, "%" PRId32).c_str(),
2665 info->packageName.c_str(), info->ownerUid, info->id,
2666 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frameLeft,
2667 info->frameTop, info->frameRight, info->frameBottom,
2668 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
2669 info->flags.string().c_str(), info->inputFeatures.string().c_str(),
2670 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
2671 toString(info->applicationInfo.token).c_str());
2672 }
2673
isTouchTrustedLocked(const TouchOcclusionInfo & occlusionInfo) const2674 bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2675 if (occlusionInfo.hasBlockingOcclusion) {
2676 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2677 occlusionInfo.obscuringUid);
2678 return false;
2679 }
2680 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2681 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2682 "%.2f, maximum allowed = %.2f)",
2683 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2684 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2685 return false;
2686 }
2687 return true;
2688 }
2689
isWindowObscuredAtPointLocked(const sp<WindowInfoHandle> & windowHandle,int32_t x,int32_t y) const2690 bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
2691 int32_t x, int32_t y) const {
2692 int32_t displayId = windowHandle->getInfo()->displayId;
2693 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2694 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
2695 if (windowHandle == otherHandle) {
2696 break; // All future windows are below us. Exit early.
2697 }
2698 const WindowInfo* otherInfo = otherHandle->getInfo();
2699 if (canBeObscuredBy(windowHandle, otherHandle) &&
2700 otherInfo->frameContainsPoint(x, y)) {
2701 return true;
2702 }
2703 }
2704 return false;
2705 }
2706
isWindowObscuredLocked(const sp<WindowInfoHandle> & windowHandle) const2707 bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
2708 int32_t displayId = windowHandle->getInfo()->displayId;
2709 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2710 const WindowInfo* windowInfo = windowHandle->getInfo();
2711 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
2712 if (windowHandle == otherHandle) {
2713 break; // All future windows are below us. Exit early.
2714 }
2715 const WindowInfo* otherInfo = otherHandle->getInfo();
2716 if (canBeObscuredBy(windowHandle, otherHandle) &&
2717 otherInfo->overlaps(windowInfo)) {
2718 return true;
2719 }
2720 }
2721 return false;
2722 }
2723
getApplicationWindowLabel(const InputApplicationHandle * applicationHandle,const sp<WindowInfoHandle> & windowHandle)2724 std::string InputDispatcher::getApplicationWindowLabel(
2725 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
2726 if (applicationHandle != nullptr) {
2727 if (windowHandle != nullptr) {
2728 return applicationHandle->getName() + " - " + windowHandle->getName();
2729 } else {
2730 return applicationHandle->getName();
2731 }
2732 } else if (windowHandle != nullptr) {
2733 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
2734 } else {
2735 return "<unknown application or window>";
2736 }
2737 }
2738
pokeUserActivityLocked(const EventEntry & eventEntry)2739 void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
2740 if (eventEntry.type == EventEntry::Type::FOCUS ||
2741 eventEntry.type == EventEntry::Type::POINTER_CAPTURE_CHANGED ||
2742 eventEntry.type == EventEntry::Type::DRAG) {
2743 // Focus or pointer capture changed events are passed to apps, but do not represent user
2744 // activity.
2745 return;
2746 }
2747 int32_t displayId = getTargetDisplayId(eventEntry);
2748 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
2749 if (focusedWindowHandle != nullptr) {
2750 const WindowInfo* info = focusedWindowHandle->getInfo();
2751 if (info->inputFeatures.test(WindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
2752 #if DEBUG_DISPATCH_CYCLE
2753 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2754 #endif
2755 return;
2756 }
2757 }
2758
2759 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
2760 switch (eventEntry.type) {
2761 case EventEntry::Type::MOTION: {
2762 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2763 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2764 return;
2765 }
2766
2767 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
2768 eventType = USER_ACTIVITY_EVENT_TOUCH;
2769 }
2770 break;
2771 }
2772 case EventEntry::Type::KEY: {
2773 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2774 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
2775 return;
2776 }
2777 eventType = USER_ACTIVITY_EVENT_BUTTON;
2778 break;
2779 }
2780 case EventEntry::Type::FOCUS:
2781 case EventEntry::Type::CONFIGURATION_CHANGED:
2782 case EventEntry::Type::DEVICE_RESET:
2783 case EventEntry::Type::SENSOR:
2784 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
2785 case EventEntry::Type::DRAG: {
2786 LOG_ALWAYS_FATAL("%s events are not user activity",
2787 NamedEnum::string(eventEntry.type).c_str());
2788 break;
2789 }
2790 }
2791
2792 std::unique_ptr<CommandEntry> commandEntry =
2793 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
2794 commandEntry->eventTime = eventEntry.eventTime;
2795 commandEntry->userActivityEventType = eventType;
2796 commandEntry->displayId = displayId;
2797 postCommandLocked(std::move(commandEntry));
2798 }
2799
prepareDispatchCycleLocked(nsecs_t currentTime,const sp<Connection> & connection,std::shared_ptr<EventEntry> eventEntry,const InputTarget & inputTarget)2800 void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
2801 const sp<Connection>& connection,
2802 std::shared_ptr<EventEntry> eventEntry,
2803 const InputTarget& inputTarget) {
2804 if (ATRACE_ENABLED()) {
2805 std::string message =
2806 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
2807 connection->getInputChannelName().c_str(), eventEntry->id);
2808 ATRACE_NAME(message.c_str());
2809 }
2810 #if DEBUG_DISPATCH_CYCLE
2811 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2812 "globalScaleFactor=%f, pointerIds=0x%x %s",
2813 connection->getInputChannelName().c_str(), inputTarget.flags,
2814 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2815 inputTarget.getPointerInfoString().c_str());
2816 #endif
2817
2818 // Skip this event if the connection status is not normal.
2819 // We don't want to enqueue additional outbound events if the connection is broken.
2820 if (connection->status != Connection::STATUS_NORMAL) {
2821 #if DEBUG_DISPATCH_CYCLE
2822 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
2823 connection->getInputChannelName().c_str(), connection->getStatusLabel());
2824 #endif
2825 return;
2826 }
2827
2828 // Split a motion event if needed.
2829 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2830 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2831 "Entry type %s should not have FLAG_SPLIT",
2832 NamedEnum::string(eventEntry->type).c_str());
2833
2834 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
2835 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
2836 std::unique_ptr<MotionEntry> splitMotionEntry =
2837 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
2838 if (!splitMotionEntry) {
2839 return; // split event was dropped
2840 }
2841 if (DEBUG_FOCUS) {
2842 ALOGD("channel '%s' ~ Split motion event.",
2843 connection->getInputChannelName().c_str());
2844 logOutboundMotionDetails(" ", *splitMotionEntry);
2845 }
2846 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2847 inputTarget);
2848 return;
2849 }
2850 }
2851
2852 // Not splitting. Enqueue dispatch entries for the event as is.
2853 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2854 }
2855
enqueueDispatchEntriesLocked(nsecs_t currentTime,const sp<Connection> & connection,std::shared_ptr<EventEntry> eventEntry,const InputTarget & inputTarget)2856 void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
2857 const sp<Connection>& connection,
2858 std::shared_ptr<EventEntry> eventEntry,
2859 const InputTarget& inputTarget) {
2860 if (ATRACE_ENABLED()) {
2861 std::string message =
2862 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
2863 connection->getInputChannelName().c_str(), eventEntry->id);
2864 ATRACE_NAME(message.c_str());
2865 }
2866
2867 bool wasEmpty = connection->outboundQueue.empty();
2868
2869 // Enqueue dispatch entries for the requested modes.
2870 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2871 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
2872 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2873 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
2874 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2875 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
2876 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2877 InputTarget::FLAG_DISPATCH_AS_IS);
2878 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2879 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
2880 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
2881 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
2882
2883 // If the outbound queue was previously empty, start the dispatch cycle going.
2884 if (wasEmpty && !connection->outboundQueue.empty()) {
2885 startDispatchCycleLocked(currentTime, connection);
2886 }
2887 }
2888
enqueueDispatchEntryLocked(const sp<Connection> & connection,std::shared_ptr<EventEntry> eventEntry,const InputTarget & inputTarget,int32_t dispatchMode)2889 void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2890 std::shared_ptr<EventEntry> eventEntry,
2891 const InputTarget& inputTarget,
2892 int32_t dispatchMode) {
2893 if (ATRACE_ENABLED()) {
2894 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2895 connection->getInputChannelName().c_str(),
2896 dispatchModeToString(dispatchMode).c_str());
2897 ATRACE_NAME(message.c_str());
2898 }
2899 int32_t inputTargetFlags = inputTarget.flags;
2900 if (!(inputTargetFlags & dispatchMode)) {
2901 return;
2902 }
2903 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2904
2905 // This is a new event.
2906 // Enqueue a new dispatch entry onto the outbound queue for this connection.
2907 std::unique_ptr<DispatchEntry> dispatchEntry =
2908 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
2909
2910 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2911 // different EventEntry than what was passed in.
2912 EventEntry& newEntry = *(dispatchEntry->eventEntry);
2913 // Apply target flags and update the connection's input state.
2914 switch (newEntry.type) {
2915 case EventEntry::Type::KEY: {
2916 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
2917 dispatchEntry->resolvedEventId = keyEntry.id;
2918 dispatchEntry->resolvedAction = keyEntry.action;
2919 dispatchEntry->resolvedFlags = keyEntry.flags;
2920
2921 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2922 dispatchEntry->resolvedFlags)) {
2923 #if DEBUG_DISPATCH_CYCLE
2924 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2925 connection->getInputChannelName().c_str());
2926 #endif
2927 return; // skip the inconsistent event
2928 }
2929 break;
2930 }
2931
2932 case EventEntry::Type::MOTION: {
2933 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
2934 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2935 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2936 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2937 static_cast<int32_t>(IdGenerator::Source::OTHER);
2938 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
2939 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2940 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2941 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2942 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2943 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2944 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2945 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2946 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2947 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2948 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2949 } else {
2950 dispatchEntry->resolvedAction = motionEntry.action;
2951 dispatchEntry->resolvedEventId = motionEntry.id;
2952 }
2953 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
2954 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2955 motionEntry.displayId)) {
2956 #if DEBUG_DISPATCH_CYCLE
2957 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2958 "event",
2959 connection->getInputChannelName().c_str());
2960 #endif
2961 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
2962 // this is a one-to-one event conversion.
2963 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2964 }
2965
2966 dispatchEntry->resolvedFlags = motionEntry.flags;
2967 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2968 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2969 }
2970 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2971 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2972 }
2973
2974 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2975 dispatchEntry->resolvedFlags)) {
2976 #if DEBUG_DISPATCH_CYCLE
2977 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2978 "event",
2979 connection->getInputChannelName().c_str());
2980 #endif
2981 return; // skip the inconsistent event
2982 }
2983
2984 dispatchEntry->resolvedEventId =
2985 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2986 ? mIdGenerator.nextId()
2987 : motionEntry.id;
2988 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2989 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2990 ") to MotionEvent(id=0x%" PRIx32 ").",
2991 motionEntry.id, dispatchEntry->resolvedEventId);
2992 ATRACE_NAME(message.c_str());
2993 }
2994
2995 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
2996 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
2997 // Skip reporting pointer down outside focus to the policy.
2998 break;
2999 }
3000
3001 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
3002 inputTarget.inputChannel->getConnectionToken());
3003
3004 break;
3005 }
3006 case EventEntry::Type::FOCUS:
3007 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3008 case EventEntry::Type::DRAG: {
3009 break;
3010 }
3011 case EventEntry::Type::SENSOR: {
3012 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3013 break;
3014 }
3015 case EventEntry::Type::CONFIGURATION_CHANGED:
3016 case EventEntry::Type::DEVICE_RESET: {
3017 LOG_ALWAYS_FATAL("%s events should not go to apps",
3018 NamedEnum::string(newEntry.type).c_str());
3019 break;
3020 }
3021 }
3022
3023 // Remember that we are waiting for this dispatch to complete.
3024 if (dispatchEntry->hasForegroundTarget()) {
3025 incrementPendingForegroundDispatches(newEntry);
3026 }
3027
3028 // Enqueue the dispatch entry.
3029 connection->outboundQueue.push_back(dispatchEntry.release());
3030 traceOutboundQueueLength(*connection);
3031 }
3032
3033 /**
3034 * This function is purely for debugging. It helps us understand where the user interaction
3035 * was taking place. For example, if user is touching launcher, we will see a log that user
3036 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3037 * We will see both launcher and wallpaper in that list.
3038 * Once the interaction with a particular set of connections starts, no new logs will be printed
3039 * until the set of interacted connections changes.
3040 *
3041 * The following items are skipped, to reduce the logspam:
3042 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3043 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3044 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3045 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3046 * Both of those ACTION_UP events would not be logged
3047 */
updateInteractionTokensLocked(const EventEntry & entry,const std::vector<InputTarget> & targets)3048 void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3049 const std::vector<InputTarget>& targets) {
3050 // Skip ACTION_UP events, and all events other than keys and motions
3051 if (entry.type == EventEntry::Type::KEY) {
3052 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3053 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3054 return;
3055 }
3056 } else if (entry.type == EventEntry::Type::MOTION) {
3057 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3058 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3059 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3060 return;
3061 }
3062 } else {
3063 return; // Not a key or a motion
3064 }
3065
3066 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
3067 std::vector<sp<Connection>> newConnections;
3068 for (const InputTarget& target : targets) {
3069 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3070 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3071 continue; // Skip windows that receive ACTION_OUTSIDE
3072 }
3073
3074 sp<IBinder> token = target.inputChannel->getConnectionToken();
3075 sp<Connection> connection = getConnectionLocked(token);
3076 if (connection == nullptr) {
3077 continue;
3078 }
3079 newConnectionTokens.insert(std::move(token));
3080 newConnections.emplace_back(connection);
3081 }
3082 if (newConnectionTokens == mInteractionConnectionTokens) {
3083 return; // no change
3084 }
3085 mInteractionConnectionTokens = newConnectionTokens;
3086
3087 std::string targetList;
3088 for (const sp<Connection>& connection : newConnections) {
3089 targetList += connection->getWindowName() + ", ";
3090 }
3091 std::string message = "Interaction with: " + targetList;
3092 if (targetList.empty()) {
3093 message += "<none>";
3094 }
3095 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3096 }
3097
dispatchPointerDownOutsideFocus(uint32_t source,int32_t action,const sp<IBinder> & token)3098 void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
3099 const sp<IBinder>& token) {
3100 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
3101 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3102 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
3103 return;
3104 }
3105
3106 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
3107 if (focusedToken == token) {
3108 // ignore since token is focused
3109 return;
3110 }
3111
3112 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
3113 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
3114 commandEntry->newToken = token;
3115 postCommandLocked(std::move(commandEntry));
3116 }
3117
startDispatchCycleLocked(nsecs_t currentTime,const sp<Connection> & connection)3118 void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
3119 const sp<Connection>& connection) {
3120 if (ATRACE_ENABLED()) {
3121 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3122 connection->getInputChannelName().c_str());
3123 ATRACE_NAME(message.c_str());
3124 }
3125 #if DEBUG_DISPATCH_CYCLE
3126 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3127 #endif
3128
3129 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
3130 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
3131 dispatchEntry->deliveryTime = currentTime;
3132 const std::chrono::nanoseconds timeout =
3133 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
3134 dispatchEntry->timeoutTime = currentTime + timeout.count();
3135
3136 // Publish the event.
3137 status_t status;
3138 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3139 switch (eventEntry.type) {
3140 case EventEntry::Type::KEY: {
3141 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3142 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
3143
3144 // Publish the key event.
3145 status = connection->inputPublisher
3146 .publishKeyEvent(dispatchEntry->seq,
3147 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3148 keyEntry.source, keyEntry.displayId,
3149 std::move(hmac), dispatchEntry->resolvedAction,
3150 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3151 keyEntry.scanCode, keyEntry.metaState,
3152 keyEntry.repeatCount, keyEntry.downTime,
3153 keyEntry.eventTime);
3154 break;
3155 }
3156
3157 case EventEntry::Type::MOTION: {
3158 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3159
3160 PointerCoords scaledCoords[MAX_POINTERS];
3161 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3162
3163 // Set the X and Y offset and X and Y scale depending on the input source.
3164 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
3165 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3166 float globalScaleFactor = dispatchEntry->globalScaleFactor;
3167 if (globalScaleFactor != 1.0f) {
3168 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3169 scaledCoords[i] = motionEntry.pointerCoords[i];
3170 // Don't apply window scale here since we don't want scale to affect raw
3171 // coordinates. The scale will be sent back to the client and applied
3172 // later when requesting relative coordinates.
3173 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3174 1 /* windowYScale */);
3175 }
3176 usingCoords = scaledCoords;
3177 }
3178 } else {
3179 // We don't want the dispatch target to know.
3180 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
3181 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3182 scaledCoords[i].clear();
3183 }
3184 usingCoords = scaledCoords;
3185 }
3186 }
3187
3188 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
3189
3190 // Publish the motion event.
3191 status = connection->inputPublisher
3192 .publishMotionEvent(dispatchEntry->seq,
3193 dispatchEntry->resolvedEventId,
3194 motionEntry.deviceId, motionEntry.source,
3195 motionEntry.displayId, std::move(hmac),
3196 dispatchEntry->resolvedAction,
3197 motionEntry.actionButton,
3198 dispatchEntry->resolvedFlags,
3199 motionEntry.edgeFlags, motionEntry.metaState,
3200 motionEntry.buttonState,
3201 motionEntry.classification,
3202 dispatchEntry->transform,
3203 motionEntry.xPrecision, motionEntry.yPrecision,
3204 motionEntry.xCursorPosition,
3205 motionEntry.yCursorPosition,
3206 dispatchEntry->displayOrientation,
3207 dispatchEntry->displaySize.x,
3208 dispatchEntry->displaySize.y,
3209 motionEntry.downTime, motionEntry.eventTime,
3210 motionEntry.pointerCount,
3211 motionEntry.pointerProperties, usingCoords);
3212 break;
3213 }
3214
3215 case EventEntry::Type::FOCUS: {
3216 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
3217 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
3218 focusEntry.id,
3219 focusEntry.hasFocus,
3220 mInTouchMode);
3221 break;
3222 }
3223
3224 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3225 const auto& captureEntry =
3226 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3227 status = connection->inputPublisher
3228 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
3229 captureEntry.pointerCaptureRequest.enable);
3230 break;
3231 }
3232
3233 case EventEntry::Type::DRAG: {
3234 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3235 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3236 dragEntry.id, dragEntry.x,
3237 dragEntry.y,
3238 dragEntry.isExiting);
3239 break;
3240 }
3241
3242 case EventEntry::Type::CONFIGURATION_CHANGED:
3243 case EventEntry::Type::DEVICE_RESET:
3244 case EventEntry::Type::SENSOR: {
3245 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
3246 NamedEnum::string(eventEntry.type).c_str());
3247 return;
3248 }
3249 }
3250
3251 // Check the result.
3252 if (status) {
3253 if (status == WOULD_BLOCK) {
3254 if (connection->waitQueue.empty()) {
3255 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
3256 "This is unexpected because the wait queue is empty, so the pipe "
3257 "should be empty and we shouldn't have any problems writing an "
3258 "event to it, status=%s(%d)",
3259 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3260 status);
3261 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3262 } else {
3263 // Pipe is full and we are waiting for the app to finish process some events
3264 // before sending more events to it.
3265 #if DEBUG_DISPATCH_CYCLE
3266 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3267 "waiting for the application to catch up",
3268 connection->getInputChannelName().c_str());
3269 #endif
3270 }
3271 } else {
3272 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
3273 "status=%s(%d)",
3274 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3275 status);
3276 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3277 }
3278 return;
3279 }
3280
3281 // Re-enqueue the event on the wait queue.
3282 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3283 connection->outboundQueue.end(),
3284 dispatchEntry));
3285 traceOutboundQueueLength(*connection);
3286 connection->waitQueue.push_back(dispatchEntry);
3287 if (connection->responsive) {
3288 mAnrTracker.insert(dispatchEntry->timeoutTime,
3289 connection->inputChannel->getConnectionToken());
3290 }
3291 traceWaitQueueLength(*connection);
3292 }
3293 }
3294
sign(const VerifiedInputEvent & event) const3295 std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3296 size_t size;
3297 switch (event.type) {
3298 case VerifiedInputEvent::Type::KEY: {
3299 size = sizeof(VerifiedKeyEvent);
3300 break;
3301 }
3302 case VerifiedInputEvent::Type::MOTION: {
3303 size = sizeof(VerifiedMotionEvent);
3304 break;
3305 }
3306 }
3307 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3308 return mHmacKeyManager.sign(start, size);
3309 }
3310
getSignature(const MotionEntry & motionEntry,const DispatchEntry & dispatchEntry) const3311 const std::array<uint8_t, 32> InputDispatcher::getSignature(
3312 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
3313 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3314 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
3315 // Only sign events up and down events as the purely move events
3316 // are tied to their up/down counterparts so signing would be redundant.
3317 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
3318 verifiedEvent.actionMasked = actionMasked;
3319 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3320 return sign(verifiedEvent);
3321 }
3322 return INVALID_HMAC;
3323 }
3324
getSignature(const KeyEntry & keyEntry,const DispatchEntry & dispatchEntry) const3325 const std::array<uint8_t, 32> InputDispatcher::getSignature(
3326 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3327 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3328 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3329 verifiedEvent.action = dispatchEntry.resolvedAction;
3330 return sign(verifiedEvent);
3331 }
3332
finishDispatchCycleLocked(nsecs_t currentTime,const sp<Connection> & connection,uint32_t seq,bool handled,nsecs_t consumeTime)3333 void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
3334 const sp<Connection>& connection, uint32_t seq,
3335 bool handled, nsecs_t consumeTime) {
3336 #if DEBUG_DISPATCH_CYCLE
3337 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3338 connection->getInputChannelName().c_str(), seq, toString(handled));
3339 #endif
3340
3341 if (connection->status == Connection::STATUS_BROKEN ||
3342 connection->status == Connection::STATUS_ZOMBIE) {
3343 return;
3344 }
3345
3346 // Notify other system components and prepare to start the next dispatch cycle.
3347 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled, consumeTime);
3348 }
3349
abortBrokenDispatchCycleLocked(nsecs_t currentTime,const sp<Connection> & connection,bool notify)3350 void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
3351 const sp<Connection>& connection,
3352 bool notify) {
3353 #if DEBUG_DISPATCH_CYCLE
3354 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3355 connection->getInputChannelName().c_str(), toString(notify));
3356 #endif
3357
3358 // Clear the dispatch queues.
3359 drainDispatchQueue(connection->outboundQueue);
3360 traceOutboundQueueLength(*connection);
3361 drainDispatchQueue(connection->waitQueue);
3362 traceWaitQueueLength(*connection);
3363
3364 // The connection appears to be unrecoverably broken.
3365 // Ignore already broken or zombie connections.
3366 if (connection->status == Connection::STATUS_NORMAL) {
3367 connection->status = Connection::STATUS_BROKEN;
3368
3369 if (notify) {
3370 // Notify other system components.
3371 onDispatchCycleBrokenLocked(currentTime, connection);
3372 }
3373 }
3374 }
3375
drainDispatchQueue(std::deque<DispatchEntry * > & queue)3376 void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3377 while (!queue.empty()) {
3378 DispatchEntry* dispatchEntry = queue.front();
3379 queue.pop_front();
3380 releaseDispatchEntry(dispatchEntry);
3381 }
3382 }
3383
releaseDispatchEntry(DispatchEntry * dispatchEntry)3384 void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
3385 if (dispatchEntry->hasForegroundTarget()) {
3386 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
3387 }
3388 delete dispatchEntry;
3389 }
3390
handleReceiveCallback(int events,sp<IBinder> connectionToken)3391 int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3392 std::scoped_lock _l(mLock);
3393 sp<Connection> connection = getConnectionLocked(connectionToken);
3394 if (connection == nullptr) {
3395 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3396 connectionToken.get(), events);
3397 return 0; // remove the callback
3398 }
3399
3400 bool notify;
3401 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3402 if (!(events & ALOOPER_EVENT_INPUT)) {
3403 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3404 "events=0x%x",
3405 connection->getInputChannelName().c_str(), events);
3406 return 1;
3407 }
3408
3409 nsecs_t currentTime = now();
3410 bool gotOne = false;
3411 status_t status = OK;
3412 for (;;) {
3413 Result<InputPublisher::ConsumerResponse> result =
3414 connection->inputPublisher.receiveConsumerResponse();
3415 if (!result.ok()) {
3416 status = result.error().code();
3417 break;
3418 }
3419
3420 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3421 const InputPublisher::Finished& finish =
3422 std::get<InputPublisher::Finished>(*result);
3423 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3424 finish.consumeTime);
3425 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
3426 if (shouldReportMetricsForConnection(*connection)) {
3427 const InputPublisher::Timeline& timeline =
3428 std::get<InputPublisher::Timeline>(*result);
3429 mLatencyTracker
3430 .trackGraphicsLatency(timeline.inputEventId,
3431 connection->inputChannel->getConnectionToken(),
3432 std::move(timeline.graphicsTimeline));
3433 }
3434 }
3435 gotOne = true;
3436 }
3437 if (gotOne) {
3438 runCommandsLockedInterruptible();
3439 if (status == WOULD_BLOCK) {
3440 return 1;
3441 }
3442 }
3443
3444 notify = status != DEAD_OBJECT || !connection->monitor;
3445 if (notify) {
3446 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3447 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3448 status);
3449 }
3450 } else {
3451 // Monitor channels are never explicitly unregistered.
3452 // We do it automatically when the remote endpoint is closed so don't warn about them.
3453 const bool stillHaveWindowHandle =
3454 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3455 notify = !connection->monitor && stillHaveWindowHandle;
3456 if (notify) {
3457 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3458 connection->getInputChannelName().c_str(), events);
3459 }
3460 }
3461
3462 // Remove the channel.
3463 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3464 return 0; // remove the callback
3465 }
3466
synthesizeCancelationEventsForAllConnectionsLocked(const CancelationOptions & options)3467 void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
3468 const CancelationOptions& options) {
3469 for (const auto& [token, connection] : mConnectionsByToken) {
3470 synthesizeCancelationEventsForConnectionLocked(connection, options);
3471 }
3472 }
3473
synthesizeCancelationEventsForMonitorsLocked(const CancelationOptions & options)3474 void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3475 const CancelationOptions& options) {
3476 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
3477 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
3478 }
3479
synthesizeCancelationEventsForMonitorsLocked(const CancelationOptions & options,std::unordered_map<int32_t,std::vector<Monitor>> & monitorsByDisplay)3480 void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
3481 const CancelationOptions& options,
3482 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3483 for (const auto& it : monitorsByDisplay) {
3484 const std::vector<Monitor>& monitors = it.second;
3485 for (const Monitor& monitor : monitors) {
3486 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
3487 }
3488 }
3489 }
3490
synthesizeCancelationEventsForInputChannelLocked(const std::shared_ptr<InputChannel> & channel,const CancelationOptions & options)3491 void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
3492 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
3493 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
3494 if (connection == nullptr) {
3495 return;
3496 }
3497
3498 synthesizeCancelationEventsForConnectionLocked(connection, options);
3499 }
3500
synthesizeCancelationEventsForConnectionLocked(const sp<Connection> & connection,const CancelationOptions & options)3501 void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3502 const sp<Connection>& connection, const CancelationOptions& options) {
3503 if (connection->status == Connection::STATUS_BROKEN) {
3504 return;
3505 }
3506
3507 nsecs_t currentTime = now();
3508
3509 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
3510 connection->inputState.synthesizeCancelationEvents(currentTime, options);
3511
3512 if (cancelationEvents.empty()) {
3513 return;
3514 }
3515 #if DEBUG_OUTBOUND_EVENT_DETAILS
3516 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3517 "with reality: %s, mode=%d.",
3518 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3519 options.mode);
3520 #endif
3521
3522 InputTarget target;
3523 sp<WindowInfoHandle> windowHandle =
3524 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3525 if (windowHandle != nullptr) {
3526 const WindowInfo* windowInfo = windowHandle->getInfo();
3527 target.setDefaultPointerTransform(windowInfo->transform);
3528 target.globalScaleFactor = windowInfo->globalScaleFactor;
3529 }
3530 target.inputChannel = connection->inputChannel;
3531 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3532
3533 for (size_t i = 0; i < cancelationEvents.size(); i++) {
3534 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
3535 switch (cancelationEventEntry->type) {
3536 case EventEntry::Type::KEY: {
3537 logOutboundKeyDetails("cancel - ",
3538 static_cast<const KeyEntry&>(*cancelationEventEntry));
3539 break;
3540 }
3541 case EventEntry::Type::MOTION: {
3542 logOutboundMotionDetails("cancel - ",
3543 static_cast<const MotionEntry&>(*cancelationEventEntry));
3544 break;
3545 }
3546 case EventEntry::Type::FOCUS:
3547 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3548 case EventEntry::Type::DRAG: {
3549 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
3550 NamedEnum::string(cancelationEventEntry->type).c_str());
3551 break;
3552 }
3553 case EventEntry::Type::CONFIGURATION_CHANGED:
3554 case EventEntry::Type::DEVICE_RESET:
3555 case EventEntry::Type::SENSOR: {
3556 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3557 NamedEnum::string(cancelationEventEntry->type).c_str());
3558 break;
3559 }
3560 }
3561
3562 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3563 InputTarget::FLAG_DISPATCH_AS_IS);
3564 }
3565
3566 startDispatchCycleLocked(currentTime, connection);
3567 }
3568
synthesizePointerDownEventsForConnectionLocked(const sp<Connection> & connection)3569 void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3570 const sp<Connection>& connection) {
3571 if (connection->status == Connection::STATUS_BROKEN) {
3572 return;
3573 }
3574
3575 nsecs_t currentTime = now();
3576
3577 std::vector<std::unique_ptr<EventEntry>> downEvents =
3578 connection->inputState.synthesizePointerDownEvents(currentTime);
3579
3580 if (downEvents.empty()) {
3581 return;
3582 }
3583
3584 #if DEBUG_OUTBOUND_EVENT_DETAILS
3585 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3586 connection->getInputChannelName().c_str(), downEvents.size());
3587 #endif
3588
3589 InputTarget target;
3590 sp<WindowInfoHandle> windowHandle =
3591 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3592 if (windowHandle != nullptr) {
3593 const WindowInfo* windowInfo = windowHandle->getInfo();
3594 target.setDefaultPointerTransform(windowInfo->transform);
3595 target.globalScaleFactor = windowInfo->globalScaleFactor;
3596 }
3597 target.inputChannel = connection->inputChannel;
3598 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3599
3600 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
3601 switch (downEventEntry->type) {
3602 case EventEntry::Type::MOTION: {
3603 logOutboundMotionDetails("down - ",
3604 static_cast<const MotionEntry&>(*downEventEntry));
3605 break;
3606 }
3607
3608 case EventEntry::Type::KEY:
3609 case EventEntry::Type::FOCUS:
3610 case EventEntry::Type::CONFIGURATION_CHANGED:
3611 case EventEntry::Type::DEVICE_RESET:
3612 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3613 case EventEntry::Type::SENSOR:
3614 case EventEntry::Type::DRAG: {
3615 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
3616 NamedEnum::string(downEventEntry->type).c_str());
3617 break;
3618 }
3619 }
3620
3621 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3622 InputTarget::FLAG_DISPATCH_AS_IS);
3623 }
3624
3625 startDispatchCycleLocked(currentTime, connection);
3626 }
3627
splitMotionEvent(const MotionEntry & originalMotionEntry,BitSet32 pointerIds)3628 std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3629 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
3630 ALOG_ASSERT(pointerIds.value != 0);
3631
3632 uint32_t splitPointerIndexMap[MAX_POINTERS];
3633 PointerProperties splitPointerProperties[MAX_POINTERS];
3634 PointerCoords splitPointerCoords[MAX_POINTERS];
3635
3636 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
3637 uint32_t splitPointerCount = 0;
3638
3639 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
3640 originalPointerIndex++) {
3641 const PointerProperties& pointerProperties =
3642 originalMotionEntry.pointerProperties[originalPointerIndex];
3643 uint32_t pointerId = uint32_t(pointerProperties.id);
3644 if (pointerIds.hasBit(pointerId)) {
3645 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3646 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3647 splitPointerCoords[splitPointerCount].copyFrom(
3648 originalMotionEntry.pointerCoords[originalPointerIndex]);
3649 splitPointerCount += 1;
3650 }
3651 }
3652
3653 if (splitPointerCount != pointerIds.count()) {
3654 // This is bad. We are missing some of the pointers that we expected to deliver.
3655 // Most likely this indicates that we received an ACTION_MOVE events that has
3656 // different pointer ids than we expected based on the previous ACTION_DOWN
3657 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3658 // in this way.
3659 ALOGW("Dropping split motion event because the pointer count is %d but "
3660 "we expected there to be %d pointers. This probably means we received "
3661 "a broken sequence of pointer ids from the input device.",
3662 splitPointerCount, pointerIds.count());
3663 return nullptr;
3664 }
3665
3666 int32_t action = originalMotionEntry.action;
3667 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
3668 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3669 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
3670 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3671 const PointerProperties& pointerProperties =
3672 originalMotionEntry.pointerProperties[originalPointerIndex];
3673 uint32_t pointerId = uint32_t(pointerProperties.id);
3674 if (pointerIds.hasBit(pointerId)) {
3675 if (pointerIds.count() == 1) {
3676 // The first/last pointer went down/up.
3677 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
3678 ? AMOTION_EVENT_ACTION_DOWN
3679 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3680 ? AMOTION_EVENT_ACTION_CANCEL
3681 : AMOTION_EVENT_ACTION_UP;
3682 } else {
3683 // A secondary pointer went down/up.
3684 uint32_t splitPointerIndex = 0;
3685 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3686 splitPointerIndex += 1;
3687 }
3688 action = maskedAction |
3689 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3690 }
3691 } else {
3692 // An unrelated pointer changed.
3693 action = AMOTION_EVENT_ACTION_MOVE;
3694 }
3695 }
3696
3697 int32_t newId = mIdGenerator.nextId();
3698 if (ATRACE_ENABLED()) {
3699 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3700 ") to MotionEvent(id=0x%" PRIx32 ").",
3701 originalMotionEntry.id, newId);
3702 ATRACE_NAME(message.c_str());
3703 }
3704 std::unique_ptr<MotionEntry> splitMotionEntry =
3705 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3706 originalMotionEntry.deviceId, originalMotionEntry.source,
3707 originalMotionEntry.displayId,
3708 originalMotionEntry.policyFlags, action,
3709 originalMotionEntry.actionButton,
3710 originalMotionEntry.flags, originalMotionEntry.metaState,
3711 originalMotionEntry.buttonState,
3712 originalMotionEntry.classification,
3713 originalMotionEntry.edgeFlags,
3714 originalMotionEntry.xPrecision,
3715 originalMotionEntry.yPrecision,
3716 originalMotionEntry.xCursorPosition,
3717 originalMotionEntry.yCursorPosition,
3718 originalMotionEntry.downTime, splitPointerCount,
3719 splitPointerProperties, splitPointerCoords, 0, 0);
3720
3721 if (originalMotionEntry.injectionState) {
3722 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
3723 splitMotionEntry->injectionState->refCount += 1;
3724 }
3725
3726 return splitMotionEntry;
3727 }
3728
notifyConfigurationChanged(const NotifyConfigurationChangedArgs * args)3729 void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3730 #if DEBUG_INBOUND_EVENT_DETAILS
3731 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3732 #endif
3733
3734 bool needWake;
3735 { // acquire lock
3736 std::scoped_lock _l(mLock);
3737
3738 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3739 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3740 needWake = enqueueInboundEventLocked(std::move(newEntry));
3741 } // release lock
3742
3743 if (needWake) {
3744 mLooper->wake();
3745 }
3746 }
3747
3748 /**
3749 * If one of the meta shortcuts is detected, process them here:
3750 * Meta + Backspace -> generate BACK
3751 * Meta + Enter -> generate HOME
3752 * This will potentially overwrite keyCode and metaState.
3753 */
accelerateMetaShortcuts(const int32_t deviceId,const int32_t action,int32_t & keyCode,int32_t & metaState)3754 void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
3755 int32_t& keyCode, int32_t& metaState) {
3756 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3757 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3758 if (keyCode == AKEYCODE_DEL) {
3759 newKeyCode = AKEYCODE_BACK;
3760 } else if (keyCode == AKEYCODE_ENTER) {
3761 newKeyCode = AKEYCODE_HOME;
3762 }
3763 if (newKeyCode != AKEYCODE_UNKNOWN) {
3764 std::scoped_lock _l(mLock);
3765 struct KeyReplacement replacement = {keyCode, deviceId};
3766 mReplacedKeys[replacement] = newKeyCode;
3767 keyCode = newKeyCode;
3768 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3769 }
3770 } else if (action == AKEY_EVENT_ACTION_UP) {
3771 // In order to maintain a consistent stream of up and down events, check to see if the key
3772 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3773 // even if the modifier was released between the down and the up events.
3774 std::scoped_lock _l(mLock);
3775 struct KeyReplacement replacement = {keyCode, deviceId};
3776 auto replacementIt = mReplacedKeys.find(replacement);
3777 if (replacementIt != mReplacedKeys.end()) {
3778 keyCode = replacementIt->second;
3779 mReplacedKeys.erase(replacementIt);
3780 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3781 }
3782 }
3783 }
3784
notifyKey(const NotifyKeyArgs * args)3785 void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3786 #if DEBUG_INBOUND_EVENT_DETAILS
3787 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3788 "policyFlags=0x%x, action=0x%x, "
3789 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3790 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3791 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3792 args->downTime);
3793 #endif
3794 if (!validateKeyEvent(args->action)) {
3795 return;
3796 }
3797
3798 uint32_t policyFlags = args->policyFlags;
3799 int32_t flags = args->flags;
3800 int32_t metaState = args->metaState;
3801 // InputDispatcher tracks and generates key repeats on behalf of
3802 // whatever notifies it, so repeatCount should always be set to 0
3803 constexpr int32_t repeatCount = 0;
3804 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3805 policyFlags |= POLICY_FLAG_VIRTUAL;
3806 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3807 }
3808 if (policyFlags & POLICY_FLAG_FUNCTION) {
3809 metaState |= AMETA_FUNCTION_ON;
3810 }
3811
3812 policyFlags |= POLICY_FLAG_TRUSTED;
3813
3814 int32_t keyCode = args->keyCode;
3815 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
3816
3817 KeyEvent event;
3818 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3819 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3820 args->downTime, args->eventTime);
3821
3822 android::base::Timer t;
3823 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
3824 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3825 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3826 std::to_string(t.duration().count()).c_str());
3827 }
3828
3829 bool needWake;
3830 { // acquire lock
3831 mLock.lock();
3832
3833 if (shouldSendKeyToInputFilterLocked(args)) {
3834 mLock.unlock();
3835
3836 policyFlags |= POLICY_FLAG_FILTERED;
3837 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3838 return; // event was consumed by the filter
3839 }
3840
3841 mLock.lock();
3842 }
3843
3844 std::unique_ptr<KeyEntry> newEntry =
3845 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3846 args->displayId, policyFlags, args->action, flags,
3847 keyCode, args->scanCode, metaState, repeatCount,
3848 args->downTime);
3849
3850 needWake = enqueueInboundEventLocked(std::move(newEntry));
3851 mLock.unlock();
3852 } // release lock
3853
3854 if (needWake) {
3855 mLooper->wake();
3856 }
3857 }
3858
shouldSendKeyToInputFilterLocked(const NotifyKeyArgs * args)3859 bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3860 return mInputFilterEnabled;
3861 }
3862
notifyMotion(const NotifyMotionArgs * args)3863 void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3864 #if DEBUG_INBOUND_EVENT_DETAILS
3865 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3866 "displayId=%" PRId32 ", policyFlags=0x%x, "
3867 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3868 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3869 "yCursorPosition=%f, downTime=%" PRId64,
3870 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3871 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3872 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3873 args->xCursorPosition, args->yCursorPosition, args->downTime);
3874 for (uint32_t i = 0; i < args->pointerCount; i++) {
3875 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3876 "x=%f, y=%f, pressure=%f, size=%f, "
3877 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3878 "orientation=%f",
3879 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3880 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3881 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3882 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3883 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3884 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3885 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3886 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3887 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3888 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
3889 }
3890 #endif
3891 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3892 args->pointerProperties)) {
3893 return;
3894 }
3895
3896 uint32_t policyFlags = args->policyFlags;
3897 policyFlags |= POLICY_FLAG_TRUSTED;
3898
3899 android::base::Timer t;
3900 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
3901 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3902 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3903 std::to_string(t.duration().count()).c_str());
3904 }
3905
3906 bool needWake;
3907 { // acquire lock
3908 mLock.lock();
3909
3910 if (shouldSendMotionToInputFilterLocked(args)) {
3911 mLock.unlock();
3912
3913 MotionEvent event;
3914 ui::Transform transform;
3915 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3916 args->action, args->actionButton, args->flags, args->edgeFlags,
3917 args->metaState, args->buttonState, args->classification, transform,
3918 args->xPrecision, args->yPrecision, args->xCursorPosition,
3919 args->yCursorPosition, ui::Transform::ROT_0, INVALID_DISPLAY_SIZE,
3920 INVALID_DISPLAY_SIZE, args->downTime, args->eventTime,
3921 args->pointerCount, args->pointerProperties, args->pointerCoords);
3922
3923 policyFlags |= POLICY_FLAG_FILTERED;
3924 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3925 return; // event was consumed by the filter
3926 }
3927
3928 mLock.lock();
3929 }
3930
3931 // Just enqueue a new motion event.
3932 std::unique_ptr<MotionEntry> newEntry =
3933 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
3934 args->source, args->displayId, policyFlags,
3935 args->action, args->actionButton, args->flags,
3936 args->metaState, args->buttonState,
3937 args->classification, args->edgeFlags,
3938 args->xPrecision, args->yPrecision,
3939 args->xCursorPosition, args->yCursorPosition,
3940 args->downTime, args->pointerCount,
3941 args->pointerProperties, args->pointerCoords, 0, 0);
3942
3943 needWake = enqueueInboundEventLocked(std::move(newEntry));
3944 mLock.unlock();
3945 } // release lock
3946
3947 if (needWake) {
3948 mLooper->wake();
3949 }
3950 }
3951
notifySensor(const NotifySensorArgs * args)3952 void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
3953 #if DEBUG_INBOUND_EVENT_DETAILS
3954 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3955 " sensorType=%s",
3956 args->id, args->eventTime, args->deviceId, args->source,
3957 NamedEnum::string(args->sensorType).c_str());
3958 #endif
3959
3960 bool needWake;
3961 { // acquire lock
3962 mLock.lock();
3963
3964 // Just enqueue a new sensor event.
3965 std::unique_ptr<SensorEntry> newEntry =
3966 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
3967 args->source, 0 /* policyFlags*/, args->hwTimestamp,
3968 args->sensorType, args->accuracy,
3969 args->accuracyChanged, args->values);
3970
3971 needWake = enqueueInboundEventLocked(std::move(newEntry));
3972 mLock.unlock();
3973 } // release lock
3974
3975 if (needWake) {
3976 mLooper->wake();
3977 }
3978 }
3979
notifyVibratorState(const NotifyVibratorStateArgs * args)3980 void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
3981 #if DEBUG_INBOUND_EVENT_DETAILS
3982 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
3983 args->deviceId, args->isOn);
3984 #endif
3985 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
3986 }
3987
shouldSendMotionToInputFilterLocked(const NotifyMotionArgs * args)3988 bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
3989 return mInputFilterEnabled;
3990 }
3991
notifySwitch(const NotifySwitchArgs * args)3992 void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3993 #if DEBUG_INBOUND_EVENT_DETAILS
3994 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
3995 "switchMask=0x%08x",
3996 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
3997 #endif
3998
3999 uint32_t policyFlags = args->policyFlags;
4000 policyFlags |= POLICY_FLAG_TRUSTED;
4001 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
4002 }
4003
notifyDeviceReset(const NotifyDeviceResetArgs * args)4004 void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
4005 #if DEBUG_INBOUND_EVENT_DETAILS
4006 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4007 args->deviceId);
4008 #endif
4009
4010 bool needWake;
4011 { // acquire lock
4012 std::scoped_lock _l(mLock);
4013
4014 std::unique_ptr<DeviceResetEntry> newEntry =
4015 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4016 needWake = enqueueInboundEventLocked(std::move(newEntry));
4017 } // release lock
4018
4019 if (needWake) {
4020 mLooper->wake();
4021 }
4022 }
4023
notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs * args)4024 void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
4025 #if DEBUG_INBOUND_EVENT_DETAILS
4026 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
4027 args->request.enable ? "true" : "false");
4028 #endif
4029
4030 bool needWake;
4031 { // acquire lock
4032 std::scoped_lock _l(mLock);
4033 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
4034 args->request);
4035 needWake = enqueueInboundEventLocked(std::move(entry));
4036 } // release lock
4037
4038 if (needWake) {
4039 mLooper->wake();
4040 }
4041 }
4042
injectInputEvent(const InputEvent * event,int32_t injectorPid,int32_t injectorUid,InputEventInjectionSync syncMode,std::chrono::milliseconds timeout,uint32_t policyFlags)4043 InputEventInjectionResult InputDispatcher::injectInputEvent(
4044 const InputEvent* event, int32_t injectorPid, int32_t injectorUid,
4045 InputEventInjectionSync syncMode, std::chrono::milliseconds timeout, uint32_t policyFlags) {
4046 #if DEBUG_INBOUND_EVENT_DETAILS
4047 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
4048 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
4049 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
4050 #endif
4051 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
4052
4053 policyFlags |= POLICY_FLAG_INJECTED;
4054 if (hasInjectionPermission(injectorPid, injectorUid)) {
4055 policyFlags |= POLICY_FLAG_TRUSTED;
4056 }
4057
4058 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
4059 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4060 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4061 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4062 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4063 // from events that originate from actual hardware.
4064 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
4065 if (policyFlags & POLICY_FLAG_FILTERED) {
4066 resolvedDeviceId = event->getDeviceId();
4067 }
4068
4069 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
4070 switch (event->getType()) {
4071 case AINPUT_EVENT_TYPE_KEY: {
4072 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4073 int32_t action = incomingKey.getAction();
4074 if (!validateKeyEvent(action)) {
4075 return InputEventInjectionResult::FAILED;
4076 }
4077
4078 int32_t flags = incomingKey.getFlags();
4079 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4080 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4081 }
4082 int32_t keyCode = incomingKey.getKeyCode();
4083 int32_t metaState = incomingKey.getMetaState();
4084 accelerateMetaShortcuts(resolvedDeviceId, action,
4085 /*byref*/ keyCode, /*byref*/ metaState);
4086 KeyEvent keyEvent;
4087 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
4088 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4089 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4090 incomingKey.getDownTime(), incomingKey.getEventTime());
4091
4092 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4093 policyFlags |= POLICY_FLAG_VIRTUAL;
4094 }
4095
4096 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4097 android::base::Timer t;
4098 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4099 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4100 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4101 std::to_string(t.duration().count()).c_str());
4102 }
4103 }
4104
4105 mLock.lock();
4106 std::unique_ptr<KeyEntry> injectedEntry =
4107 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
4108 resolvedDeviceId, incomingKey.getSource(),
4109 incomingKey.getDisplayId(), policyFlags, action,
4110 flags, keyCode, incomingKey.getScanCode(), metaState,
4111 incomingKey.getRepeatCount(),
4112 incomingKey.getDownTime());
4113 injectedEntries.push(std::move(injectedEntry));
4114 break;
4115 }
4116
4117 case AINPUT_EVENT_TYPE_MOTION: {
4118 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
4119 int32_t action = motionEvent.getAction();
4120 size_t pointerCount = motionEvent.getPointerCount();
4121 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
4122 int32_t actionButton = motionEvent.getActionButton();
4123 int32_t flags = motionEvent.getFlags();
4124 int32_t displayId = motionEvent.getDisplayId();
4125 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
4126 return InputEventInjectionResult::FAILED;
4127 }
4128
4129 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4130 nsecs_t eventTime = motionEvent.getEventTime();
4131 android::base::Timer t;
4132 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4133 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4134 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4135 std::to_string(t.duration().count()).c_str());
4136 }
4137 }
4138
4139 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4140 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4141 }
4142
4143 mLock.lock();
4144 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4145 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
4146 std::unique_ptr<MotionEntry> injectedEntry =
4147 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4148 resolvedDeviceId, motionEvent.getSource(),
4149 motionEvent.getDisplayId(), policyFlags, action,
4150 actionButton, flags, motionEvent.getMetaState(),
4151 motionEvent.getButtonState(),
4152 motionEvent.getClassification(),
4153 motionEvent.getEdgeFlags(),
4154 motionEvent.getXPrecision(),
4155 motionEvent.getYPrecision(),
4156 motionEvent.getRawXCursorPosition(),
4157 motionEvent.getRawYCursorPosition(),
4158 motionEvent.getDownTime(), uint32_t(pointerCount),
4159 pointerProperties, samplePointerCoords,
4160 motionEvent.getXOffset(),
4161 motionEvent.getYOffset());
4162 injectedEntries.push(std::move(injectedEntry));
4163 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
4164 sampleEventTimes += 1;
4165 samplePointerCoords += pointerCount;
4166 std::unique_ptr<MotionEntry> nextInjectedEntry =
4167 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4168 resolvedDeviceId, motionEvent.getSource(),
4169 motionEvent.getDisplayId(), policyFlags,
4170 action, actionButton, flags,
4171 motionEvent.getMetaState(),
4172 motionEvent.getButtonState(),
4173 motionEvent.getClassification(),
4174 motionEvent.getEdgeFlags(),
4175 motionEvent.getXPrecision(),
4176 motionEvent.getYPrecision(),
4177 motionEvent.getRawXCursorPosition(),
4178 motionEvent.getRawYCursorPosition(),
4179 motionEvent.getDownTime(),
4180 uint32_t(pointerCount), pointerProperties,
4181 samplePointerCoords, motionEvent.getXOffset(),
4182 motionEvent.getYOffset());
4183 injectedEntries.push(std::move(nextInjectedEntry));
4184 }
4185 break;
4186 }
4187
4188 default:
4189 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
4190 return InputEventInjectionResult::FAILED;
4191 }
4192
4193 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
4194 if (syncMode == InputEventInjectionSync::NONE) {
4195 injectionState->injectionIsAsync = true;
4196 }
4197
4198 injectionState->refCount += 1;
4199 injectedEntries.back()->injectionState = injectionState;
4200
4201 bool needWake = false;
4202 while (!injectedEntries.empty()) {
4203 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
4204 injectedEntries.pop();
4205 }
4206
4207 mLock.unlock();
4208
4209 if (needWake) {
4210 mLooper->wake();
4211 }
4212
4213 InputEventInjectionResult injectionResult;
4214 { // acquire lock
4215 std::unique_lock _l(mLock);
4216
4217 if (syncMode == InputEventInjectionSync::NONE) {
4218 injectionResult = InputEventInjectionResult::SUCCEEDED;
4219 } else {
4220 for (;;) {
4221 injectionResult = injectionState->injectionResult;
4222 if (injectionResult != InputEventInjectionResult::PENDING) {
4223 break;
4224 }
4225
4226 nsecs_t remainingTimeout = endTime - now();
4227 if (remainingTimeout <= 0) {
4228 #if DEBUG_INJECTION
4229 ALOGD("injectInputEvent - Timed out waiting for injection result "
4230 "to become available.");
4231 #endif
4232 injectionResult = InputEventInjectionResult::TIMED_OUT;
4233 break;
4234 }
4235
4236 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
4237 }
4238
4239 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4240 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
4241 while (injectionState->pendingForegroundDispatches != 0) {
4242 #if DEBUG_INJECTION
4243 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4244 injectionState->pendingForegroundDispatches);
4245 #endif
4246 nsecs_t remainingTimeout = endTime - now();
4247 if (remainingTimeout <= 0) {
4248 #if DEBUG_INJECTION
4249 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4250 "dispatches to finish.");
4251 #endif
4252 injectionResult = InputEventInjectionResult::TIMED_OUT;
4253 break;
4254 }
4255
4256 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
4257 }
4258 }
4259 }
4260
4261 injectionState->release();
4262 } // release lock
4263
4264 #if DEBUG_INJECTION
4265 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
4266 injectionResult, injectorPid, injectorUid);
4267 #endif
4268
4269 return injectionResult;
4270 }
4271
verifyInputEvent(const InputEvent & event)4272 std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
4273 std::array<uint8_t, 32> calculatedHmac;
4274 std::unique_ptr<VerifiedInputEvent> result;
4275 switch (event.getType()) {
4276 case AINPUT_EVENT_TYPE_KEY: {
4277 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4278 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4279 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
4280 calculatedHmac = sign(verifiedKeyEvent);
4281 break;
4282 }
4283 case AINPUT_EVENT_TYPE_MOTION: {
4284 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4285 VerifiedMotionEvent verifiedMotionEvent =
4286 verifiedMotionEventFromMotionEvent(motionEvent);
4287 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
4288 calculatedHmac = sign(verifiedMotionEvent);
4289 break;
4290 }
4291 default: {
4292 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4293 return nullptr;
4294 }
4295 }
4296 if (calculatedHmac == INVALID_HMAC) {
4297 return nullptr;
4298 }
4299 if (calculatedHmac != event.getHmac()) {
4300 return nullptr;
4301 }
4302 return result;
4303 }
4304
hasInjectionPermission(int32_t injectorPid,int32_t injectorUid)4305 bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
4306 return injectorUid == 0 ||
4307 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
4308 }
4309
setInjectionResult(EventEntry & entry,InputEventInjectionResult injectionResult)4310 void InputDispatcher::setInjectionResult(EventEntry& entry,
4311 InputEventInjectionResult injectionResult) {
4312 InjectionState* injectionState = entry.injectionState;
4313 if (injectionState) {
4314 #if DEBUG_INJECTION
4315 ALOGD("Setting input event injection result to %d. "
4316 "injectorPid=%d, injectorUid=%d",
4317 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
4318 #endif
4319
4320 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
4321 // Log the outcome since the injector did not wait for the injection result.
4322 switch (injectionResult) {
4323 case InputEventInjectionResult::SUCCEEDED:
4324 ALOGV("Asynchronous input event injection succeeded.");
4325 break;
4326 case InputEventInjectionResult::FAILED:
4327 ALOGW("Asynchronous input event injection failed.");
4328 break;
4329 case InputEventInjectionResult::PERMISSION_DENIED:
4330 ALOGW("Asynchronous input event injection permission denied.");
4331 break;
4332 case InputEventInjectionResult::TIMED_OUT:
4333 ALOGW("Asynchronous input event injection timed out.");
4334 break;
4335 case InputEventInjectionResult::PENDING:
4336 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4337 break;
4338 }
4339 }
4340
4341 injectionState->injectionResult = injectionResult;
4342 mInjectionResultAvailable.notify_all();
4343 }
4344 }
4345
incrementPendingForegroundDispatches(EventEntry & entry)4346 void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4347 InjectionState* injectionState = entry.injectionState;
4348 if (injectionState) {
4349 injectionState->pendingForegroundDispatches += 1;
4350 }
4351 }
4352
decrementPendingForegroundDispatches(EventEntry & entry)4353 void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4354 InjectionState* injectionState = entry.injectionState;
4355 if (injectionState) {
4356 injectionState->pendingForegroundDispatches -= 1;
4357
4358 if (injectionState->pendingForegroundDispatches == 0) {
4359 mInjectionSyncFinished.notify_all();
4360 }
4361 }
4362 }
4363
getWindowHandlesLocked(int32_t displayId) const4364 const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
4365 int32_t displayId) const {
4366 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
4367 auto it = mWindowHandlesByDisplay.find(displayId);
4368 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
4369 }
4370
getWindowHandleLocked(const sp<IBinder> & windowHandleToken) const4371 sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4372 const sp<IBinder>& windowHandleToken) const {
4373 if (windowHandleToken == nullptr) {
4374 return nullptr;
4375 }
4376
4377 for (auto& it : mWindowHandlesByDisplay) {
4378 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4379 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
4380 if (windowHandle->getToken() == windowHandleToken) {
4381 return windowHandle;
4382 }
4383 }
4384 }
4385 return nullptr;
4386 }
4387
getWindowHandleLocked(const sp<IBinder> & windowHandleToken,int displayId) const4388 sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4389 int displayId) const {
4390 if (windowHandleToken == nullptr) {
4391 return nullptr;
4392 }
4393
4394 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
4395 if (windowHandle->getToken() == windowHandleToken) {
4396 return windowHandle;
4397 }
4398 }
4399 return nullptr;
4400 }
4401
getWindowHandleLocked(const sp<WindowInfoHandle> & windowHandle) const4402 sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4403 const sp<WindowInfoHandle>& windowHandle) const {
4404 for (auto& it : mWindowHandlesByDisplay) {
4405 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4406 for (const sp<WindowInfoHandle>& handle : windowHandles) {
4407 if (handle->getId() == windowHandle->getId() &&
4408 handle->getToken() == windowHandle->getToken()) {
4409 if (windowHandle->getInfo()->displayId != it.first) {
4410 ALOGE("Found window %s in display %" PRId32
4411 ", but it should belong to display %" PRId32,
4412 windowHandle->getName().c_str(), it.first,
4413 windowHandle->getInfo()->displayId);
4414 }
4415 return handle;
4416 }
4417 }
4418 }
4419 return nullptr;
4420 }
4421
getFocusedWindowHandleLocked(int displayId) const4422 sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
4423 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4424 return getWindowHandleLocked(focusedToken, displayId);
4425 }
4426
hasResponsiveConnectionLocked(WindowInfoHandle & windowHandle) const4427 bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
4428 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4429 const bool noInputChannel =
4430 windowHandle.getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4431 if (connection != nullptr && noInputChannel) {
4432 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4433 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4434 return false;
4435 }
4436
4437 if (connection == nullptr) {
4438 if (!noInputChannel) {
4439 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4440 }
4441 return false;
4442 }
4443 if (!connection->responsive) {
4444 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4445 return false;
4446 }
4447 return true;
4448 }
4449
getInputChannelLocked(const sp<IBinder> & token) const4450 std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4451 const sp<IBinder>& token) const {
4452 auto connectionIt = mConnectionsByToken.find(token);
4453 if (connectionIt == mConnectionsByToken.end()) {
4454 return nullptr;
4455 }
4456 return connectionIt->second->inputChannel;
4457 }
4458
updateWindowHandlesForDisplayLocked(const std::vector<sp<WindowInfoHandle>> & windowInfoHandles,int32_t displayId)4459 void InputDispatcher::updateWindowHandlesForDisplayLocked(
4460 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4461 if (windowInfoHandles.empty()) {
4462 // Remove all handles on a display if there are no windows left.
4463 mWindowHandlesByDisplay.erase(displayId);
4464 return;
4465 }
4466
4467 // Since we compare the pointer of input window handles across window updates, we need
4468 // to make sure the handle object for the same window stays unchanged across updates.
4469 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4470 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4471 for (const sp<WindowInfoHandle>& handle : oldHandles) {
4472 oldHandlesById[handle->getId()] = handle;
4473 }
4474
4475 std::vector<sp<WindowInfoHandle>> newHandles;
4476 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
4477 const WindowInfo* info = handle->getInfo();
4478 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
4479 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
4480 const bool noInputChannel =
4481 info->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4482 const bool canReceiveInput = !info->flags.test(WindowInfo::Flag::NOT_TOUCHABLE) ||
4483 !info->flags.test(WindowInfo::Flag::NOT_FOCUSABLE);
4484 if (canReceiveInput && !noInputChannel) {
4485 ALOGV("Window handle %s has no registered input channel",
4486 handle->getName().c_str());
4487 continue;
4488 }
4489 }
4490
4491 if (info->displayId != displayId) {
4492 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4493 handle->getName().c_str(), displayId, info->displayId);
4494 continue;
4495 }
4496
4497 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4498 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
4499 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
4500 oldHandle->updateFrom(handle);
4501 newHandles.push_back(oldHandle);
4502 } else {
4503 newHandles.push_back(handle);
4504 }
4505 }
4506
4507 // Insert or replace
4508 mWindowHandlesByDisplay[displayId] = newHandles;
4509 }
4510
setInputWindows(const std::unordered_map<int32_t,std::vector<sp<WindowInfoHandle>>> & handlesPerDisplay)4511 void InputDispatcher::setInputWindows(
4512 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
4513 { // acquire lock
4514 std::scoped_lock _l(mLock);
4515 for (const auto& [displayId, handles] : handlesPerDisplay) {
4516 setInputWindowsLocked(handles, displayId);
4517 }
4518 }
4519 // Wake up poll loop since it may need to make new input dispatching choices.
4520 mLooper->wake();
4521 }
4522
4523 /**
4524 * Called from InputManagerService, update window handle list by displayId that can receive input.
4525 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4526 * If set an empty list, remove all handles from the specific display.
4527 * For focused handle, check if need to change and send a cancel event to previous one.
4528 * For removed handle, check if need to send a cancel event if already in touch.
4529 */
setInputWindowsLocked(const std::vector<sp<WindowInfoHandle>> & windowInfoHandles,int32_t displayId)4530 void InputDispatcher::setInputWindowsLocked(
4531 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4532 if (DEBUG_FOCUS) {
4533 std::string windowList;
4534 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
4535 windowList += iwh->getName() + " ";
4536 }
4537 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4538 }
4539
4540 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
4541 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
4542 const bool noInputWindow =
4543 window->getInfo()->inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL);
4544 if (noInputWindow && window->getToken() != nullptr) {
4545 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4546 window->getName().c_str());
4547 window->releaseChannel();
4548 }
4549 }
4550
4551 // Copy old handles for release if they are no longer present.
4552 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
4553
4554 // Save the old windows' orientation by ID before it gets updated.
4555 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
4556 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
4557 oldWindowOrientations.emplace(handle->getId(),
4558 handle->getInfo()->transform.getOrientation());
4559 }
4560
4561 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
4562
4563 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
4564 if (mLastHoverWindowHandle &&
4565 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4566 windowHandles.end()) {
4567 mLastHoverWindowHandle = nullptr;
4568 }
4569
4570 std::optional<FocusResolver::FocusChanges> changes =
4571 mFocusResolver.setInputWindows(displayId, windowHandles);
4572 if (changes) {
4573 onFocusChangedLocked(*changes);
4574 }
4575
4576 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4577 mTouchStatesByDisplay.find(displayId);
4578 if (stateIt != mTouchStatesByDisplay.end()) {
4579 TouchState& state = stateIt->second;
4580 for (size_t i = 0; i < state.windows.size();) {
4581 TouchedWindow& touchedWindow = state.windows[i];
4582 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
4583 if (DEBUG_FOCUS) {
4584 ALOGD("Touched window was removed: %s in display %" PRId32,
4585 touchedWindow.windowHandle->getName().c_str(), displayId);
4586 }
4587 std::shared_ptr<InputChannel> touchedInputChannel =
4588 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4589 if (touchedInputChannel != nullptr) {
4590 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4591 "touched window was removed");
4592 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
4593 }
4594 state.windows.erase(state.windows.begin() + i);
4595 } else {
4596 ++i;
4597 }
4598 }
4599
4600 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
4601 // could just clear the state here.
4602 if (mDragState &&
4603 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
4604 windowHandles.end()) {
4605 mDragState.reset();
4606 }
4607 }
4608
4609 if (isPerWindowInputRotationEnabled()) {
4610 // Determine if the orientation of any of the input windows have changed, and cancel all
4611 // pointer events if necessary.
4612 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4613 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4614 if (newWindowHandle != nullptr &&
4615 newWindowHandle->getInfo()->transform.getOrientation() !=
4616 oldWindowOrientations[oldWindowHandle->getId()]) {
4617 std::shared_ptr<InputChannel> inputChannel =
4618 getInputChannelLocked(newWindowHandle->getToken());
4619 if (inputChannel != nullptr) {
4620 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4621 "touched window's orientation changed");
4622 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4623 }
4624 }
4625 }
4626 }
4627
4628 // Release information for windows that are no longer present.
4629 // This ensures that unused input channels are released promptly.
4630 // Otherwise, they might stick around until the window handle is destroyed
4631 // which might not happen until the next GC.
4632 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4633 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
4634 if (DEBUG_FOCUS) {
4635 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
4636 }
4637 oldWindowHandle->releaseChannel();
4638 // To avoid making too many calls into the compat framework, only
4639 // check for window flags when windows are going away.
4640 // TODO(b/157929241) : delete this. This is only needed temporarily
4641 // in order to gather some data about the flag usage
4642 if (oldWindowHandle->getInfo()->flags.test(WindowInfo::Flag::SLIPPERY)) {
4643 ALOGW("%s has FLAG_SLIPPERY. Please report this in b/157929241",
4644 oldWindowHandle->getName().c_str());
4645 if (mCompatService != nullptr) {
4646 mCompatService->reportChangeByUid(IInputConstants::BLOCK_FLAG_SLIPPERY,
4647 oldWindowHandle->getInfo()->ownerUid);
4648 }
4649 }
4650 }
4651 }
4652 }
4653
setFocusedApplication(int32_t displayId,const std::shared_ptr<InputApplicationHandle> & inputApplicationHandle)4654 void InputDispatcher::setFocusedApplication(
4655 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4656 if (DEBUG_FOCUS) {
4657 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4658 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4659 }
4660 { // acquire lock
4661 std::scoped_lock _l(mLock);
4662 setFocusedApplicationLocked(displayId, inputApplicationHandle);
4663 } // release lock
4664
4665 // Wake up poll loop since it may need to make new input dispatching choices.
4666 mLooper->wake();
4667 }
4668
setFocusedApplicationLocked(int32_t displayId,const std::shared_ptr<InputApplicationHandle> & inputApplicationHandle)4669 void InputDispatcher::setFocusedApplicationLocked(
4670 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4671 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4672 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4673
4674 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4675 return; // This application is already focused. No need to wake up or change anything.
4676 }
4677
4678 // Set the new application handle.
4679 if (inputApplicationHandle != nullptr) {
4680 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4681 } else {
4682 mFocusedApplicationHandlesByDisplay.erase(displayId);
4683 }
4684
4685 // No matter what the old focused application was, stop waiting on it because it is
4686 // no longer focused.
4687 resetNoFocusedWindowTimeoutLocked();
4688 }
4689
4690 /**
4691 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4692 * the display not specified.
4693 *
4694 * We track any unreleased events for each window. If a window loses the ability to receive the
4695 * released event, we will send a cancel event to it. So when the focused display is changed, we
4696 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4697 * display. The display-specified events won't be affected.
4698 */
setFocusedDisplay(int32_t displayId)4699 void InputDispatcher::setFocusedDisplay(int32_t displayId) {
4700 if (DEBUG_FOCUS) {
4701 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4702 }
4703 { // acquire lock
4704 std::scoped_lock _l(mLock);
4705
4706 if (mFocusedDisplayId != displayId) {
4707 sp<IBinder> oldFocusedWindowToken =
4708 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
4709 if (oldFocusedWindowToken != nullptr) {
4710 std::shared_ptr<InputChannel> inputChannel =
4711 getInputChannelLocked(oldFocusedWindowToken);
4712 if (inputChannel != nullptr) {
4713 CancelationOptions
4714 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4715 "The display which contains this window no longer has focus.");
4716 options.displayId = ADISPLAY_ID_NONE;
4717 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4718 }
4719 }
4720 mFocusedDisplayId = displayId;
4721
4722 // Find new focused window and validate
4723 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
4724 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
4725
4726 if (newFocusedWindowToken == nullptr) {
4727 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
4728 if (mFocusResolver.hasFocusedWindowTokens()) {
4729 ALOGE("But another display has a focused window\n%s",
4730 mFocusResolver.dumpFocusedWindows().c_str());
4731 }
4732 }
4733 }
4734
4735 if (DEBUG_FOCUS) {
4736 logDispatchStateLocked();
4737 }
4738 } // release lock
4739
4740 // Wake up poll loop since it may need to make new input dispatching choices.
4741 mLooper->wake();
4742 }
4743
setInputDispatchMode(bool enabled,bool frozen)4744 void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
4745 if (DEBUG_FOCUS) {
4746 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4747 }
4748
4749 bool changed;
4750 { // acquire lock
4751 std::scoped_lock _l(mLock);
4752
4753 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4754 if (mDispatchFrozen && !frozen) {
4755 resetNoFocusedWindowTimeoutLocked();
4756 }
4757
4758 if (mDispatchEnabled && !enabled) {
4759 resetAndDropEverythingLocked("dispatcher is being disabled");
4760 }
4761
4762 mDispatchEnabled = enabled;
4763 mDispatchFrozen = frozen;
4764 changed = true;
4765 } else {
4766 changed = false;
4767 }
4768
4769 if (DEBUG_FOCUS) {
4770 logDispatchStateLocked();
4771 }
4772 } // release lock
4773
4774 if (changed) {
4775 // Wake up poll loop since it may need to make new input dispatching choices.
4776 mLooper->wake();
4777 }
4778 }
4779
setInputFilterEnabled(bool enabled)4780 void InputDispatcher::setInputFilterEnabled(bool enabled) {
4781 if (DEBUG_FOCUS) {
4782 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4783 }
4784
4785 { // acquire lock
4786 std::scoped_lock _l(mLock);
4787
4788 if (mInputFilterEnabled == enabled) {
4789 return;
4790 }
4791
4792 mInputFilterEnabled = enabled;
4793 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4794 } // release lock
4795
4796 // Wake up poll loop since there might be work to do to drop everything.
4797 mLooper->wake();
4798 }
4799
setInTouchMode(bool inTouchMode)4800 void InputDispatcher::setInTouchMode(bool inTouchMode) {
4801 std::scoped_lock lock(mLock);
4802 mInTouchMode = inTouchMode;
4803 }
4804
setMaximumObscuringOpacityForTouch(float opacity)4805 void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
4806 if (opacity < 0 || opacity > 1) {
4807 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
4808 return;
4809 }
4810
4811 std::scoped_lock lock(mLock);
4812 mMaximumObscuringOpacityForTouch = opacity;
4813 }
4814
setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode)4815 void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
4816 std::scoped_lock lock(mLock);
4817 mBlockUntrustedTouchesMode = mode;
4818 }
4819
findTouchStateAndWindowLocked(const sp<IBinder> & token)4820 std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
4821 const sp<IBinder>& token) {
4822 for (auto& [displayId, state] : mTouchStatesByDisplay) {
4823 for (TouchedWindow& w : state.windows) {
4824 if (w.windowHandle->getToken() == token) {
4825 return std::make_pair(&state, &w);
4826 }
4827 }
4828 }
4829 return std::make_pair(nullptr, nullptr);
4830 }
4831
transferTouchFocus(const sp<IBinder> & fromToken,const sp<IBinder> & toToken,bool isDragDrop)4832 bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
4833 bool isDragDrop) {
4834 if (fromToken == toToken) {
4835 if (DEBUG_FOCUS) {
4836 ALOGD("Trivial transfer to same window.");
4837 }
4838 return true;
4839 }
4840
4841 { // acquire lock
4842 std::scoped_lock _l(mLock);
4843
4844 // Find the target touch state and touched window by fromToken.
4845 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
4846 if (state == nullptr || touchedWindow == nullptr) {
4847 ALOGD("Focus transfer failed because from window is not being touched.");
4848 return false;
4849 }
4850
4851 const int32_t displayId = state->displayId;
4852 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
4853 if (toWindowHandle == nullptr) {
4854 ALOGW("Cannot transfer focus because to window not found.");
4855 return false;
4856 }
4857
4858 if (DEBUG_FOCUS) {
4859 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4860 touchedWindow->windowHandle->getName().c_str(),
4861 toWindowHandle->getName().c_str());
4862 }
4863
4864 // Erase old window.
4865 int32_t oldTargetFlags = touchedWindow->targetFlags;
4866 BitSet32 pointerIds = touchedWindow->pointerIds;
4867 state->removeWindowByToken(fromToken);
4868
4869 // Add new window.
4870 int32_t newTargetFlags = oldTargetFlags &
4871 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4872 InputTarget::FLAG_DISPATCH_AS_IS);
4873 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
4874
4875 // Store the dragging window.
4876 if (isDragDrop) {
4877 mDragState = std::make_unique<DragState>(toWindowHandle);
4878 }
4879
4880 // Synthesize cancel for old window and down for new window.
4881 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4882 sp<Connection> toConnection = getConnectionLocked(toToken);
4883 if (fromConnection != nullptr && toConnection != nullptr) {
4884 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
4885 CancelationOptions
4886 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4887 "transferring touch focus from this window to another window");
4888 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
4889 synthesizePointerDownEventsForConnectionLocked(toConnection);
4890 }
4891
4892 if (DEBUG_FOCUS) {
4893 logDispatchStateLocked();
4894 }
4895 } // release lock
4896
4897 // Wake up poll loop since it may need to make new input dispatching choices.
4898 mLooper->wake();
4899 return true;
4900 }
4901
4902 // Binder call
transferTouch(const sp<IBinder> & destChannelToken)4903 bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken) {
4904 sp<IBinder> fromToken;
4905 { // acquire lock
4906 std::scoped_lock _l(mLock);
4907
4908 auto it = std::find_if(mTouchStatesByDisplay.begin(), mTouchStatesByDisplay.end(),
4909 [](const auto& pair) { return pair.second.windows.size() == 1; });
4910 if (it == mTouchStatesByDisplay.end()) {
4911 ALOGW("Cannot transfer touch state because there is no exact window being touched");
4912 return false;
4913 }
4914 const int32_t displayId = it->first;
4915 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
4916 if (toWindowHandle == nullptr) {
4917 ALOGW("Could not find window associated with token=%p", destChannelToken.get());
4918 return false;
4919 }
4920
4921 TouchState& state = it->second;
4922 const TouchedWindow& touchedWindow = state.windows[0];
4923 fromToken = touchedWindow.windowHandle->getToken();
4924 } // release lock
4925
4926 return transferTouchFocus(fromToken, destChannelToken);
4927 }
4928
resetAndDropEverythingLocked(const char * reason)4929 void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
4930 if (DEBUG_FOCUS) {
4931 ALOGD("Resetting and dropping all events (%s).", reason);
4932 }
4933
4934 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4935 synthesizeCancelationEventsForAllConnectionsLocked(options);
4936
4937 resetKeyRepeatLocked();
4938 releasePendingEventLocked();
4939 drainInboundQueueLocked();
4940 resetNoFocusedWindowTimeoutLocked();
4941
4942 mAnrTracker.clear();
4943 mTouchStatesByDisplay.clear();
4944 mLastHoverWindowHandle.clear();
4945 mReplacedKeys.clear();
4946 }
4947
logDispatchStateLocked()4948 void InputDispatcher::logDispatchStateLocked() {
4949 std::string dump;
4950 dumpDispatchStateLocked(dump);
4951
4952 std::istringstream stream(dump);
4953 std::string line;
4954
4955 while (std::getline(stream, line, '\n')) {
4956 ALOGD("%s", line.c_str());
4957 }
4958 }
4959
dumpPointerCaptureStateLocked()4960 std::string InputDispatcher::dumpPointerCaptureStateLocked() {
4961 std::string dump;
4962
4963 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
4964 toString(mCurrentPointerCaptureRequest.enable));
4965
4966 std::string windowName = "None";
4967 if (mWindowTokenWithPointerCapture) {
4968 const sp<WindowInfoHandle> captureWindowHandle =
4969 getWindowHandleLocked(mWindowTokenWithPointerCapture);
4970 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
4971 : "token has capture without window";
4972 }
4973 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
4974
4975 return dump;
4976 }
4977
dumpDispatchStateLocked(std::string & dump)4978 void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
4979 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4980 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4981 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
4982 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
4983
4984 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4985 dump += StringPrintf(INDENT "FocusedApplications:\n");
4986 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4987 const int32_t displayId = it.first;
4988 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
4989 const std::chrono::duration timeout =
4990 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
4991 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4992 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
4993 displayId, applicationHandle->getName().c_str(), millis(timeout));
4994 }
4995 } else {
4996 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
4997 }
4998
4999 dump += mFocusResolver.dump();
5000 dump += dumpPointerCaptureStateLocked();
5001
5002 if (!mTouchStatesByDisplay.empty()) {
5003 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
5004 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5005 const TouchState& state = pair.second;
5006 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
5007 state.displayId, toString(state.down), toString(state.split),
5008 state.deviceId, state.source);
5009 if (!state.windows.empty()) {
5010 dump += INDENT3 "Windows:\n";
5011 for (size_t i = 0; i < state.windows.size(); i++) {
5012 const TouchedWindow& touchedWindow = state.windows[i];
5013 dump += StringPrintf(INDENT4
5014 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5015 i, touchedWindow.windowHandle->getName().c_str(),
5016 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
5017 }
5018 } else {
5019 dump += INDENT3 "Windows: <none>\n";
5020 }
5021 if (!state.portalWindows.empty()) {
5022 dump += INDENT3 "Portal windows:\n";
5023 for (size_t i = 0; i < state.portalWindows.size(); i++) {
5024 const sp<WindowInfoHandle> portalWindowHandle = state.portalWindows[i];
5025 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
5026 portalWindowHandle->getName().c_str());
5027 }
5028 }
5029 }
5030 } else {
5031 dump += INDENT "TouchStates: <no displays touched>\n";
5032 }
5033
5034 if (mDragState) {
5035 dump += StringPrintf(INDENT "DragState:\n");
5036 mDragState->dump(dump, INDENT2);
5037 }
5038
5039 if (!mWindowHandlesByDisplay.empty()) {
5040 for (auto& it : mWindowHandlesByDisplay) {
5041 const std::vector<sp<WindowInfoHandle>> windowHandles = it.second;
5042 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
5043 if (!windowHandles.empty()) {
5044 dump += INDENT2 "Windows:\n";
5045 for (size_t i = 0; i < windowHandles.size(); i++) {
5046 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5047 const WindowInfo* windowInfo = windowHandle->getInfo();
5048
5049 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
5050 "portalToDisplayId=%d, paused=%s, focusable=%s, "
5051 "hasWallpaper=%s, visible=%s, alpha=%.2f, "
5052 "flags=%s, type=%s, "
5053 "frame=[%d,%d][%d,%d], globalScale=%f, "
5054 "applicationInfo.name=%s, "
5055 "applicationInfo.token=%s, "
5056 "touchableRegion=",
5057 i, windowInfo->name.c_str(), windowInfo->id,
5058 windowInfo->displayId, windowInfo->portalToDisplayId,
5059 toString(windowInfo->paused),
5060 toString(windowInfo->focusable),
5061 toString(windowInfo->hasWallpaper),
5062 toString(windowInfo->visible), windowInfo->alpha,
5063 windowInfo->flags.string().c_str(),
5064 NamedEnum::string(windowInfo->type).c_str(),
5065 windowInfo->frameLeft, windowInfo->frameTop,
5066 windowInfo->frameRight, windowInfo->frameBottom,
5067 windowInfo->globalScaleFactor,
5068 windowInfo->applicationInfo.name.c_str(),
5069 toString(windowInfo->applicationInfo.token).c_str());
5070 dump += dumpRegion(windowInfo->touchableRegion);
5071 dump += StringPrintf(", inputFeatures=%s",
5072 windowInfo->inputFeatures.string().c_str());
5073 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
5074 "ms, trustedOverlay=%s, hasToken=%s, "
5075 "touchOcclusionMode=%s, displayOrientation=%d\n",
5076 windowInfo->ownerPid, windowInfo->ownerUid,
5077 millis(windowInfo->dispatchingTimeout),
5078 toString(windowInfo->trustedOverlay),
5079 toString(windowInfo->token != nullptr),
5080 toString(windowInfo->touchOcclusionMode).c_str(),
5081 windowInfo->displayOrientation);
5082 windowInfo->transform.dump(dump, "transform", INDENT4);
5083 }
5084 } else {
5085 dump += INDENT2 "Windows: <none>\n";
5086 }
5087 }
5088 } else {
5089 dump += INDENT "Displays: <none>\n";
5090 }
5091
5092 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
5093 for (auto& it : mGlobalMonitorsByDisplay) {
5094 const std::vector<Monitor>& monitors = it.second;
5095 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
5096 dumpMonitors(dump, monitors);
5097 }
5098 for (auto& it : mGestureMonitorsByDisplay) {
5099 const std::vector<Monitor>& monitors = it.second;
5100 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
5101 dumpMonitors(dump, monitors);
5102 }
5103 } else {
5104 dump += INDENT "Monitors: <none>\n";
5105 }
5106
5107 nsecs_t currentTime = now();
5108
5109 // Dump recently dispatched or dropped events from oldest to newest.
5110 if (!mRecentQueue.empty()) {
5111 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
5112 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
5113 dump += INDENT2;
5114 dump += entry->getDescription();
5115 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
5116 }
5117 } else {
5118 dump += INDENT "RecentQueue: <empty>\n";
5119 }
5120
5121 // Dump event currently being dispatched.
5122 if (mPendingEvent) {
5123 dump += INDENT "PendingEvent:\n";
5124 dump += INDENT2;
5125 dump += mPendingEvent->getDescription();
5126 dump += StringPrintf(", age=%" PRId64 "ms\n",
5127 ns2ms(currentTime - mPendingEvent->eventTime));
5128 } else {
5129 dump += INDENT "PendingEvent: <none>\n";
5130 }
5131
5132 // Dump inbound events from oldest to newest.
5133 if (!mInboundQueue.empty()) {
5134 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
5135 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
5136 dump += INDENT2;
5137 dump += entry->getDescription();
5138 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
5139 }
5140 } else {
5141 dump += INDENT "InboundQueue: <empty>\n";
5142 }
5143
5144 if (!mReplacedKeys.empty()) {
5145 dump += INDENT "ReplacedKeys:\n";
5146 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5147 const KeyReplacement& replacement = pair.first;
5148 int32_t newKeyCode = pair.second;
5149 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
5150 replacement.keyCode, replacement.deviceId, newKeyCode);
5151 }
5152 } else {
5153 dump += INDENT "ReplacedKeys: <empty>\n";
5154 }
5155
5156 if (!mConnectionsByToken.empty()) {
5157 dump += INDENT "Connections:\n";
5158 for (const auto& [token, connection] : mConnectionsByToken) {
5159 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
5160 "status=%s, monitor=%s, responsive=%s\n",
5161 connection->inputChannel->getFd().get(),
5162 connection->getInputChannelName().c_str(),
5163 connection->getWindowName().c_str(), connection->getStatusLabel(),
5164 toString(connection->monitor), toString(connection->responsive));
5165
5166 if (!connection->outboundQueue.empty()) {
5167 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5168 connection->outboundQueue.size());
5169 dump += dumpQueue(connection->outboundQueue, currentTime);
5170
5171 } else {
5172 dump += INDENT3 "OutboundQueue: <empty>\n";
5173 }
5174
5175 if (!connection->waitQueue.empty()) {
5176 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5177 connection->waitQueue.size());
5178 dump += dumpQueue(connection->waitQueue, currentTime);
5179 } else {
5180 dump += INDENT3 "WaitQueue: <empty>\n";
5181 }
5182 }
5183 } else {
5184 dump += INDENT "Connections: <none>\n";
5185 }
5186
5187 if (isAppSwitchPendingLocked()) {
5188 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5189 ns2ms(mAppSwitchDueTime - now()));
5190 } else {
5191 dump += INDENT "AppSwitch: not pending\n";
5192 }
5193
5194 dump += INDENT "Configuration:\n";
5195 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5196 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5197 ns2ms(mConfig.keyRepeatTimeout));
5198 dump += mLatencyTracker.dump(INDENT2);
5199 dump += mLatencyAggregator.dump(INDENT2);
5200 }
5201
dumpMonitors(std::string & dump,const std::vector<Monitor> & monitors)5202 void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5203 const size_t numMonitors = monitors.size();
5204 for (size_t i = 0; i < numMonitors; i++) {
5205 const Monitor& monitor = monitors[i];
5206 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
5207 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5208 dump += "\n";
5209 }
5210 }
5211
5212 class LooperEventCallback : public LooperCallback {
5213 public:
LooperEventCallback(std::function<int (int events)> callback)5214 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
handleEvent(int,int events,void *)5215 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5216
5217 private:
5218 std::function<int(int events)> mCallback;
5219 };
5220
createInputChannel(const std::string & name)5221 Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
5222 #if DEBUG_CHANNEL_CREATION
5223 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5224 #endif
5225
5226 std::unique_ptr<InputChannel> serverChannel;
5227 std::unique_ptr<InputChannel> clientChannel;
5228 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
5229
5230 if (result) {
5231 return base::Error(result) << "Failed to open input channel pair with name " << name;
5232 }
5233
5234 { // acquire lock
5235 std::scoped_lock _l(mLock);
5236 const sp<IBinder>& token = serverChannel->getConnectionToken();
5237 int fd = serverChannel->getFd();
5238 sp<Connection> connection =
5239 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
5240
5241 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5242 ALOGE("Created a new connection, but the token %p is already known", token.get());
5243 }
5244 mConnectionsByToken.emplace(token, connection);
5245
5246 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5247 this, std::placeholders::_1, token);
5248
5249 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
5250 } // release lock
5251
5252 // Wake the looper because some connections have changed.
5253 mLooper->wake();
5254 return clientChannel;
5255 }
5256
createInputMonitor(int32_t displayId,bool isGestureMonitor,const std::string & name,int32_t pid)5257 Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
5258 bool isGestureMonitor,
5259 const std::string& name,
5260 int32_t pid) {
5261 std::shared_ptr<InputChannel> serverChannel;
5262 std::unique_ptr<InputChannel> clientChannel;
5263 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5264 if (result) {
5265 return base::Error(result) << "Failed to open input channel pair with name " << name;
5266 }
5267
5268 { // acquire lock
5269 std::scoped_lock _l(mLock);
5270
5271 if (displayId < 0) {
5272 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5273 << " without a specified display.";
5274 }
5275
5276 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
5277 const sp<IBinder>& token = serverChannel->getConnectionToken();
5278 const int fd = serverChannel->getFd();
5279
5280 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5281 ALOGE("Created a new connection, but the token %p is already known", token.get());
5282 }
5283 mConnectionsByToken.emplace(token, connection);
5284 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5285 this, std::placeholders::_1, token);
5286
5287 auto& monitorsByDisplay =
5288 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
5289 monitorsByDisplay[displayId].emplace_back(serverChannel, pid);
5290
5291 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
5292 ALOGI("Created monitor %s for display %" PRId32 ", gesture=%s, pid=%" PRId32, name.c_str(),
5293 displayId, toString(isGestureMonitor), pid);
5294 }
5295
5296 // Wake the looper because some connections have changed.
5297 mLooper->wake();
5298 return clientChannel;
5299 }
5300
removeInputChannel(const sp<IBinder> & connectionToken)5301 status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
5302 { // acquire lock
5303 std::scoped_lock _l(mLock);
5304
5305 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
5306 if (status) {
5307 return status;
5308 }
5309 } // release lock
5310
5311 // Wake the poll loop because removing the connection may have changed the current
5312 // synchronization state.
5313 mLooper->wake();
5314 return OK;
5315 }
5316
removeInputChannelLocked(const sp<IBinder> & connectionToken,bool notify)5317 status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5318 bool notify) {
5319 sp<Connection> connection = getConnectionLocked(connectionToken);
5320 if (connection == nullptr) {
5321 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
5322 return BAD_VALUE;
5323 }
5324
5325 removeConnectionLocked(connection);
5326
5327 if (connection->monitor) {
5328 removeMonitorChannelLocked(connectionToken);
5329 }
5330
5331 mLooper->removeFd(connection->inputChannel->getFd());
5332
5333 nsecs_t currentTime = now();
5334 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5335
5336 connection->status = Connection::STATUS_ZOMBIE;
5337 return OK;
5338 }
5339
removeMonitorChannelLocked(const sp<IBinder> & connectionToken)5340 void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
5341 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
5342 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
5343 }
5344
removeMonitorChannelLocked(const sp<IBinder> & connectionToken,std::unordered_map<int32_t,std::vector<Monitor>> & monitorsByDisplay)5345 void InputDispatcher::removeMonitorChannelLocked(
5346 const sp<IBinder>& connectionToken,
5347 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
5348 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
5349 std::vector<Monitor>& monitors = it->second;
5350 const size_t numMonitors = monitors.size();
5351 for (size_t i = 0; i < numMonitors; i++) {
5352 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
5353 ALOGI("Erasing monitor %s on display %" PRId32 ", pid=%" PRId32,
5354 monitors[i].inputChannel->getName().c_str(), it->first, monitors[i].pid);
5355 monitors.erase(monitors.begin() + i);
5356 break;
5357 }
5358 }
5359 if (monitors.empty()) {
5360 it = monitorsByDisplay.erase(it);
5361 } else {
5362 ++it;
5363 }
5364 }
5365 }
5366
pilferPointers(const sp<IBinder> & token)5367 status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
5368 { // acquire lock
5369 std::scoped_lock _l(mLock);
5370 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
5371
5372 if (!foundDisplayId) {
5373 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
5374 return BAD_VALUE;
5375 }
5376 int32_t displayId = foundDisplayId.value();
5377
5378 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5379 mTouchStatesByDisplay.find(displayId);
5380 if (stateIt == mTouchStatesByDisplay.end()) {
5381 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
5382 return BAD_VALUE;
5383 }
5384
5385 TouchState& state = stateIt->second;
5386 std::shared_ptr<InputChannel> requestingChannel;
5387 std::optional<int32_t> foundDeviceId;
5388 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
5389 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
5390 requestingChannel = touchedMonitor.monitor.inputChannel;
5391 foundDeviceId = state.deviceId;
5392 }
5393 }
5394 if (!foundDeviceId || !state.down) {
5395 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
5396 " Ignoring.");
5397 return BAD_VALUE;
5398 }
5399 int32_t deviceId = foundDeviceId.value();
5400
5401 // Send cancel events to all the input channels we're stealing from.
5402 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5403 "gesture monitor stole pointer stream");
5404 options.deviceId = deviceId;
5405 options.displayId = displayId;
5406 std::string canceledWindows = "[";
5407 for (const TouchedWindow& window : state.windows) {
5408 std::shared_ptr<InputChannel> channel =
5409 getInputChannelLocked(window.windowHandle->getToken());
5410 if (channel != nullptr) {
5411 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5412 canceledWindows += channel->getName() + ", ";
5413 }
5414 }
5415 canceledWindows += "]";
5416 ALOGI("Monitor %s is stealing touch from %s", requestingChannel->getName().c_str(),
5417 canceledWindows.c_str());
5418
5419 // Then clear the current touch state so we stop dispatching to them as well.
5420 state.split = false;
5421 state.filterNonMonitors();
5422 }
5423 return OK;
5424 }
5425
requestPointerCapture(const sp<IBinder> & windowToken,bool enabled)5426 void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5427 { // acquire lock
5428 std::scoped_lock _l(mLock);
5429 if (DEBUG_FOCUS) {
5430 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
5431 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5432 windowHandle != nullptr ? windowHandle->getName().c_str()
5433 : "token without window");
5434 }
5435
5436 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5437 if (focusedToken != windowToken) {
5438 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5439 enabled ? "enable" : "disable");
5440 return;
5441 }
5442
5443 if (enabled == mCurrentPointerCaptureRequest.enable) {
5444 ALOGW("Ignoring request to %s Pointer Capture: "
5445 "window has %s requested pointer capture.",
5446 enabled ? "enable" : "disable", enabled ? "already" : "not");
5447 return;
5448 }
5449
5450 setPointerCaptureLocked(enabled);
5451 } // release lock
5452
5453 // Wake the thread to process command entries.
5454 mLooper->wake();
5455 }
5456
findGestureMonitorDisplayByTokenLocked(const sp<IBinder> & token)5457 std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
5458 const sp<IBinder>& token) {
5459 for (const auto& it : mGestureMonitorsByDisplay) {
5460 const std::vector<Monitor>& monitors = it.second;
5461 for (const Monitor& monitor : monitors) {
5462 if (monitor.inputChannel->getConnectionToken() == token) {
5463 return it.first;
5464 }
5465 }
5466 }
5467 return std::nullopt;
5468 }
5469
findMonitorPidByTokenLocked(const sp<IBinder> & token)5470 std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5471 std::optional<int32_t> gesturePid = findMonitorPidByToken(mGestureMonitorsByDisplay, token);
5472 if (gesturePid.has_value()) {
5473 return gesturePid;
5474 }
5475 return findMonitorPidByToken(mGlobalMonitorsByDisplay, token);
5476 }
5477
getConnectionLocked(const sp<IBinder> & inputConnectionToken) const5478 sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
5479 if (inputConnectionToken == nullptr) {
5480 return nullptr;
5481 }
5482
5483 for (const auto& [token, connection] : mConnectionsByToken) {
5484 if (token == inputConnectionToken) {
5485 return connection;
5486 }
5487 }
5488
5489 return nullptr;
5490 }
5491
getConnectionNameLocked(const sp<IBinder> & connectionToken) const5492 std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5493 sp<Connection> connection = getConnectionLocked(connectionToken);
5494 if (connection == nullptr) {
5495 return "<nullptr>";
5496 }
5497 return connection->getInputChannelName();
5498 }
5499
removeConnectionLocked(const sp<Connection> & connection)5500 void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
5501 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
5502 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
5503 }
5504
onDispatchCycleFinishedLocked(nsecs_t currentTime,const sp<Connection> & connection,uint32_t seq,bool handled,nsecs_t consumeTime)5505 void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
5506 const sp<Connection>& connection, uint32_t seq,
5507 bool handled, nsecs_t consumeTime) {
5508 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5509 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
5510 commandEntry->connection = connection;
5511 commandEntry->eventTime = currentTime;
5512 commandEntry->seq = seq;
5513 commandEntry->handled = handled;
5514 commandEntry->consumeTime = consumeTime;
5515 postCommandLocked(std::move(commandEntry));
5516 }
5517
onDispatchCycleBrokenLocked(nsecs_t currentTime,const sp<Connection> & connection)5518 void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
5519 const sp<Connection>& connection) {
5520 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
5521 connection->getInputChannelName().c_str());
5522
5523 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5524 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
5525 commandEntry->connection = connection;
5526 postCommandLocked(std::move(commandEntry));
5527 }
5528
notifyFocusChangedLocked(const sp<IBinder> & oldToken,const sp<IBinder> & newToken)5529 void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
5530 const sp<IBinder>& newToken) {
5531 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5532 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
5533 commandEntry->oldToken = oldToken;
5534 commandEntry->newToken = newToken;
5535 postCommandLocked(std::move(commandEntry));
5536 }
5537
notifyDropWindowLocked(const sp<IBinder> & token,float x,float y)5538 void InputDispatcher::notifyDropWindowLocked(const sp<IBinder>& token, float x, float y) {
5539 std::unique_ptr<CommandEntry> commandEntry =
5540 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyDropWindowLockedInterruptible);
5541 commandEntry->newToken = token;
5542 commandEntry->x = x;
5543 commandEntry->y = y;
5544 postCommandLocked(std::move(commandEntry));
5545 }
5546
onAnrLocked(const sp<Connection> & connection)5547 void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5548 if (connection == nullptr) {
5549 LOG_ALWAYS_FATAL("Caller must check for nullness");
5550 }
5551 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5552 // is already healthy again. Don't raise ANR in this situation
5553 if (connection->waitQueue.empty()) {
5554 ALOGI("Not raising ANR because the connection %s has recovered",
5555 connection->inputChannel->getName().c_str());
5556 return;
5557 }
5558 /**
5559 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5560 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5561 * has changed. This could cause newer entries to time out before the already dispatched
5562 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5563 * processes the events linearly. So providing information about the oldest entry seems to be
5564 * most useful.
5565 */
5566 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
5567 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5568 std::string reason =
5569 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
5570 connection->inputChannel->getName().c_str(),
5571 ns2ms(currentWait),
5572 oldestEntry->eventEntry->getDescription().c_str());
5573 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
5574 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
5575
5576 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5577
5578 // Stop waking up for events on this connection, it is already unresponsive
5579 cancelEventsForAnrLocked(connection);
5580 }
5581
onAnrLocked(std::shared_ptr<InputApplicationHandle> application)5582 void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5583 std::string reason =
5584 StringPrintf("%s does not have a focused window", application->getName().c_str());
5585 updateLastAnrStateLocked(*application, reason);
5586
5587 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5588 &InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible);
5589 commandEntry->inputApplicationHandle = std::move(application);
5590 postCommandLocked(std::move(commandEntry));
5591 }
5592
onUntrustedTouchLocked(const std::string & obscuringPackage)5593 void InputDispatcher::onUntrustedTouchLocked(const std::string& obscuringPackage) {
5594 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
5595 &InputDispatcher::doNotifyUntrustedTouchLockedInterruptible);
5596 commandEntry->obscuringPackage = obscuringPackage;
5597 postCommandLocked(std::move(commandEntry));
5598 }
5599
updateLastAnrStateLocked(const sp<WindowInfoHandle> & window,const std::string & reason)5600 void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
5601 const std::string& reason) {
5602 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5603 updateLastAnrStateLocked(windowLabel, reason);
5604 }
5605
updateLastAnrStateLocked(const InputApplicationHandle & application,const std::string & reason)5606 void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5607 const std::string& reason) {
5608 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
5609 updateLastAnrStateLocked(windowLabel, reason);
5610 }
5611
updateLastAnrStateLocked(const std::string & windowLabel,const std::string & reason)5612 void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5613 const std::string& reason) {
5614 // Capture a record of the InputDispatcher state at the time of the ANR.
5615 time_t t = time(nullptr);
5616 struct tm tm;
5617 localtime_r(&t, &tm);
5618 char timestr[64];
5619 strftime(timestr, sizeof(timestr), "%F %T", &tm);
5620 mLastAnrState.clear();
5621 mLastAnrState += INDENT "ANR:\n";
5622 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
5623 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5624 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
5625 dumpDispatchStateLocked(mLastAnrState);
5626 }
5627
doNotifyConfigurationChangedLockedInterruptible(CommandEntry * commandEntry)5628 void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
5629 mLock.unlock();
5630
5631 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
5632
5633 mLock.lock();
5634 }
5635
doNotifyInputChannelBrokenLockedInterruptible(CommandEntry * commandEntry)5636 void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
5637 sp<Connection> connection = commandEntry->connection;
5638
5639 if (connection->status != Connection::STATUS_ZOMBIE) {
5640 mLock.unlock();
5641
5642 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
5643
5644 mLock.lock();
5645 }
5646 }
5647
doNotifyFocusChangedLockedInterruptible(CommandEntry * commandEntry)5648 void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
5649 sp<IBinder> oldToken = commandEntry->oldToken;
5650 sp<IBinder> newToken = commandEntry->newToken;
5651 mLock.unlock();
5652 mPolicy->notifyFocusChanged(oldToken, newToken);
5653 mLock.lock();
5654 }
5655
doNotifyDropWindowLockedInterruptible(CommandEntry * commandEntry)5656 void InputDispatcher::doNotifyDropWindowLockedInterruptible(CommandEntry* commandEntry) {
5657 sp<IBinder> newToken = commandEntry->newToken;
5658 mLock.unlock();
5659 mPolicy->notifyDropWindow(newToken, commandEntry->x, commandEntry->y);
5660 mLock.lock();
5661 }
5662
doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry * commandEntry)5663 void InputDispatcher::doNotifyNoFocusedWindowAnrLockedInterruptible(CommandEntry* commandEntry) {
5664 mLock.unlock();
5665
5666 mPolicy->notifyNoFocusedWindowAnr(commandEntry->inputApplicationHandle);
5667
5668 mLock.lock();
5669 }
5670
doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry * commandEntry)5671 void InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
5672 mLock.unlock();
5673
5674 mPolicy->notifyWindowUnresponsive(commandEntry->connectionToken, commandEntry->reason);
5675
5676 mLock.lock();
5677 }
5678
doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry * commandEntry)5679 void InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible(CommandEntry* commandEntry) {
5680 mLock.unlock();
5681
5682 mPolicy->notifyMonitorUnresponsive(commandEntry->pid, commandEntry->reason);
5683
5684 mLock.lock();
5685 }
5686
doNotifyWindowResponsiveLockedInterruptible(CommandEntry * commandEntry)5687 void InputDispatcher::doNotifyWindowResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5688 mLock.unlock();
5689
5690 mPolicy->notifyWindowResponsive(commandEntry->connectionToken);
5691
5692 mLock.lock();
5693 }
5694
doNotifyMonitorResponsiveLockedInterruptible(CommandEntry * commandEntry)5695 void InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible(CommandEntry* commandEntry) {
5696 mLock.unlock();
5697
5698 mPolicy->notifyMonitorResponsive(commandEntry->pid);
5699
5700 mLock.lock();
5701 }
5702
doNotifyUntrustedTouchLockedInterruptible(CommandEntry * commandEntry)5703 void InputDispatcher::doNotifyUntrustedTouchLockedInterruptible(CommandEntry* commandEntry) {
5704 mLock.unlock();
5705
5706 mPolicy->notifyUntrustedTouch(commandEntry->obscuringPackage);
5707
5708 mLock.lock();
5709 }
5710
doInterceptKeyBeforeDispatchingLockedInterruptible(CommandEntry * commandEntry)5711 void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
5712 CommandEntry* commandEntry) {
5713 KeyEntry& entry = *(commandEntry->keyEntry);
5714 KeyEvent event = createKeyEvent(entry);
5715
5716 mLock.unlock();
5717
5718 android::base::Timer t;
5719 const sp<IBinder>& token = commandEntry->connectionToken;
5720 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry.policyFlags);
5721 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5722 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5723 std::to_string(t.duration().count()).c_str());
5724 }
5725
5726 mLock.lock();
5727
5728 if (delay < 0) {
5729 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
5730 } else if (!delay) {
5731 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
5732 } else {
5733 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5734 entry.interceptKeyWakeupTime = now() + delay;
5735 }
5736 }
5737
doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry * commandEntry)5738 void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
5739 mLock.unlock();
5740 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
5741 mLock.lock();
5742 }
5743
5744 /**
5745 * Connection is responsive if it has no events in the waitQueue that are older than the
5746 * current time.
5747 */
isConnectionResponsive(const Connection & connection)5748 static bool isConnectionResponsive(const Connection& connection) {
5749 const nsecs_t currentTime = now();
5750 for (const DispatchEntry* entry : connection.waitQueue) {
5751 if (entry->timeoutTime < currentTime) {
5752 return false;
5753 }
5754 }
5755 return true;
5756 }
5757
doDispatchCycleFinishedLockedInterruptible(CommandEntry * commandEntry)5758 void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
5759 sp<Connection> connection = commandEntry->connection;
5760 const nsecs_t finishTime = commandEntry->eventTime;
5761 uint32_t seq = commandEntry->seq;
5762 const bool handled = commandEntry->handled;
5763
5764 // Handle post-event policy actions.
5765 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5766 if (dispatchEntryIt == connection->waitQueue.end()) {
5767 return;
5768 }
5769 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5770 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5771 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5772 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5773 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5774 }
5775 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5776 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5777 connection->inputChannel->getConnectionToken(),
5778 dispatchEntry->deliveryTime, commandEntry->consumeTime,
5779 finishTime);
5780 }
5781
5782 bool restartEvent;
5783 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5784 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5785 restartEvent =
5786 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
5787 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5788 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5789 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
5790 handled);
5791 } else {
5792 restartEvent = false;
5793 }
5794
5795 // Dequeue the event and start the next cycle.
5796 // Because the lock might have been released, it is possible that the
5797 // contents of the wait queue to have been drained, so we need to double-check
5798 // a few things.
5799 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5800 if (dispatchEntryIt != connection->waitQueue.end()) {
5801 dispatchEntry = *dispatchEntryIt;
5802 connection->waitQueue.erase(dispatchEntryIt);
5803 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5804 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5805 if (!connection->responsive) {
5806 connection->responsive = isConnectionResponsive(*connection);
5807 if (connection->responsive) {
5808 // The connection was unresponsive, and now it's responsive.
5809 processConnectionResponsiveLocked(*connection);
5810 }
5811 }
5812 traceWaitQueueLength(*connection);
5813 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
5814 connection->outboundQueue.push_front(dispatchEntry);
5815 traceOutboundQueueLength(*connection);
5816 } else {
5817 releaseDispatchEntry(dispatchEntry);
5818 }
5819 }
5820
5821 // Start the next dispatch cycle for this connection.
5822 startDispatchCycleLocked(now(), connection);
5823 }
5824
sendMonitorUnresponsiveCommandLocked(int32_t pid,std::string reason)5825 void InputDispatcher::sendMonitorUnresponsiveCommandLocked(int32_t pid, std::string reason) {
5826 std::unique_ptr<CommandEntry> monitorUnresponsiveCommand = std::make_unique<CommandEntry>(
5827 &InputDispatcher::doNotifyMonitorUnresponsiveLockedInterruptible);
5828 monitorUnresponsiveCommand->pid = pid;
5829 monitorUnresponsiveCommand->reason = std::move(reason);
5830 postCommandLocked(std::move(monitorUnresponsiveCommand));
5831 }
5832
sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,std::string reason)5833 void InputDispatcher::sendWindowUnresponsiveCommandLocked(sp<IBinder> connectionToken,
5834 std::string reason) {
5835 std::unique_ptr<CommandEntry> windowUnresponsiveCommand = std::make_unique<CommandEntry>(
5836 &InputDispatcher::doNotifyWindowUnresponsiveLockedInterruptible);
5837 windowUnresponsiveCommand->connectionToken = std::move(connectionToken);
5838 windowUnresponsiveCommand->reason = std::move(reason);
5839 postCommandLocked(std::move(windowUnresponsiveCommand));
5840 }
5841
sendMonitorResponsiveCommandLocked(int32_t pid)5842 void InputDispatcher::sendMonitorResponsiveCommandLocked(int32_t pid) {
5843 std::unique_ptr<CommandEntry> monitorResponsiveCommand = std::make_unique<CommandEntry>(
5844 &InputDispatcher::doNotifyMonitorResponsiveLockedInterruptible);
5845 monitorResponsiveCommand->pid = pid;
5846 postCommandLocked(std::move(monitorResponsiveCommand));
5847 }
5848
sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken)5849 void InputDispatcher::sendWindowResponsiveCommandLocked(sp<IBinder> connectionToken) {
5850 std::unique_ptr<CommandEntry> windowResponsiveCommand = std::make_unique<CommandEntry>(
5851 &InputDispatcher::doNotifyWindowResponsiveLockedInterruptible);
5852 windowResponsiveCommand->connectionToken = std::move(connectionToken);
5853 postCommandLocked(std::move(windowResponsiveCommand));
5854 }
5855
5856 /**
5857 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5858 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5859 * command entry to the command queue.
5860 */
processConnectionUnresponsiveLocked(const Connection & connection,std::string reason)5861 void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5862 std::string reason) {
5863 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5864 if (connection.monitor) {
5865 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5866 reason.c_str());
5867 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5868 if (!pid.has_value()) {
5869 ALOGE("Could not find unresponsive monitor for connection %s",
5870 connection.inputChannel->getName().c_str());
5871 return;
5872 }
5873 sendMonitorUnresponsiveCommandLocked(pid.value(), std::move(reason));
5874 return;
5875 }
5876 // If not a monitor, must be a window
5877 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5878 reason.c_str());
5879 sendWindowUnresponsiveCommandLocked(connectionToken, std::move(reason));
5880 }
5881
5882 /**
5883 * Tell the policy that a connection has become responsive so that it can stop ANR.
5884 */
processConnectionResponsiveLocked(const Connection & connection)5885 void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5886 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
5887 if (connection.monitor) {
5888 std::optional<int32_t> pid = findMonitorPidByTokenLocked(connectionToken);
5889 if (!pid.has_value()) {
5890 ALOGE("Could not find responsive monitor for connection %s",
5891 connection.inputChannel->getName().c_str());
5892 return;
5893 }
5894 sendMonitorResponsiveCommandLocked(pid.value());
5895 return;
5896 }
5897 // If not a monitor, must be a window
5898 sendWindowResponsiveCommandLocked(connectionToken);
5899 }
5900
afterKeyEventLockedInterruptible(const sp<Connection> & connection,DispatchEntry * dispatchEntry,KeyEntry & keyEntry,bool handled)5901 bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
5902 DispatchEntry* dispatchEntry,
5903 KeyEntry& keyEntry, bool handled) {
5904 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
5905 if (!handled) {
5906 // Report the key as unhandled, since the fallback was not handled.
5907 mReporter->reportUnhandledKey(keyEntry.id);
5908 }
5909 return false;
5910 }
5911
5912 // Get the fallback key state.
5913 // Clear it out after dispatching the UP.
5914 int32_t originalKeyCode = keyEntry.keyCode;
5915 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
5916 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
5917 connection->inputState.removeFallbackKey(originalKeyCode);
5918 }
5919
5920 if (handled || !dispatchEntry->hasForegroundTarget()) {
5921 // If the application handles the original key for which we previously
5922 // generated a fallback or if the window is not a foreground window,
5923 // then cancel the associated fallback key, if any.
5924 if (fallbackKeyCode != -1) {
5925 // Dispatch the unhandled key to the policy with the cancel flag.
5926 #if DEBUG_OUTBOUND_EVENT_DETAILS
5927 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
5928 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5929 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5930 #endif
5931 KeyEvent event = createKeyEvent(keyEntry);
5932 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
5933
5934 mLock.unlock();
5935
5936 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
5937 keyEntry.policyFlags, &event);
5938
5939 mLock.lock();
5940
5941 // Cancel the fallback key.
5942 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
5943 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5944 "application handled the original non-fallback key "
5945 "or is no longer a foreground target, "
5946 "canceling previously dispatched fallback key");
5947 options.keyCode = fallbackKeyCode;
5948 synthesizeCancelationEventsForConnectionLocked(connection, options);
5949 }
5950 connection->inputState.removeFallbackKey(originalKeyCode);
5951 }
5952 } else {
5953 // If the application did not handle a non-fallback key, first check
5954 // that we are in a good state to perform unhandled key event processing
5955 // Then ask the policy what to do with it.
5956 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
5957 if (fallbackKeyCode == -1 && !initialDown) {
5958 #if DEBUG_OUTBOUND_EVENT_DETAILS
5959 ALOGD("Unhandled key event: Skipping unhandled key event processing "
5960 "since this is not an initial down. "
5961 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5962 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5963 #endif
5964 return false;
5965 }
5966
5967 // Dispatch the unhandled key to the policy.
5968 #if DEBUG_OUTBOUND_EVENT_DETAILS
5969 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
5970 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5971 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
5972 #endif
5973 KeyEvent event = createKeyEvent(keyEntry);
5974
5975 mLock.unlock();
5976
5977 bool fallback =
5978 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
5979 &event, keyEntry.policyFlags, &event);
5980
5981 mLock.lock();
5982
5983 if (connection->status != Connection::STATUS_NORMAL) {
5984 connection->inputState.removeFallbackKey(originalKeyCode);
5985 return false;
5986 }
5987
5988 // Latch the fallback keycode for this key on an initial down.
5989 // The fallback keycode cannot change at any other point in the lifecycle.
5990 if (initialDown) {
5991 if (fallback) {
5992 fallbackKeyCode = event.getKeyCode();
5993 } else {
5994 fallbackKeyCode = AKEYCODE_UNKNOWN;
5995 }
5996 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5997 }
5998
5999 ALOG_ASSERT(fallbackKeyCode != -1);
6000
6001 // Cancel the fallback key if the policy decides not to send it anymore.
6002 // We will continue to dispatch the key to the policy but we will no
6003 // longer dispatch a fallback key to the application.
6004 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6005 (!fallback || fallbackKeyCode != event.getKeyCode())) {
6006 #if DEBUG_OUTBOUND_EVENT_DETAILS
6007 if (fallback) {
6008 ALOGD("Unhandled key event: Policy requested to send key %d"
6009 "as a fallback for %d, but on the DOWN it had requested "
6010 "to send %d instead. Fallback canceled.",
6011 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6012 } else {
6013 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6014 "but on the DOWN it had requested to send %d. "
6015 "Fallback canceled.",
6016 originalKeyCode, fallbackKeyCode);
6017 }
6018 #endif
6019
6020 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6021 "canceling fallback, policy no longer desires it");
6022 options.keyCode = fallbackKeyCode;
6023 synthesizeCancelationEventsForConnectionLocked(connection, options);
6024
6025 fallback = false;
6026 fallbackKeyCode = AKEYCODE_UNKNOWN;
6027 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
6028 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6029 }
6030 }
6031
6032 #if DEBUG_OUTBOUND_EVENT_DETAILS
6033 {
6034 std::string msg;
6035 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6036 connection->inputState.getFallbackKeys();
6037 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6038 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6039 }
6040 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6041 fallbackKeys.size(), msg.c_str());
6042 }
6043 #endif
6044
6045 if (fallback) {
6046 // Restart the dispatch cycle using the fallback key.
6047 keyEntry.eventTime = event.getEventTime();
6048 keyEntry.deviceId = event.getDeviceId();
6049 keyEntry.source = event.getSource();
6050 keyEntry.displayId = event.getDisplayId();
6051 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6052 keyEntry.keyCode = fallbackKeyCode;
6053 keyEntry.scanCode = event.getScanCode();
6054 keyEntry.metaState = event.getMetaState();
6055 keyEntry.repeatCount = event.getRepeatCount();
6056 keyEntry.downTime = event.getDownTime();
6057 keyEntry.syntheticRepeat = false;
6058
6059 #if DEBUG_OUTBOUND_EVENT_DETAILS
6060 ALOGD("Unhandled key event: Dispatching fallback key. "
6061 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6062 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6063 #endif
6064 return true; // restart the event
6065 } else {
6066 #if DEBUG_OUTBOUND_EVENT_DETAILS
6067 ALOGD("Unhandled key event: No fallback key.");
6068 #endif
6069
6070 // Report the key as unhandled, since there is no fallback key.
6071 mReporter->reportUnhandledKey(keyEntry.id);
6072 }
6073 }
6074 return false;
6075 }
6076
afterMotionEventLockedInterruptible(const sp<Connection> & connection,DispatchEntry * dispatchEntry,MotionEntry & motionEntry,bool handled)6077 bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
6078 DispatchEntry* dispatchEntry,
6079 MotionEntry& motionEntry, bool handled) {
6080 return false;
6081 }
6082
doPokeUserActivityLockedInterruptible(CommandEntry * commandEntry)6083 void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
6084 mLock.unlock();
6085
6086 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType,
6087 commandEntry->displayId);
6088
6089 mLock.lock();
6090 }
6091
traceInboundQueueLengthLocked()6092 void InputDispatcher::traceInboundQueueLengthLocked() {
6093 if (ATRACE_ENABLED()) {
6094 ATRACE_INT("iq", mInboundQueue.size());
6095 }
6096 }
6097
traceOutboundQueueLength(const Connection & connection)6098 void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
6099 if (ATRACE_ENABLED()) {
6100 char counterName[40];
6101 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6102 ATRACE_INT(counterName, connection.outboundQueue.size());
6103 }
6104 }
6105
traceWaitQueueLength(const Connection & connection)6106 void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
6107 if (ATRACE_ENABLED()) {
6108 char counterName[40];
6109 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6110 ATRACE_INT(counterName, connection.waitQueue.size());
6111 }
6112 }
6113
dump(std::string & dump)6114 void InputDispatcher::dump(std::string& dump) {
6115 std::scoped_lock _l(mLock);
6116
6117 dump += "Input Dispatcher State:\n";
6118 dumpDispatchStateLocked(dump);
6119
6120 if (!mLastAnrState.empty()) {
6121 dump += "\nInput Dispatcher State at time of last ANR:\n";
6122 dump += mLastAnrState;
6123 }
6124 }
6125
monitor()6126 void InputDispatcher::monitor() {
6127 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
6128 std::unique_lock _l(mLock);
6129 mLooper->wake();
6130 mDispatcherIsAlive.wait(_l);
6131 }
6132
6133 /**
6134 * Wake up the dispatcher and wait until it processes all events and commands.
6135 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6136 * this method can be safely called from any thread, as long as you've ensured that
6137 * the work you are interested in completing has already been queued.
6138 */
waitForIdle()6139 bool InputDispatcher::waitForIdle() {
6140 /**
6141 * Timeout should represent the longest possible time that a device might spend processing
6142 * events and commands.
6143 */
6144 constexpr std::chrono::duration TIMEOUT = 100ms;
6145 std::unique_lock lock(mLock);
6146 mLooper->wake();
6147 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6148 return result == std::cv_status::no_timeout;
6149 }
6150
6151 /**
6152 * Sets focus to the window identified by the token. This must be called
6153 * after updating any input window handles.
6154 *
6155 * Params:
6156 * request.token - input channel token used to identify the window that should gain focus.
6157 * request.focusedToken - the token that the caller expects currently to be focused. If the
6158 * specified token does not match the currently focused window, this request will be dropped.
6159 * If the specified focused token matches the currently focused window, the call will succeed.
6160 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6161 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6162 * when requesting the focus change. This determines which request gets
6163 * precedence if there is a focus change request from another source such as pointer down.
6164 */
setFocusedWindow(const FocusRequest & request)6165 void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6166 { // acquire lock
6167 std::scoped_lock _l(mLock);
6168 std::optional<FocusResolver::FocusChanges> changes =
6169 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6170 if (changes) {
6171 onFocusChangedLocked(*changes);
6172 }
6173 } // release lock
6174 // Wake up poll loop since it may need to make new input dispatching choices.
6175 mLooper->wake();
6176 }
6177
onFocusChangedLocked(const FocusResolver::FocusChanges & changes)6178 void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6179 if (changes.oldFocus) {
6180 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
6181 if (focusedInputChannel) {
6182 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6183 "focus left window");
6184 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
6185 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
6186 }
6187 }
6188 if (changes.newFocus) {
6189 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
6190 }
6191
6192 // If a window has pointer capture, then it must have focus. We need to ensure that this
6193 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6194 // If the window loses focus before it loses pointer capture, then the window can be in a state
6195 // where it has pointer capture but not focus, violating the contract. Therefore we must
6196 // dispatch the pointer capture event before the focus event. Since focus events are added to
6197 // the front of the queue (above), we add the pointer capture event to the front of the queue
6198 // after the focus events are added. This ensures the pointer capture event ends up at the
6199 // front.
6200 disablePointerCaptureForcedLocked();
6201
6202 if (mFocusedDisplayId == changes.displayId) {
6203 notifyFocusChangedLocked(changes.oldFocus, changes.newFocus);
6204 }
6205 }
6206
disablePointerCaptureForcedLocked()6207 void InputDispatcher::disablePointerCaptureForcedLocked() {
6208 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
6209 return;
6210 }
6211
6212 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6213
6214 if (mCurrentPointerCaptureRequest.enable) {
6215 setPointerCaptureLocked(false);
6216 }
6217
6218 if (!mWindowTokenWithPointerCapture) {
6219 // No need to send capture changes because no window has capture.
6220 return;
6221 }
6222
6223 if (mPendingEvent != nullptr) {
6224 // Move the pending event to the front of the queue. This will give the chance
6225 // for the pending event to be dropped if it is a captured event.
6226 mInboundQueue.push_front(mPendingEvent);
6227 mPendingEvent = nullptr;
6228 }
6229
6230 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
6231 mCurrentPointerCaptureRequest);
6232 mInboundQueue.push_front(std::move(entry));
6233 }
6234
setPointerCaptureLocked(bool enabled)6235 void InputDispatcher::setPointerCaptureLocked(bool enabled) {
6236 mCurrentPointerCaptureRequest.enable = enabled;
6237 mCurrentPointerCaptureRequest.seq++;
6238 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
6239 &InputDispatcher::doSetPointerCaptureLockedInterruptible);
6240 commandEntry->pointerCaptureRequest = mCurrentPointerCaptureRequest;
6241 postCommandLocked(std::move(commandEntry));
6242 }
6243
doSetPointerCaptureLockedInterruptible(android::inputdispatcher::CommandEntry * commandEntry)6244 void InputDispatcher::doSetPointerCaptureLockedInterruptible(
6245 android::inputdispatcher::CommandEntry* commandEntry) {
6246 mLock.unlock();
6247
6248 mPolicy->setPointerCapture(commandEntry->pointerCaptureRequest);
6249
6250 mLock.lock();
6251 }
6252
displayRemoved(int32_t displayId)6253 void InputDispatcher::displayRemoved(int32_t displayId) {
6254 { // acquire lock
6255 std::scoped_lock _l(mLock);
6256 // Set an empty list to remove all handles from the specific display.
6257 setInputWindowsLocked(/* window handles */ {}, displayId);
6258 setFocusedApplicationLocked(displayId, nullptr);
6259 // Call focus resolver to clean up stale requests. This must be called after input windows
6260 // have been removed for the removed display.
6261 mFocusResolver.displayRemoved(displayId);
6262 } // release lock
6263
6264 // Wake up poll loop since it may need to make new input dispatching choices.
6265 mLooper->wake();
6266 }
6267
onWindowInfosChanged(const std::vector<gui::WindowInfo> & windowInfos)6268 void InputDispatcher::onWindowInfosChanged(const std::vector<gui::WindowInfo>& windowInfos) {
6269 // The listener sends the windows as a flattened array. Separate the windows by display for
6270 // more convenient parsing.
6271 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
6272
6273 for (const auto& info : windowInfos) {
6274 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6275 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6276 }
6277 setInputWindows(handlesPerDisplay);
6278 }
6279
shouldDropInput(const EventEntry & entry,const sp<android::gui::WindowInfoHandle> & windowHandle) const6280 bool InputDispatcher::shouldDropInput(
6281 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
6282 if (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT) ||
6283 (windowHandle->getInfo()->inputFeatures.test(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED) &&
6284 isWindowObscuredLocked(windowHandle))) {
6285 ALOGW("Dropping %s event targeting %s as requested by input feature %s on display "
6286 "%" PRId32 ".",
6287 NamedEnum::string(entry.type).c_str(), windowHandle->getName().c_str(),
6288 windowHandle->getInfo()->inputFeatures.string().c_str(),
6289 windowHandle->getInfo()->displayId);
6290 return true;
6291 }
6292 return false;
6293 }
6294
6295 } // namespace android::inputdispatcher
6296