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