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